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
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
59
lastlog=log --line -r-10..-1
60
ll=log --line -r-10..-1
69
from fnmatch import fnmatch
73
import bzrlib.errors as errors
74
from bzrlib.osutils import pathjoin
75
from bzrlib.trace import mutter
76
import bzrlib.util.configobj.configobj as configobj
77
from StringIO import StringIO
84
class ConfigObj(configobj.ConfigObj):
86
def get_bool(self, section, key):
87
return self[section].as_bool(key)
89
def get_value(self, section, name):
90
# Try [] for the old DEFAULT section.
91
if section == "DEFAULT":
96
return self[section][name]
100
"""A configuration policy - what username, editor, gpg needs etc."""
102
def get_editor(self):
103
"""Get the users pop up editor."""
104
raise NotImplementedError
106
def _get_signature_checking(self):
107
"""Template method to override signature checking policy."""
109
def _get_user_option(self, option_name):
110
"""Template method to provide a user option."""
113
def get_user_option(self, option_name):
114
"""Get a generic option - no special process, no default."""
115
return self._get_user_option(option_name)
117
def gpg_signing_command(self):
118
"""What program should be used to sign signatures?"""
119
result = self._gpg_signing_command()
124
def _gpg_signing_command(self):
125
"""See gpg_signing_command()."""
128
def log_format(self):
129
"""What log format should be used"""
130
result = self._log_format()
135
def _log_format(self):
136
"""See log_format()."""
140
super(Config, self).__init__()
142
def post_commit(self):
143
"""An ordered list of python functions to call.
145
Each function takes branch, rev_id as parameters.
147
return self._post_commit()
149
def _post_commit(self):
150
"""See Config.post_commit."""
153
def user_email(self):
154
"""Return just the email component of a username."""
155
return extract_email_address(self.username())
158
"""Return email-style username.
160
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
162
$BZREMAIL can be set to override this, then
163
the concrete policy type is checked, and finally
165
If none is found, a reasonable default is (hopefully)
168
TODO: Check it's reasonably well-formed.
170
v = os.environ.get('BZREMAIL')
172
return v.decode(bzrlib.user_encoding)
174
v = self._get_user_id()
178
v = os.environ.get('EMAIL')
180
return v.decode(bzrlib.user_encoding)
182
name, email = _auto_user_id()
184
return '%s <%s>' % (name, email)
188
def signature_checking(self):
189
"""What is the current policy for signature checking?."""
190
policy = self._get_signature_checking()
191
if policy is not None:
193
return CHECK_IF_POSSIBLE
195
def signature_needed(self):
196
"""Is a signature needed when committing ?."""
197
policy = self._get_signature_checking()
198
if policy == CHECK_ALWAYS:
202
def get_alias(self, value):
203
return self._get_alias(value)
205
def _get_alias(self, value):
209
class IniBasedConfig(Config):
210
"""A configuration policy that draws from ini files."""
212
def _get_parser(self, file=None):
213
if self._parser is not None:
216
input = self._get_filename()
220
self._parser = ConfigObj(input, encoding='utf-8')
221
except configobj.ConfigObjError, e:
222
raise errors.ParseConfigError(e.errors, e.config.filename)
225
def _get_section(self):
226
"""Override this to define the section used by the config."""
229
def _get_signature_checking(self):
230
"""See Config._get_signature_checking."""
231
policy = self._get_user_option('check_signatures')
233
return self._string_to_signature_policy(policy)
235
def _get_user_id(self):
236
"""Get the user id from the 'email' key in the current section."""
237
return self._get_user_option('email')
239
def _get_user_option(self, option_name):
240
"""See Config._get_user_option."""
242
return self._get_parser().get_value(self._get_section(),
247
def _gpg_signing_command(self):
248
"""See Config.gpg_signing_command."""
249
return self._get_user_option('gpg_signing_command')
251
def _log_format(self):
252
"""See Config.log_format."""
253
return self._get_user_option('log_format')
255
def __init__(self, get_filename):
256
super(IniBasedConfig, self).__init__()
257
self._get_filename = get_filename
260
def _post_commit(self):
261
"""See Config.post_commit."""
262
return self._get_user_option('post_commit')
264
def _string_to_signature_policy(self, signature_string):
265
"""Convert a string to a signing policy."""
266
if signature_string.lower() == 'check-available':
267
return CHECK_IF_POSSIBLE
268
if signature_string.lower() == 'ignore':
270
if signature_string.lower() == 'require':
272
raise errors.BzrError("Invalid signatures policy '%s'"
275
def _get_alias(self, value):
277
return self._get_parser().get_value("ALIASES",
283
class GlobalConfig(IniBasedConfig):
284
"""The configuration that should be used for a specific location."""
286
def get_editor(self):
287
return self._get_user_option('editor')
290
super(GlobalConfig, self).__init__(config_filename)
293
class LocationConfig(IniBasedConfig):
294
"""A configuration object that gives the policy for a location."""
296
def __init__(self, location):
297
super(LocationConfig, self).__init__(branches_config_filename)
298
self._global_config = None
299
self.location = location
301
def _get_global_config(self):
302
if self._global_config is None:
303
self._global_config = GlobalConfig()
304
return self._global_config
306
def _get_section(self):
307
"""Get the section we should look in for config items.
309
Returns None if none exists.
310
TODO: perhaps return a NullSection that thunks through to the
313
sections = self._get_parser()
314
location_names = self.location.split('/')
315
if self.location.endswith('/'):
316
del location_names[-1]
318
for section in sections:
319
section_names = section.split('/')
320
if section.endswith('/'):
321
del section_names[-1]
322
names = zip(location_names, section_names)
325
if not fnmatch(name[0], name[1]):
330
# so, for the common prefix they matched.
331
# if section is longer, no match.
332
if len(section_names) > len(location_names):
334
# if path is longer, and recurse is not true, no match
335
if len(section_names) < len(location_names):
337
if not self._get_parser()[section].as_bool('recurse'):
341
matches.append((len(section_names), section))
344
matches.sort(reverse=True)
347
def _gpg_signing_command(self):
348
"""See Config.gpg_signing_command."""
349
command = super(LocationConfig, self)._gpg_signing_command()
350
if command is not None:
352
return self._get_global_config()._gpg_signing_command()
354
def _log_format(self):
355
"""See Config.log_format."""
356
command = super(LocationConfig, self)._log_format()
357
if command is not None:
359
return self._get_global_config()._log_format()
361
def _get_user_id(self):
362
user_id = super(LocationConfig, self)._get_user_id()
363
if user_id is not None:
365
return self._get_global_config()._get_user_id()
367
def _get_user_option(self, option_name):
368
"""See Config._get_user_option."""
369
option_value = super(LocationConfig,
370
self)._get_user_option(option_name)
371
if option_value is not None:
373
return self._get_global_config()._get_user_option(option_name)
375
def _get_signature_checking(self):
376
"""See Config._get_signature_checking."""
377
check = super(LocationConfig, self)._get_signature_checking()
378
if check is not None:
380
return self._get_global_config()._get_signature_checking()
382
def _post_commit(self):
383
"""See Config.post_commit."""
384
hook = self._get_user_option('post_commit')
387
return self._get_global_config()._post_commit()
389
def set_user_option(self, option, value):
390
"""Save option and its value in the configuration."""
391
# FIXME: RBC 20051029 This should refresh the parser and also take a
392
# file lock on branches.conf.
393
conf_dir = os.path.dirname(self._get_filename())
394
ensure_config_dir_exists(conf_dir)
395
location = self.location
396
if location.endswith('/'):
397
location = location[:-1]
398
if (not location in self._get_parser() and
399
not location + '/' in self._get_parser()):
400
self._get_parser()[location]={}
401
elif location + '/' in self._get_parser():
402
location = location + '/'
403
self._get_parser()[location][option]=value
404
self._get_parser().write()
407
class BranchConfig(Config):
408
"""A configuration object giving the policy for a branch."""
410
def _get_location_config(self):
411
if self._location_config is None:
412
self._location_config = LocationConfig(self.branch.base)
413
return self._location_config
415
def _get_user_id(self):
416
"""Return the full user id for the branch.
418
e.g. "John Hacker <jhacker@foo.org>"
419
This is looked up in the email controlfile for the branch.
422
return (self.branch.control_files.get_utf8("email")
424
.decode(bzrlib.user_encoding)
426
except errors.NoSuchFile, e:
429
return self._get_location_config()._get_user_id()
431
def _get_signature_checking(self):
432
"""See Config._get_signature_checking."""
433
return self._get_location_config()._get_signature_checking()
435
def _get_user_option(self, option_name):
436
"""See Config._get_user_option."""
437
return self._get_location_config()._get_user_option(option_name)
439
def _gpg_signing_command(self):
440
"""See Config.gpg_signing_command."""
441
return self._get_location_config()._gpg_signing_command()
443
def __init__(self, branch):
444
super(BranchConfig, self).__init__()
445
self._location_config = None
448
def _post_commit(self):
449
"""See Config.post_commit."""
450
return self._get_location_config()._post_commit()
452
def _log_format(self):
453
"""See Config.log_format."""
454
return self._get_location_config()._log_format()
457
def ensure_config_dir_exists(path=None):
458
"""Make sure a configuration directory exists.
459
This makes sure that the directory exists.
460
On windows, since configuration directories are 2 levels deep,
461
it makes sure both the directory and the parent directory exists.
465
if not os.path.isdir(path):
466
if sys.platform == 'win32':
467
parent_dir = os.path.dirname(path)
468
if not os.path.isdir(parent_dir):
469
mutter('creating config parent directory: %r', parent_dir)
471
mutter('creating config directory: %r', path)
476
"""Return per-user configuration directory.
478
By default this is ~/.bazaar/
480
TODO: Global option --config-dir to override this.
482
base = os.environ.get('BZR_HOME', None)
483
if sys.platform == 'win32':
485
base = os.environ.get('APPDATA', None)
487
base = os.environ.get('HOME', None)
489
raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
490
return pathjoin(base, 'bazaar', '2.0')
492
# cygwin, linux, and darwin all have a $HOME directory
494
base = os.path.expanduser("~")
495
return pathjoin(base, ".bazaar")
498
def config_filename():
499
"""Return per-user configuration ini file filename."""
500
return pathjoin(config_dir(), 'bazaar.conf')
503
def branches_config_filename():
504
"""Return per-user configuration ini file filename."""
505
return pathjoin(config_dir(), 'branches.conf')
509
"""Calculate automatic user identification.
511
Returns (realname, email).
513
Only used when none is set in the environment or the id file.
515
This previously used the FQDN as the default domain, but that can
516
be very slow on machines where DNS is broken. So now we simply
521
# XXX: Any good way to get real user name on win32?
526
w = pwd.getpwuid(uid)
529
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
530
username = w.pw_name.decode(bzrlib.user_encoding)
531
except UnicodeDecodeError:
532
# We're using pwd, therefore we're on Unix, so /etc/passwd is ok.
533
raise errors.BzrError("Can't decode username in " \
534
"/etc/passwd as %s." % bzrlib.user_encoding)
536
comma = gecos.find(',')
540
realname = gecos[:comma]
547
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
548
except UnicodeDecodeError:
549
raise errors.BzrError("Can't decode username as %s." % \
550
bzrlib.user_encoding)
552
return realname, (username + '@' + socket.gethostname())
555
def extract_email_address(e):
556
"""Return just the address part of an email string.
558
That is just the user@domain part, nothing else.
559
This part is required to contain only ascii characters.
560
If it can't be extracted, raises an error.
562
>>> extract_email_address('Jane Tester <jane@test.com>')
565
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
567
raise errors.BzrError("%r doesn't seem to contain "
568
"a reasonable email address" % e)
571
class TreeConfig(object):
572
"""Branch configuration data associated with its contents, not location"""
573
def __init__(self, branch):
576
def _get_config(self):
578
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
580
except errors.NoSuchFile:
581
obj = ConfigObj(encoding='utf=8')
584
def get_option(self, name, section=None, default=None):
585
self.branch.lock_read()
587
obj = self._get_config()
589
if section is not None:
598
def set_option(self, value, name, section=None):
599
"""Set a per-branch configuration option"""
600
self.branch.lock_write()
602
cfg_obj = self._get_config()
607
obj = cfg_obj[section]
609
cfg_obj[section] = {}
610
obj = cfg_obj[section]
612
out_file = StringIO()
613
cfg_obj.write(out_file)
615
self.branch.control_files.put('branch.conf', out_file)