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
30
log_format=name-of-format
32
in branches.conf, you specify the url of a branch and options for it.
33
Wildcards may be used - * and ? as normal in shell completion. Options
34
set in both bazaar.conf and branches.conf are overriden by the branches.conf
36
[/home/robertc/source]
37
recurse=False|True(default)
39
check_signatures= as abive
40
create_signatures= as above.
42
explanation of options
43
----------------------
44
editor - this option sets the pop up editor to use during commits.
45
email - this option sets the user id bzr will use when committing.
46
check_signatures - this option controls whether bzr will require good gpg
47
signatures, ignore them, or check them if they are
49
create_signatures - this option controls whether bzr will always create
50
gpg signatures, never create them, or create them if the
51
branch is configured to require them.
52
NB: This option is planned, but not implemented yet.
53
log_format - This options set the default log format. Options are long,
54
short, line, or a plugin can register new formats
61
from fnmatch import fnmatch
65
import bzrlib.errors as errors
66
from bzrlib.osutils import pathjoin
67
from bzrlib.trace import mutter
68
import bzrlib.util.configobj.configobj as configobj
69
from StringIO import StringIO
76
class ConfigObj(configobj.ConfigObj):
78
def get_bool(self, section, key):
79
val = self[section][key].lower()
80
if val in ('1', 'yes', 'true', 'on'):
82
elif val in ('0', 'no', 'false', 'off'):
85
raise ValueError("Value %r is not boolean" % val)
87
def get_value(self, section, name):
88
# Try [] for the old DEFAULT section.
89
if section == "DEFAULT":
94
return self[section][name]
98
"""A configuration policy - what username, editor, gpg needs etc."""
100
def get_editor(self):
101
"""Get the users pop up editor."""
102
raise NotImplementedError
104
def _get_signature_checking(self):
105
"""Template method to override signature checking policy."""
107
def _get_user_option(self, option_name):
108
"""Template method to provide a user option."""
111
def get_user_option(self, option_name):
112
"""Get a generic option - no special process, no default."""
113
return self._get_user_option(option_name)
115
def gpg_signing_command(self):
116
"""What program should be used to sign signatures?"""
117
result = self._gpg_signing_command()
122
def _gpg_signing_command(self):
123
"""See gpg_signing_command()."""
126
def log_format(self):
127
"""What log format should be used"""
128
result = self._log_format()
133
def _log_format(self):
134
"""See log_format()."""
138
super(Config, self).__init__()
140
def post_commit(self):
141
"""An ordered list of python functions to call.
143
Each function takes branch, rev_id as parameters.
145
return self._post_commit()
147
def _post_commit(self):
148
"""See Config.post_commit."""
151
def user_email(self):
152
"""Return just the email component of a username."""
153
return extract_email_address(self.username())
156
"""Return email-style username.
158
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
160
$BZREMAIL can be set to override this, then
161
the concrete policy type is checked, and finally
163
If none is found, a reasonable default is (hopefully)
166
TODO: Check it's reasonably well-formed.
168
v = os.environ.get('BZREMAIL')
170
return v.decode(bzrlib.user_encoding)
172
v = self._get_user_id()
176
v = os.environ.get('EMAIL')
178
return v.decode(bzrlib.user_encoding)
180
name, email = _auto_user_id()
182
return '%s <%s>' % (name, email)
186
def signature_checking(self):
187
"""What is the current policy for signature checking?."""
188
policy = self._get_signature_checking()
189
if policy is not None:
191
return CHECK_IF_POSSIBLE
193
def signature_needed(self):
194
"""Is a signature needed when committing ?."""
195
policy = self._get_signature_checking()
196
if policy == CHECK_ALWAYS:
201
class IniBasedConfig(Config):
202
"""A configuration policy that draws from ini files."""
204
def _get_parser(self, file=None):
205
if self._parser is not None:
208
input = self._get_filename()
212
self._parser = ConfigObj(input)
213
except configobj.ConfigObjError, e:
214
raise errors.ParseConfigError(e.errors, e.config.filename)
217
def _get_section(self):
218
"""Override this to define the section used by the config."""
221
def _get_signature_checking(self):
222
"""See Config._get_signature_checking."""
223
policy = self._get_user_option('check_signatures')
225
return self._string_to_signature_policy(policy)
227
def _get_user_id(self):
228
"""Get the user id from the 'email' key in the current section."""
229
return self._get_user_option('email')
231
def _get_user_option(self, option_name):
232
"""See Config._get_user_option."""
234
return self._get_parser().get_value(self._get_section(),
239
def _gpg_signing_command(self):
240
"""See Config.gpg_signing_command."""
241
return self._get_user_option('gpg_signing_command')
243
def _log_format(self):
244
"""See Config.log_format."""
245
return self._get_user_option('log_format')
247
def __init__(self, get_filename):
248
super(IniBasedConfig, self).__init__()
249
self._get_filename = get_filename
252
def _post_commit(self):
253
"""See Config.post_commit."""
254
return self._get_user_option('post_commit')
256
def _string_to_signature_policy(self, signature_string):
257
"""Convert a string to a signing policy."""
258
if signature_string.lower() == 'check-available':
259
return CHECK_IF_POSSIBLE
260
if signature_string.lower() == 'ignore':
262
if signature_string.lower() == 'require':
264
raise errors.BzrError("Invalid signatures policy '%s'"
268
class GlobalConfig(IniBasedConfig):
269
"""The configuration that should be used for a specific location."""
271
def get_editor(self):
272
return self._get_user_option('editor')
275
super(GlobalConfig, self).__init__(config_filename)
278
class LocationConfig(IniBasedConfig):
279
"""A configuration object that gives the policy for a location."""
281
def __init__(self, location):
282
super(LocationConfig, self).__init__(branches_config_filename)
283
self._global_config = None
284
self.location = location
286
def _get_global_config(self):
287
if self._global_config is None:
288
self._global_config = GlobalConfig()
289
return self._global_config
291
def _get_section(self):
292
"""Get the section we should look in for config items.
294
Returns None if none exists.
295
TODO: perhaps return a NullSection that thunks through to the
298
sections = self._get_parser()
299
location_names = self.location.split('/')
300
if self.location.endswith('/'):
301
del location_names[-1]
303
for section in sections:
304
section_names = section.split('/')
305
if section.endswith('/'):
306
del section_names[-1]
307
names = zip(location_names, section_names)
310
if not fnmatch(name[0], name[1]):
315
# so, for the common prefix they matched.
316
# if section is longer, no match.
317
if len(section_names) > len(location_names):
319
# if path is longer, and recurse is not true, no match
320
if len(section_names) < len(location_names):
322
if not self._get_parser().get_bool(section, 'recurse'):
326
matches.append((len(section_names), section))
329
matches.sort(reverse=True)
332
def _gpg_signing_command(self):
333
"""See Config.gpg_signing_command."""
334
command = super(LocationConfig, self)._gpg_signing_command()
335
if command is not None:
337
return self._get_global_config()._gpg_signing_command()
339
def _log_format(self):
340
"""See Config.log_format."""
341
command = super(LocationConfig, self)._log_format()
342
if command is not None:
344
return self._get_global_config()._log_format()
346
def _get_user_id(self):
347
user_id = super(LocationConfig, self)._get_user_id()
348
if user_id is not None:
350
return self._get_global_config()._get_user_id()
352
def _get_user_option(self, option_name):
353
"""See Config._get_user_option."""
354
option_value = super(LocationConfig,
355
self)._get_user_option(option_name)
356
if option_value is not None:
358
return self._get_global_config()._get_user_option(option_name)
360
def _get_signature_checking(self):
361
"""See Config._get_signature_checking."""
362
check = super(LocationConfig, self)._get_signature_checking()
363
if check is not None:
365
return self._get_global_config()._get_signature_checking()
367
def _post_commit(self):
368
"""See Config.post_commit."""
369
hook = self._get_user_option('post_commit')
372
return self._get_global_config()._post_commit()
374
def set_user_option(self, option, value):
375
"""Save option and its value in the configuration."""
376
# FIXME: RBC 20051029 This should refresh the parser and also take a
377
# file lock on branches.conf.
378
conf_dir = os.path.dirname(self._get_filename())
379
ensure_config_dir_exists(conf_dir)
380
location = self.location
381
if location.endswith('/'):
382
location = location[:-1]
383
if (not location in self._get_parser() and
384
not location + '/' in self._get_parser()):
385
self._get_parser()[location]={}
386
elif location + '/' in self._get_parser():
387
location = location + '/'
388
self._get_parser()[location][option]=value
389
self._get_parser().write()
392
class BranchConfig(Config):
393
"""A configuration object giving the policy for a branch."""
395
def _get_location_config(self):
396
if self._location_config is None:
397
self._location_config = LocationConfig(self.branch.base)
398
return self._location_config
400
def _get_user_id(self):
401
"""Return the full user id for the branch.
403
e.g. "John Hacker <jhacker@foo.org>"
404
This is looked up in the email controlfile for the branch.
407
return (self.branch.control_files.get_utf8("email")
409
.decode(bzrlib.user_encoding)
411
except errors.NoSuchFile, e:
414
return self._get_location_config()._get_user_id()
416
def _get_signature_checking(self):
417
"""See Config._get_signature_checking."""
418
return self._get_location_config()._get_signature_checking()
420
def _get_user_option(self, option_name):
421
"""See Config._get_user_option."""
422
return self._get_location_config()._get_user_option(option_name)
424
def _gpg_signing_command(self):
425
"""See Config.gpg_signing_command."""
426
return self._get_location_config()._gpg_signing_command()
428
def __init__(self, branch):
429
super(BranchConfig, self).__init__()
430
self._location_config = None
433
def _post_commit(self):
434
"""See Config.post_commit."""
435
return self._get_location_config()._post_commit()
437
def _log_format(self):
438
"""See Config.log_format."""
439
return self._get_location_config()._log_format()
441
def ensure_config_dir_exists(path=None):
442
"""Make sure a configuration directory exists.
443
This makes sure that the directory exists.
444
On windows, since configuration directories are 2 levels deep,
445
it makes sure both the directory and the parent directory exists.
449
if not os.path.isdir(path):
450
if sys.platform == 'win32':
451
parent_dir = os.path.dirname(path)
452
if not os.path.isdir(parent_dir):
453
mutter('creating config parent directory: %r', parent_dir)
455
mutter('creating config directory: %r', path)
460
"""Return per-user configuration directory.
462
By default this is ~/.bazaar/
464
TODO: Global option --config-dir to override this.
466
base = os.environ.get('BZR_HOME', None)
467
if sys.platform == 'win32':
469
base = os.environ.get('APPDATA', None)
471
base = os.environ.get('HOME', None)
473
raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
474
return pathjoin(base, 'bazaar', '2.0')
476
# cygwin, linux, and darwin all have a $HOME directory
478
base = os.path.expanduser("~")
479
return pathjoin(base, ".bazaar")
482
def config_filename():
483
"""Return per-user configuration ini file filename."""
484
return pathjoin(config_dir(), 'bazaar.conf')
487
def branches_config_filename():
488
"""Return per-user configuration ini file filename."""
489
return pathjoin(config_dir(), 'branches.conf')
493
"""Calculate automatic user identification.
495
Returns (realname, email).
497
Only used when none is set in the environment or the id file.
499
This previously used the FQDN as the default domain, but that can
500
be very slow on machines where DNS is broken. So now we simply
505
# XXX: Any good way to get real user name on win32?
510
w = pwd.getpwuid(uid)
511
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
512
username = w.pw_name.decode(bzrlib.user_encoding)
513
comma = gecos.find(',')
517
realname = gecos[:comma]
523
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
525
return realname, (username + '@' + socket.gethostname())
528
def extract_email_address(e):
529
"""Return just the address part of an email string.
531
That is just the user@domain part, nothing else.
532
This part is required to contain only ascii characters.
533
If it can't be extracted, raises an error.
535
>>> extract_email_address('Jane Tester <jane@test.com>')
538
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
540
raise errors.BzrError("%r doesn't seem to contain "
541
"a reasonable email address" % e)
544
class TreeConfig(object):
545
"""Branch configuration data associated with its contents, not location"""
546
def __init__(self, branch):
549
def _get_config(self):
551
obj = ConfigObj(self.branch.control_files.get('branch.conf'
554
except errors.NoSuchFile:
558
def get_option(self, name, section=None, default=None):
559
self.branch.lock_read()
561
obj = self._get_config()
563
if section is not None:
572
def set_option(self, value, name, section=None):
573
"""Set a per-branch configuration option"""
574
self.branch.lock_write()
576
cfg_obj = self._get_config()
581
obj = cfg_obj[section]
583
cfg_obj[section] = {}
584
obj = cfg_obj[section]
586
cfg_obj.encode('UTF-8')
587
out_file = StringIO(''.join([l+'\n' for l in cfg_obj.write()]))
589
self.branch.control_files.put('branch.conf', out_file)