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/locations.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 locations.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 locations.conf are overridden by the locations.conf
 
 
36
[/home/robertc/source]
 
 
37
recurse=False|True(default)
 
 
39
check_signatures= as above 
 
 
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
log_format - This options set the default log format.  Options are long, 
 
 
53
             short, line, or a plugin can register new formats
 
 
55
In bazaar.conf you can also define aliases in the ALIASES sections, example
 
 
58
lastlog=log --line -r-10..-1
 
 
59
ll=log --line -r-10..-1
 
 
66
from fnmatch import fnmatch
 
 
70
from StringIO import StringIO
 
 
73
import bzrlib.errors as errors
 
 
74
from bzrlib.osutils import pathjoin
 
 
75
from bzrlib.trace import mutter, warning
 
 
76
import bzrlib.util.configobj.configobj as configobj
 
 
89
class ConfigObj(configobj.ConfigObj):
 
 
91
    def get_bool(self, section, key):
 
 
92
        return self[section].as_bool(key)
 
 
94
    def get_value(self, section, name):
 
 
95
        # Try [] for the old DEFAULT section.
 
 
96
        if section == "DEFAULT":
 
 
101
        return self[section][name]
 
 
104
class Config(object):
 
 
105
    """A configuration policy - what username, editor, gpg needs etc."""
 
 
107
    def get_editor(self):
 
 
108
        """Get the users pop up editor."""
 
 
109
        raise NotImplementedError
 
 
111
    def _get_signature_checking(self):
 
 
112
        """Template method to override signature checking policy."""
 
 
114
    def _get_signing_policy(self):
 
 
115
        """Template method to override signature creation policy."""
 
 
117
    def _get_user_option(self, option_name):
 
 
118
        """Template method to provide a user option."""
 
 
121
    def get_user_option(self, option_name):
 
 
122
        """Get a generic option - no special process, no default."""
 
 
123
        return self._get_user_option(option_name)
 
 
125
    def gpg_signing_command(self):
 
 
126
        """What program should be used to sign signatures?"""
 
 
127
        result = self._gpg_signing_command()
 
 
132
    def _gpg_signing_command(self):
 
 
133
        """See gpg_signing_command()."""
 
 
136
    def log_format(self):
 
 
137
        """What log format should be used"""
 
 
138
        result = self._log_format()
 
 
143
    def _log_format(self):
 
 
144
        """See log_format()."""
 
 
148
        super(Config, self).__init__()
 
 
150
    def post_commit(self):
 
 
151
        """An ordered list of python functions to call.
 
 
153
        Each function takes branch, rev_id as parameters.
 
 
155
        return self._post_commit()
 
 
157
    def _post_commit(self):
 
 
158
        """See Config.post_commit."""
 
 
161
    def user_email(self):
 
 
162
        """Return just the email component of a username."""
 
 
163
        return extract_email_address(self.username())
 
 
166
        """Return email-style username.
 
 
168
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
 
170
        $BZREMAIL can be set to override this, then
 
 
171
        the concrete policy type is checked, and finally
 
 
173
        If none is found, a reasonable default is (hopefully)
 
 
176
        TODO: Check it's reasonably well-formed.
 
 
178
        v = os.environ.get('BZREMAIL')
 
 
180
            return v.decode(bzrlib.user_encoding)
 
 
182
        v = self._get_user_id()
 
 
186
        v = os.environ.get('EMAIL')
 
 
188
            return v.decode(bzrlib.user_encoding)
 
 
190
        name, email = _auto_user_id()
 
 
192
            return '%s <%s>' % (name, email)
 
 
196
    def signature_checking(self):
 
 
197
        """What is the current policy for signature checking?."""
 
 
198
        policy = self._get_signature_checking()
 
 
199
        if policy is not None:
 
 
201
        return CHECK_IF_POSSIBLE
 
 
203
    def signing_policy(self):
 
 
204
        """What is the current policy for signature checking?."""
 
 
205
        policy = self._get_signing_policy()
 
 
206
        if policy is not None:
 
 
208
        return SIGN_WHEN_REQUIRED
 
 
210
    def signature_needed(self):
 
 
211
        """Is a signature needed when committing ?."""
 
 
212
        policy = self._get_signing_policy()
 
 
214
            policy = self._get_signature_checking()
 
 
215
            if policy is not None:
 
 
216
                warning("Please use create_signatures, not check_signatures "
 
 
217
                        "to set signing policy.")
 
 
218
            if policy == CHECK_ALWAYS:
 
 
220
        elif policy == SIGN_ALWAYS:
 
 
224
    def get_alias(self, value):
 
 
225
        return self._get_alias(value)
 
 
227
    def _get_alias(self, value):
 
 
230
    def get_nickname(self):
 
 
231
        return self._get_nickname()
 
 
233
    def _get_nickname(self):
 
 
237
class IniBasedConfig(Config):
 
 
238
    """A configuration policy that draws from ini files."""
 
 
240
    def _get_parser(self, file=None):
 
 
241
        if self._parser is not None:
 
 
244
            input = self._get_filename()
 
 
248
            self._parser = ConfigObj(input, encoding='utf-8')
 
 
249
        except configobj.ConfigObjError, e:
 
 
250
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
 
253
    def _get_section(self):
 
 
254
        """Override this to define the section used by the config."""
 
 
257
    def _get_signature_checking(self):
 
 
258
        """See Config._get_signature_checking."""
 
 
259
        policy = self._get_user_option('check_signatures')
 
 
261
            return self._string_to_signature_policy(policy)
 
 
263
    def _get_signing_policy(self):
 
 
264
        """See Config._get_signing_policy"""
 
 
265
        policy = self._get_user_option('create_signatures')
 
 
267
            return self._string_to_signing_policy(policy)
 
 
269
    def _get_user_id(self):
 
 
270
        """Get the user id from the 'email' key in the current section."""
 
 
271
        return self._get_user_option('email')
 
 
273
    def _get_user_option(self, option_name):
 
 
274
        """See Config._get_user_option."""
 
 
276
            return self._get_parser().get_value(self._get_section(),
 
 
281
    def _gpg_signing_command(self):
 
 
282
        """See Config.gpg_signing_command."""
 
 
283
        return self._get_user_option('gpg_signing_command')
 
 
285
    def _log_format(self):
 
 
286
        """See Config.log_format."""
 
 
287
        return self._get_user_option('log_format')
 
 
289
    def __init__(self, get_filename):
 
 
290
        super(IniBasedConfig, self).__init__()
 
 
291
        self._get_filename = get_filename
 
 
294
    def _post_commit(self):
 
 
295
        """See Config.post_commit."""
 
 
296
        return self._get_user_option('post_commit')
 
 
298
    def _string_to_signature_policy(self, signature_string):
 
 
299
        """Convert a string to a signing policy."""
 
 
300
        if signature_string.lower() == 'check-available':
 
 
301
            return CHECK_IF_POSSIBLE
 
 
302
        if signature_string.lower() == 'ignore':
 
 
304
        if signature_string.lower() == 'require':
 
 
306
        raise errors.BzrError("Invalid signatures policy '%s'"
 
 
309
    def _string_to_signing_policy(self, signature_string):
 
 
310
        """Convert a string to a signing policy."""
 
 
311
        if signature_string.lower() == 'when-required':
 
 
312
            return SIGN_WHEN_REQUIRED
 
 
313
        if signature_string.lower() == 'never':
 
 
315
        if signature_string.lower() == 'always':
 
 
317
        raise errors.BzrError("Invalid signing policy '%s'"
 
 
320
    def _get_alias(self, value):
 
 
322
            return self._get_parser().get_value("ALIASES", 
 
 
327
    def _get_nickname(self):
 
 
328
        return self.get_user_option('nickname')
 
 
331
class GlobalConfig(IniBasedConfig):
 
 
332
    """The configuration that should be used for a specific location."""
 
 
334
    def get_editor(self):
 
 
335
        return self._get_user_option('editor')
 
 
338
        super(GlobalConfig, self).__init__(config_filename)
 
 
341
class LocationConfig(IniBasedConfig):
 
 
342
    """A configuration object that gives the policy for a location."""
 
 
344
    def __init__(self, location):
 
 
345
        name_generator = locations_config_filename
 
 
346
        if (not os.path.exists(name_generator()) and 
 
 
347
                os.path.exists(branches_config_filename())):
 
 
348
            warning('Please rename branches.conf to locations.conf')
 
 
349
            name_generator = branches_config_filename
 
 
350
        super(LocationConfig, self).__init__(name_generator)
 
 
351
        self.location = location
 
 
353
    def _get_section(self):
 
 
354
        """Get the section we should look in for config items.
 
 
356
        Returns None if none exists. 
 
 
357
        TODO: perhaps return a NullSection that thunks through to the 
 
 
360
        sections = self._get_parser()
 
 
361
        location_names = self.location.split('/')
 
 
362
        if self.location.endswith('/'):
 
 
363
            del location_names[-1]
 
 
365
        for section in sections:
 
 
366
            section_names = section.split('/')
 
 
367
            if section.endswith('/'):
 
 
368
                del section_names[-1]
 
 
369
            names = zip(location_names, section_names)
 
 
372
                if not fnmatch(name[0], name[1]):
 
 
377
            # so, for the common prefix they matched.
 
 
378
            # if section is longer, no match.
 
 
379
            if len(section_names) > len(location_names):
 
 
381
            # if path is longer, and recurse is not true, no match
 
 
382
            if len(section_names) < len(location_names):
 
 
384
                    if not self._get_parser()[section].as_bool('recurse'):
 
 
388
            matches.append((len(section_names), section))
 
 
391
        matches.sort(reverse=True)
 
 
394
    def set_user_option(self, option, value):
 
 
395
        """Save option and its value in the configuration."""
 
 
396
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
 
397
        # file lock on locations.conf.
 
 
398
        conf_dir = os.path.dirname(self._get_filename())
 
 
399
        ensure_config_dir_exists(conf_dir)
 
 
400
        location = self.location
 
 
401
        if location.endswith('/'):
 
 
402
            location = location[:-1]
 
 
403
        if (not location in self._get_parser() and
 
 
404
            not location + '/' in self._get_parser()):
 
 
405
            self._get_parser()[location]={}
 
 
406
        elif location + '/' in self._get_parser():
 
 
407
            location = location + '/'
 
 
408
        self._get_parser()[location][option]=value
 
 
409
        self._get_parser().write(file(self._get_filename(), 'wb'))
 
 
412
class BranchConfig(Config):
 
 
413
    """A configuration object giving the policy for a branch."""
 
 
415
    def _get_branch_data_config(self):
 
 
416
        if self._branch_data_config is None:
 
 
417
            self._branch_data_config = TreeConfig(self.branch)
 
 
418
        return self._branch_data_config
 
 
420
    def _get_location_config(self):
 
 
421
        if self._location_config is None:
 
 
422
            self._location_config = LocationConfig(self.branch.base)
 
 
423
        return self._location_config
 
 
425
    def _get_global_config(self):
 
 
426
        if self._global_config is None:
 
 
427
            self._global_config = GlobalConfig()
 
 
428
        return self._global_config
 
 
430
    def _get_best_value(self, option_name):
 
 
431
        """This returns a user option from local, tree or global config.
 
 
433
        They are tried in that order.  Use get_safe_value if trusted values
 
 
436
        for source in self.option_sources:
 
 
437
            value = getattr(source(), option_name)()
 
 
438
            if value is not None:
 
 
442
    def _get_safe_value(self, option_name):
 
 
443
        """This variant of get_best_value never returns untrusted values.
 
 
445
        It does not return values from the branch data, because the branch may
 
 
446
        not be controlled by the user.
 
 
448
        We may wish to allow locations.conf to control whether branches are
 
 
449
        trusted in the future.
 
 
451
        for source in (self._get_location_config, self._get_global_config):
 
 
452
            value = getattr(source(), option_name)()
 
 
453
            if value is not None:
 
 
457
    def _get_user_id(self):
 
 
458
        """Return the full user id for the branch.
 
 
460
        e.g. "John Hacker <jhacker@foo.org>"
 
 
461
        This is looked up in the email controlfile for the branch.
 
 
464
            return (self.branch.control_files.get_utf8("email") 
 
 
466
                    .decode(bzrlib.user_encoding)
 
 
468
        except errors.NoSuchFile, e:
 
 
471
        return self._get_best_value('_get_user_id')
 
 
473
    def _get_signature_checking(self):
 
 
474
        """See Config._get_signature_checking."""
 
 
475
        return self._get_best_value('_get_signature_checking')
 
 
477
    def _get_signing_policy(self):
 
 
478
        """See Config._get_signing_policy."""
 
 
479
        return self._get_best_value('_get_signing_policy')
 
 
481
    def _get_user_option(self, option_name):
 
 
482
        """See Config._get_user_option."""
 
 
483
        for source in self.option_sources:
 
 
484
            value = source()._get_user_option(option_name)
 
 
485
            if value is not None:
 
 
489
    def set_user_option(self, name, value, local=False):
 
 
491
            self._get_location_config().set_user_option(name, value)
 
 
493
            self._get_branch_data_config().set_option(value, name)
 
 
496
    def _gpg_signing_command(self):
 
 
497
        """See Config.gpg_signing_command."""
 
 
498
        return self._get_safe_value('_gpg_signing_command')
 
 
500
    def __init__(self, branch):
 
 
501
        super(BranchConfig, self).__init__()
 
 
502
        self._location_config = None
 
 
503
        self._branch_data_config = None
 
 
504
        self._global_config = None
 
 
506
        self.option_sources = (self._get_location_config, 
 
 
507
                               self._get_branch_data_config,
 
 
508
                               self._get_global_config)
 
 
510
    def _post_commit(self):
 
 
511
        """See Config.post_commit."""
 
 
512
        return self._get_safe_value('_post_commit')
 
 
514
    def _get_nickname(self):
 
 
515
        value = self._get_best_value('_get_nickname')
 
 
516
        if value is not None:
 
 
518
        return self.branch.base.split('/')[-2]
 
 
520
    def _log_format(self):
 
 
521
        """See Config.log_format."""
 
 
522
        return self._get_best_value('_log_format')
 
 
525
def ensure_config_dir_exists(path=None):
 
 
526
    """Make sure a configuration directory exists.
 
 
527
    This makes sure that the directory exists.
 
 
528
    On windows, since configuration directories are 2 levels deep,
 
 
529
    it makes sure both the directory and the parent directory exists.
 
 
533
    if not os.path.isdir(path):
 
 
534
        if sys.platform == 'win32':
 
 
535
            parent_dir = os.path.dirname(path)
 
 
536
            if not os.path.isdir(parent_dir):
 
 
537
                mutter('creating config parent directory: %r', parent_dir)
 
 
539
        mutter('creating config directory: %r', path)
 
 
544
    """Return per-user configuration directory.
 
 
546
    By default this is ~/.bazaar/
 
 
548
    TODO: Global option --config-dir to override this.
 
 
550
    base = os.environ.get('BZR_HOME', None)
 
 
551
    if sys.platform == 'win32':
 
 
553
            base = os.environ.get('APPDATA', None)
 
 
555
            base = os.environ.get('HOME', None)
 
 
557
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
 
 
558
        return pathjoin(base, 'bazaar', '2.0')
 
 
560
        # cygwin, linux, and darwin all have a $HOME directory
 
 
562
            base = os.path.expanduser("~")
 
 
563
        return pathjoin(base, ".bazaar")
 
 
566
def config_filename():
 
 
567
    """Return per-user configuration ini file filename."""
 
 
568
    return pathjoin(config_dir(), 'bazaar.conf')
 
 
571
def branches_config_filename():
 
 
572
    """Return per-user configuration ini file filename."""
 
 
573
    return pathjoin(config_dir(), 'branches.conf')
 
 
575
def locations_config_filename():
 
 
576
    """Return per-user configuration ini file filename."""
 
 
577
    return pathjoin(config_dir(), 'locations.conf')
 
 
581
    """Calculate automatic user identification.
 
 
583
    Returns (realname, email).
 
 
585
    Only used when none is set in the environment or the id file.
 
 
587
    This previously used the FQDN as the default domain, but that can
 
 
588
    be very slow on machines where DNS is broken.  So now we simply
 
 
593
    # XXX: Any good way to get real user name on win32?
 
 
598
        w = pwd.getpwuid(uid)
 
 
601
            gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
 
602
            username = w.pw_name.decode(bzrlib.user_encoding)
 
 
603
        except UnicodeDecodeError:
 
 
604
            # We're using pwd, therefore we're on Unix, so /etc/passwd is ok.
 
 
605
            raise errors.BzrError("Can't decode username in " \
 
 
606
                    "/etc/passwd as %s." % bzrlib.user_encoding)
 
 
608
        comma = gecos.find(',')
 
 
612
            realname = gecos[:comma]
 
 
619
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
 
620
        except UnicodeDecodeError:
 
 
621
            raise errors.BzrError("Can't decode username as %s." % \
 
 
622
                    bzrlib.user_encoding)
 
 
624
    return realname, (username + '@' + socket.gethostname())
 
 
627
def extract_email_address(e):
 
 
628
    """Return just the address part of an email string.
 
 
630
    That is just the user@domain part, nothing else. 
 
 
631
    This part is required to contain only ascii characters.
 
 
632
    If it can't be extracted, raises an error.
 
 
634
    >>> extract_email_address('Jane Tester <jane@test.com>')
 
 
637
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
 
639
        raise errors.BzrError("%r doesn't seem to contain "
 
 
640
                              "a reasonable email address" % e)
 
 
644
class TreeConfig(IniBasedConfig):
 
 
645
    """Branch configuration data associated with its contents, not location"""
 
 
646
    def __init__(self, branch):
 
 
649
    def _get_parser(self, file=None):
 
 
651
            return IniBasedConfig._get_parser(file)
 
 
652
        return self._get_config()
 
 
654
    def _get_config(self):
 
 
656
            obj = ConfigObj(self.branch.control_files.get('branch.conf'), 
 
 
658
        except errors.NoSuchFile:
 
 
659
            obj = ConfigObj(encoding='utf=8')
 
 
662
    def get_option(self, name, section=None, default=None):
 
 
663
        self.branch.lock_read()
 
 
665
            obj = self._get_config()
 
 
667
                if section is not None:
 
 
676
    def set_option(self, value, name, section=None):
 
 
677
        """Set a per-branch configuration option"""
 
 
678
        self.branch.lock_write()
 
 
680
            cfg_obj = self._get_config()
 
 
685
                    obj = cfg_obj[section]
 
 
687
                    cfg_obj[section] = {}
 
 
688
                    obj = cfg_obj[section]
 
 
690
            out_file = StringIO()
 
 
691
            cfg_obj.write(out_file)
 
 
693
            self.branch.control_files.put('branch.conf', out_file)