~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Patch Queue Manager
  • Date: 2014-02-12 18:22:22 UTC
  • mfrom: (6589.2.1 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20140212182222-beouo25gaf1cny76
(vila) The XDG Base Directory Specification uses the XDG_CACHE_HOME,
 not XDG_CACHE_DIR. (Andrew Starr-Bochicchio)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005-2012 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#            and others
4
4
#
31
31
log_format=name-of-format
32
32
validate_signatures_in_log=true|false(default)
33
33
acceptable_keys=pattern1,pattern2
 
34
gpg_signing_key=amy@example.com
34
35
 
35
36
in locations.conf, you specify the url of a branch and options for it.
36
37
Wildcards may be used - * and ? as normal in shell completion. Options
54
55
                   turns on create_signatures.
55
56
create_signatures - this option controls whether bzr will always create
56
57
                    gpg signatures or not on commits.  There is an unused
57
 
                    option which in future is expected to work if               
 
58
                    option which in future is expected to work if
58
59
                    branch settings require signatures.
59
60
log_format - this option sets the default log format.  Possible values are
60
61
             long, short, line, or a plugin can register new formats.
71
72
up=pull
72
73
"""
73
74
 
 
75
from __future__ import absolute_import
 
76
from cStringIO import StringIO
74
77
import os
75
 
import string
76
78
import sys
77
79
 
78
 
 
 
80
import bzrlib
79
81
from bzrlib.decorators import needs_write_lock
80
82
from bzrlib.lazy_import import lazy_import
81
83
lazy_import(globals(), """
 
84
import base64
82
85
import fnmatch
83
86
import re
84
 
from cStringIO import StringIO
85
87
 
86
88
from bzrlib import (
87
89
    atomicfile,
88
 
    bzrdir,
 
90
    controldir,
89
91
    debug,
 
92
    directory_service,
90
93
    errors,
91
94
    lazy_regex,
 
95
    library_state,
92
96
    lockdir,
93
 
    mail_client,
94
97
    mergetools,
95
98
    osutils,
96
99
    symbol_versioning,
100
103
    urlutils,
101
104
    win32utils,
102
105
    )
 
106
from bzrlib.i18n import gettext
103
107
from bzrlib.util.configobj import configobj
104
108
""")
105
109
from bzrlib import (
106
110
    commands,
107
111
    hooks,
 
112
    lazy_regex,
108
113
    registry,
109
114
    )
110
115
from bzrlib.symbol_versioning import (
147
152
STORE_GLOBAL = 4
148
153
 
149
154
 
 
155
def signature_policy_from_unicode(signature_string):
 
156
    """Convert a string to a signing policy."""
 
157
    if signature_string.lower() == 'check-available':
 
158
        return CHECK_IF_POSSIBLE
 
159
    if signature_string.lower() == 'ignore':
 
160
        return CHECK_NEVER
 
161
    if signature_string.lower() == 'require':
 
162
        return CHECK_ALWAYS
 
163
    raise ValueError("Invalid signatures policy '%s'"
 
164
                     % signature_string)
 
165
 
 
166
 
 
167
def signing_policy_from_unicode(signature_string):
 
168
    """Convert a string to a signing policy."""
 
169
    if signature_string.lower() == 'when-required':
 
170
        return SIGN_WHEN_REQUIRED
 
171
    if signature_string.lower() == 'never':
 
172
        return SIGN_NEVER
 
173
    if signature_string.lower() == 'always':
 
174
        return SIGN_ALWAYS
 
175
    raise ValueError("Invalid signing policy '%s'"
 
176
                     % signature_string)
 
177
 
 
178
 
150
179
class ConfigObj(configobj.ConfigObj):
151
180
 
152
181
    def __init__(self, infile=None, **kwargs):
168
197
        return self[section][name]
169
198
 
170
199
 
171
 
# FIXME: Until we can guarantee that each config file is loaded once and
172
 
# only once for a given bzrlib session, we don't want to re-read the file every
173
 
# time we query for an option so we cache the value (bad ! watch out for tests
174
 
# needing to restore the proper value).This shouldn't be part of 2.4.0 final,
175
 
# yell at mgz^W vila and the RM if this is still present at that time
176
 
# -- vila 20110219
177
 
_expand_default_value = None
178
 
def _get_expand_default_value():
179
 
    global _expand_default_value
180
 
    if _expand_default_value is not None:
181
 
        return _expand_default_value
182
 
    conf = GlobalConfig()
183
 
    # Note that we must not use None for the expand value below or we'll run
184
 
    # into infinite recursion. Using False really would be quite silly ;)
185
 
    expand = conf.get_user_option_as_bool('bzr.config.expand', expand=True)
186
 
    if expand is None:
187
 
        # This is an opt-in feature, you *really* need to clearly say you want
188
 
        # to activate it !
189
 
        expand = False
190
 
    _expand_default_value = expand
191
 
    return expand
192
 
 
193
 
 
194
200
class Config(object):
195
201
    """A configuration policy - what username, editor, gpg needs etc."""
196
202
 
201
207
        """Returns a unique ID for the config."""
202
208
        raise NotImplementedError(self.config_id)
203
209
 
204
 
    @deprecated_method(deprecated_in((2, 4, 0)))
205
 
    def get_editor(self):
206
 
        """Get the users pop up editor."""
207
 
        raise NotImplementedError
208
 
 
209
210
    def get_change_editor(self, old_tree, new_tree):
210
211
        from bzrlib import diff
211
212
        cmd = self._get_change_editor()
214
215
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
215
216
                                             sys.stdout)
216
217
 
217
 
    def get_mail_client(self):
218
 
        """Get a mail client to use"""
219
 
        selected_client = self.get_user_option('mail_client')
220
 
        _registry = mail_client.mail_client_registry
221
 
        try:
222
 
            mail_client_class = _registry.get(selected_client)
223
 
        except KeyError:
224
 
            raise errors.UnknownMailClient(selected_client)
225
 
        return mail_client_class(self)
226
 
 
227
218
    def _get_signature_checking(self):
228
219
        """Template method to override signature checking policy."""
229
220
 
358
349
        """Template method to provide a user option."""
359
350
        return None
360
351
 
361
 
    def get_user_option(self, option_name, expand=None):
 
352
    def get_user_option(self, option_name, expand=True):
362
353
        """Get a generic option - no special process, no default.
363
354
 
364
355
        :param option_name: The queried option.
367
358
 
368
359
        :returns: The value of the option.
369
360
        """
370
 
        if expand is None:
371
 
            expand = _get_expand_default_value()
372
361
        value = self._get_user_option(option_name)
373
362
        if expand:
374
363
            if isinstance(value, list):
415
404
            l = [l]
416
405
        return l
417
406
 
 
407
    @deprecated_method(deprecated_in((2, 5, 0)))
 
408
    def get_user_option_as_int_from_SI(self, option_name, default=None):
 
409
        """Get a generic option from a human readable size in SI units, e.g 10MB
 
410
 
 
411
        Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
412
        by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
413
        pedantic.
 
414
 
 
415
        :return Integer, expanded to its base-10 value if a proper SI unit is 
 
416
            found. If the option doesn't exist, or isn't a value in 
 
417
            SI units, return default (which defaults to None)
 
418
        """
 
419
        val = self.get_user_option(option_name)
 
420
        if isinstance(val, list):
 
421
            val = val[0]
 
422
        if val is None:
 
423
            val = default
 
424
        else:
 
425
            p = re.compile("^(\d+)([kmg])*b*$", re.IGNORECASE)
 
426
            try:
 
427
                m = p.match(val)
 
428
                if m is not None:
 
429
                    val = int(m.group(1))
 
430
                    if m.group(2) is not None:
 
431
                        if m.group(2).lower() == 'k':
 
432
                            val *= 10**3
 
433
                        elif m.group(2).lower() == 'm':
 
434
                            val *= 10**6
 
435
                        elif m.group(2).lower() == 'g':
 
436
                            val *= 10**9
 
437
                else:
 
438
                    ui.ui_factory.show_warning(gettext('Invalid config value for "{0}" '
 
439
                                               ' value {1!r} is not an SI unit.').format(
 
440
                                                option_name, val))
 
441
                    val = default
 
442
            except TypeError:
 
443
                val = default
 
444
        return val
 
445
 
 
446
    @deprecated_method(deprecated_in((2, 5, 0)))
418
447
    def gpg_signing_command(self):
419
448
        """What program should be used to sign signatures?"""
420
449
        result = self._gpg_signing_command()
426
455
        """See gpg_signing_command()."""
427
456
        return None
428
457
 
 
458
    @deprecated_method(deprecated_in((2, 5, 0)))
429
459
    def log_format(self):
430
460
        """What log format should be used"""
431
461
        result = self._log_format()
450
480
        """See validate_signatures_in_log()."""
451
481
        return None
452
482
 
 
483
    @deprecated_method(deprecated_in((2, 5, 0)))
453
484
    def acceptable_keys(self):
454
485
        """Comma separated list of key patterns acceptable to 
455
486
        verify-signatures command"""
460
491
        """See acceptable_keys()."""
461
492
        return None
462
493
 
 
494
    @deprecated_method(deprecated_in((2, 5, 0)))
463
495
    def post_commit(self):
464
496
        """An ordered list of python functions to call.
465
497
 
491
523
        v = self._get_user_id()
492
524
        if v:
493
525
            return v
494
 
        v = os.environ.get('EMAIL')
495
 
        if v:
496
 
            return v.decode(osutils.get_user_encoding())
497
 
        name, email = _auto_user_id()
498
 
        if name and email:
499
 
            return '%s <%s>' % (name, email)
500
 
        elif email:
501
 
            return email
502
 
        raise errors.NoWhoami()
 
526
        return default_email()
503
527
 
504
528
    def ensure_username(self):
505
529
        """Raise errors.NoWhoami if username is not set.
508
532
        """
509
533
        self.username()
510
534
 
 
535
    @deprecated_method(deprecated_in((2, 5, 0)))
511
536
    def signature_checking(self):
512
537
        """What is the current policy for signature checking?."""
513
538
        policy = self._get_signature_checking()
515
540
            return policy
516
541
        return CHECK_IF_POSSIBLE
517
542
 
 
543
    @deprecated_method(deprecated_in((2, 5, 0)))
518
544
    def signing_policy(self):
519
545
        """What is the current policy for signature checking?."""
520
546
        policy = self._get_signing_policy()
522
548
            return policy
523
549
        return SIGN_WHEN_REQUIRED
524
550
 
 
551
    @deprecated_method(deprecated_in((2, 5, 0)))
525
552
    def signature_needed(self):
526
553
        """Is a signature needed when committing ?."""
527
554
        policy = self._get_signing_policy()
536
563
            return True
537
564
        return False
538
565
 
 
566
    @deprecated_method(deprecated_in((2, 5, 0)))
 
567
    def gpg_signing_key(self):
 
568
        """GPG user-id to sign commits"""
 
569
        key = self.get_user_option('gpg_signing_key')
 
570
        if key == "default" or key == None:
 
571
            return self.user_email()
 
572
        else:
 
573
            return key
 
574
 
539
575
    def get_alias(self, value):
540
576
        return self._get_alias(value)
541
577
 
575
611
        for (oname, value, section, conf_id, parser) in self._get_options():
576
612
            if oname.startswith('bzr.mergetool.'):
577
613
                tool_name = oname[len('bzr.mergetool.'):]
578
 
                tools[tool_name] = value
 
614
                tools[tool_name] = self.get_user_option(oname, False)
579
615
        trace.mutter('loaded merge tools: %r' % tools)
580
616
        return tools
581
617
 
818
854
        """See Config._get_signature_checking."""
819
855
        policy = self._get_user_option('check_signatures')
820
856
        if policy:
821
 
            return self._string_to_signature_policy(policy)
 
857
            return signature_policy_from_unicode(policy)
822
858
 
823
859
    def _get_signing_policy(self):
824
860
        """See Config._get_signing_policy"""
825
861
        policy = self._get_user_option('create_signatures')
826
862
        if policy:
827
 
            return self._string_to_signing_policy(policy)
 
863
            return signing_policy_from_unicode(policy)
828
864
 
829
865
    def _get_user_id(self):
830
866
        """Get the user id from the 'email' key in the current section."""
875
911
        """See Config.post_commit."""
876
912
        return self._get_user_option('post_commit')
877
913
 
878
 
    def _string_to_signature_policy(self, signature_string):
879
 
        """Convert a string to a signing policy."""
880
 
        if signature_string.lower() == 'check-available':
881
 
            return CHECK_IF_POSSIBLE
882
 
        if signature_string.lower() == 'ignore':
883
 
            return CHECK_NEVER
884
 
        if signature_string.lower() == 'require':
885
 
            return CHECK_ALWAYS
886
 
        raise errors.BzrError("Invalid signatures policy '%s'"
887
 
                              % signature_string)
888
 
 
889
 
    def _string_to_signing_policy(self, signature_string):
890
 
        """Convert a string to a signing policy."""
891
 
        if signature_string.lower() == 'when-required':
892
 
            return SIGN_WHEN_REQUIRED
893
 
        if signature_string.lower() == 'never':
894
 
            return SIGN_NEVER
895
 
        if signature_string.lower() == 'always':
896
 
            return SIGN_ALWAYS
897
 
        raise errors.BzrError("Invalid signing policy '%s'"
898
 
                              % signature_string)
899
 
 
900
914
    def _get_alias(self, value):
901
915
        try:
902
916
            return self._get_parser().get_value("ALIASES",
978
992
        # local transports are not shared. But if/when we start using
979
993
        # LockableConfig for other kind of transports, we will need to reuse
980
994
        # whatever connection is already established -- vila 20100929
981
 
        self.transport = transport.get_transport(self.dir)
 
995
        self.transport = transport.get_transport_from_path(self.dir)
982
996
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
983
997
 
984
998
    def _create_from_string(self, unicode_bytes, save):
1039
1053
        conf._create_from_string(str_or_unicode, save)
1040
1054
        return conf
1041
1055
 
1042
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1043
 
    def get_editor(self):
1044
 
        return self._get_user_option('editor')
1045
 
 
1046
1056
    @needs_write_lock
1047
1057
    def set_user_option(self, option, value):
1048
1058
        """Save option and its value in the configuration."""
1346
1356
        e.g. "John Hacker <jhacker@example.com>"
1347
1357
        This is looked up in the email controlfile for the branch.
1348
1358
        """
1349
 
        try:
1350
 
            return (self.branch._transport.get_bytes("email")
1351
 
                    .decode(osutils.get_user_encoding())
1352
 
                    .rstrip("\r\n"))
1353
 
        except errors.NoSuchFile, e:
1354
 
            pass
1355
 
 
1356
1359
        return self._get_best_value('_get_user_id')
1357
1360
 
1358
1361
    def _get_change_editor(self):
1438
1441
        value = self._get_explicit_nickname()
1439
1442
        if value is not None:
1440
1443
            return value
 
1444
        if self.branch.name:
 
1445
            return self.branch.name
1441
1446
        return urlutils.unescape(self.branch.base.split('/')[-2])
1442
1447
 
1443
1448
    def has_explicit_nickname(self):
1480
1485
 
1481
1486
 
1482
1487
def config_dir():
1483
 
    """Return per-user configuration directory.
 
1488
    """Return per-user configuration directory as unicode string
1484
1489
 
1485
1490
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
1486
1491
    and Linux.  On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
1488
1493
 
1489
1494
    TODO: Global option --config-dir to override this.
1490
1495
    """
1491
 
    base = os.environ.get('BZR_HOME', None)
 
1496
    base = osutils.path_from_environ('BZR_HOME')
1492
1497
    if sys.platform == 'win32':
1493
 
        # environ variables on Windows are in user encoding/mbcs. So decode
1494
 
        # before using one
1495
 
        if base is not None:
1496
 
            base = base.decode('mbcs')
1497
 
        if base is None:
1498
 
            base = win32utils.get_appdata_location_unicode()
1499
 
        if base is None:
1500
 
            base = os.environ.get('HOME', None)
1501
 
            if base is not None:
1502
 
                base = base.decode('mbcs')
1503
 
        if base is None:
1504
 
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1505
 
                                  ' or HOME set')
 
1498
        if base is None:
 
1499
            base = win32utils.get_appdata_location()
 
1500
        if base is None:
 
1501
            base = win32utils.get_home_location()
 
1502
        # GZ 2012-02-01: Really the two level subdirs only make sense inside
 
1503
        #                APPDATA, but hard to move. See bug 348640 for more.
1506
1504
        return osutils.pathjoin(base, 'bazaar', '2.0')
1507
 
    elif sys.platform == 'darwin':
1508
 
        if base is None:
1509
 
            # this takes into account $HOME
1510
 
            base = os.path.expanduser("~")
1511
 
        return osutils.pathjoin(base, '.bazaar')
1512
 
    else:
1513
 
        if base is None:
1514
 
 
1515
 
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
 
1505
    if base is None:
 
1506
        # GZ 2012-02-01: What should OSX use instead of XDG if anything?
 
1507
        if sys.platform != 'darwin':
 
1508
            xdg_dir = osutils.path_from_environ('XDG_CONFIG_HOME')
1516
1509
            if xdg_dir is None:
1517
 
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
 
1510
                xdg_dir = osutils.pathjoin(osutils._get_home_dir(), ".config")
1518
1511
            xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
1519
1512
            if osutils.isdir(xdg_dir):
1520
1513
                trace.mutter(
1521
1514
                    "Using configuration in XDG directory %s." % xdg_dir)
1522
1515
                return xdg_dir
1523
 
 
1524
 
            base = os.path.expanduser("~")
1525
 
        return osutils.pathjoin(base, ".bazaar")
 
1516
        base = osutils._get_home_dir()
 
1517
    return osutils.pathjoin(base, ".bazaar")
1526
1518
 
1527
1519
 
1528
1520
def config_filename():
1565
1557
def xdg_cache_dir():
1566
1558
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
1567
1559
    # Possibly this should be different on Windows?
1568
 
    e = os.environ.get('XDG_CACHE_DIR', None)
 
1560
    e = os.environ.get('XDG_CACHE_HOME', None)
1569
1561
    if e:
1570
1562
        return e
1571
1563
    else:
1572
1564
        return os.path.expanduser('~/.cache')
1573
1565
 
1574
1566
 
1575
 
def _get_default_mail_domain():
 
1567
def _get_default_mail_domain(mailname_file='/etc/mailname'):
1576
1568
    """If possible, return the assumed default email domain.
1577
1569
 
1578
1570
    :returns: string mail domain, or None.
1581
1573
        # No implementation yet; patches welcome
1582
1574
        return None
1583
1575
    try:
1584
 
        f = open('/etc/mailname')
 
1576
        f = open(mailname_file)
1585
1577
    except (IOError, OSError), e:
1586
1578
        return None
1587
1579
    try:
1588
 
        domain = f.read().strip()
 
1580
        domain = f.readline().strip()
1589
1581
        return domain
1590
1582
    finally:
1591
1583
        f.close()
1592
1584
 
1593
1585
 
 
1586
def default_email():
 
1587
    v = os.environ.get('BZR_EMAIL')
 
1588
    if v:
 
1589
        return v.decode(osutils.get_user_encoding())
 
1590
    v = os.environ.get('EMAIL')
 
1591
    if v:
 
1592
        return v.decode(osutils.get_user_encoding())
 
1593
    name, email = _auto_user_id()
 
1594
    if name and email:
 
1595
        return u'%s <%s>' % (name, email)
 
1596
    elif email:
 
1597
        return email
 
1598
    raise errors.NoWhoami()
 
1599
 
 
1600
 
1594
1601
def _auto_user_id():
1595
1602
    """Calculate automatic user identification.
1596
1603
 
1785
1792
        :param user: login (optional)
1786
1793
 
1787
1794
        :param path: the absolute path on the server (optional)
1788
 
        
 
1795
 
1789
1796
        :param realm: the http authentication realm (optional)
1790
1797
 
1791
1798
        :return: A dict containing the matching credentials or None.
2126
2133
credential_store_registry.default_key = 'plain'
2127
2134
 
2128
2135
 
 
2136
class Base64CredentialStore(CredentialStore):
 
2137
    __doc__ = """Base64 credential store for the authentication.conf file"""
 
2138
 
 
2139
    def decode_password(self, credentials):
 
2140
        """See CredentialStore.decode_password."""
 
2141
        # GZ 2012-07-28: Will raise binascii.Error if password is not base64,
 
2142
        #                should probably propogate as something more useful.
 
2143
        return base64.decodestring(credentials['password'])
 
2144
 
 
2145
credential_store_registry.register('base64', Base64CredentialStore,
 
2146
                                   help=Base64CredentialStore.__doc__)
 
2147
 
 
2148
 
2129
2149
class BzrDirConfig(object):
2130
2150
 
2131
2151
    def __init__(self, bzrdir):
2137
2157
 
2138
2158
        It may be set to a location, or None.
2139
2159
 
2140
 
        This policy affects all branches contained by this bzrdir, except for
2141
 
        those under repositories.
 
2160
        This policy affects all branches contained by this control dir, except
 
2161
        for those under repositories.
2142
2162
        """
2143
2163
        if self._config is None:
2144
 
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
 
2164
            raise errors.BzrError("Cannot set configuration in %s"
 
2165
                                  % self._bzrdir)
2145
2166
        if value is None:
2146
2167
            self._config.set_option('', 'default_stack_on')
2147
2168
        else:
2152
2173
 
2153
2174
        This will either be a location, or None.
2154
2175
 
2155
 
        This policy affects all branches contained by this bzrdir, except for
2156
 
        those under repositories.
 
2176
        This policy affects all branches contained by this control dir, except
 
2177
        for those under repositories.
2157
2178
        """
2158
2179
        if self._config is None:
2159
2180
            return None
2230
2251
            return f
2231
2252
        except errors.NoSuchFile:
2232
2253
            return StringIO()
 
2254
        except errors.PermissionDenied, e:
 
2255
            trace.warning("Permission denied while trying to open "
 
2256
                "configuration file %s.", urlutils.unescape_for_display(
 
2257
                urlutils.join(self._transport.base, self._filename), "utf-8"))
 
2258
            return StringIO()
2233
2259
 
2234
2260
    def _external_url(self):
2235
2261
        return urlutils.join(self._transport.external_url(), self._filename)
2262
2288
    The option *values* are stored in config files and found in sections.
2263
2289
 
2264
2290
    Here we define various properties about the option itself, its default
2265
 
    value, in which config files it can be stored, etc (TBC).
 
2291
    value, how to convert it from stores, what to do when invalid values are
 
2292
    encoutered, in which config files it can be stored.
2266
2293
    """
2267
2294
 
2268
 
    def __init__(self, name, default=None):
 
2295
    def __init__(self, name, override_from_env=None,
 
2296
                 default=None, default_from_env=None,
 
2297
                 help=None, from_unicode=None, invalid=None, unquote=True):
 
2298
        """Build an option definition.
 
2299
 
 
2300
        :param name: the name used to refer to the option.
 
2301
 
 
2302
        :param override_from_env: A list of environment variables which can
 
2303
           provide override any configuration setting.
 
2304
 
 
2305
        :param default: the default value to use when none exist in the config
 
2306
            stores. This is either a string that ``from_unicode`` will convert
 
2307
            into the proper type, a callable returning a unicode string so that
 
2308
            ``from_unicode`` can be used on the return value, or a python
 
2309
            object that can be stringified (so only the empty list is supported
 
2310
            for example).
 
2311
 
 
2312
        :param default_from_env: A list of environment variables which can
 
2313
           provide a default value. 'default' will be used only if none of the
 
2314
           variables specified here are set in the environment.
 
2315
 
 
2316
        :param help: a doc string to explain the option to the user.
 
2317
 
 
2318
        :param from_unicode: a callable to convert the unicode string
 
2319
            representing the option value in a store or its default value.
 
2320
 
 
2321
        :param invalid: the action to be taken when an invalid value is
 
2322
            encountered in a store. This is called only when from_unicode is
 
2323
            invoked to convert a string and returns None or raise ValueError or
 
2324
            TypeError. Accepted values are: None (ignore invalid values),
 
2325
            'warning' (emit a warning), 'error' (emit an error message and
 
2326
            terminates).
 
2327
 
 
2328
        :param unquote: should the unicode value be unquoted before conversion.
 
2329
           This should be used only when the store providing the values cannot
 
2330
           safely unquote them (see http://pad.lv/906897). It is provided so
 
2331
           daughter classes can handle the quoting themselves.
 
2332
        """
 
2333
        if override_from_env is None:
 
2334
            override_from_env = []
 
2335
        if default_from_env is None:
 
2336
            default_from_env = []
2269
2337
        self.name = name
2270
 
        self.default = default
 
2338
        self.override_from_env = override_from_env
 
2339
        # Convert the default value to a unicode string so all values are
 
2340
        # strings internally before conversion (via from_unicode) is attempted.
 
2341
        if default is None:
 
2342
            self.default = None
 
2343
        elif isinstance(default, list):
 
2344
            # Only the empty list is supported
 
2345
            if default:
 
2346
                raise AssertionError(
 
2347
                    'Only empty lists are supported as default values')
 
2348
            self.default = u','
 
2349
        elif isinstance(default, (str, unicode, bool, int, float)):
 
2350
            # Rely on python to convert strings, booleans and integers
 
2351
            self.default = u'%s' % (default,)
 
2352
        elif callable(default):
 
2353
            self.default = default
 
2354
        else:
 
2355
            # other python objects are not expected
 
2356
            raise AssertionError('%r is not supported as a default value'
 
2357
                                 % (default,))
 
2358
        self.default_from_env = default_from_env
 
2359
        self._help = help
 
2360
        self.from_unicode = from_unicode
 
2361
        self.unquote = unquote
 
2362
        if invalid and invalid not in ('warning', 'error'):
 
2363
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
 
2364
        self.invalid = invalid
 
2365
 
 
2366
    @property
 
2367
    def help(self):
 
2368
        return self._help
 
2369
 
 
2370
    def convert_from_unicode(self, store, unicode_value):
 
2371
        if self.unquote and store is not None and unicode_value is not None:
 
2372
            unicode_value = store.unquote(unicode_value)
 
2373
        if self.from_unicode is None or unicode_value is None:
 
2374
            # Don't convert or nothing to convert
 
2375
            return unicode_value
 
2376
        try:
 
2377
            converted = self.from_unicode(unicode_value)
 
2378
        except (ValueError, TypeError):
 
2379
            # Invalid values are ignored
 
2380
            converted = None
 
2381
        if converted is None and self.invalid is not None:
 
2382
            # The conversion failed
 
2383
            if self.invalid == 'warning':
 
2384
                trace.warning('Value "%s" is not valid for "%s"',
 
2385
                              unicode_value, self.name)
 
2386
            elif self.invalid == 'error':
 
2387
                raise errors.ConfigOptionValueError(self.name, unicode_value)
 
2388
        return converted
 
2389
 
 
2390
    def get_override(self):
 
2391
        value = None
 
2392
        for var in self.override_from_env:
 
2393
            try:
 
2394
                # If the env variable is defined, its value takes precedence
 
2395
                value = os.environ[var].decode(osutils.get_user_encoding())
 
2396
                break
 
2397
            except KeyError:
 
2398
                continue
 
2399
        return value
2271
2400
 
2272
2401
    def get_default(self):
2273
 
        return self.default
2274
 
 
2275
 
 
2276
 
# Options registry
2277
 
 
2278
 
option_registry = registry.Registry()
2279
 
 
2280
 
 
2281
 
option_registry.register(
2282
 
    'editor', Option('editor'),
2283
 
    help='The command called to launch an editor to enter a message.')
 
2402
        value = None
 
2403
        for var in self.default_from_env:
 
2404
            try:
 
2405
                # If the env variable is defined, its value is the default one
 
2406
                value = os.environ[var].decode(osutils.get_user_encoding())
 
2407
                break
 
2408
            except KeyError:
 
2409
                continue
 
2410
        if value is None:
 
2411
            # Otherwise, fallback to the value defined at registration
 
2412
            if callable(self.default):
 
2413
                value = self.default()
 
2414
                if not isinstance(value, unicode):
 
2415
                    raise AssertionError(
 
2416
                        "Callable default value for '%s' should be unicode"
 
2417
                        % (self.name))
 
2418
            else:
 
2419
                value = self.default
 
2420
        return value
 
2421
 
 
2422
    def get_help_topic(self):
 
2423
        return self.name
 
2424
 
 
2425
    def get_help_text(self, additional_see_also=None, plain=True):
 
2426
        result = self.help
 
2427
        from bzrlib import help_topics
 
2428
        result += help_topics._format_see_also(additional_see_also)
 
2429
        if plain:
 
2430
            result = help_topics.help_as_plain_text(result)
 
2431
        return result
 
2432
 
 
2433
 
 
2434
# Predefined converters to get proper values from store
 
2435
 
 
2436
def bool_from_store(unicode_str):
 
2437
    return ui.bool_from_string(unicode_str)
 
2438
 
 
2439
 
 
2440
def int_from_store(unicode_str):
 
2441
    return int(unicode_str)
 
2442
 
 
2443
 
 
2444
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
 
2445
 
 
2446
def int_SI_from_store(unicode_str):
 
2447
    """Convert a human readable size in SI units, e.g 10MB into an integer.
 
2448
 
 
2449
    Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
2450
    by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
2451
    pedantic.
 
2452
 
 
2453
    :return Integer, expanded to its base-10 value if a proper SI unit is 
 
2454
        found, None otherwise.
 
2455
    """
 
2456
    regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
 
2457
    p = re.compile(regexp, re.IGNORECASE)
 
2458
    m = p.match(unicode_str)
 
2459
    val = None
 
2460
    if m is not None:
 
2461
        val, _, unit = m.groups()
 
2462
        val = int(val)
 
2463
        if unit:
 
2464
            try:
 
2465
                coeff = _unit_suffixes[unit.upper()]
 
2466
            except KeyError:
 
2467
                raise ValueError(gettext('{0} is not an SI unit.').format(unit))
 
2468
            val *= coeff
 
2469
    return val
 
2470
 
 
2471
 
 
2472
def float_from_store(unicode_str):
 
2473
    return float(unicode_str)
 
2474
 
 
2475
 
 
2476
# Use an empty dict to initialize an empty configobj avoiding all parsing and
 
2477
# encoding checks
 
2478
_list_converter_config = configobj.ConfigObj(
 
2479
    {}, encoding='utf-8', list_values=True, interpolation=False)
 
2480
 
 
2481
 
 
2482
class ListOption(Option):
 
2483
 
 
2484
    def __init__(self, name, default=None, default_from_env=None,
 
2485
                 help=None, invalid=None):
 
2486
        """A list Option definition.
 
2487
 
 
2488
        This overrides the base class so the conversion from a unicode string
 
2489
        can take quoting into account.
 
2490
        """
 
2491
        super(ListOption, self).__init__(
 
2492
            name, default=default, default_from_env=default_from_env,
 
2493
            from_unicode=self.from_unicode, help=help,
 
2494
            invalid=invalid, unquote=False)
 
2495
 
 
2496
    def from_unicode(self, unicode_str):
 
2497
        if not isinstance(unicode_str, basestring):
 
2498
            raise TypeError
 
2499
        # Now inject our string directly as unicode. All callers got their
 
2500
        # value from configobj, so values that need to be quoted are already
 
2501
        # properly quoted.
 
2502
        _list_converter_config.reset()
 
2503
        _list_converter_config._parse([u"list=%s" % (unicode_str,)])
 
2504
        maybe_list = _list_converter_config['list']
 
2505
        if isinstance(maybe_list, basestring):
 
2506
            if maybe_list:
 
2507
                # A single value, most probably the user forgot (or didn't care
 
2508
                # to add) the final ','
 
2509
                l = [maybe_list]
 
2510
            else:
 
2511
                # The empty string, convert to empty list
 
2512
                l = []
 
2513
        else:
 
2514
            # We rely on ConfigObj providing us with a list already
 
2515
            l = maybe_list
 
2516
        return l
 
2517
 
 
2518
 
 
2519
class RegistryOption(Option):
 
2520
    """Option for a choice from a registry."""
 
2521
 
 
2522
    def __init__(self, name, registry, default_from_env=None,
 
2523
                 help=None, invalid=None):
 
2524
        """A registry based Option definition.
 
2525
 
 
2526
        This overrides the base class so the conversion from a unicode string
 
2527
        can take quoting into account.
 
2528
        """
 
2529
        super(RegistryOption, self).__init__(
 
2530
            name, default=lambda: unicode(registry.default_key),
 
2531
            default_from_env=default_from_env,
 
2532
            from_unicode=self.from_unicode, help=help,
 
2533
            invalid=invalid, unquote=False)
 
2534
        self.registry = registry
 
2535
 
 
2536
    def from_unicode(self, unicode_str):
 
2537
        if not isinstance(unicode_str, basestring):
 
2538
            raise TypeError
 
2539
        try:
 
2540
            return self.registry.get(unicode_str)
 
2541
        except KeyError:
 
2542
            raise ValueError(
 
2543
                "Invalid value %s for %s."
 
2544
                "See help for a list of possible values." % (unicode_str,
 
2545
                    self.name))
 
2546
 
 
2547
    @property
 
2548
    def help(self):
 
2549
        ret = [self._help, "\n\nThe following values are supported:\n"]
 
2550
        for key in self.registry.keys():
 
2551
            ret.append(" %s - %s\n" % (key, self.registry.get_help(key)))
 
2552
        return "".join(ret)
 
2553
 
 
2554
 
 
2555
_option_ref_re = lazy_regex.lazy_compile('({[^\d\W](?:\.\w|\w)*})')
 
2556
"""Describes an expandable option reference.
 
2557
 
 
2558
We want to match the most embedded reference first.
 
2559
 
 
2560
I.e. for '{{foo}}' we will get '{foo}',
 
2561
for '{bar{baz}}' we will get '{baz}'
 
2562
"""
 
2563
 
 
2564
def iter_option_refs(string):
 
2565
    # Split isolate refs so every other chunk is a ref
 
2566
    is_ref = False
 
2567
    for chunk  in _option_ref_re.split(string):
 
2568
        yield is_ref, chunk
 
2569
        is_ref = not is_ref
 
2570
 
 
2571
 
 
2572
class OptionRegistry(registry.Registry):
 
2573
    """Register config options by their name.
 
2574
 
 
2575
    This overrides ``registry.Registry`` to simplify registration by acquiring
 
2576
    some information from the option object itself.
 
2577
    """
 
2578
 
 
2579
    def _check_option_name(self, option_name):
 
2580
        """Ensures an option name is valid.
 
2581
 
 
2582
        :param option_name: The name to validate.
 
2583
        """
 
2584
        if _option_ref_re.match('{%s}' % option_name) is None:
 
2585
            raise errors.IllegalOptionName(option_name)
 
2586
 
 
2587
    def register(self, option):
 
2588
        """Register a new option to its name.
 
2589
 
 
2590
        :param option: The option to register. Its name is used as the key.
 
2591
        """
 
2592
        self._check_option_name(option.name)
 
2593
        super(OptionRegistry, self).register(option.name, option,
 
2594
                                             help=option.help)
 
2595
 
 
2596
    def register_lazy(self, key, module_name, member_name):
 
2597
        """Register a new option to be loaded on request.
 
2598
 
 
2599
        :param key: the key to request the option later. Since the registration
 
2600
            is lazy, it should be provided and match the option name.
 
2601
 
 
2602
        :param module_name: the python path to the module. Such as 'os.path'.
 
2603
 
 
2604
        :param member_name: the member of the module to return.  If empty or 
 
2605
                None, get() will return the module itself.
 
2606
        """
 
2607
        self._check_option_name(key)
 
2608
        super(OptionRegistry, self).register_lazy(key,
 
2609
                                                  module_name, member_name)
 
2610
 
 
2611
    def get_help(self, key=None):
 
2612
        """Get the help text associated with the given key"""
 
2613
        option = self.get(key)
 
2614
        the_help = option.help
 
2615
        if callable(the_help):
 
2616
            return the_help(self, key)
 
2617
        return the_help
 
2618
 
 
2619
 
 
2620
option_registry = OptionRegistry()
 
2621
 
 
2622
 
 
2623
# Registered options in lexicographical order
 
2624
 
 
2625
option_registry.register(
 
2626
    Option('append_revisions_only',
 
2627
           default=None, from_unicode=bool_from_store, invalid='warning',
 
2628
           help='''\
 
2629
Whether to only append revisions to the mainline.
 
2630
 
 
2631
If this is set to true, then it is not possible to change the
 
2632
existing mainline of the branch.
 
2633
'''))
 
2634
option_registry.register(
 
2635
    ListOption('acceptable_keys',
 
2636
           default=None,
 
2637
           help="""\
 
2638
List of GPG key patterns which are acceptable for verification.
 
2639
"""))
 
2640
option_registry.register(
 
2641
    Option('add.maximum_file_size',
 
2642
           default=u'20MB', from_unicode=int_SI_from_store,
 
2643
           help="""\
 
2644
Size above which files should be added manually.
 
2645
 
 
2646
Files below this size are added automatically when using ``bzr add`` without
 
2647
arguments.
 
2648
 
 
2649
A negative value means disable the size check.
 
2650
"""))
 
2651
option_registry.register(
 
2652
    Option('bound',
 
2653
           default=None, from_unicode=bool_from_store,
 
2654
           help="""\
 
2655
Is the branch bound to ``bound_location``.
 
2656
 
 
2657
If set to "True", the branch should act as a checkout, and push each commit to
 
2658
the bound_location.  This option is normally set by ``bind``/``unbind``.
 
2659
 
 
2660
See also: bound_location.
 
2661
"""))
 
2662
option_registry.register(
 
2663
    Option('bound_location',
 
2664
           default=None,
 
2665
           help="""\
 
2666
The location that commits should go to when acting as a checkout.
 
2667
 
 
2668
This option is normally set by ``bind``.
 
2669
 
 
2670
See also: bound.
 
2671
"""))
 
2672
option_registry.register(
 
2673
    Option('branch.fetch_tags', default=False,  from_unicode=bool_from_store,
 
2674
           help="""\
 
2675
Whether revisions associated with tags should be fetched.
 
2676
"""))
 
2677
option_registry.register_lazy(
 
2678
    'bzr.transform.orphan_policy', 'bzrlib.transform', 'opt_transform_orphan')
 
2679
option_registry.register(
 
2680
    Option('bzr.workingtree.worth_saving_limit', default=10,
 
2681
           from_unicode=int_from_store,  invalid='warning',
 
2682
           help='''\
 
2683
How many changes before saving the dirstate.
 
2684
 
 
2685
-1 means that we will never rewrite the dirstate file for only
 
2686
stat-cache changes. Regardless of this setting, we will always rewrite
 
2687
the dirstate file if a file is added/removed/renamed/etc. This flag only
 
2688
affects the behavior of updating the dirstate file after we notice that
 
2689
a file has been touched.
 
2690
'''))
 
2691
option_registry.register(
 
2692
    Option('bugtracker', default=None,
 
2693
           help='''\
 
2694
Default bug tracker to use.
 
2695
 
 
2696
This bug tracker will be used for example when marking bugs
 
2697
as fixed using ``bzr commit --fixes``, if no explicit
 
2698
bug tracker was specified.
 
2699
'''))
 
2700
option_registry.register(
 
2701
    Option('check_signatures', default=CHECK_IF_POSSIBLE,
 
2702
           from_unicode=signature_policy_from_unicode,
 
2703
           help='''\
 
2704
GPG checking policy.
 
2705
 
 
2706
Possible values: require, ignore, check-available (default)
 
2707
 
 
2708
this option will control whether bzr will require good gpg
 
2709
signatures, ignore them, or check them if they are
 
2710
present.
 
2711
'''))
 
2712
option_registry.register(
 
2713
    Option('child_submit_format',
 
2714
           help='''The preferred format of submissions to this branch.'''))
 
2715
option_registry.register(
 
2716
    Option('child_submit_to',
 
2717
           help='''Where submissions to this branch are mailed to.'''))
 
2718
option_registry.register(
 
2719
    Option('create_signatures', default=SIGN_WHEN_REQUIRED,
 
2720
           from_unicode=signing_policy_from_unicode,
 
2721
           help='''\
 
2722
GPG Signing policy.
 
2723
 
 
2724
Possible values: always, never, when-required (default)
 
2725
 
 
2726
This option controls whether bzr will always create
 
2727
gpg signatures or not on commits.
 
2728
'''))
 
2729
option_registry.register(
 
2730
    Option('dirstate.fdatasync', default=True,
 
2731
           from_unicode=bool_from_store,
 
2732
           help='''\
 
2733
Flush dirstate changes onto physical disk?
 
2734
 
 
2735
If true (default), working tree metadata changes are flushed through the
 
2736
OS buffers to physical disk.  This is somewhat slower, but means data
 
2737
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2738
'''))
 
2739
option_registry.register(
 
2740
    ListOption('debug_flags', default=[],
 
2741
           help='Debug flags to activate.'))
 
2742
option_registry.register(
 
2743
    Option('default_format', default='2a',
 
2744
           help='Format used when creating branches.'))
 
2745
option_registry.register(
 
2746
    Option('dpush_strict', default=None,
 
2747
           from_unicode=bool_from_store,
 
2748
           help='''\
 
2749
The default value for ``dpush --strict``.
 
2750
 
 
2751
If present, defines the ``--strict`` option default value for checking
 
2752
uncommitted changes before pushing into a different VCS without any
 
2753
custom bzr metadata.
 
2754
'''))
 
2755
option_registry.register(
 
2756
    Option('editor',
 
2757
           help='The command called to launch an editor to enter a message.'))
 
2758
option_registry.register(
 
2759
    Option('email', override_from_env=['BZR_EMAIL'], default=default_email,
 
2760
           help='The users identity'))
 
2761
option_registry.register(
 
2762
    Option('gpg_signing_command',
 
2763
           default='gpg',
 
2764
           help="""\
 
2765
Program to use use for creating signatures.
 
2766
 
 
2767
This should support at least the -u and --clearsign options.
 
2768
"""))
 
2769
option_registry.register(
 
2770
    Option('gpg_signing_key',
 
2771
           default=None,
 
2772
           help="""\
 
2773
GPG key to use for signing.
 
2774
 
 
2775
This defaults to the first key associated with the users email.
 
2776
"""))
 
2777
option_registry.register(
 
2778
    Option('ignore_missing_extensions', default=False,
 
2779
           from_unicode=bool_from_store,
 
2780
           help='''\
 
2781
Control the missing extensions warning display.
 
2782
 
 
2783
The warning will not be emitted if set to True.
 
2784
'''))
 
2785
option_registry.register(
 
2786
    Option('language',
 
2787
           help='Language to translate messages into.'))
 
2788
option_registry.register(
 
2789
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
 
2790
           help='''\
 
2791
Steal locks that appears to be dead.
 
2792
 
 
2793
If set to True, bzr will check if a lock is supposed to be held by an
 
2794
active process from the same user on the same machine. If the user and
 
2795
machine match, but no process with the given PID is active, then bzr
 
2796
will automatically break the stale lock, and create a new lock for
 
2797
this process.
 
2798
Otherwise, bzr will prompt as normal to break the lock.
 
2799
'''))
 
2800
option_registry.register(
 
2801
    Option('log_format', default='long',
 
2802
           help= '''\
 
2803
Log format to use when displaying revisions.
 
2804
 
 
2805
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
 
2806
may be provided by plugins.
 
2807
'''))
 
2808
option_registry.register_lazy('mail_client', 'bzrlib.mail_client',
 
2809
    'opt_mail_client')
 
2810
option_registry.register(
 
2811
    Option('output_encoding',
 
2812
           help= 'Unicode encoding for output'
 
2813
           ' (terminal encoding if not specified).'))
 
2814
option_registry.register(
 
2815
    Option('parent_location',
 
2816
           default=None,
 
2817
           help="""\
 
2818
The location of the default branch for pull or merge.
 
2819
 
 
2820
This option is normally set when creating a branch, the first ``pull`` or by
 
2821
``pull --remember``.
 
2822
"""))
 
2823
option_registry.register(
 
2824
    Option('post_commit', default=None,
 
2825
           help='''\
 
2826
Post commit functions.
 
2827
 
 
2828
An ordered list of python functions to call, separated by spaces.
 
2829
 
 
2830
Each function takes branch, rev_id as parameters.
 
2831
'''))
 
2832
option_registry.register_lazy('progress_bar', 'bzrlib.ui.text',
 
2833
                              'opt_progress_bar')
 
2834
option_registry.register(
 
2835
    Option('public_branch',
 
2836
           default=None,
 
2837
           help="""\
 
2838
A publically-accessible version of this branch.
 
2839
 
 
2840
This implies that the branch setting this option is not publically-accessible.
 
2841
Used and set by ``bzr send``.
 
2842
"""))
 
2843
option_registry.register(
 
2844
    Option('push_location',
 
2845
           default=None,
 
2846
           help="""\
 
2847
The location of the default branch for push.
 
2848
 
 
2849
This option is normally set by the first ``push`` or ``push --remember``.
 
2850
"""))
 
2851
option_registry.register(
 
2852
    Option('push_strict', default=None,
 
2853
           from_unicode=bool_from_store,
 
2854
           help='''\
 
2855
The default value for ``push --strict``.
 
2856
 
 
2857
If present, defines the ``--strict`` option default value for checking
 
2858
uncommitted changes before sending a merge directive.
 
2859
'''))
 
2860
option_registry.register(
 
2861
    Option('repository.fdatasync', default=True,
 
2862
           from_unicode=bool_from_store,
 
2863
           help='''\
 
2864
Flush repository changes onto physical disk?
 
2865
 
 
2866
If true (default), repository changes are flushed through the OS buffers
 
2867
to physical disk.  This is somewhat slower, but means data should not be
 
2868
lost if the machine crashes.  See also dirstate.fdatasync.
 
2869
'''))
 
2870
option_registry.register_lazy('smtp_server',
 
2871
    'bzrlib.smtp_connection', 'smtp_server')
 
2872
option_registry.register_lazy('smtp_password',
 
2873
    'bzrlib.smtp_connection', 'smtp_password')
 
2874
option_registry.register_lazy('smtp_username',
 
2875
    'bzrlib.smtp_connection', 'smtp_username')
 
2876
option_registry.register(
 
2877
    Option('selftest.timeout',
 
2878
        default='600',
 
2879
        from_unicode=int_from_store,
 
2880
        help='Abort selftest if one test takes longer than this many seconds',
 
2881
        ))
 
2882
 
 
2883
option_registry.register(
 
2884
    Option('send_strict', default=None,
 
2885
           from_unicode=bool_from_store,
 
2886
           help='''\
 
2887
The default value for ``send --strict``.
 
2888
 
 
2889
If present, defines the ``--strict`` option default value for checking
 
2890
uncommitted changes before sending a bundle.
 
2891
'''))
 
2892
 
 
2893
option_registry.register(
 
2894
    Option('serve.client_timeout',
 
2895
           default=300.0, from_unicode=float_from_store,
 
2896
           help="If we wait for a new request from a client for more than"
 
2897
                " X seconds, consider the client idle, and hangup."))
 
2898
option_registry.register(
 
2899
    Option('stacked_on_location',
 
2900
           default=None,
 
2901
           help="""The location where this branch is stacked on."""))
 
2902
option_registry.register(
 
2903
    Option('submit_branch',
 
2904
           default=None,
 
2905
           help="""\
 
2906
The branch you intend to submit your current work to.
 
2907
 
 
2908
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
 
2909
by the ``submit:`` revision spec.
 
2910
"""))
 
2911
option_registry.register(
 
2912
    Option('submit_to',
 
2913
           help='''Where submissions from this branch are mailed to.'''))
 
2914
option_registry.register(
 
2915
    ListOption('suppress_warnings',
 
2916
           default=[],
 
2917
           help="List of warning classes to suppress."))
 
2918
option_registry.register(
 
2919
    Option('validate_signatures_in_log', default=False,
 
2920
           from_unicode=bool_from_store, invalid='warning',
 
2921
           help='''Whether to validate signatures in bzr log.'''))
 
2922
option_registry.register_lazy('ssl.ca_certs',
 
2923
    'bzrlib.transport.http._urllib2_wrappers', 'opt_ssl_ca_certs')
 
2924
 
 
2925
option_registry.register_lazy('ssl.cert_reqs',
 
2926
    'bzrlib.transport.http._urllib2_wrappers', 'opt_ssl_cert_reqs')
2284
2927
 
2285
2928
 
2286
2929
class Section(object):
2296
2939
        # We re-use the dict-like object received
2297
2940
        self.options = options
2298
2941
 
2299
 
    def get(self, name, default=None):
 
2942
    def get(self, name, default=None, expand=True):
2300
2943
        return self.options.get(name, default)
2301
2944
 
 
2945
    def iter_option_names(self):
 
2946
        for k in self.options.iterkeys():
 
2947
            yield k
 
2948
 
2302
2949
    def __repr__(self):
2303
2950
        # Mostly for debugging use
2304
2951
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2306
2953
 
2307
2954
_NewlyCreatedOption = object()
2308
2955
"""Was the option created during the MutableSection lifetime"""
 
2956
_DeletedOption = object()
 
2957
"""Was the option deleted during the MutableSection lifetime"""
2309
2958
 
2310
2959
 
2311
2960
class MutableSection(Section):
2313
2962
 
2314
2963
    def __init__(self, section_id, options):
2315
2964
        super(MutableSection, self).__init__(section_id, options)
2316
 
        self.orig = {}
 
2965
        self.reset_changes()
2317
2966
 
2318
2967
    def set(self, name, value):
2319
2968
        if name not in self.options:
2324
2973
        self.options[name] = value
2325
2974
 
2326
2975
    def remove(self, name):
2327
 
        if name not in self.orig:
 
2976
        if name not in self.orig and name in self.options:
2328
2977
            self.orig[name] = self.get(name, None)
2329
2978
        del self.options[name]
2330
2979
 
 
2980
    def reset_changes(self):
 
2981
        self.orig = {}
 
2982
 
 
2983
    def apply_changes(self, dirty, store):
 
2984
        """Apply option value changes.
 
2985
 
 
2986
        ``self`` has been reloaded from the persistent storage. ``dirty``
 
2987
        contains the changes made since the previous loading.
 
2988
 
 
2989
        :param dirty: the mutable section containing the changes.
 
2990
 
 
2991
        :param store: the store containing the section
 
2992
        """
 
2993
        for k, expected in dirty.orig.iteritems():
 
2994
            actual = dirty.get(k, _DeletedOption)
 
2995
            reloaded = self.get(k, _NewlyCreatedOption)
 
2996
            if actual is _DeletedOption:
 
2997
                if k in self.options:
 
2998
                    self.remove(k)
 
2999
            else:
 
3000
                self.set(k, actual)
 
3001
            # Report concurrent updates in an ad-hoc way. This should only
 
3002
            # occurs when different processes try to update the same option
 
3003
            # which is not supported (as in: the config framework is not meant
 
3004
            # to be used as a sharing mechanism).
 
3005
            if expected != reloaded:
 
3006
                if actual is _DeletedOption:
 
3007
                    actual = '<DELETED>'
 
3008
                if reloaded is _NewlyCreatedOption:
 
3009
                    reloaded = '<CREATED>'
 
3010
                if expected is _NewlyCreatedOption:
 
3011
                    expected = '<CREATED>'
 
3012
                # Someone changed the value since we get it from the persistent
 
3013
                # storage.
 
3014
                trace.warning(gettext(
 
3015
                        "Option {0} in section {1} of {2} was changed"
 
3016
                        " from {3} to {4}. The {5} value will be saved.".format(
 
3017
                            k, self.id, store.external_url(), expected,
 
3018
                            reloaded, actual)))
 
3019
        # No need to keep track of these changes
 
3020
        self.reset_changes()
 
3021
 
2331
3022
 
2332
3023
class Store(object):
2333
3024
    """Abstract interface to persistent storage for configuration options."""
2335
3026
    readonly_section_class = Section
2336
3027
    mutable_section_class = MutableSection
2337
3028
 
 
3029
    def __init__(self):
 
3030
        # Which sections need to be saved (by section id). We use a dict here
 
3031
        # so the dirty sections can be shared by multiple callers.
 
3032
        self.dirty_sections = {}
 
3033
 
2338
3034
    def is_loaded(self):
2339
3035
        """Returns True if the Store has been loaded.
2340
3036
 
2363
3059
        """
2364
3060
        raise NotImplementedError(self.unload)
2365
3061
 
 
3062
    def quote(self, value):
 
3063
        """Quote a configuration option value for storing purposes.
 
3064
 
 
3065
        This allows Stacks to present values as they will be stored.
 
3066
        """
 
3067
        return value
 
3068
 
 
3069
    def unquote(self, value):
 
3070
        """Unquote a configuration option value into unicode.
 
3071
 
 
3072
        The received value is quoted as stored.
 
3073
        """
 
3074
        return value
 
3075
 
2366
3076
    def save(self):
2367
3077
        """Saves the Store to persistent storage."""
2368
3078
        raise NotImplementedError(self.save)
2369
3079
 
 
3080
    def _need_saving(self):
 
3081
        for s in self.dirty_sections.values():
 
3082
            if s.orig:
 
3083
                # At least one dirty section contains a modification
 
3084
                return True
 
3085
        return False
 
3086
 
 
3087
    def apply_changes(self, dirty_sections):
 
3088
        """Apply changes from dirty sections while checking for coherency.
 
3089
 
 
3090
        The Store content is discarded and reloaded from persistent storage to
 
3091
        acquire up-to-date values.
 
3092
 
 
3093
        Dirty sections are MutableSection which kept track of the value they
 
3094
        are expected to update.
 
3095
        """
 
3096
        # We need an up-to-date version from the persistent storage, unload the
 
3097
        # store. The reload will occur when needed (triggered by the first
 
3098
        # get_mutable_section() call below.
 
3099
        self.unload()
 
3100
        # Apply the changes from the preserved dirty sections
 
3101
        for section_id, dirty in dirty_sections.iteritems():
 
3102
            clean = self.get_mutable_section(section_id)
 
3103
            clean.apply_changes(dirty, self)
 
3104
        # Everything is clean now
 
3105
        self.dirty_sections = {}
 
3106
 
 
3107
    def save_changes(self):
 
3108
        """Saves the Store to persistent storage if changes occurred.
 
3109
 
 
3110
        Apply the changes recorded in the mutable sections to a store content
 
3111
        refreshed from persistent storage.
 
3112
        """
 
3113
        raise NotImplementedError(self.save_changes)
 
3114
 
2370
3115
    def external_url(self):
2371
3116
        raise NotImplementedError(self.external_url)
2372
3117
 
2373
3118
    def get_sections(self):
2374
3119
        """Returns an ordered iterable of existing sections.
2375
3120
 
2376
 
        :returns: An iterable of (name, dict).
 
3121
        :returns: An iterable of (store, section).
2377
3122
        """
2378
3123
        raise NotImplementedError(self.get_sections)
2379
3124
 
2380
 
    def get_mutable_section(self, section_name=None):
 
3125
    def get_mutable_section(self, section_id=None):
2381
3126
        """Returns the specified mutable section.
2382
3127
 
2383
 
        :param section_name: The section identifier
 
3128
        :param section_id: The section identifier
2384
3129
        """
2385
3130
        raise NotImplementedError(self.get_mutable_section)
2386
3131
 
2390
3135
                                    self.external_url())
2391
3136
 
2392
3137
 
 
3138
class CommandLineStore(Store):
 
3139
    "A store to carry command line overrides for the config options."""
 
3140
 
 
3141
    def __init__(self, opts=None):
 
3142
        super(CommandLineStore, self).__init__()
 
3143
        if opts is None:
 
3144
            opts = {}
 
3145
        self.options = {}
 
3146
        self.id = 'cmdline'
 
3147
 
 
3148
    def _reset(self):
 
3149
        # The dict should be cleared but not replaced so it can be shared.
 
3150
        self.options.clear()
 
3151
 
 
3152
    def _from_cmdline(self, overrides):
 
3153
        # Reset before accepting new definitions
 
3154
        self._reset()
 
3155
        for over in overrides:
 
3156
            try:
 
3157
                name, value = over.split('=', 1)
 
3158
            except ValueError:
 
3159
                raise errors.BzrCommandError(
 
3160
                    gettext("Invalid '%s', should be of the form 'name=value'")
 
3161
                    % (over,))
 
3162
            self.options[name] = value
 
3163
 
 
3164
    def external_url(self):
 
3165
        # Not an url but it makes debugging easier and is never needed
 
3166
        # otherwise
 
3167
        return 'cmdline'
 
3168
 
 
3169
    def get_sections(self):
 
3170
        yield self,  self.readonly_section_class(None, self.options)
 
3171
 
 
3172
 
2393
3173
class IniFileStore(Store):
2394
3174
    """A config Store using ConfigObj for storage.
2395
3175
 
2396
 
    :ivar transport: The transport object where the config file is located.
2397
 
 
2398
 
    :ivar file_name: The config file basename in the transport directory.
2399
 
 
2400
3176
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
2401
3177
        serialize/deserialize the config file.
2402
3178
    """
2403
3179
 
2404
 
    def __init__(self, transport, file_name):
 
3180
    def __init__(self):
2405
3181
        """A config Store using ConfigObj for storage.
2406
 
 
2407
 
        :param transport: The transport object where the config file is located.
2408
 
 
2409
 
        :param file_name: The config file basename in the transport directory.
2410
3182
        """
2411
3183
        super(IniFileStore, self).__init__()
2412
 
        self.transport = transport
2413
 
        self.file_name = file_name
2414
3184
        self._config_obj = None
2415
3185
 
2416
3186
    def is_loaded(self):
2418
3188
 
2419
3189
    def unload(self):
2420
3190
        self._config_obj = None
 
3191
        self.dirty_sections = {}
 
3192
 
 
3193
    def _load_content(self):
 
3194
        """Load the config file bytes.
 
3195
 
 
3196
        This should be provided by subclasses
 
3197
 
 
3198
        :return: Byte string
 
3199
        """
 
3200
        raise NotImplementedError(self._load_content)
 
3201
 
 
3202
    def _save_content(self, content):
 
3203
        """Save the config file bytes.
 
3204
 
 
3205
        This should be provided by subclasses
 
3206
 
 
3207
        :param content: Config file bytes to write
 
3208
        """
 
3209
        raise NotImplementedError(self._save_content)
2421
3210
 
2422
3211
    def load(self):
2423
3212
        """Load the store from the associated file."""
2424
3213
        if self.is_loaded():
2425
3214
            return
2426
 
        content = self.transport.get_bytes(self.file_name)
 
3215
        content = self._load_content()
2427
3216
        self._load_from_string(content)
2428
3217
        for hook in ConfigHooks['load']:
2429
3218
            hook(self)
2438
3227
        co_input = StringIO(bytes)
2439
3228
        try:
2440
3229
            # The config files are always stored utf8-encoded
2441
 
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
 
3230
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
 
3231
                                         list_values=False)
2442
3232
        except configobj.ConfigObjError, e:
2443
3233
            self._config_obj = None
2444
3234
            raise errors.ParseConfigError(e.errors, self.external_url())
2445
3235
        except UnicodeDecodeError:
2446
3236
            raise errors.ConfigContentError(self.external_url())
2447
3237
 
 
3238
    def save_changes(self):
 
3239
        if not self.is_loaded():
 
3240
            # Nothing to save
 
3241
            return
 
3242
        if not self._need_saving():
 
3243
            return
 
3244
        # Preserve the current version
 
3245
        dirty_sections = dict(self.dirty_sections.items())
 
3246
        self.apply_changes(dirty_sections)
 
3247
        # Save to the persistent storage
 
3248
        self.save()
 
3249
 
2448
3250
    def save(self):
2449
3251
        if not self.is_loaded():
2450
3252
            # Nothing to save
2451
3253
            return
2452
3254
        out = StringIO()
2453
3255
        self._config_obj.write(out)
2454
 
        self.transport.put_bytes(self.file_name, out.getvalue())
 
3256
        self._save_content(out.getvalue())
2455
3257
        for hook in ConfigHooks['save']:
2456
3258
            hook(self)
2457
3259
 
2458
 
    def external_url(self):
2459
 
        # FIXME: external_url should really accepts an optional relpath
2460
 
        # parameter (bug #750169) :-/ -- vila 2011-04-04
2461
 
        # The following will do in the interim but maybe we don't want to
2462
 
        # expose a path here but rather a config ID and its associated
2463
 
        # object </hand wawe>.
2464
 
        return urlutils.join(self.transport.external_url(), self.file_name)
2465
 
 
2466
3260
    def get_sections(self):
2467
3261
        """Get the configobj section in the file order.
2468
3262
 
2469
 
        :returns: An iterable of (name, dict).
 
3263
        :returns: An iterable of (store, section).
2470
3264
        """
2471
3265
        # We need a loaded store
2472
3266
        try:
2473
3267
            self.load()
2474
 
        except errors.NoSuchFile:
2475
 
            # If the file doesn't exist, there is no sections
 
3268
        except (errors.NoSuchFile, errors.PermissionDenied):
 
3269
            # If the file can't be read, there is no sections
2476
3270
            return
2477
3271
        cobj = self._config_obj
2478
3272
        if cobj.scalars:
2479
 
            yield self.readonly_section_class(None, cobj)
 
3273
            yield self, self.readonly_section_class(None, cobj)
2480
3274
        for section_name in cobj.sections:
2481
 
            yield self.readonly_section_class(section_name, cobj[section_name])
 
3275
            yield (self,
 
3276
                   self.readonly_section_class(section_name,
 
3277
                                               cobj[section_name]))
2482
3278
 
2483
 
    def get_mutable_section(self, section_name=None):
 
3279
    def get_mutable_section(self, section_id=None):
2484
3280
        # We need a loaded store
2485
3281
        try:
2486
3282
            self.load()
2487
3283
        except errors.NoSuchFile:
2488
3284
            # The file doesn't exist, let's pretend it was empty
2489
3285
            self._load_from_string('')
2490
 
        if section_name is None:
 
3286
        if section_id in self.dirty_sections:
 
3287
            # We already created a mutable section for this id
 
3288
            return self.dirty_sections[section_id]
 
3289
        if section_id is None:
2491
3290
            section = self._config_obj
2492
3291
        else:
2493
 
            section = self._config_obj.setdefault(section_name, {})
2494
 
        return self.mutable_section_class(section_name, section)
 
3292
            section = self._config_obj.setdefault(section_id, {})
 
3293
        mutable_section = self.mutable_section_class(section_id, section)
 
3294
        # All mutable sections can become dirty
 
3295
        self.dirty_sections[section_id] = mutable_section
 
3296
        return mutable_section
 
3297
 
 
3298
    def quote(self, value):
 
3299
        try:
 
3300
            # configobj conflates automagical list values and quoting
 
3301
            self._config_obj.list_values = True
 
3302
            return self._config_obj._quote(value)
 
3303
        finally:
 
3304
            self._config_obj.list_values = False
 
3305
 
 
3306
    def unquote(self, value):
 
3307
        if value and isinstance(value, basestring):
 
3308
            # _unquote doesn't handle None nor empty strings nor anything that
 
3309
            # is not a string, really.
 
3310
            value = self._config_obj._unquote(value)
 
3311
        return value
 
3312
 
 
3313
    def external_url(self):
 
3314
        # Since an IniFileStore can be used without a file (at least in tests),
 
3315
        # it's better to provide something than raising a NotImplementedError.
 
3316
        # All daughter classes are supposed to provide an implementation
 
3317
        # anyway.
 
3318
        return 'In-Process Store, no URL'
 
3319
 
 
3320
 
 
3321
class TransportIniFileStore(IniFileStore):
 
3322
    """IniFileStore that loads files from a transport.
 
3323
 
 
3324
    :ivar transport: The transport object where the config file is located.
 
3325
 
 
3326
    :ivar file_name: The config file basename in the transport directory.
 
3327
    """
 
3328
 
 
3329
    def __init__(self, transport, file_name):
 
3330
        """A Store using a ini file on a Transport
 
3331
 
 
3332
        :param transport: The transport object where the config file is located.
 
3333
        :param file_name: The config file basename in the transport directory.
 
3334
        """
 
3335
        super(TransportIniFileStore, self).__init__()
 
3336
        self.transport = transport
 
3337
        self.file_name = file_name
 
3338
 
 
3339
    def _load_content(self):
 
3340
        try:
 
3341
            return self.transport.get_bytes(self.file_name)
 
3342
        except errors.PermissionDenied:
 
3343
            trace.warning("Permission denied while trying to load "
 
3344
                          "configuration store %s.", self.external_url())
 
3345
            raise
 
3346
 
 
3347
    def _save_content(self, content):
 
3348
        self.transport.put_bytes(self.file_name, content)
 
3349
 
 
3350
    def external_url(self):
 
3351
        # FIXME: external_url should really accepts an optional relpath
 
3352
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
3353
        # The following will do in the interim but maybe we don't want to
 
3354
        # expose a path here but rather a config ID and its associated
 
3355
        # object </hand wawe>.
 
3356
        return urlutils.join(self.transport.external_url(), self.file_name)
2495
3357
 
2496
3358
 
2497
3359
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2500
3362
# they may face the same issue.
2501
3363
 
2502
3364
 
2503
 
class LockableIniFileStore(IniFileStore):
 
3365
class LockableIniFileStore(TransportIniFileStore):
2504
3366
    """A ConfigObjStore using locks on save to ensure store integrity."""
2505
3367
 
2506
3368
    def __init__(self, transport, file_name, lock_dir_name=None):
2551
3413
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2552
3414
# on a poolie's remark)
2553
3415
class GlobalStore(LockableIniFileStore):
 
3416
    """A config store for global options.
 
3417
 
 
3418
    There is a single GlobalStore for a given process.
 
3419
    """
2554
3420
 
2555
3421
    def __init__(self, possible_transports=None):
2556
 
        t = transport.get_transport(config_dir(),
2557
 
                                    possible_transports=possible_transports)
 
3422
        t = transport.get_transport_from_path(
 
3423
            config_dir(), possible_transports=possible_transports)
2558
3424
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
3425
        self.id = 'bazaar'
2559
3426
 
2560
3427
 
2561
3428
class LocationStore(LockableIniFileStore):
 
3429
    """A config store for options specific to a location.
 
3430
 
 
3431
    There is a single LocationStore for a given process.
 
3432
    """
2562
3433
 
2563
3434
    def __init__(self, possible_transports=None):
2564
 
        t = transport.get_transport(config_dir(),
2565
 
                                    possible_transports=possible_transports)
 
3435
        t = transport.get_transport_from_path(
 
3436
            config_dir(), possible_transports=possible_transports)
2566
3437
        super(LocationStore, self).__init__(t, 'locations.conf')
2567
 
 
2568
 
 
2569
 
class BranchStore(IniFileStore):
 
3438
        self.id = 'locations'
 
3439
 
 
3440
 
 
3441
class BranchStore(TransportIniFileStore):
 
3442
    """A config store for branch options.
 
3443
 
 
3444
    There is a single BranchStore for a given branch.
 
3445
    """
2570
3446
 
2571
3447
    def __init__(self, branch):
2572
3448
        super(BranchStore, self).__init__(branch.control_transport,
2573
3449
                                          'branch.conf')
2574
3450
        self.branch = branch
2575
 
 
2576
 
    def lock_write(self, token=None):
2577
 
        return self.branch.lock_write(token)
2578
 
 
2579
 
    def unlock(self):
2580
 
        return self.branch.unlock()
2581
 
 
2582
 
    @needs_write_lock
2583
 
    def save(self):
2584
 
        # We need to be able to override the undecorated implementation
2585
 
        self.save_without_locking()
2586
 
 
2587
 
    def save_without_locking(self):
2588
 
        super(BranchStore, self).save()
 
3451
        self.id = 'branch'
 
3452
 
 
3453
 
 
3454
class ControlStore(LockableIniFileStore):
 
3455
 
 
3456
    def __init__(self, bzrdir):
 
3457
        super(ControlStore, self).__init__(bzrdir.transport,
 
3458
                                          'control.conf',
 
3459
                                           lock_dir_name='branch_lock')
 
3460
        self.id = 'control'
2589
3461
 
2590
3462
 
2591
3463
class SectionMatcher(object):
2592
3464
    """Select sections into a given Store.
2593
3465
 
2594
 
    This intended to be used to postpone getting an iterable of sections from a
2595
 
    store.
 
3466
    This is intended to be used to postpone getting an iterable of sections
 
3467
    from a store.
2596
3468
    """
2597
3469
 
2598
3470
    def __init__(self, store):
2603
3475
        # sections.
2604
3476
        sections = self.store.get_sections()
2605
3477
        # Walk the revisions in the order provided
2606
 
        for s in sections:
 
3478
        for store, s in sections:
2607
3479
            if self.match(s):
2608
 
                yield s
2609
 
 
2610
 
    def match(self, secion):
 
3480
                yield store, s
 
3481
 
 
3482
    def match(self, section):
 
3483
        """Does the proposed section match.
 
3484
 
 
3485
        :param section: A Section object.
 
3486
 
 
3487
        :returns: True if the section matches, False otherwise.
 
3488
        """
2611
3489
        raise NotImplementedError(self.match)
2612
3490
 
2613
3491
 
 
3492
class NameMatcher(SectionMatcher):
 
3493
 
 
3494
    def __init__(self, store, section_id):
 
3495
        super(NameMatcher, self).__init__(store)
 
3496
        self.section_id = section_id
 
3497
 
 
3498
    def match(self, section):
 
3499
        return section.id == self.section_id
 
3500
 
 
3501
 
2614
3502
class LocationSection(Section):
2615
3503
 
2616
 
    def __init__(self, section, length, extra_path):
 
3504
    def __init__(self, section, extra_path, branch_name=None):
2617
3505
        super(LocationSection, self).__init__(section.id, section.options)
2618
 
        self.length = length
2619
3506
        self.extra_path = extra_path
 
3507
        if branch_name is None:
 
3508
            branch_name = ''
 
3509
        self.locals = {'relpath': extra_path,
 
3510
                       'basename': urlutils.basename(extra_path),
 
3511
                       'branchname': branch_name}
2620
3512
 
2621
 
    def get(self, name, default=None):
 
3513
    def get(self, name, default=None, expand=True):
2622
3514
        value = super(LocationSection, self).get(name, default)
2623
 
        if value is not None:
 
3515
        if value is not None and expand:
2624
3516
            policy_name = self.get(name + ':policy', None)
2625
3517
            policy = _policy_value.get(policy_name, POLICY_NONE)
2626
3518
            if policy == POLICY_APPENDPATH:
2627
3519
                value = urlutils.join(value, self.extra_path)
 
3520
            # expand section local options right now (since POLICY_APPENDPATH
 
3521
            # will never add options references, it's ok to expand after it).
 
3522
            chunks = []
 
3523
            for is_ref, chunk in iter_option_refs(value):
 
3524
                if not is_ref:
 
3525
                    chunks.append(chunk)
 
3526
                else:
 
3527
                    ref = chunk[1:-1]
 
3528
                    if ref in self.locals:
 
3529
                        chunks.append(self.locals[ref])
 
3530
                    else:
 
3531
                        chunks.append(chunk)
 
3532
            value = ''.join(chunks)
2628
3533
        return value
2629
3534
 
2630
3535
 
 
3536
class StartingPathMatcher(SectionMatcher):
 
3537
    """Select sections for a given location respecting the Store order."""
 
3538
 
 
3539
    # FIXME: Both local paths and urls can be used for section names as well as
 
3540
    # ``location`` to stay consistent with ``LocationMatcher`` which itself
 
3541
    # inherited the fuzziness from the previous ``LocationConfig``
 
3542
    # implementation. We probably need to revisit which encoding is allowed for
 
3543
    # both ``location`` and section names and how we normalize
 
3544
    # them. http://pad.lv/85479, http://pad.lv/437009 and http://359320 are
 
3545
    # related too. -- vila 2012-01-04
 
3546
 
 
3547
    def __init__(self, store, location):
 
3548
        super(StartingPathMatcher, self).__init__(store)
 
3549
        if location.startswith('file://'):
 
3550
            location = urlutils.local_path_from_url(location)
 
3551
        self.location = location
 
3552
 
 
3553
    def get_sections(self):
 
3554
        """Get all sections matching ``location`` in the store.
 
3555
 
 
3556
        The most generic sections are described first in the store, then more
 
3557
        specific ones can be provided for reduced scopes.
 
3558
 
 
3559
        The returned section are therefore returned in the reversed order so
 
3560
        the most specific ones can be found first.
 
3561
        """
 
3562
        location_parts = self.location.rstrip('/').split('/')
 
3563
        store = self.store
 
3564
        sections = []
 
3565
        # Later sections are more specific, they should be returned first
 
3566
        for _, section in reversed(list(store.get_sections())):
 
3567
            if section.id is None:
 
3568
                # The no-name section is always included if present
 
3569
                yield store, LocationSection(section, self.location)
 
3570
                continue
 
3571
            section_path = section.id
 
3572
            if section_path.startswith('file://'):
 
3573
                # the location is already a local path or URL, convert the
 
3574
                # section id to the same format
 
3575
                section_path = urlutils.local_path_from_url(section_path)
 
3576
            if (self.location.startswith(section_path)
 
3577
                or fnmatch.fnmatch(self.location, section_path)):
 
3578
                section_parts = section_path.rstrip('/').split('/')
 
3579
                extra_path = '/'.join(location_parts[len(section_parts):])
 
3580
                yield store, LocationSection(section, extra_path)
 
3581
 
 
3582
 
2631
3583
class LocationMatcher(SectionMatcher):
2632
3584
 
2633
3585
    def __init__(self, store, location):
2634
3586
        super(LocationMatcher, self).__init__(store)
 
3587
        url, params = urlutils.split_segment_parameters(location)
2635
3588
        if location.startswith('file://'):
2636
3589
            location = urlutils.local_path_from_url(location)
2637
3590
        self.location = location
 
3591
        branch_name = params.get('branch')
 
3592
        if branch_name is None:
 
3593
            self.branch_name = urlutils.basename(self.location)
 
3594
        else:
 
3595
            self.branch_name = urlutils.unescape(branch_name)
2638
3596
 
2639
3597
    def _get_matching_sections(self):
2640
3598
        """Get all sections matching ``location``."""
2641
3599
        # We slightly diverge from LocalConfig here by allowing the no-name
2642
3600
        # section as the most generic one and the lower priority.
2643
3601
        no_name_section = None
2644
 
        sections = []
 
3602
        all_sections = []
2645
3603
        # Filter out the no_name_section so _iter_for_location_by_parts can be
2646
3604
        # used (it assumes all sections have a name).
2647
 
        for section in self.store.get_sections():
 
3605
        for _, section in self.store.get_sections():
2648
3606
            if section.id is None:
2649
3607
                no_name_section = section
2650
3608
            else:
2651
 
                sections.append(section)
 
3609
                all_sections.append(section)
2652
3610
        # Unfortunately _iter_for_location_by_parts deals with section names so
2653
3611
        # we have to resync.
2654
3612
        filtered_sections = _iter_for_location_by_parts(
2655
 
            [s.id for s in sections], self.location)
2656
 
        iter_sections = iter(sections)
 
3613
            [s.id for s in all_sections], self.location)
 
3614
        iter_all_sections = iter(all_sections)
2657
3615
        matching_sections = []
2658
3616
        if no_name_section is not None:
2659
3617
            matching_sections.append(
2660
 
                LocationSection(no_name_section, 0, self.location))
 
3618
                (0, LocationSection(no_name_section, self.location)))
2661
3619
        for section_id, extra_path, length in filtered_sections:
2662
 
            # a section id is unique for a given store so it's safe to iterate
2663
 
            # again
2664
 
            section = iter_sections.next()
2665
 
            if section_id == section.id:
2666
 
                matching_sections.append(
2667
 
                    LocationSection(section, length, extra_path))
 
3620
            # a section id is unique for a given store so it's safe to take the
 
3621
            # first matching section while iterating. Also, all filtered
 
3622
            # sections are part of 'all_sections' and will always be found
 
3623
            # there.
 
3624
            while True:
 
3625
                section = iter_all_sections.next()
 
3626
                if section_id == section.id:
 
3627
                    section = LocationSection(section, extra_path,
 
3628
                                              self.branch_name)
 
3629
                    matching_sections.append((length, section))
 
3630
                    break
2668
3631
        return matching_sections
2669
3632
 
2670
3633
    def get_sections(self):
2672
3635
        matching_sections = self._get_matching_sections()
2673
3636
        # We want the longest (aka more specific) locations first
2674
3637
        sections = sorted(matching_sections,
2675
 
                          key=lambda section: (section.length, section.id),
 
3638
                          key=lambda (length, section): (length, section.id),
2676
3639
                          reverse=True)
2677
3640
        # Sections mentioning 'ignore_parents' restrict the selection
2678
 
        for section in sections:
 
3641
        for _, section in sections:
2679
3642
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
2680
3643
            ignore = section.get('ignore_parents', None)
2681
3644
            if ignore is not None:
2683
3646
            if ignore:
2684
3647
                break
2685
3648
            # Finally, we have a valid section
2686
 
            yield section
2687
 
 
 
3649
            yield self.store, section
 
3650
 
 
3651
 
 
3652
# FIXME: _shared_stores should be an attribute of a library state once a
 
3653
# library_state object is always available.
 
3654
_shared_stores = {}
 
3655
_shared_stores_at_exit_installed = False
2688
3656
 
2689
3657
class Stack(object):
2690
3658
    """A stack of configurations where an option can be defined"""
2691
3659
 
2692
 
    def __init__(self, sections_def, store=None, mutable_section_name=None):
 
3660
    def __init__(self, sections_def, store=None, mutable_section_id=None):
2693
3661
        """Creates a stack of sections with an optional store for changes.
2694
3662
 
2695
3663
        :param sections_def: A list of Section or callables that returns an
2699
3667
        :param store: The optional Store where modifications will be
2700
3668
            recorded. If none is specified, no modifications can be done.
2701
3669
 
2702
 
        :param mutable_section_name: The name of the MutableSection where
2703
 
            changes are recorded. This requires the ``store`` parameter to be
 
3670
        :param mutable_section_id: The id of the MutableSection where changes
 
3671
            are recorded. This requires the ``store`` parameter to be
2704
3672
            specified.
2705
3673
        """
2706
3674
        self.sections_def = sections_def
2707
3675
        self.store = store
2708
 
        self.mutable_section_name = mutable_section_name
2709
 
 
2710
 
    def get(self, name):
 
3676
        self.mutable_section_id = mutable_section_id
 
3677
 
 
3678
    def iter_sections(self):
 
3679
        """Iterate all the defined sections."""
 
3680
        # Ensuring lazy loading is achieved by delaying section matching (which
 
3681
        # implies querying the persistent storage) until it can't be avoided
 
3682
        # anymore by using callables to describe (possibly empty) section
 
3683
        # lists.
 
3684
        for sections in self.sections_def:
 
3685
            for store, section in sections():
 
3686
                yield store, section
 
3687
 
 
3688
    def get(self, name, expand=True, convert=True):
2711
3689
        """Return the *first* option value found in the sections.
2712
3690
 
2713
3691
        This is where we guarantee that sections coming from Store are loaded
2715
3693
        option exists or get its value, which in turn may require to discover
2716
3694
        in which sections it can be defined. Both of these (section and option
2717
3695
        existence) require loading the store (even partially).
 
3696
 
 
3697
        :param name: The queried option.
 
3698
 
 
3699
        :param expand: Whether options references should be expanded.
 
3700
 
 
3701
        :param convert: Whether the option value should be converted from
 
3702
            unicode (do nothing for non-registered options).
 
3703
 
 
3704
        :returns: The value of the option.
2718
3705
        """
2719
3706
        # FIXME: No caching of options nor sections yet -- vila 20110503
2720
3707
        value = None
2721
 
        # Ensuring lazy loading is achieved by delaying section matching (which
2722
 
        # implies querying the persistent storage) until it can't be avoided
2723
 
        # anymore by using callables to describe (possibly empty) section
2724
 
        # lists.
2725
 
        for section_or_callable in self.sections_def:
2726
 
            # Each section can expand to multiple ones when a callable is used
2727
 
            if callable(section_or_callable):
2728
 
                sections = section_or_callable()
2729
 
            else:
2730
 
                sections = [section_or_callable]
2731
 
            for section in sections:
 
3708
        found_store = None # Where the option value has been found
 
3709
        # If the option is registered, it may provide additional info about
 
3710
        # value handling
 
3711
        try:
 
3712
            opt = option_registry.get(name)
 
3713
        except KeyError:
 
3714
            # Not registered
 
3715
            opt = None
 
3716
 
 
3717
        def expand_and_convert(val):
 
3718
            # This may need to be called in different contexts if the value is
 
3719
            # None or ends up being None during expansion or conversion.
 
3720
            if val is not None:
 
3721
                if expand:
 
3722
                    if isinstance(val, basestring):
 
3723
                        val = self._expand_options_in_string(val)
 
3724
                    else:
 
3725
                        trace.warning('Cannot expand "%s":'
 
3726
                                      ' %s does not support option expansion'
 
3727
                                      % (name, type(val)))
 
3728
                if opt is None:
 
3729
                    val = found_store.unquote(val)
 
3730
                elif convert:
 
3731
                    val = opt.convert_from_unicode(found_store, val)
 
3732
            return val
 
3733
 
 
3734
        # First of all, check if the environment can override the configuration
 
3735
        # value
 
3736
        if opt is not None and opt.override_from_env:
 
3737
            value = opt.get_override()
 
3738
            value = expand_and_convert(value)
 
3739
        if value is None:
 
3740
            for store, section in self.iter_sections():
2732
3741
                value = section.get(name)
2733
3742
                if value is not None:
 
3743
                    found_store = store
2734
3744
                    break
2735
 
            if value is not None:
2736
 
                break
2737
 
        if value is None:
2738
 
            # If the option is registered, it may provide a default value
2739
 
            try:
2740
 
                opt = option_registry.get(name)
2741
 
            except KeyError:
2742
 
                # Not registered
2743
 
                opt = None
2744
 
            if opt is not None:
 
3745
            value = expand_and_convert(value)
 
3746
            if opt is not None and value is None:
 
3747
                # If the option is registered, it may provide a default value
2745
3748
                value = opt.get_default()
 
3749
                value = expand_and_convert(value)
2746
3750
        for hook in ConfigHooks['get']:
2747
3751
            hook(self, name, value)
2748
3752
        return value
2749
3753
 
 
3754
    def expand_options(self, string, env=None):
 
3755
        """Expand option references in the string in the configuration context.
 
3756
 
 
3757
        :param string: The string containing option(s) to expand.
 
3758
 
 
3759
        :param env: An option dict defining additional configuration options or
 
3760
            overriding existing ones.
 
3761
 
 
3762
        :returns: The expanded string.
 
3763
        """
 
3764
        return self._expand_options_in_string(string, env)
 
3765
 
 
3766
    def _expand_options_in_string(self, string, env=None, _refs=None):
 
3767
        """Expand options in the string in the configuration context.
 
3768
 
 
3769
        :param string: The string to be expanded.
 
3770
 
 
3771
        :param env: An option dict defining additional configuration options or
 
3772
            overriding existing ones.
 
3773
 
 
3774
        :param _refs: Private list (FIFO) containing the options being expanded
 
3775
            to detect loops.
 
3776
 
 
3777
        :returns: The expanded string.
 
3778
        """
 
3779
        if string is None:
 
3780
            # Not much to expand there
 
3781
            return None
 
3782
        if _refs is None:
 
3783
            # What references are currently resolved (to detect loops)
 
3784
            _refs = []
 
3785
        result = string
 
3786
        # We need to iterate until no more refs appear ({{foo}} will need two
 
3787
        # iterations for example).
 
3788
        expanded = True
 
3789
        while expanded:
 
3790
            expanded = False
 
3791
            chunks = []
 
3792
            for is_ref, chunk in iter_option_refs(result):
 
3793
                if not is_ref:
 
3794
                    chunks.append(chunk)
 
3795
                else:
 
3796
                    expanded = True
 
3797
                    name = chunk[1:-1]
 
3798
                    if name in _refs:
 
3799
                        raise errors.OptionExpansionLoop(string, _refs)
 
3800
                    _refs.append(name)
 
3801
                    value = self._expand_option(name, env, _refs)
 
3802
                    if value is None:
 
3803
                        raise errors.ExpandingUnknownOption(name, string)
 
3804
                    chunks.append(value)
 
3805
                    _refs.pop()
 
3806
            result = ''.join(chunks)
 
3807
        return result
 
3808
 
 
3809
    def _expand_option(self, name, env, _refs):
 
3810
        if env is not None and name in env:
 
3811
            # Special case, values provided in env takes precedence over
 
3812
            # anything else
 
3813
            value = env[name]
 
3814
        else:
 
3815
            value = self.get(name, expand=False, convert=False)
 
3816
            value = self._expand_options_in_string(value, env, _refs)
 
3817
        return value
 
3818
 
2750
3819
    def _get_mutable_section(self):
2751
3820
        """Get the MutableSection for the Stack.
2752
3821
 
2753
3822
        This is where we guarantee that the mutable section is lazily loaded:
2754
3823
        this means we won't load the corresponding store before setting a value
2755
3824
        or deleting an option. In practice the store will often be loaded but
2756
 
        this allows helps catching some programming errors.
 
3825
        this helps catching some programming errors.
2757
3826
        """
2758
 
        section = self.store.get_mutable_section(self.mutable_section_name)
2759
 
        return section
 
3827
        store = self.store
 
3828
        section = store.get_mutable_section(self.mutable_section_id)
 
3829
        return store, section
2760
3830
 
2761
3831
    def set(self, name, value):
2762
3832
        """Set a new value for the option."""
2763
 
        section = self._get_mutable_section()
2764
 
        section.set(name, value)
 
3833
        store, section = self._get_mutable_section()
 
3834
        section.set(name, store.quote(value))
2765
3835
        for hook in ConfigHooks['set']:
2766
3836
            hook(self, name, value)
2767
3837
 
2768
3838
    def remove(self, name):
2769
3839
        """Remove an existing option."""
2770
 
        section = self._get_mutable_section()
 
3840
        _, section = self._get_mutable_section()
2771
3841
        section.remove(name)
2772
3842
        for hook in ConfigHooks['remove']:
2773
3843
            hook(self, name)
2776
3846
        # Mostly for debugging use
2777
3847
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2778
3848
 
 
3849
    def _get_overrides(self):
 
3850
        # FIXME: Hack around library_state.initialize never called
 
3851
        if bzrlib.global_state is not None:
 
3852
            return bzrlib.global_state.cmdline_overrides.get_sections()
 
3853
        return []
 
3854
 
 
3855
    def get_shared_store(self, store, state=None):
 
3856
        """Get a known shared store.
 
3857
 
 
3858
        Store urls uniquely identify them and are used to ensure a single copy
 
3859
        is shared across all users.
 
3860
 
 
3861
        :param store: The store known to the caller.
 
3862
 
 
3863
        :param state: The library state where the known stores are kept.
 
3864
 
 
3865
        :returns: The store received if it's not a known one, an already known
 
3866
            otherwise.
 
3867
        """
 
3868
        if state is None:
 
3869
            state = bzrlib.global_state
 
3870
        if state is None:
 
3871
            global _shared_stores_at_exit_installed
 
3872
            stores = _shared_stores
 
3873
            def save_config_changes():
 
3874
                for k, store in stores.iteritems():
 
3875
                    store.save_changes()
 
3876
            if not _shared_stores_at_exit_installed:
 
3877
                # FIXME: Ugly hack waiting for library_state to always be
 
3878
                # available. -- vila 20120731
 
3879
                import atexit
 
3880
                atexit.register(save_config_changes)
 
3881
                _shared_stores_at_exit_installed = True
 
3882
        else:
 
3883
            stores = state.config_stores
 
3884
        url = store.external_url()
 
3885
        try:
 
3886
            return stores[url]
 
3887
        except KeyError:
 
3888
            stores[url] = store
 
3889
            return store
 
3890
 
 
3891
 
 
3892
class MemoryStack(Stack):
 
3893
    """A configuration stack defined from a string.
 
3894
 
 
3895
    This is mainly intended for tests and requires no disk resources.
 
3896
    """
 
3897
 
 
3898
    def __init__(self, content=None):
 
3899
        """Create an in-memory stack from a given content.
 
3900
 
 
3901
        It uses a single store based on configobj and support reading and
 
3902
        writing options.
 
3903
 
 
3904
        :param content: The initial content of the store. If None, the store is
 
3905
            not loaded and ``_load_from_string`` can and should be used if
 
3906
            needed.
 
3907
        """
 
3908
        store = IniFileStore()
 
3909
        if content is not None:
 
3910
            store._load_from_string(content)
 
3911
        super(MemoryStack, self).__init__(
 
3912
            [store.get_sections], store)
 
3913
 
2779
3914
 
2780
3915
class _CompatibleStack(Stack):
2781
3916
    """Place holder for compatibility with previous design.
2786
3921
    One assumption made here is that the daughter classes will all use Stores
2787
3922
    derived from LockableIniFileStore).
2788
3923
 
2789
 
    It implements set() by re-loading the store before applying the
2790
 
    modification and saving it.
 
3924
    It implements set() and remove () by re-loading the store before applying
 
3925
    the modification and saving it.
2791
3926
 
2792
3927
    The long term plan being to implement a single write by store to save
2793
3928
    all modifications, this class should not be used in the interim.
2800
3935
        # Force a write to persistent storage
2801
3936
        self.store.save()
2802
3937
 
2803
 
 
2804
 
class GlobalStack(_CompatibleStack):
 
3938
    def remove(self, name):
 
3939
        # Force a reload
 
3940
        self.store.unload()
 
3941
        super(_CompatibleStack, self).remove(name)
 
3942
        # Force a write to persistent storage
 
3943
        self.store.save()
 
3944
 
 
3945
 
 
3946
class GlobalStack(Stack):
 
3947
    """Global options only stack.
 
3948
 
 
3949
    The following sections are queried:
 
3950
 
 
3951
    * command-line overrides,
 
3952
 
 
3953
    * the 'DEFAULT' section in bazaar.conf
 
3954
 
 
3955
    This stack will use the ``DEFAULT`` section in bazaar.conf as its
 
3956
    MutableSection.
 
3957
    """
2805
3958
 
2806
3959
    def __init__(self):
2807
 
        # Get a GlobalStore
2808
 
        gstore = GlobalStore()
2809
 
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
2810
 
 
2811
 
 
2812
 
class LocationStack(_CompatibleStack):
 
3960
        gstore = self.get_shared_store(GlobalStore())
 
3961
        super(GlobalStack, self).__init__(
 
3962
            [self._get_overrides,
 
3963
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
3964
            gstore, mutable_section_id='DEFAULT')
 
3965
 
 
3966
 
 
3967
class LocationStack(Stack):
 
3968
    """Per-location options falling back to global options stack.
 
3969
 
 
3970
 
 
3971
    The following sections are queried:
 
3972
 
 
3973
    * command-line overrides,
 
3974
 
 
3975
    * the sections matching ``location`` in ``locations.conf``, the order being
 
3976
      defined by the number of path components in the section glob, higher
 
3977
      numbers first (from most specific section to most generic).
 
3978
 
 
3979
    * the 'DEFAULT' section in bazaar.conf
 
3980
 
 
3981
    This stack will use the ``location`` section in locations.conf as its
 
3982
    MutableSection.
 
3983
    """
2813
3984
 
2814
3985
    def __init__(self, location):
2815
 
        lstore = LocationStore()
2816
 
        matcher = LocationMatcher(lstore, location)
2817
 
        gstore = GlobalStore()
 
3986
        """Make a new stack for a location and global configuration.
 
3987
 
 
3988
        :param location: A URL prefix to """
 
3989
        lstore = self.get_shared_store(LocationStore())
 
3990
        if location.startswith('file://'):
 
3991
            location = urlutils.local_path_from_url(location)
 
3992
        gstore = self.get_shared_store(GlobalStore())
2818
3993
        super(LocationStack, self).__init__(
2819
 
            [matcher.get_sections, gstore.get_sections], lstore)
2820
 
 
2821
 
class BranchStack(_CompatibleStack):
 
3994
            [self._get_overrides,
 
3995
             LocationMatcher(lstore, location).get_sections,
 
3996
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
3997
            lstore, mutable_section_id=location)
 
3998
 
 
3999
 
 
4000
class BranchStack(Stack):
 
4001
    """Per-location options falling back to branch then global options stack.
 
4002
 
 
4003
    The following sections are queried:
 
4004
 
 
4005
    * command-line overrides,
 
4006
 
 
4007
    * the sections matching ``location`` in ``locations.conf``, the order being
 
4008
      defined by the number of path components in the section glob, higher
 
4009
      numbers first (from most specific section to most generic),
 
4010
 
 
4011
    * the no-name section in branch.conf,
 
4012
 
 
4013
    * the ``DEFAULT`` section in ``bazaar.conf``.
 
4014
 
 
4015
    This stack will use the no-name section in ``branch.conf`` as its
 
4016
    MutableSection.
 
4017
    """
2822
4018
 
2823
4019
    def __init__(self, branch):
2824
 
        bstore = BranchStore(branch)
2825
 
        lstore = LocationStore()
2826
 
        matcher = LocationMatcher(lstore, branch.base)
2827
 
        gstore = GlobalStore()
 
4020
        lstore = self.get_shared_store(LocationStore())
 
4021
        bstore = branch._get_config_store()
 
4022
        gstore = self.get_shared_store(GlobalStore())
2828
4023
        super(BranchStack, self).__init__(
2829
 
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
2830
 
            bstore)
2831
 
        self.branch = branch
 
4024
            [self._get_overrides,
 
4025
             LocationMatcher(lstore, branch.base).get_sections,
 
4026
             NameMatcher(bstore, None).get_sections,
 
4027
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
4028
            bstore)
 
4029
        self.branch = branch
 
4030
 
 
4031
    def lock_write(self, token=None):
 
4032
        return self.branch.lock_write(token)
 
4033
 
 
4034
    def unlock(self):
 
4035
        return self.branch.unlock()
 
4036
 
 
4037
    @needs_write_lock
 
4038
    def set(self, name, value):
 
4039
        super(BranchStack, self).set(name, value)
 
4040
        # Unlocking the branch will trigger a store.save_changes() so the last
 
4041
        # unlock saves all the changes.
 
4042
 
 
4043
    @needs_write_lock
 
4044
    def remove(self, name):
 
4045
        super(BranchStack, self).remove(name)
 
4046
        # Unlocking the branch will trigger a store.save_changes() so the last
 
4047
        # unlock saves all the changes.
 
4048
 
 
4049
 
 
4050
class RemoteControlStack(Stack):
 
4051
    """Remote control-only options stack."""
 
4052
 
 
4053
    # FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
 
4054
    # with the stack used for remote bzr dirs. RemoteControlStack only uses
 
4055
    # control.conf and is used only for stack options.
 
4056
 
 
4057
    def __init__(self, bzrdir):
 
4058
        cstore = bzrdir._get_config_store()
 
4059
        super(RemoteControlStack, self).__init__(
 
4060
            [NameMatcher(cstore, None).get_sections],
 
4061
            cstore)
 
4062
        self.bzrdir = bzrdir
 
4063
 
 
4064
 
 
4065
class BranchOnlyStack(Stack):
 
4066
    """Branch-only options stack."""
 
4067
 
 
4068
    # FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
 
4069
    # stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
 
4070
    # -- vila 2011-12-16
 
4071
 
 
4072
    def __init__(self, branch):
 
4073
        bstore = branch._get_config_store()
 
4074
        super(BranchOnlyStack, self).__init__(
 
4075
            [NameMatcher(bstore, None).get_sections],
 
4076
            bstore)
 
4077
        self.branch = branch
 
4078
 
 
4079
    def lock_write(self, token=None):
 
4080
        return self.branch.lock_write(token)
 
4081
 
 
4082
    def unlock(self):
 
4083
        return self.branch.unlock()
 
4084
 
 
4085
    @needs_write_lock
 
4086
    def set(self, name, value):
 
4087
        super(BranchOnlyStack, self).set(name, value)
 
4088
        # Force a write to persistent storage
 
4089
        self.store.save_changes()
 
4090
 
 
4091
    @needs_write_lock
 
4092
    def remove(self, name):
 
4093
        super(BranchOnlyStack, self).remove(name)
 
4094
        # Force a write to persistent storage
 
4095
        self.store.save_changes()
2832
4096
 
2833
4097
 
2834
4098
class cmd_config(commands.Command):
2835
4099
    __doc__ = """Display, set or remove a configuration option.
2836
4100
 
2837
 
    Display the active value for a given option.
 
4101
    Display the active value for option NAME.
2838
4102
 
2839
4103
    If --all is specified, NAME is interpreted as a regular expression and all
2840
 
    matching options are displayed mentioning their scope. The active value
2841
 
    that bzr will take into account is the first one displayed for each option.
2842
 
 
2843
 
    If no NAME is given, --all .* is implied.
2844
 
 
2845
 
    Setting a value is achieved by using name=value without spaces. The value
 
4104
    matching options are displayed mentioning their scope and without resolving
 
4105
    option references in the value). The active value that bzr will take into
 
4106
    account is the first one displayed for each option.
 
4107
 
 
4108
    If NAME is not given, --all .* is implied (all options are displayed for the
 
4109
    current scope).
 
4110
 
 
4111
    Setting a value is achieved by using NAME=value without spaces. The value
2846
4112
    is set in the most relevant scope and can be checked by displaying the
2847
4113
    option again.
 
4114
 
 
4115
    Removing a value is achieved by using --remove NAME.
2848
4116
    """
2849
4117
 
2850
4118
    takes_args = ['name?']
2852
4120
    takes_options = [
2853
4121
        'directory',
2854
4122
        # FIXME: This should be a registry option so that plugins can register
2855
 
        # their own config files (or not) -- vila 20101002
 
4123
        # their own config files (or not) and will also address
 
4124
        # http://pad.lv/788991 -- vila 20101115
2856
4125
        commands.Option('scope', help='Reduce the scope to the specified'
2857
 
                        ' configuration file',
 
4126
                        ' configuration file.',
2858
4127
                        type=unicode),
2859
4128
        commands.Option('all',
2860
4129
            help='Display all the defined values for the matching options.',
2861
4130
            ),
2862
4131
        commands.Option('remove', help='Remove the option from'
2863
 
                        ' the configuration file'),
 
4132
                        ' the configuration file.'),
2864
4133
        ]
2865
4134
 
2866
4135
    _see_also = ['configuration']
2870
4139
            remove=False):
2871
4140
        if directory is None:
2872
4141
            directory = '.'
 
4142
        directory = directory_service.directories.dereference(directory)
2873
4143
        directory = urlutils.normalize_url(directory)
2874
4144
        if remove and all:
2875
4145
            raise errors.BzrError(
2896
4166
                # Set the option value
2897
4167
                self._set_config_option(name, value, directory, scope)
2898
4168
 
2899
 
    def _get_configs(self, directory, scope=None):
2900
 
        """Iterate the configurations specified by ``directory`` and ``scope``.
 
4169
    def _get_stack(self, directory, scope=None, write_access=False):
 
4170
        """Get the configuration stack specified by ``directory`` and ``scope``.
2901
4171
 
2902
4172
        :param directory: Where the configurations are derived from.
2903
4173
 
2904
4174
        :param scope: A specific config to start from.
 
4175
 
 
4176
        :param write_access: Whether a write access to the stack will be
 
4177
            attempted.
2905
4178
        """
 
4179
        # FIXME: scope should allow access to plugin-specific stacks (even
 
4180
        # reduced to the plugin-specific store), related to
 
4181
        # http://pad.lv/788991 -- vila 2011-11-15
2906
4182
        if scope is not None:
2907
4183
            if scope == 'bazaar':
2908
 
                yield GlobalConfig()
 
4184
                return GlobalStack()
2909
4185
            elif scope == 'locations':
2910
 
                yield LocationConfig(directory)
 
4186
                return LocationStack(directory)
2911
4187
            elif scope == 'branch':
2912
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2913
 
                    directory)
2914
 
                yield br.get_config()
 
4188
                (_, br, _) = (
 
4189
                    controldir.ControlDir.open_containing_tree_or_branch(
 
4190
                        directory))
 
4191
                if write_access:
 
4192
                    self.add_cleanup(br.lock_write().unlock)
 
4193
                return br.get_config_stack()
 
4194
            raise errors.NoSuchConfig(scope)
2915
4195
        else:
2916
4196
            try:
2917
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2918
 
                    directory)
2919
 
                yield br.get_config()
 
4197
                (_, br, _) = (
 
4198
                    controldir.ControlDir.open_containing_tree_or_branch(
 
4199
                        directory))
 
4200
                if write_access:
 
4201
                    self.add_cleanup(br.lock_write().unlock)
 
4202
                return br.get_config_stack()
2920
4203
            except errors.NotBranchError:
2921
 
                yield LocationConfig(directory)
2922
 
                yield GlobalConfig()
 
4204
                return LocationStack(directory)
 
4205
 
 
4206
    def _quote_multiline(self, value):
 
4207
        if '\n' in value:
 
4208
            value = '"""' + value + '"""'
 
4209
        return value
2923
4210
 
2924
4211
    def _show_value(self, name, directory, scope):
2925
 
        displayed = False
2926
 
        for c in self._get_configs(directory, scope):
2927
 
            if displayed:
2928
 
                break
2929
 
            for (oname, value, section, conf_id, parser) in c._get_options():
2930
 
                if name == oname:
2931
 
                    # Display only the first value and exit
2932
 
 
2933
 
                    # FIXME: We need to use get_user_option to take policies
2934
 
                    # into account and we need to make sure the option exists
2935
 
                    # too (hence the two for loops), this needs a better API
2936
 
                    # -- vila 20101117
2937
 
                    value = c.get_user_option(name)
2938
 
                    # Quote the value appropriately
2939
 
                    value = parser._quote(value)
2940
 
                    self.outf.write('%s\n' % (value,))
2941
 
                    displayed = True
2942
 
                    break
2943
 
        if not displayed:
 
4212
        conf = self._get_stack(directory, scope)
 
4213
        value = conf.get(name, expand=True, convert=False)
 
4214
        if value is not None:
 
4215
            # Quote the value appropriately
 
4216
            value = self._quote_multiline(value)
 
4217
            self.outf.write('%s\n' % (value,))
 
4218
        else:
2944
4219
            raise errors.NoSuchConfigOption(name)
2945
4220
 
2946
4221
    def _show_matching_options(self, name, directory, scope):
2949
4224
        # avoid the delay introduced by the lazy regexp.  But, we still do
2950
4225
        # want the nicer errors raised by lazy_regex.
2951
4226
        name._compile_and_collapse()
2952
 
        cur_conf_id = None
 
4227
        cur_store_id = None
2953
4228
        cur_section = None
2954
 
        for c in self._get_configs(directory, scope):
2955
 
            for (oname, value, section, conf_id, parser) in c._get_options():
 
4229
        conf = self._get_stack(directory, scope)
 
4230
        for store, section in conf.iter_sections():
 
4231
            for oname in section.iter_option_names():
2956
4232
                if name.search(oname):
2957
 
                    if cur_conf_id != conf_id:
 
4233
                    if cur_store_id != store.id:
2958
4234
                        # Explain where the options are defined
2959
 
                        self.outf.write('%s:\n' % (conf_id,))
2960
 
                        cur_conf_id = conf_id
 
4235
                        self.outf.write('%s:\n' % (store.id,))
 
4236
                        cur_store_id = store.id
2961
4237
                        cur_section = None
2962
 
                    if (section not in (None, 'DEFAULT')
2963
 
                        and cur_section != section):
2964
 
                        # Display the section if it's not the default (or only)
2965
 
                        # one.
2966
 
                        self.outf.write('  [%s]\n' % (section,))
2967
 
                        cur_section = section
 
4238
                    if (section.id is not None and cur_section != section.id):
 
4239
                        # Display the section id as it appears in the store
 
4240
                        # (None doesn't appear by definition)
 
4241
                        self.outf.write('  [%s]\n' % (section.id,))
 
4242
                        cur_section = section.id
 
4243
                    value = section.get(oname, expand=False)
 
4244
                    # Quote the value appropriately
 
4245
                    value = self._quote_multiline(value)
2968
4246
                    self.outf.write('  %s = %s\n' % (oname, value))
2969
4247
 
2970
4248
    def _set_config_option(self, name, value, directory, scope):
2971
 
        for conf in self._get_configs(directory, scope):
2972
 
            conf.set_user_option(name, value)
2973
 
            break
2974
 
        else:
2975
 
            raise errors.NoSuchConfig(scope)
 
4249
        conf = self._get_stack(directory, scope, write_access=True)
 
4250
        conf.set(name, value)
2976
4251
 
2977
4252
    def _remove_config_option(self, name, directory, scope):
2978
4253
        if name is None:
2979
4254
            raise errors.BzrCommandError(
2980
4255
                '--remove expects an option to remove.')
2981
 
        removed = False
2982
 
        for conf in self._get_configs(directory, scope):
2983
 
            for (section_name, section, conf_id) in conf._get_sections():
2984
 
                if scope is not None and conf_id != scope:
2985
 
                    # Not the right configuration file
2986
 
                    continue
2987
 
                if name in section:
2988
 
                    if conf_id != conf.config_id():
2989
 
                        conf = self._get_configs(directory, conf_id).next()
2990
 
                    # We use the first section in the first config where the
2991
 
                    # option is defined to remove it
2992
 
                    conf.remove_user_option(name, section_name)
2993
 
                    removed = True
2994
 
                    break
2995
 
            break
2996
 
        else:
2997
 
            raise errors.NoSuchConfig(scope)
2998
 
        if not removed:
 
4256
        conf = self._get_stack(directory, scope, write_access=True)
 
4257
        try:
 
4258
            conf.remove(name)
 
4259
        except KeyError:
2999
4260
            raise errors.NoSuchConfigOption(name)
3000
4261
 
 
4262
 
3001
4263
# Test registries
3002
4264
#
3003
4265
# We need adapters that can build a Store or a Stack in a test context. Test
3006
4268
# ready-to-use store or stack.  Plugins that define new store/stacks can also
3007
4269
# register themselves here to be tested against the tests defined in
3008
4270
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3009
 
# for the same tests.
 
4271
# for the same test.
3010
4272
 
3011
4273
# The registered object should be a callable receiving a test instance
3012
4274
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store