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
if not os.path.isdir(conf_dir):
355
if sys.platform == 'win32':
356
parent_dir = os.path.dirname(conf_dir)
357
if not os.path.isdir(parent_dir):
358
mutter('creating config parent directory: %r', parent_dir)
360
mutter('creating config directory: %r', conf_dir)
362
location = self.location
363
if location.endswith('/'):
364
location = location[:-1]
365
if (not location in self._get_parser() and
366
not location + '/' in self._get_parser()):
367
self._get_parser()[location]={}
368
elif location + '/' in self._get_parser():
369
location = location + '/'
370
self._get_parser()[location][option]=value
371
self._get_parser().write()
374
class BranchConfig(Config):
375
"""A configuration object giving the policy for a branch."""
377
def _get_location_config(self):
378
if self._location_config is None:
379
self._location_config = LocationConfig(self.branch.base)
380
return self._location_config
382
def _get_user_id(self):
383
"""Return the full user id for the branch.
385
e.g. "John Hacker <jhacker@foo.org>"
386
This is looked up in the email controlfile for the branch.
389
return (self.branch.controlfile("email", "r")
391
.decode(bzrlib.user_encoding)
393
except errors.NoSuchFile, e:
396
return self._get_location_config()._get_user_id()
398
def _get_signature_checking(self):
399
"""See Config._get_signature_checking."""
400
return self._get_location_config()._get_signature_checking()
402
def _get_user_option(self, option_name):
403
"""See Config._get_user_option."""
404
return self._get_location_config()._get_user_option(option_name)
406
def _gpg_signing_command(self):
407
"""See Config.gpg_signing_command."""
408
return self._get_location_config()._gpg_signing_command()
410
def __init__(self, branch):
411
super(BranchConfig, self).__init__()
412
self._location_config = None
415
def _post_commit(self):
416
"""See Config.post_commit."""
417
return self._get_location_config()._post_commit()
421
"""Return per-user configuration directory.
423
By default this is ~/.bazaar/
425
TODO: Global option --config-dir to override this.
427
base = os.environ.get('BZR_HOME', None)
428
if sys.platform == 'win32':
430
base = os.environ.get('APPDATA', None)
432
base = os.environ.get('HOME', None)
434
raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
435
return pathjoin(base, 'bazaar', '2.0')
437
# cygwin, linux, and darwin all have a $HOME directory
439
base = os.path.expanduser("~")
440
return pathjoin(base, ".bazaar")
443
def config_filename():
444
"""Return per-user configuration ini file filename."""
445
return pathjoin(config_dir(), 'bazaar.conf')
448
def branches_config_filename():
449
"""Return per-user configuration ini file filename."""
450
return pathjoin(config_dir(), 'branches.conf')
454
"""Calculate automatic user identification.
456
Returns (realname, email).
458
Only used when none is set in the environment or the id file.
460
This previously used the FQDN as the default domain, but that can
461
be very slow on machines where DNS is broken. So now we simply
466
# XXX: Any good way to get real user name on win32?
471
w = pwd.getpwuid(uid)
472
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
473
username = w.pw_name.decode(bzrlib.user_encoding)
474
comma = gecos.find(',')
478
realname = gecos[:comma]
484
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
486
return realname, (username + '@' + socket.gethostname())
489
def extract_email_address(e):
490
"""Return just the address part of an email string.
492
That is just the user@domain part, nothing else.
493
This part is required to contain only ascii characters.
494
If it can't be extracted, raises an error.
496
>>> extract_email_address('Jane Tester <jane@test.com>')
499
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
501
raise errors.BzrError("%r doesn't seem to contain "
502
"a reasonable email address" % e)
505
class TreeConfig(object):
506
"""Branch configuration data associated with its contents, not location"""
507
def __init__(self, branch):
510
def _get_config(self):
512
obj = ConfigObj(self.branch.controlfile('branch.conf',
515
except errors.NoSuchFile:
519
def get_option(self, name, section=None, default=None):
520
self.branch.lock_read()
522
obj = self._get_config()
524
if section is not None:
533
def set_option(self, value, name, section=None):
534
"""Set a per-branch configuration option"""
535
self.branch.lock_write()
537
cfg_obj = self._get_config()
542
obj = cfg_obj[section]
544
cfg_obj[section] = {}
545
obj = cfg_obj[section]
547
cfg_obj.encode('UTF-8')
548
out_file = StringIO(''.join([l+'\n' for l in cfg_obj.write()]))
550
self.branch.put_controlfile('branch.conf', out_file, encode=False)