~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

(gz) Fix deprecations of win32utils path function unicode wrappers (Martin
 Packman)

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
71
72
up=pull
72
73
"""
73
74
 
 
75
from __future__ import absolute_import
 
76
 
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(), """
85
87
 
86
88
from bzrlib import (
87
89
    atomicfile,
88
 
    bzrdir,
 
90
    controldir,
89
91
    debug,
90
92
    errors,
91
93
    lazy_regex,
 
94
    library_state,
92
95
    lockdir,
93
96
    mail_client,
94
97
    mergetools,
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):
171
200
# FIXME: Until we can guarantee that each config file is loaded once and
172
201
# only once for a given bzrlib session, we don't want to re-read the file every
173
202
# 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
 
203
# needing to restore the proper value). -- vila 20110219
177
204
_expand_default_value = None
178
205
def _get_expand_default_value():
179
206
    global _expand_default_value
415
442
            l = [l]
416
443
        return l
417
444
 
 
445
    @deprecated_method(deprecated_in((2, 5, 0)))
 
446
    def get_user_option_as_int_from_SI(self, option_name, default=None):
 
447
        """Get a generic option from a human readable size in SI units, e.g 10MB
 
448
 
 
449
        Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
450
        by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
451
        pedantic.
 
452
 
 
453
        :return Integer, expanded to its base-10 value if a proper SI unit is 
 
454
            found. If the option doesn't exist, or isn't a value in 
 
455
            SI units, return default (which defaults to None)
 
456
        """
 
457
        val = self.get_user_option(option_name)
 
458
        if isinstance(val, list):
 
459
            val = val[0]
 
460
        if val is None:
 
461
            val = default
 
462
        else:
 
463
            p = re.compile("^(\d+)([kmg])*b*$", re.IGNORECASE)
 
464
            try:
 
465
                m = p.match(val)
 
466
                if m is not None:
 
467
                    val = int(m.group(1))
 
468
                    if m.group(2) is not None:
 
469
                        if m.group(2).lower() == 'k':
 
470
                            val *= 10**3
 
471
                        elif m.group(2).lower() == 'm':
 
472
                            val *= 10**6
 
473
                        elif m.group(2).lower() == 'g':
 
474
                            val *= 10**9
 
475
                else:
 
476
                    ui.ui_factory.show_warning(gettext('Invalid config value for "{0}" '
 
477
                                               ' value {1!r} is not an SI unit.').format(
 
478
                                                option_name, val))
 
479
                    val = default
 
480
            except TypeError:
 
481
                val = default
 
482
        return val
 
483
 
 
484
    @deprecated_method(deprecated_in((2, 5, 0)))
418
485
    def gpg_signing_command(self):
419
486
        """What program should be used to sign signatures?"""
420
487
        result = self._gpg_signing_command()
426
493
        """See gpg_signing_command()."""
427
494
        return None
428
495
 
 
496
    @deprecated_method(deprecated_in((2, 5, 0)))
429
497
    def log_format(self):
430
498
        """What log format should be used"""
431
499
        result = self._log_format()
450
518
        """See validate_signatures_in_log()."""
451
519
        return None
452
520
 
 
521
    @deprecated_method(deprecated_in((2, 5, 0)))
453
522
    def acceptable_keys(self):
454
523
        """Comma separated list of key patterns acceptable to 
455
524
        verify-signatures command"""
460
529
        """See acceptable_keys()."""
461
530
        return None
462
531
 
 
532
    @deprecated_method(deprecated_in((2, 5, 0)))
463
533
    def post_commit(self):
464
534
        """An ordered list of python functions to call.
465
535
 
491
561
        v = self._get_user_id()
492
562
        if v:
493
563
            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()
 
564
        return default_email()
503
565
 
504
566
    def ensure_username(self):
505
567
        """Raise errors.NoWhoami if username is not set.
508
570
        """
509
571
        self.username()
510
572
 
 
573
    @deprecated_method(deprecated_in((2, 5, 0)))
511
574
    def signature_checking(self):
512
575
        """What is the current policy for signature checking?."""
513
576
        policy = self._get_signature_checking()
515
578
            return policy
516
579
        return CHECK_IF_POSSIBLE
517
580
 
 
581
    @deprecated_method(deprecated_in((2, 5, 0)))
518
582
    def signing_policy(self):
519
583
        """What is the current policy for signature checking?."""
520
584
        policy = self._get_signing_policy()
522
586
            return policy
523
587
        return SIGN_WHEN_REQUIRED
524
588
 
 
589
    @deprecated_method(deprecated_in((2, 5, 0)))
525
590
    def signature_needed(self):
526
591
        """Is a signature needed when committing ?."""
527
592
        policy = self._get_signing_policy()
536
601
            return True
537
602
        return False
538
603
 
 
604
    @deprecated_method(deprecated_in((2, 5, 0)))
 
605
    def gpg_signing_key(self):
 
606
        """GPG user-id to sign commits"""
 
607
        key = self.get_user_option('gpg_signing_key')
 
608
        if key == "default" or key == None:
 
609
            return self.user_email()
 
610
        else:
 
611
            return key
 
612
 
539
613
    def get_alias(self, value):
540
614
        return self._get_alias(value)
541
615
 
575
649
        for (oname, value, section, conf_id, parser) in self._get_options():
576
650
            if oname.startswith('bzr.mergetool.'):
577
651
                tool_name = oname[len('bzr.mergetool.'):]
578
 
                tools[tool_name] = value
 
652
                tools[tool_name] = self.get_user_option(oname)
579
653
        trace.mutter('loaded merge tools: %r' % tools)
580
654
        return tools
581
655
 
818
892
        """See Config._get_signature_checking."""
819
893
        policy = self._get_user_option('check_signatures')
820
894
        if policy:
821
 
            return self._string_to_signature_policy(policy)
 
895
            return signature_policy_from_unicode(policy)
822
896
 
823
897
    def _get_signing_policy(self):
824
898
        """See Config._get_signing_policy"""
825
899
        policy = self._get_user_option('create_signatures')
826
900
        if policy:
827
 
            return self._string_to_signing_policy(policy)
 
901
            return signing_policy_from_unicode(policy)
828
902
 
829
903
    def _get_user_id(self):
830
904
        """Get the user id from the 'email' key in the current section."""
875
949
        """See Config.post_commit."""
876
950
        return self._get_user_option('post_commit')
877
951
 
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
952
    def _get_alias(self, value):
901
953
        try:
902
954
            return self._get_parser().get_value("ALIASES",
978
1030
        # local transports are not shared. But if/when we start using
979
1031
        # LockableConfig for other kind of transports, we will need to reuse
980
1032
        # whatever connection is already established -- vila 20100929
981
 
        self.transport = transport.get_transport(self.dir)
 
1033
        self.transport = transport.get_transport_from_path(self.dir)
982
1034
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
983
1035
 
984
1036
    def _create_from_string(self, unicode_bytes, save):
1346
1398
        e.g. "John Hacker <jhacker@example.com>"
1347
1399
        This is looked up in the email controlfile for the branch.
1348
1400
        """
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
1401
        return self._get_best_value('_get_user_id')
1357
1402
 
1358
1403
    def _get_change_editor(self):
1504
1549
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1505
1550
                                  ' or HOME set')
1506
1551
        return osutils.pathjoin(base, 'bazaar', '2.0')
1507
 
    elif sys.platform == 'darwin':
 
1552
    else:
 
1553
        if base is not None:
 
1554
            base = base.decode(osutils._fs_enc)
 
1555
    if sys.platform == 'darwin':
1508
1556
        if base is None:
1509
1557
            # this takes into account $HOME
1510
1558
            base = os.path.expanduser("~")
1511
1559
        return osutils.pathjoin(base, '.bazaar')
1512
1560
    else:
1513
1561
        if base is None:
1514
 
 
1515
1562
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
1516
1563
            if xdg_dir is None:
1517
1564
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
1520
1567
                trace.mutter(
1521
1568
                    "Using configuration in XDG directory %s." % xdg_dir)
1522
1569
                return xdg_dir
1523
 
 
1524
1570
            base = os.path.expanduser("~")
1525
1571
        return osutils.pathjoin(base, ".bazaar")
1526
1572
 
1591
1637
        f.close()
1592
1638
 
1593
1639
 
 
1640
def default_email():
 
1641
    v = os.environ.get('BZR_EMAIL')
 
1642
    if v:
 
1643
        return v.decode(osutils.get_user_encoding())
 
1644
    v = os.environ.get('EMAIL')
 
1645
    if v:
 
1646
        return v.decode(osutils.get_user_encoding())
 
1647
    name, email = _auto_user_id()
 
1648
    if name and email:
 
1649
        return u'%s <%s>' % (name, email)
 
1650
    elif email:
 
1651
        return email
 
1652
    raise errors.NoWhoami()
 
1653
 
 
1654
 
 
1655
def email_from_store(unicode_str):
 
1656
    """Unlike other env vars, BZR_EMAIL takes precedence over config settings.
 
1657
 
 
1658
    Whatever comes from a config file is then overridden.
 
1659
    """
 
1660
    value = os.environ.get('BZR_EMAIL')
 
1661
    if value:
 
1662
        return value.decode(osutils.get_user_encoding())
 
1663
    return unicode_str
 
1664
 
 
1665
 
1594
1666
def _auto_user_id():
1595
1667
    """Calculate automatic user identification.
1596
1668
 
1785
1857
        :param user: login (optional)
1786
1858
 
1787
1859
        :param path: the absolute path on the server (optional)
1788
 
        
 
1860
 
1789
1861
        :param realm: the http authentication realm (optional)
1790
1862
 
1791
1863
        :return: A dict containing the matching credentials or None.
2230
2302
            return f
2231
2303
        except errors.NoSuchFile:
2232
2304
            return StringIO()
 
2305
        except errors.PermissionDenied, e:
 
2306
            trace.warning("Permission denied while trying to open "
 
2307
                "configuration file %s.", urlutils.unescape_for_display(
 
2308
                urlutils.join(self._transport.base, self._filename), "utf-8"))
 
2309
            return StringIO()
2233
2310
 
2234
2311
    def _external_url(self):
2235
2312
        return urlutils.join(self._transport.external_url(), self._filename)
2262
2339
    The option *values* are stored in config files and found in sections.
2263
2340
 
2264
2341
    Here we define various properties about the option itself, its default
2265
 
    value, in which config files it can be stored, etc (TBC).
 
2342
    value, how to convert it from stores, what to do when invalid values are
 
2343
    encoutered, in which config files it can be stored.
2266
2344
    """
2267
2345
 
2268
 
    def __init__(self, name, default=None):
 
2346
    def __init__(self, name, default=None, default_from_env=None,
 
2347
                 help=None, from_unicode=None, invalid=None):
 
2348
        """Build an option definition.
 
2349
 
 
2350
        :param name: the name used to refer to the option.
 
2351
 
 
2352
        :param default: the default value to use when none exist in the config
 
2353
            stores. This is either a string that ``from_unicode`` will convert
 
2354
            into the proper type, a callable returning a unicode string so that
 
2355
            ``from_unicode`` can be used on the return value, or a python
 
2356
            object that can be stringified (so only the empty list is supported
 
2357
            for example).
 
2358
 
 
2359
        :param default_from_env: A list of environment variables which can
 
2360
           provide a default value. 'default' will be used only if none of the
 
2361
           variables specified here are set in the environment.
 
2362
 
 
2363
        :param help: a doc string to explain the option to the user.
 
2364
 
 
2365
        :param from_unicode: a callable to convert the unicode string
 
2366
            representing the option value in a store. This is not called for
 
2367
            the default value.
 
2368
 
 
2369
        :param invalid: the action to be taken when an invalid value is
 
2370
            encountered in a store. This is called only when from_unicode is
 
2371
            invoked to convert a string and returns None or raise ValueError or
 
2372
            TypeError. Accepted values are: None (ignore invalid values),
 
2373
            'warning' (emit a warning), 'error' (emit an error message and
 
2374
            terminates).
 
2375
        """
 
2376
        if default_from_env is None:
 
2377
            default_from_env = []
2269
2378
        self.name = name
2270
 
        self.default = default
 
2379
        # Convert the default value to a unicode string so all values are
 
2380
        # strings internally before conversion (via from_unicode) is attempted.
 
2381
        if default is None:
 
2382
            self.default = None
 
2383
        elif isinstance(default, list):
 
2384
            # Only the empty list is supported
 
2385
            if default:
 
2386
                raise AssertionError(
 
2387
                    'Only empty lists are supported as default values')
 
2388
            self.default = u','
 
2389
        elif isinstance(default, (str, unicode, bool, int, float)):
 
2390
            # Rely on python to convert strings, booleans and integers
 
2391
            self.default = u'%s' % (default,)
 
2392
        elif callable(default):
 
2393
            self.default = default
 
2394
        else:
 
2395
            # other python objects are not expected
 
2396
            raise AssertionError('%r is not supported as a default value'
 
2397
                                 % (default,))
 
2398
        self.default_from_env = default_from_env
 
2399
        self.help = help
 
2400
        self.from_unicode = from_unicode
 
2401
        if invalid and invalid not in ('warning', 'error'):
 
2402
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
 
2403
        self.invalid = invalid
 
2404
 
 
2405
    def convert_from_unicode(self, unicode_value):
 
2406
        if self.from_unicode is None or unicode_value is None:
 
2407
            # Don't convert or nothing to convert
 
2408
            return unicode_value
 
2409
        try:
 
2410
            converted = self.from_unicode(unicode_value)
 
2411
        except (ValueError, TypeError):
 
2412
            # Invalid values are ignored
 
2413
            converted = None
 
2414
        if converted is None and self.invalid is not None:
 
2415
            # The conversion failed
 
2416
            if self.invalid == 'warning':
 
2417
                trace.warning('Value "%s" is not valid for "%s"',
 
2418
                              unicode_value, self.name)
 
2419
            elif self.invalid == 'error':
 
2420
                raise errors.ConfigOptionValueError(self.name, unicode_value)
 
2421
        return converted
2271
2422
 
2272
2423
    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.')
 
2424
        value = None
 
2425
        for var in self.default_from_env:
 
2426
            try:
 
2427
                # If the env variable is defined, its value is the default one
 
2428
                value = os.environ[var].decode(osutils.get_user_encoding())
 
2429
                break
 
2430
            except KeyError:
 
2431
                continue
 
2432
        if value is None:
 
2433
            # Otherwise, fallback to the value defined at registration
 
2434
            if callable(self.default):
 
2435
                value = self.default()
 
2436
                if not isinstance(value, unicode):
 
2437
                    raise AssertionError(
 
2438
                    'Callable default values should be unicode')
 
2439
            else:
 
2440
                value = self.default
 
2441
        return value
 
2442
 
 
2443
    def get_help_text(self, additional_see_also=None, plain=True):
 
2444
        result = self.help
 
2445
        from bzrlib import help_topics
 
2446
        result += help_topics._format_see_also(additional_see_also)
 
2447
        if plain:
 
2448
            result = help_topics.help_as_plain_text(result)
 
2449
        return result
 
2450
 
 
2451
 
 
2452
# Predefined converters to get proper values from store
 
2453
 
 
2454
def bool_from_store(unicode_str):
 
2455
    return ui.bool_from_string(unicode_str)
 
2456
 
 
2457
 
 
2458
def int_from_store(unicode_str):
 
2459
    return int(unicode_str)
 
2460
 
 
2461
 
 
2462
_unit_sfxs = dict(K=10**3, M=10**6, G=10**9)
 
2463
 
 
2464
def int_SI_from_store(unicode_str):
 
2465
    """Convert a human readable size in SI units, e.g 10MB into an integer.
 
2466
 
 
2467
    Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
2468
    by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
2469
    pedantic.
 
2470
 
 
2471
    :return Integer, expanded to its base-10 value if a proper SI unit is 
 
2472
        found, None otherwise.
 
2473
    """
 
2474
    regexp = "^(\d+)(([" + ''.join(_unit_sfxs) + "])b?)?$"
 
2475
    p = re.compile(regexp, re.IGNORECASE)
 
2476
    m = p.match(unicode_str)
 
2477
    val = None
 
2478
    if m is not None:
 
2479
        val, _, unit = m.groups()
 
2480
        val = int(val)
 
2481
        if unit:
 
2482
            try:
 
2483
                coeff = _unit_sfxs[unit.upper()]
 
2484
            except KeyError:
 
2485
                raise ValueError(gettext('{0} is not an SI unit.').format(unit))
 
2486
            val *= coeff
 
2487
    return val
 
2488
 
 
2489
 
 
2490
def float_from_store(unicode_str):
 
2491
    return float(unicode_str)
 
2492
 
 
2493
 
 
2494
# Use a an empty dict to initialize an empty configobj avoiding all
 
2495
# parsing and encoding checks
 
2496
_list_converter_config = configobj.ConfigObj(
 
2497
    {}, encoding='utf-8', list_values=True, interpolation=False)
 
2498
 
 
2499
 
 
2500
def list_from_store(unicode_str):
 
2501
    if not isinstance(unicode_str, basestring):
 
2502
        raise TypeError
 
2503
    # Now inject our string directly as unicode. All callers got their value
 
2504
    # from configobj, so values that need to be quoted are already properly
 
2505
    # quoted.
 
2506
    _list_converter_config.reset()
 
2507
    _list_converter_config._parse([u"list=%s" % (unicode_str,)])
 
2508
    maybe_list = _list_converter_config['list']
 
2509
    # ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
 
2510
    if isinstance(maybe_list, basestring):
 
2511
        if maybe_list:
 
2512
            # A single value, most probably the user forgot (or didn't care to
 
2513
            # add) the final ','
 
2514
            l = [maybe_list]
 
2515
        else:
 
2516
            # The empty string, convert to empty list
 
2517
            l = []
 
2518
    else:
 
2519
        # We rely on ConfigObj providing us with a list already
 
2520
        l = maybe_list
 
2521
    return l
 
2522
 
 
2523
 
 
2524
class OptionRegistry(registry.Registry):
 
2525
    """Register config options by their name.
 
2526
 
 
2527
    This overrides ``registry.Registry`` to simplify registration by acquiring
 
2528
    some information from the option object itself.
 
2529
    """
 
2530
 
 
2531
    def register(self, option):
 
2532
        """Register a new option to its name.
 
2533
 
 
2534
        :param option: The option to register. Its name is used as the key.
 
2535
        """
 
2536
        super(OptionRegistry, self).register(option.name, option,
 
2537
                                             help=option.help)
 
2538
 
 
2539
    def register_lazy(self, key, module_name, member_name):
 
2540
        """Register a new option to be loaded on request.
 
2541
 
 
2542
        :param key: the key to request the option later. Since the registration
 
2543
            is lazy, it should be provided and match the option name.
 
2544
 
 
2545
        :param module_name: the python path to the module. Such as 'os.path'.
 
2546
 
 
2547
        :param member_name: the member of the module to return.  If empty or 
 
2548
                None, get() will return the module itself.
 
2549
        """
 
2550
        super(OptionRegistry, self).register_lazy(key,
 
2551
                                                  module_name, member_name)
 
2552
 
 
2553
    def get_help(self, key=None):
 
2554
        """Get the help text associated with the given key"""
 
2555
        option = self.get(key)
 
2556
        the_help = option.help
 
2557
        if callable(the_help):
 
2558
            return the_help(self, key)
 
2559
        return the_help
 
2560
 
 
2561
 
 
2562
option_registry = OptionRegistry()
 
2563
 
 
2564
 
 
2565
# Registered options in lexicographical order
 
2566
 
 
2567
option_registry.register(
 
2568
    Option('append_revisions_only',
 
2569
           default=None, from_unicode=bool_from_store, invalid='warning',
 
2570
           help='''\
 
2571
Whether to only append revisions to the mainline.
 
2572
 
 
2573
If this is set to true, then it is not possible to change the
 
2574
existing mainline of the branch.
 
2575
'''))
 
2576
option_registry.register(
 
2577
    Option('acceptable_keys',
 
2578
           default=None, from_unicode=list_from_store,
 
2579
           help="""\
 
2580
List of GPG key patterns which are acceptable for verification.
 
2581
"""))
 
2582
option_registry.register(
 
2583
    Option('add.maximum_file_size',
 
2584
           default=u'20MB', from_unicode=int_SI_from_store,
 
2585
           help="""\
 
2586
Size above which files should be added manually.
 
2587
 
 
2588
Files below this size are added automatically when using ``bzr add`` without
 
2589
arguments.
 
2590
 
 
2591
A negative value means disable the size check.
 
2592
"""))
 
2593
option_registry.register(
 
2594
    Option('bzr.workingtree.worth_saving_limit', default=10,
 
2595
           from_unicode=int_from_store,  invalid='warning',
 
2596
           help='''\
 
2597
How many changes before saving the dirstate.
 
2598
 
 
2599
-1 means that we will never rewrite the dirstate file for only
 
2600
stat-cache changes. Regardless of this setting, we will always rewrite
 
2601
the dirstate file if a file is added/removed/renamed/etc. This flag only
 
2602
affects the behavior of updating the dirstate file after we notice that
 
2603
a file has been touched.
 
2604
'''))
 
2605
option_registry.register(
 
2606
    Option('check_signatures', default=CHECK_IF_POSSIBLE,
 
2607
           from_unicode=signature_policy_from_unicode,
 
2608
           help='''\
 
2609
GPG checking policy.
 
2610
 
 
2611
Possible values: require, ignore, check-available (default)
 
2612
 
 
2613
this option will control whether bzr will require good gpg
 
2614
signatures, ignore them, or check them if they are
 
2615
present.
 
2616
'''))
 
2617
option_registry.register(
 
2618
    Option('create_signatures', default=SIGN_WHEN_REQUIRED,
 
2619
           from_unicode=signing_policy_from_unicode,
 
2620
           help='''\
 
2621
GPG Signing policy.
 
2622
 
 
2623
Possible values: always, never, when-required (default)
 
2624
 
 
2625
This option controls whether bzr will always create
 
2626
gpg signatures or not on commits.
 
2627
'''))
 
2628
option_registry.register(
 
2629
    Option('dirstate.fdatasync', default=True,
 
2630
           from_unicode=bool_from_store,
 
2631
           help='''\
 
2632
Flush dirstate changes onto physical disk?
 
2633
 
 
2634
If true (default), working tree metadata changes are flushed through the
 
2635
OS buffers to physical disk.  This is somewhat slower, but means data
 
2636
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2637
'''))
 
2638
option_registry.register(
 
2639
    Option('debug_flags', default=[], from_unicode=list_from_store,
 
2640
           help='Debug flags to activate.'))
 
2641
option_registry.register(
 
2642
    Option('default_format', default='2a',
 
2643
           help='Format used when creating branches.'))
 
2644
option_registry.register(
 
2645
    Option('dpush_strict', default=None,
 
2646
           from_unicode=bool_from_store,
 
2647
           help='''\
 
2648
The default value for ``dpush --strict``.
 
2649
 
 
2650
If present, defines the ``--strict`` option default value for checking
 
2651
uncommitted changes before pushing into a different VCS without any
 
2652
custom bzr metadata.
 
2653
'''))
 
2654
option_registry.register(
 
2655
    Option('editor',
 
2656
           help='The command called to launch an editor to enter a message.'))
 
2657
option_registry.register(
 
2658
    Option('email', default=default_email,
 
2659
           from_unicode=email_from_store,
 
2660
           help='The users identity'))
 
2661
option_registry.register(
 
2662
    Option('gpg_signing_command',
 
2663
           default='gpg',
 
2664
           help="""\
 
2665
Program to use use for creating signatures.
 
2666
 
 
2667
This should support at least the -u and --clearsign options.
 
2668
"""))
 
2669
option_registry.register(
 
2670
    Option('gpg_signing_key',
 
2671
           default=None,
 
2672
           help="""\
 
2673
GPG key to use for signing.
 
2674
 
 
2675
This defaults to the first key associated with the users email.
 
2676
"""))
 
2677
option_registry.register(
 
2678
    Option('ignore_missing_extensions', default=False,
 
2679
           from_unicode=bool_from_store,
 
2680
           help='''\
 
2681
Control the missing extensions warning display.
 
2682
 
 
2683
The warning will not be emitted if set to True.
 
2684
'''))
 
2685
option_registry.register(
 
2686
    Option('language',
 
2687
           help='Language to translate messages into.'))
 
2688
option_registry.register(
 
2689
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
 
2690
           help='''\
 
2691
Steal locks that appears to be dead.
 
2692
 
 
2693
If set to True, bzr will check if a lock is supposed to be held by an
 
2694
active process from the same user on the same machine. If the user and
 
2695
machine match, but no process with the given PID is active, then bzr
 
2696
will automatically break the stale lock, and create a new lock for
 
2697
this process.
 
2698
Otherwise, bzr will prompt as normal to break the lock.
 
2699
'''))
 
2700
option_registry.register(
 
2701
    Option('log_format', default='long',
 
2702
           help= '''\
 
2703
Log format to use when displaying revisions.
 
2704
 
 
2705
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
 
2706
may be provided by plugins.
 
2707
'''))
 
2708
option_registry.register(
 
2709
    Option('output_encoding',
 
2710
           help= 'Unicode encoding for output'
 
2711
           ' (terminal encoding if not specified).'))
 
2712
option_registry.register(
 
2713
    Option('post_commit', default=None,
 
2714
           help='''\
 
2715
Post commit functions.
 
2716
 
 
2717
An ordered list of python functions to call, separated by spaces.
 
2718
 
 
2719
Each function takes branch, rev_id as parameters.
 
2720
'''))
 
2721
option_registry.register(
 
2722
    Option('push_strict', default=None,
 
2723
           from_unicode=bool_from_store,
 
2724
           help='''\
 
2725
The default value for ``push --strict``.
 
2726
 
 
2727
If present, defines the ``--strict`` option default value for checking
 
2728
uncommitted changes before sending a merge directive.
 
2729
'''))
 
2730
option_registry.register(
 
2731
    Option('repository.fdatasync', default=True,
 
2732
           from_unicode=bool_from_store,
 
2733
           help='''\
 
2734
Flush repository changes onto physical disk?
 
2735
 
 
2736
If true (default), repository changes are flushed through the OS buffers
 
2737
to physical disk.  This is somewhat slower, but means data should not be
 
2738
lost if the machine crashes.  See also dirstate.fdatasync.
 
2739
'''))
 
2740
option_registry.register_lazy('smtp_server',
 
2741
    'bzrlib.smtp_connection', 'smtp_server')
 
2742
option_registry.register_lazy('smtp_password',
 
2743
    'bzrlib.smtp_connection', 'smtp_password')
 
2744
option_registry.register_lazy('smtp_username',
 
2745
    'bzrlib.smtp_connection', 'smtp_username')
 
2746
option_registry.register(
 
2747
    Option('selftest.timeout',
 
2748
        default='600',
 
2749
        from_unicode=int_from_store,
 
2750
        help='Abort selftest if one test takes longer than this many seconds',
 
2751
        ))
 
2752
 
 
2753
option_registry.register(
 
2754
    Option('send_strict', default=None,
 
2755
           from_unicode=bool_from_store,
 
2756
           help='''\
 
2757
The default value for ``send --strict``.
 
2758
 
 
2759
If present, defines the ``--strict`` option default value for checking
 
2760
uncommitted changes before pushing.
 
2761
'''))
 
2762
 
 
2763
option_registry.register(
 
2764
    Option('serve.client_timeout',
 
2765
           default=300.0, from_unicode=float_from_store,
 
2766
           help="If we wait for a new request from a client for more than"
 
2767
                " X seconds, consider the client idle, and hangup."))
2284
2768
 
2285
2769
 
2286
2770
class Section(object):
2296
2780
        # We re-use the dict-like object received
2297
2781
        self.options = options
2298
2782
 
2299
 
    def get(self, name, default=None):
 
2783
    def get(self, name, default=None, expand=True):
2300
2784
        return self.options.get(name, default)
2301
2785
 
 
2786
    def iter_option_names(self):
 
2787
        for k in self.options.iterkeys():
 
2788
            yield k
 
2789
 
2302
2790
    def __repr__(self):
2303
2791
        # Mostly for debugging use
2304
2792
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2373
2861
    def get_sections(self):
2374
2862
        """Returns an ordered iterable of existing sections.
2375
2863
 
2376
 
        :returns: An iterable of (name, dict).
 
2864
        :returns: An iterable of (store, section).
2377
2865
        """
2378
2866
        raise NotImplementedError(self.get_sections)
2379
2867
 
2380
 
    def get_mutable_section(self, section_name=None):
 
2868
    def get_mutable_section(self, section_id=None):
2381
2869
        """Returns the specified mutable section.
2382
2870
 
2383
 
        :param section_name: The section identifier
 
2871
        :param section_id: The section identifier
2384
2872
        """
2385
2873
        raise NotImplementedError(self.get_mutable_section)
2386
2874
 
2390
2878
                                    self.external_url())
2391
2879
 
2392
2880
 
 
2881
class CommandLineStore(Store):
 
2882
    "A store to carry command line overrides for the config options."""
 
2883
 
 
2884
    def __init__(self, opts=None):
 
2885
        super(CommandLineStore, self).__init__()
 
2886
        if opts is None:
 
2887
            opts = {}
 
2888
        self.options = {}
 
2889
 
 
2890
    def _reset(self):
 
2891
        # The dict should be cleared but not replaced so it can be shared.
 
2892
        self.options.clear()
 
2893
 
 
2894
    def _from_cmdline(self, overrides):
 
2895
        # Reset before accepting new definitions
 
2896
        self._reset()
 
2897
        for over in overrides:
 
2898
            try:
 
2899
                name, value = over.split('=', 1)
 
2900
            except ValueError:
 
2901
                raise errors.BzrCommandError(
 
2902
                    gettext("Invalid '%s', should be of the form 'name=value'")
 
2903
                    % (over,))
 
2904
            self.options[name] = value
 
2905
 
 
2906
    def external_url(self):
 
2907
        # Not an url but it makes debugging easier and is never needed
 
2908
        # otherwise
 
2909
        return 'cmdline'
 
2910
 
 
2911
    def get_sections(self):
 
2912
        yield self,  self.readonly_section_class('cmdline_overrides',
 
2913
                                                 self.options)
 
2914
 
 
2915
 
2393
2916
class IniFileStore(Store):
2394
2917
    """A config Store using ConfigObj for storage.
2395
2918
 
2401
2924
        serialize/deserialize the config file.
2402
2925
    """
2403
2926
 
2404
 
    def __init__(self, transport, file_name):
 
2927
    def __init__(self):
2405
2928
        """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
2929
        """
2411
2930
        super(IniFileStore, self).__init__()
2412
 
        self.transport = transport
2413
 
        self.file_name = file_name
2414
2931
        self._config_obj = None
2415
2932
 
2416
2933
    def is_loaded(self):
2419
2936
    def unload(self):
2420
2937
        self._config_obj = None
2421
2938
 
 
2939
    def _load_content(self):
 
2940
        """Load the config file bytes.
 
2941
 
 
2942
        This should be provided by subclasses
 
2943
 
 
2944
        :return: Byte string
 
2945
        """
 
2946
        raise NotImplementedError(self._load_content)
 
2947
 
 
2948
    def _save_content(self, content):
 
2949
        """Save the config file bytes.
 
2950
 
 
2951
        This should be provided by subclasses
 
2952
 
 
2953
        :param content: Config file bytes to write
 
2954
        """
 
2955
        raise NotImplementedError(self._save_content)
 
2956
 
2422
2957
    def load(self):
2423
2958
        """Load the store from the associated file."""
2424
2959
        if self.is_loaded():
2425
2960
            return
2426
 
        content = self.transport.get_bytes(self.file_name)
 
2961
        content = self._load_content()
2427
2962
        self._load_from_string(content)
2428
2963
        for hook in ConfigHooks['load']:
2429
2964
            hook(self)
2438
2973
        co_input = StringIO(bytes)
2439
2974
        try:
2440
2975
            # The config files are always stored utf8-encoded
2441
 
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
 
2976
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
 
2977
                                         list_values=False)
2442
2978
        except configobj.ConfigObjError, e:
2443
2979
            self._config_obj = None
2444
2980
            raise errors.ParseConfigError(e.errors, self.external_url())
2451
2987
            return
2452
2988
        out = StringIO()
2453
2989
        self._config_obj.write(out)
2454
 
        self.transport.put_bytes(self.file_name, out.getvalue())
 
2990
        self._save_content(out.getvalue())
2455
2991
        for hook in ConfigHooks['save']:
2456
2992
            hook(self)
2457
2993
 
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
2994
    def get_sections(self):
2467
2995
        """Get the configobj section in the file order.
2468
2996
 
2469
 
        :returns: An iterable of (name, dict).
 
2997
        :returns: An iterable of (store, section).
2470
2998
        """
2471
2999
        # We need a loaded store
2472
3000
        try:
2473
3001
            self.load()
2474
 
        except errors.NoSuchFile:
2475
 
            # If the file doesn't exist, there is no sections
 
3002
        except (errors.NoSuchFile, errors.PermissionDenied):
 
3003
            # If the file can't be read, there is no sections
2476
3004
            return
2477
3005
        cobj = self._config_obj
2478
3006
        if cobj.scalars:
2479
 
            yield self.readonly_section_class(None, cobj)
 
3007
            yield self, self.readonly_section_class(None, cobj)
2480
3008
        for section_name in cobj.sections:
2481
 
            yield self.readonly_section_class(section_name, cobj[section_name])
 
3009
            yield (self,
 
3010
                   self.readonly_section_class(section_name,
 
3011
                                               cobj[section_name]))
2482
3012
 
2483
 
    def get_mutable_section(self, section_name=None):
 
3013
    def get_mutable_section(self, section_id=None):
2484
3014
        # We need a loaded store
2485
3015
        try:
2486
3016
            self.load()
2487
3017
        except errors.NoSuchFile:
2488
3018
            # The file doesn't exist, let's pretend it was empty
2489
3019
            self._load_from_string('')
2490
 
        if section_name is None:
 
3020
        if section_id is None:
2491
3021
            section = self._config_obj
2492
3022
        else:
2493
 
            section = self._config_obj.setdefault(section_name, {})
2494
 
        return self.mutable_section_class(section_name, section)
 
3023
            section = self._config_obj.setdefault(section_id, {})
 
3024
        return self.mutable_section_class(section_id, section)
 
3025
 
 
3026
 
 
3027
class TransportIniFileStore(IniFileStore):
 
3028
    """IniFileStore that loads files from a transport.
 
3029
    """
 
3030
 
 
3031
    def __init__(self, transport, file_name):
 
3032
        """A Store using a ini file on a Transport
 
3033
 
 
3034
        :param transport: The transport object where the config file is located.
 
3035
        :param file_name: The config file basename in the transport directory.
 
3036
        """
 
3037
        super(TransportIniFileStore, self).__init__()
 
3038
        self.transport = transport
 
3039
        self.file_name = file_name
 
3040
 
 
3041
    def _load_content(self):
 
3042
        try:
 
3043
            return self.transport.get_bytes(self.file_name)
 
3044
        except errors.PermissionDenied:
 
3045
            trace.warning("Permission denied while trying to load "
 
3046
                          "configuration store %s.", self.external_url())
 
3047
            raise
 
3048
 
 
3049
    def _save_content(self, content):
 
3050
        self.transport.put_bytes(self.file_name, content)
 
3051
 
 
3052
    def external_url(self):
 
3053
        # FIXME: external_url should really accepts an optional relpath
 
3054
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
3055
        # The following will do in the interim but maybe we don't want to
 
3056
        # expose a path here but rather a config ID and its associated
 
3057
        # object </hand wawe>.
 
3058
        return urlutils.join(self.transport.external_url(), self.file_name)
2495
3059
 
2496
3060
 
2497
3061
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2500
3064
# they may face the same issue.
2501
3065
 
2502
3066
 
2503
 
class LockableIniFileStore(IniFileStore):
 
3067
class LockableIniFileStore(TransportIniFileStore):
2504
3068
    """A ConfigObjStore using locks on save to ensure store integrity."""
2505
3069
 
2506
3070
    def __init__(self, transport, file_name, lock_dir_name=None):
2553
3117
class GlobalStore(LockableIniFileStore):
2554
3118
 
2555
3119
    def __init__(self, possible_transports=None):
2556
 
        t = transport.get_transport(config_dir(),
2557
 
                                    possible_transports=possible_transports)
 
3120
        t = transport.get_transport_from_path(
 
3121
            config_dir(), possible_transports=possible_transports)
2558
3122
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
3123
        self.id = 'bazaar'
2559
3124
 
2560
3125
 
2561
3126
class LocationStore(LockableIniFileStore):
2562
3127
 
2563
3128
    def __init__(self, possible_transports=None):
2564
 
        t = transport.get_transport(config_dir(),
2565
 
                                    possible_transports=possible_transports)
 
3129
        t = transport.get_transport_from_path(
 
3130
            config_dir(), possible_transports=possible_transports)
2566
3131
        super(LocationStore, self).__init__(t, 'locations.conf')
2567
 
 
2568
 
 
2569
 
class BranchStore(IniFileStore):
 
3132
        self.id = 'locations'
 
3133
 
 
3134
 
 
3135
class BranchStore(TransportIniFileStore):
2570
3136
 
2571
3137
    def __init__(self, branch):
2572
3138
        super(BranchStore, self).__init__(branch.control_transport,
2573
3139
                                          'branch.conf')
2574
3140
        self.branch = branch
 
3141
        self.id = 'branch'
2575
3142
 
2576
3143
    def lock_write(self, token=None):
2577
3144
        return self.branch.lock_write(token)
2588
3155
        super(BranchStore, self).save()
2589
3156
 
2590
3157
 
 
3158
class ControlStore(LockableIniFileStore):
 
3159
 
 
3160
    def __init__(self, bzrdir):
 
3161
        super(ControlStore, self).__init__(bzrdir.transport,
 
3162
                                          'control.conf',
 
3163
                                           lock_dir_name='branch_lock')
 
3164
 
 
3165
 
2591
3166
class SectionMatcher(object):
2592
3167
    """Select sections into a given Store.
2593
3168
 
2594
 
    This intended to be used to postpone getting an iterable of sections from a
2595
 
    store.
 
3169
    This is intended to be used to postpone getting an iterable of sections
 
3170
    from a store.
2596
3171
    """
2597
3172
 
2598
3173
    def __init__(self, store):
2603
3178
        # sections.
2604
3179
        sections = self.store.get_sections()
2605
3180
        # Walk the revisions in the order provided
2606
 
        for s in sections:
 
3181
        for store, s in sections:
2607
3182
            if self.match(s):
2608
 
                yield s
2609
 
 
2610
 
    def match(self, secion):
 
3183
                yield store, s
 
3184
 
 
3185
    def match(self, section):
 
3186
        """Does the proposed section match.
 
3187
 
 
3188
        :param section: A Section object.
 
3189
 
 
3190
        :returns: True if the section matches, False otherwise.
 
3191
        """
2611
3192
        raise NotImplementedError(self.match)
2612
3193
 
2613
3194
 
 
3195
class NameMatcher(SectionMatcher):
 
3196
 
 
3197
    def __init__(self, store, section_id):
 
3198
        super(NameMatcher, self).__init__(store)
 
3199
        self.section_id = section_id
 
3200
 
 
3201
    def match(self, section):
 
3202
        return section.id == self.section_id
 
3203
 
 
3204
 
2614
3205
class LocationSection(Section):
2615
3206
 
2616
3207
    def __init__(self, section, length, extra_path):
2617
3208
        super(LocationSection, self).__init__(section.id, section.options)
2618
3209
        self.length = length
2619
3210
        self.extra_path = extra_path
 
3211
        self.locals = {'relpath': extra_path,
 
3212
                       'basename': urlutils.basename(extra_path)}
2620
3213
 
2621
 
    def get(self, name, default=None):
 
3214
    def get(self, name, default=None, expand=True):
2622
3215
        value = super(LocationSection, self).get(name, default)
2623
 
        if value is not None:
 
3216
        if value is not None and expand:
2624
3217
            policy_name = self.get(name + ':policy', None)
2625
3218
            policy = _policy_value.get(policy_name, POLICY_NONE)
2626
3219
            if policy == POLICY_APPENDPATH:
2627
3220
                value = urlutils.join(value, self.extra_path)
 
3221
            # expand section local options right now (since POLICY_APPENDPATH
 
3222
            # will never add options references, it's ok to expand after it).
 
3223
            chunks = []
 
3224
            for is_ref, chunk in iter_option_refs(value):
 
3225
                if not is_ref:
 
3226
                    chunks.append(chunk)
 
3227
                else:
 
3228
                    ref = chunk[1:-1]
 
3229
                    if ref in self.locals:
 
3230
                        chunks.append(self.locals[ref])
 
3231
                    else:
 
3232
                        chunks.append(chunk)
 
3233
            value = ''.join(chunks)
2628
3234
        return value
2629
3235
 
2630
3236
 
2641
3247
        # We slightly diverge from LocalConfig here by allowing the no-name
2642
3248
        # section as the most generic one and the lower priority.
2643
3249
        no_name_section = None
2644
 
        sections = []
 
3250
        all_sections = []
2645
3251
        # Filter out the no_name_section so _iter_for_location_by_parts can be
2646
3252
        # used (it assumes all sections have a name).
2647
 
        for section in self.store.get_sections():
 
3253
        for _, section in self.store.get_sections():
2648
3254
            if section.id is None:
2649
3255
                no_name_section = section
2650
3256
            else:
2651
 
                sections.append(section)
 
3257
                all_sections.append(section)
2652
3258
        # Unfortunately _iter_for_location_by_parts deals with section names so
2653
3259
        # we have to resync.
2654
3260
        filtered_sections = _iter_for_location_by_parts(
2655
 
            [s.id for s in sections], self.location)
2656
 
        iter_sections = iter(sections)
 
3261
            [s.id for s in all_sections], self.location)
 
3262
        iter_all_sections = iter(all_sections)
2657
3263
        matching_sections = []
2658
3264
        if no_name_section is not None:
2659
3265
            matching_sections.append(
2660
3266
                LocationSection(no_name_section, 0, self.location))
2661
3267
        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))
 
3268
            # a section id is unique for a given store so it's safe to take the
 
3269
            # first matching section while iterating. Also, all filtered
 
3270
            # sections are part of 'all_sections' and will always be found
 
3271
            # there.
 
3272
            while True:
 
3273
                section = iter_all_sections.next()
 
3274
                if section_id == section.id:
 
3275
                    matching_sections.append(
 
3276
                        LocationSection(section, length, extra_path))
 
3277
                    break
2668
3278
        return matching_sections
2669
3279
 
2670
3280
    def get_sections(self):
2683
3293
            if ignore:
2684
3294
                break
2685
3295
            # Finally, we have a valid section
2686
 
            yield section
 
3296
            yield self.store, section
 
3297
 
 
3298
 
 
3299
_option_ref_re = lazy_regex.lazy_compile('({[^{}\n]+})')
 
3300
"""Describes an expandable option reference.
 
3301
 
 
3302
We want to match the most embedded reference first.
 
3303
 
 
3304
I.e. for '{{foo}}' we will get '{foo}',
 
3305
for '{bar{baz}}' we will get '{baz}'
 
3306
"""
 
3307
 
 
3308
def iter_option_refs(string):
 
3309
    # Split isolate refs so every other chunk is a ref
 
3310
    is_ref = False
 
3311
    for chunk  in _option_ref_re.split(string):
 
3312
        yield is_ref, chunk
 
3313
        is_ref = not is_ref
2687
3314
 
2688
3315
 
2689
3316
class Stack(object):
2690
3317
    """A stack of configurations where an option can be defined"""
2691
3318
 
2692
 
    def __init__(self, sections_def, store=None, mutable_section_name=None):
 
3319
    def __init__(self, sections_def, store=None, mutable_section_id=None):
2693
3320
        """Creates a stack of sections with an optional store for changes.
2694
3321
 
2695
3322
        :param sections_def: A list of Section or callables that returns an
2699
3326
        :param store: The optional Store where modifications will be
2700
3327
            recorded. If none is specified, no modifications can be done.
2701
3328
 
2702
 
        :param mutable_section_name: The name of the MutableSection where
2703
 
            changes are recorded. This requires the ``store`` parameter to be
 
3329
        :param mutable_section_id: The id of the MutableSection where changes
 
3330
            are recorded. This requires the ``store`` parameter to be
2704
3331
            specified.
2705
3332
        """
2706
3333
        self.sections_def = sections_def
2707
3334
        self.store = store
2708
 
        self.mutable_section_name = mutable_section_name
 
3335
        self.mutable_section_id = mutable_section_id
2709
3336
 
2710
 
    def get(self, name):
 
3337
    def get(self, name, expand=None):
2711
3338
        """Return the *first* option value found in the sections.
2712
3339
 
2713
3340
        This is where we guarantee that sections coming from Store are loaded
2715
3342
        option exists or get its value, which in turn may require to discover
2716
3343
        in which sections it can be defined. Both of these (section and option
2717
3344
        existence) require loading the store (even partially).
 
3345
 
 
3346
        :param name: The queried option.
 
3347
 
 
3348
        :param expand: Whether options references should be expanded.
 
3349
 
 
3350
        :returns: The value of the option.
2718
3351
        """
2719
3352
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
3353
        if expand is None:
 
3354
            expand = _get_expand_default_value()
2720
3355
        value = None
2721
3356
        # Ensuring lazy loading is achieved by delaying section matching (which
2722
3357
        # implies querying the persistent storage) until it can't be avoided
2723
3358
        # anymore by using callables to describe (possibly empty) section
2724
3359
        # 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:
 
3360
        for sections in self.sections_def:
 
3361
            for store, section in sections():
2732
3362
                value = section.get(name)
2733
3363
                if value is not None:
2734
3364
                    break
2735
3365
            if value is not None:
2736
3366
                break
2737
 
        if value is None:
 
3367
        # If the option is registered, it may provide additional info about
 
3368
        # value handling
 
3369
        try:
 
3370
            opt = option_registry.get(name)
 
3371
        except KeyError:
 
3372
            # Not registered
 
3373
            opt = None
 
3374
        def expand_and_convert(val):
 
3375
            # This may need to be called twice if the value is None or ends up
 
3376
            # being None during expansion or conversion.
 
3377
            if val is not None:
 
3378
                if expand:
 
3379
                    if isinstance(val, basestring):
 
3380
                        val = self._expand_options_in_string(val)
 
3381
                    else:
 
3382
                        trace.warning('Cannot expand "%s":'
 
3383
                                      ' %s does not support option expansion'
 
3384
                                      % (name, type(val)))
 
3385
                if opt is not None:
 
3386
                    val = opt.convert_from_unicode(val)
 
3387
            return val
 
3388
        value = expand_and_convert(value)
 
3389
        if opt is not None and value is None:
2738
3390
            # 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:
2745
 
                value = opt.get_default()
 
3391
            value = opt.get_default()
 
3392
            value = expand_and_convert(value)
2746
3393
        for hook in ConfigHooks['get']:
2747
3394
            hook(self, name, value)
2748
3395
        return value
2749
3396
 
 
3397
    def expand_options(self, string, env=None):
 
3398
        """Expand option references in the string in the configuration context.
 
3399
 
 
3400
        :param string: The string containing option(s) to expand.
 
3401
 
 
3402
        :param env: An option dict defining additional configuration options or
 
3403
            overriding existing ones.
 
3404
 
 
3405
        :returns: The expanded string.
 
3406
        """
 
3407
        return self._expand_options_in_string(string, env)
 
3408
 
 
3409
    def _expand_options_in_string(self, string, env=None, _refs=None):
 
3410
        """Expand options in the string in the configuration context.
 
3411
 
 
3412
        :param string: The string to be expanded.
 
3413
 
 
3414
        :param env: An option dict defining additional configuration options or
 
3415
            overriding existing ones.
 
3416
 
 
3417
        :param _refs: Private list (FIFO) containing the options being expanded
 
3418
            to detect loops.
 
3419
 
 
3420
        :returns: The expanded string.
 
3421
        """
 
3422
        if string is None:
 
3423
            # Not much to expand there
 
3424
            return None
 
3425
        if _refs is None:
 
3426
            # What references are currently resolved (to detect loops)
 
3427
            _refs = []
 
3428
        result = string
 
3429
        # We need to iterate until no more refs appear ({{foo}} will need two
 
3430
        # iterations for example).
 
3431
        expanded = True
 
3432
        while expanded:
 
3433
            expanded = False
 
3434
            chunks = []
 
3435
            for is_ref, chunk in iter_option_refs(result):
 
3436
                if not is_ref:
 
3437
                    chunks.append(chunk)
 
3438
                else:
 
3439
                    expanded = True
 
3440
                    name = chunk[1:-1]
 
3441
                    if name in _refs:
 
3442
                        raise errors.OptionExpansionLoop(string, _refs)
 
3443
                    _refs.append(name)
 
3444
                    value = self._expand_option(name, env, _refs)
 
3445
                    if value is None:
 
3446
                        raise errors.ExpandingUnknownOption(name, string)
 
3447
                    chunks.append(value)
 
3448
                    _refs.pop()
 
3449
            result = ''.join(chunks)
 
3450
        return result
 
3451
 
 
3452
    def _expand_option(self, name, env, _refs):
 
3453
        if env is not None and name in env:
 
3454
            # Special case, values provided in env takes precedence over
 
3455
            # anything else
 
3456
            value = env[name]
 
3457
        else:
 
3458
            value = self.get(name, expand=False)
 
3459
            value = self._expand_options_in_string(value, env, _refs)
 
3460
        return value
 
3461
 
2750
3462
    def _get_mutable_section(self):
2751
3463
        """Get the MutableSection for the Stack.
2752
3464
 
2753
3465
        This is where we guarantee that the mutable section is lazily loaded:
2754
3466
        this means we won't load the corresponding store before setting a value
2755
3467
        or deleting an option. In practice the store will often be loaded but
2756
 
        this allows helps catching some programming errors.
 
3468
        this helps catching some programming errors.
2757
3469
        """
2758
 
        section = self.store.get_mutable_section(self.mutable_section_name)
 
3470
        section = self.store.get_mutable_section(self.mutable_section_id)
2759
3471
        return section
2760
3472
 
2761
3473
    def set(self, name, value):
2776
3488
        # Mostly for debugging use
2777
3489
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2778
3490
 
 
3491
    def _get_overrides(self):
 
3492
        # Hack around library_state.initialize never called
 
3493
        if bzrlib.global_state is not None:
 
3494
            return bzrlib.global_state.cmdline_overrides.get_sections()
 
3495
        return []
 
3496
 
2779
3497
 
2780
3498
class _CompatibleStack(Stack):
2781
3499
    """Place holder for compatibility with previous design.
2786
3504
    One assumption made here is that the daughter classes will all use Stores
2787
3505
    derived from LockableIniFileStore).
2788
3506
 
2789
 
    It implements set() by re-loading the store before applying the
2790
 
    modification and saving it.
 
3507
    It implements set() and remove () by re-loading the store before applying
 
3508
    the modification and saving it.
2791
3509
 
2792
3510
    The long term plan being to implement a single write by store to save
2793
3511
    all modifications, this class should not be used in the interim.
2800
3518
        # Force a write to persistent storage
2801
3519
        self.store.save()
2802
3520
 
 
3521
    def remove(self, name):
 
3522
        # Force a reload
 
3523
        self.store.unload()
 
3524
        super(_CompatibleStack, self).remove(name)
 
3525
        # Force a write to persistent storage
 
3526
        self.store.save()
 
3527
 
2803
3528
 
2804
3529
class GlobalStack(_CompatibleStack):
 
3530
    """Global options only stack.
 
3531
 
 
3532
    The following sections are queried:
 
3533
 
 
3534
    * command-line overrides,
 
3535
 
 
3536
    * the 'DEFAULT' section in bazaar.conf
 
3537
 
 
3538
    This stack will use the ``DEFAULT`` section in bazaar.conf as its
 
3539
    MutableSection.
 
3540
    """
2805
3541
 
2806
3542
    def __init__(self):
2807
 
        # Get a GlobalStore
2808
3543
        gstore = GlobalStore()
2809
 
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
 
3544
        super(GlobalStack, self).__init__(
 
3545
            [self._get_overrides,
 
3546
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
3547
            gstore, mutable_section_id='DEFAULT')
2810
3548
 
2811
3549
 
2812
3550
class LocationStack(_CompatibleStack):
 
3551
    """Per-location options falling back to global options stack.
 
3552
 
 
3553
 
 
3554
    The following sections are queried:
 
3555
 
 
3556
    * command-line overrides,
 
3557
 
 
3558
    * the sections matching ``location`` in ``locations.conf``, the order being
 
3559
      defined by the number of path components in the section glob, higher
 
3560
      numbers first (from most specific section to most generic).
 
3561
 
 
3562
    * the 'DEFAULT' section in bazaar.conf
 
3563
 
 
3564
    This stack will use the ``location`` section in locations.conf as its
 
3565
    MutableSection.
 
3566
    """
2813
3567
 
2814
3568
    def __init__(self, location):
 
3569
        """Make a new stack for a location and global configuration.
 
3570
 
 
3571
        :param location: A URL prefix to """
2815
3572
        lstore = LocationStore()
2816
 
        matcher = LocationMatcher(lstore, location)
 
3573
        if location.startswith('file://'):
 
3574
            location = urlutils.local_path_from_url(location)
2817
3575
        gstore = GlobalStore()
2818
3576
        super(LocationStack, self).__init__(
2819
 
            [matcher.get_sections, gstore.get_sections], lstore)
 
3577
            [self._get_overrides,
 
3578
             LocationMatcher(lstore, location).get_sections,
 
3579
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
3580
            lstore, mutable_section_id=location)
 
3581
 
2820
3582
 
2821
3583
class BranchStack(_CompatibleStack):
 
3584
    """Per-location options falling back to branch then global options stack.
 
3585
 
 
3586
    The following sections are queried:
 
3587
 
 
3588
    * command-line overrides,
 
3589
 
 
3590
    * the sections matching ``location`` in ``locations.conf``, the order being
 
3591
      defined by the number of path components in the section glob, higher
 
3592
      numbers first (from most specific section to most generic),
 
3593
 
 
3594
    * the no-name section in branch.conf,
 
3595
 
 
3596
    * the ``DEFAULT`` section in ``bazaar.conf``.
 
3597
 
 
3598
    This stack will use the no-name section in ``branch.conf`` as its
 
3599
    MutableSection.
 
3600
    """
2822
3601
 
2823
3602
    def __init__(self, branch):
2824
 
        bstore = BranchStore(branch)
2825
3603
        lstore = LocationStore()
2826
 
        matcher = LocationMatcher(lstore, branch.base)
 
3604
        bstore = branch._get_config_store()
2827
3605
        gstore = GlobalStore()
2828
3606
        super(BranchStack, self).__init__(
2829
 
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
2830
 
            bstore)
2831
 
        self.branch = branch
2832
 
 
 
3607
            [self._get_overrides,
 
3608
             LocationMatcher(lstore, branch.base).get_sections,
 
3609
             NameMatcher(bstore, None).get_sections,
 
3610
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
3611
            bstore)
 
3612
        self.branch = branch
 
3613
 
 
3614
 
 
3615
class RemoteControlStack(_CompatibleStack):
 
3616
    """Remote control-only options stack."""
 
3617
 
 
3618
    # FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
 
3619
    # with the stack used for remote bzr dirs. RemoteControlStack only uses
 
3620
    # control.conf and is used only for stack options.
 
3621
 
 
3622
    def __init__(self, bzrdir):
 
3623
        cstore = bzrdir._get_config_store()
 
3624
        super(RemoteControlStack, self).__init__(
 
3625
            [NameMatcher(cstore, None).get_sections],
 
3626
            cstore)
 
3627
        self.bzrdir = bzrdir
 
3628
 
 
3629
 
 
3630
class RemoteBranchStack(_CompatibleStack):
 
3631
    """Remote branch-only options stack."""
 
3632
 
 
3633
    # FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
 
3634
    # with the stack used for remote branches. RemoteBranchStack only uses
 
3635
    # branch.conf and is used only for the stack options.
 
3636
 
 
3637
    def __init__(self, branch):
 
3638
        bstore = branch._get_config_store()
 
3639
        super(RemoteBranchStack, self).__init__(
 
3640
            [NameMatcher(bstore, None).get_sections],
 
3641
            bstore)
 
3642
        self.branch = branch
 
3643
 
 
3644
# Use a an empty dict to initialize an empty configobj avoiding all
 
3645
# parsing and encoding checks
 
3646
_quoting_config = configobj.ConfigObj(
 
3647
    {}, encoding='utf-8', interpolation=False)
2833
3648
 
2834
3649
class cmd_config(commands.Command):
2835
3650
    __doc__ = """Display, set or remove a configuration option.
2852
3667
    takes_options = [
2853
3668
        'directory',
2854
3669
        # FIXME: This should be a registry option so that plugins can register
2855
 
        # their own config files (or not) -- vila 20101002
 
3670
        # their own config files (or not) and will also address
 
3671
        # http://pad.lv/788991 -- vila 20101115
2856
3672
        commands.Option('scope', help='Reduce the scope to the specified'
2857
 
                        ' configuration file',
 
3673
                        ' configuration file.',
2858
3674
                        type=unicode),
2859
3675
        commands.Option('all',
2860
3676
            help='Display all the defined values for the matching options.',
2861
3677
            ),
2862
3678
        commands.Option('remove', help='Remove the option from'
2863
 
                        ' the configuration file'),
 
3679
                        ' the configuration file.'),
2864
3680
        ]
2865
3681
 
2866
3682
    _see_also = ['configuration']
2896
3712
                # Set the option value
2897
3713
                self._set_config_option(name, value, directory, scope)
2898
3714
 
2899
 
    def _get_configs(self, directory, scope=None):
2900
 
        """Iterate the configurations specified by ``directory`` and ``scope``.
 
3715
    def _get_stack(self, directory, scope=None):
 
3716
        """Get the configuration stack specified by ``directory`` and ``scope``.
2901
3717
 
2902
3718
        :param directory: Where the configurations are derived from.
2903
3719
 
2904
3720
        :param scope: A specific config to start from.
2905
3721
        """
 
3722
        # FIXME: scope should allow access to plugin-specific stacks (even
 
3723
        # reduced to the plugin-specific store), related to
 
3724
        # http://pad.lv/788991 -- vila 2011-11-15
2906
3725
        if scope is not None:
2907
3726
            if scope == 'bazaar':
2908
 
                yield GlobalConfig()
 
3727
                return GlobalStack()
2909
3728
            elif scope == 'locations':
2910
 
                yield LocationConfig(directory)
 
3729
                return LocationStack(directory)
2911
3730
            elif scope == 'branch':
2912
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2913
 
                    directory)
2914
 
                yield br.get_config()
 
3731
                (_, br, _) = (
 
3732
                    controldir.ControlDir.open_containing_tree_or_branch(
 
3733
                        directory))
 
3734
                return br.get_config_stack()
 
3735
            raise errors.NoSuchConfig(scope)
2915
3736
        else:
2916
3737
            try:
2917
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2918
 
                    directory)
2919
 
                yield br.get_config()
 
3738
                (_, br, _) = (
 
3739
                    controldir.ControlDir.open_containing_tree_or_branch(
 
3740
                        directory))
 
3741
                return br.get_config_stack()
2920
3742
            except errors.NotBranchError:
2921
 
                yield LocationConfig(directory)
2922
 
                yield GlobalConfig()
 
3743
                return LocationStack(directory)
2923
3744
 
2924
3745
    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:
 
3746
        conf = self._get_stack(directory, scope)
 
3747
        value = conf.get(name, expand=True)
 
3748
        if value is not None:
 
3749
            # Quote the value appropriately
 
3750
            value = _quoting_config._quote(value)
 
3751
            self.outf.write('%s\n' % (value,))
 
3752
        else:
2944
3753
            raise errors.NoSuchConfigOption(name)
2945
3754
 
2946
3755
    def _show_matching_options(self, name, directory, scope):
2949
3758
        # avoid the delay introduced by the lazy regexp.  But, we still do
2950
3759
        # want the nicer errors raised by lazy_regex.
2951
3760
        name._compile_and_collapse()
2952
 
        cur_conf_id = None
 
3761
        cur_store_id = None
2953
3762
        cur_section = None
2954
 
        for c in self._get_configs(directory, scope):
2955
 
            for (oname, value, section, conf_id, parser) in c._get_options():
2956
 
                if name.search(oname):
2957
 
                    if cur_conf_id != conf_id:
2958
 
                        # Explain where the options are defined
2959
 
                        self.outf.write('%s:\n' % (conf_id,))
2960
 
                        cur_conf_id = conf_id
2961
 
                        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
2968
 
                    self.outf.write('  %s = %s\n' % (oname, value))
 
3763
        conf = self._get_stack(directory, scope)
 
3764
        for sections in conf.sections_def:
 
3765
            for store, section in sections():
 
3766
                for oname in section.iter_option_names():
 
3767
                    if name.search(oname):
 
3768
                        if cur_store_id != store.id:
 
3769
                            # Explain where the options are defined
 
3770
                            self.outf.write('%s:\n' % (store.id,))
 
3771
                            cur_store_id = store.id
 
3772
                            cur_section = None
 
3773
                        if (section.id not in (None, 'DEFAULT')
 
3774
                            and cur_section != section.id):
 
3775
                            # Display the section if it's not the default (or
 
3776
                            # only) one.
 
3777
                            self.outf.write('  [%s]\n' % (section.id,))
 
3778
                            cur_section = section.id
 
3779
                        value = section.get(oname, expand=False)
 
3780
                        value = _quoting_config._quote(value)
 
3781
                        self.outf.write('  %s = %s\n' % (oname, value))
2969
3782
 
2970
3783
    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)
 
3784
        conf = self._get_stack(directory, scope)
 
3785
        conf.set(name, value)
2976
3786
 
2977
3787
    def _remove_config_option(self, name, directory, scope):
2978
3788
        if name is None:
2979
3789
            raise errors.BzrCommandError(
2980
3790
                '--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:
 
3791
        conf = self._get_stack(directory, scope)
 
3792
        try:
 
3793
            conf.remove(name)
 
3794
        except KeyError:
2999
3795
            raise errors.NoSuchConfigOption(name)
3000
3796
 
 
3797
 
3001
3798
# Test registries
3002
3799
#
3003
3800
# We need adapters that can build a Store or a Stack in a test context. Test
3006
3803
# ready-to-use store or stack.  Plugins that define new store/stacks can also
3007
3804
# register themselves here to be tested against the tests defined in
3008
3805
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3009
 
# for the same tests.
 
3806
# for the same test.
3010
3807
 
3011
3808
# The registered object should be a callable receiving a test instance
3012
3809
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store