1
# Copyright (C) 2005 by Canonical Ltd
2
# Authors: Robert Collins <robert.collins@canonical.com>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""Configuration that affects the behaviour of Bazaar.
20
Currently this configuration resides in ~/.bazaar/bazaar.conf
21
and ~/.bazaar/branches.conf, which is written to by bzr.
23
In bazaar.conf the following options may be set:
25
editor=name-of-program
26
email=Your Name <your@email.address>
27
check_signatures=require|ignore|check-available(default)
28
create_signatures=always|never|when-required(default)
29
gpg_signing_command=name-of-program
31
in branches.conf, you specify the url of a branch and options for it.
32
Wildcards may be used - * and ? as normal in shell completion. Options
33
set in both bazaar.conf and branches.conf are overriden by the branches.conf
35
[/home/robertc/source]
36
recurse=False|True(default)
38
check_signatures= as abive
39
create_signatures= as above.
41
explanation of options
42
----------------------
43
editor - this option sets the pop up editor to use during commits.
44
email - this option sets the user id bzr will use when committing.
45
check_signatures - this option controls whether bzr will require good gpg
46
signatures, ignore them, or check them if they are
48
create_signatures - this option controls whether bzr will always create
49
gpg signatures, never create them, or create them if the
50
branch is configured to require them.
51
NB: This option is planned, but not implemented yet.
58
from fnmatch import fnmatch
62
import bzrlib.errors as errors
63
from bzrlib.osutils import pathjoin
64
from bzrlib.trace import mutter
65
import bzrlib.util.configobj.configobj as configobj
66
from StringIO import StringIO
73
class ConfigObj(configobj.ConfigObj):
75
def get_bool(self, section, key):
76
val = self[section][key].lower()
77
if val in ('1', 'yes', 'true', 'on'):
79
elif val in ('0', 'no', 'false', 'off'):
82
raise ValueError("Value %r is not boolean" % val)
84
def get_value(self, section, name):
85
# Try [] for the old DEFAULT section.
86
if section == "DEFAULT":
91
return self[section][name]
95
"""A configuration policy - what username, editor, gpg needs etc."""
98
"""Get the users pop up editor."""
99
raise NotImplementedError
101
def _get_signature_checking(self):
102
"""Template method to override signature checking policy."""
104
def _get_user_option(self, option_name):
105
"""Template method to provide a user option."""
108
def get_user_option(self, option_name):
109
"""Get a generic option - no special process, no default."""
110
return self._get_user_option(option_name)
112
def gpg_signing_command(self):
113
"""What program should be used to sign signatures?"""
114
result = self._gpg_signing_command()
119
def _gpg_signing_command(self):
120
"""See gpg_signing_command()."""
124
super(Config, self).__init__()
126
def post_commit(self):
127
"""An ordered list of python functions to call.
129
Each function takes branch, rev_id as parameters.
131
return self._post_commit()
133
def _post_commit(self):
134
"""See Config.post_commit."""
137
def user_email(self):
138
"""Return just the email component of a username."""
139
return extract_email_address(self.username())
142
"""Return email-style username.
144
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
146
$BZREMAIL can be set to override this, then
147
the concrete policy type is checked, and finally
149
If none is found, a reasonable default is (hopefully)
152
TODO: Check it's reasonably well-formed.
154
v = os.environ.get('BZREMAIL')
156
return v.decode(bzrlib.user_encoding)
158
v = self._get_user_id()
162
v = os.environ.get('EMAIL')
164
return v.decode(bzrlib.user_encoding)
166
name, email = _auto_user_id()
168
return '%s <%s>' % (name, email)
172
def signature_checking(self):
173
"""What is the current policy for signature checking?."""
174
policy = self._get_signature_checking()
175
if policy is not None:
177
return CHECK_IF_POSSIBLE
179
def signature_needed(self):
180
"""Is a signature needed when committing ?."""
181
policy = self._get_signature_checking()
182
if policy == CHECK_ALWAYS:
187
class IniBasedConfig(Config):
188
"""A configuration policy that draws from ini files."""
190
def _get_parser(self, file=None):
191
if self._parser is not None:
194
input = self._get_filename()
198
self._parser = ConfigObj(input)
199
except configobj.ConfigObjError, e:
200
raise errors.ParseConfigError(e.errors, e.config.filename)
203
def _get_section(self):
204
"""Override this to define the section used by the config."""
207
def _get_signature_checking(self):
208
"""See Config._get_signature_checking."""
209
policy = self._get_user_option('check_signatures')
211
return self._string_to_signature_policy(policy)
213
def _get_user_id(self):
214
"""Get the user id from the 'email' key in the current section."""
215
return self._get_user_option('email')
217
def _get_user_option(self, option_name):
218
"""See Config._get_user_option."""
220
return self._get_parser().get_value(self._get_section(),
225
def _gpg_signing_command(self):
226
"""See Config.gpg_signing_command."""
227
return self._get_user_option('gpg_signing_command')
229
def __init__(self, get_filename):
230
super(IniBasedConfig, self).__init__()
231
self._get_filename = get_filename
234
def _post_commit(self):
235
"""See Config.post_commit."""
236
return self._get_user_option('post_commit')
238
def _string_to_signature_policy(self, signature_string):
239
"""Convert a string to a signing policy."""
240
if signature_string.lower() == 'check-available':
241
return CHECK_IF_POSSIBLE
242
if signature_string.lower() == 'ignore':
244
if signature_string.lower() == 'require':
246
raise errors.BzrError("Invalid signatures policy '%s'"
250
class GlobalConfig(IniBasedConfig):
251
"""The configuration that should be used for a specific location."""
253
def get_editor(self):
254
return self._get_user_option('editor')
257
super(GlobalConfig, self).__init__(config_filename)
260
class LocationConfig(IniBasedConfig):
261
"""A configuration object that gives the policy for a location."""
263
def __init__(self, location):
264
super(LocationConfig, self).__init__(branches_config_filename)
265
self._global_config = None
266
self.location = location
268
def _get_global_config(self):
269
if self._global_config is None:
270
self._global_config = GlobalConfig()
271
return self._global_config
273
def _get_section(self):
274
"""Get the section we should look in for config items.
276
Returns None if none exists.
277
TODO: perhaps return a NullSection that thunks through to the
280
sections = self._get_parser()
281
location_names = self.location.split('/')
282
if self.location.endswith('/'):
283
del location_names[-1]
285
for section in sections:
286
section_names = section.split('/')
287
if section.endswith('/'):
288
del section_names[-1]
289
names = zip(location_names, section_names)
292
if not fnmatch(name[0], name[1]):
297
# so, for the common prefix they matched.
298
# if section is longer, no match.
299
if len(section_names) > len(location_names):
301
# if path is longer, and recurse is not true, no match
302
if len(section_names) < len(location_names):
304
if not self._get_parser().get_bool(section, 'recurse'):
308
matches.append((len(section_names), section))
311
matches.sort(reverse=True)
314
def _gpg_signing_command(self):
315
"""See Config.gpg_signing_command."""
316
command = super(LocationConfig, self)._gpg_signing_command()
317
if command is not None:
319
return self._get_global_config()._gpg_signing_command()
321
def _get_user_id(self):
322
user_id = super(LocationConfig, self)._get_user_id()
323
if user_id is not None:
325
return self._get_global_config()._get_user_id()
327
def _get_user_option(self, option_name):
328
"""See Config._get_user_option."""
329
option_value = super(LocationConfig,
330
self)._get_user_option(option_name)
331
if option_value is not None:
333
return self._get_global_config()._get_user_option(option_name)
335
def _get_signature_checking(self):
336
"""See Config._get_signature_checking."""
337
check = super(LocationConfig, self)._get_signature_checking()
338
if check is not None:
340
return self._get_global_config()._get_signature_checking()
342
def _post_commit(self):
343
"""See Config.post_commit."""
344
hook = self._get_user_option('post_commit')
347
return self._get_global_config()._post_commit()
349
def set_user_option(self, option, value):
350
"""Save option and its value in the configuration."""
351
# FIXME: RBC 20051029 This should refresh the parser and also take a
352
# file lock on branches.conf.
353
conf_dir = os.path.dirname(self._get_filename())
354
ensure_config_dir_exists(conf_dir)
355
location = self.location
356
if location.endswith('/'):
357
location = location[:-1]
358
if (not location in self._get_parser() and
359
not location + '/' in self._get_parser()):
360
self._get_parser()[location]={}
361
elif location + '/' in self._get_parser():
362
location = location + '/'
363
self._get_parser()[location][option]=value
364
self._get_parser().write()
367
class BranchConfig(Config):
368
"""A configuration object giving the policy for a branch."""
370
def _get_location_config(self):
371
if self._location_config is None:
372
self._location_config = LocationConfig(self.branch.base)
373
return self._location_config
375
def _get_user_id(self):
376
"""Return the full user id for the branch.
378
e.g. "John Hacker <jhacker@foo.org>"
379
This is looked up in the email controlfile for the branch.
382
return (self.branch.controlfile("email", "r")
384
.decode(bzrlib.user_encoding)
386
except errors.NoSuchFile, e:
389
return self._get_location_config()._get_user_id()
391
def _get_signature_checking(self):
392
"""See Config._get_signature_checking."""
393
return self._get_location_config()._get_signature_checking()
395
def _get_user_option(self, option_name):
396
"""See Config._get_user_option."""
397
return self._get_location_config()._get_user_option(option_name)
399
def _gpg_signing_command(self):
400
"""See Config.gpg_signing_command."""
401
return self._get_location_config()._gpg_signing_command()
403
def __init__(self, branch):
404
super(BranchConfig, self).__init__()
405
self._location_config = None
408
def _post_commit(self):
409
"""See Config.post_commit."""
410
return self._get_location_config()._post_commit()
413
def ensure_config_dir_exists(path=None):
414
"""Make sure a configuration directory exists.
415
This makes sure that the directory exists.
416
On windows, since configuration directories are 2 levels deep,
417
it makes sure both the directory and the parent directory exists.
421
if not os.path.isdir(path):
422
if sys.platform == 'win32':
423
parent_dir = os.path.dirname(path)
424
if not os.path.isdir(parent_dir):
425
mutter('creating config parent directory: %r', parent_dir)
427
mutter('creating config directory: %r', path)
432
"""Return per-user configuration directory.
434
By default this is ~/.bazaar/
436
TODO: Global option --config-dir to override this.
438
base = os.environ.get('BZR_HOME', None)
439
if sys.platform == 'win32':
441
base = os.environ.get('APPDATA', None)
443
base = os.environ.get('HOME', None)
445
raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
446
return pathjoin(base, 'bazaar', '2.0')
448
# cygwin, linux, and darwin all have a $HOME directory
450
base = os.path.expanduser("~")
451
return pathjoin(base, ".bazaar")
454
def config_filename():
455
"""Return per-user configuration ini file filename."""
456
return pathjoin(config_dir(), 'bazaar.conf')
459
def branches_config_filename():
460
"""Return per-user configuration ini file filename."""
461
return pathjoin(config_dir(), 'branches.conf')
465
"""Calculate automatic user identification.
467
Returns (realname, email).
469
Only used when none is set in the environment or the id file.
471
This previously used the FQDN as the default domain, but that can
472
be very slow on machines where DNS is broken. So now we simply
477
# XXX: Any good way to get real user name on win32?
482
w = pwd.getpwuid(uid)
483
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
484
username = w.pw_name.decode(bzrlib.user_encoding)
485
comma = gecos.find(',')
489
realname = gecos[:comma]
495
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
497
return realname, (username + '@' + socket.gethostname())
500
def extract_email_address(e):
501
"""Return just the address part of an email string.
503
That is just the user@domain part, nothing else.
504
This part is required to contain only ascii characters.
505
If it can't be extracted, raises an error.
507
>>> extract_email_address('Jane Tester <jane@test.com>')
510
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
512
raise errors.BzrError("%r doesn't seem to contain "
513
"a reasonable email address" % e)
516
class TreeConfig(object):
517
"""Branch configuration data associated with its contents, not location"""
518
def __init__(self, branch):
521
def _get_config(self):
523
obj = ConfigObj(self.branch.controlfile('branch.conf',
526
except errors.NoSuchFile:
530
def get_option(self, name, section=None, default=None):
531
self.branch.lock_read()
533
obj = self._get_config()
535
if section is not None:
544
def set_option(self, value, name, section=None):
545
"""Set a per-branch configuration option"""
546
self.branch.lock_write()
548
cfg_obj = self._get_config()
553
obj = cfg_obj[section]
555
cfg_obj[section] = {}
556
obj = cfg_obj[section]
558
cfg_obj.encode('UTF-8')
559
out_file = StringIO(''.join([l+'\n' for l in cfg_obj.write()]))
561
self.branch.put_controlfile('branch.conf', out_file, encode=False)