~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Martin Packman
  • Date: 2012-01-05 09:50:04 UTC
  • mfrom: (6424 +trunk)
  • mto: This revision was merged to the branch mainline in revision 6426.
  • Revision ID: martin.packman@canonical.com-20120105095004-mia9xb7y0efmto0v
Merge bzr.dev to resolve conflicts in bzrlib.builtins

Show diffs side-by-side

added added

removed removed

Lines of Context:
72
72
up=pull
73
73
"""
74
74
 
 
75
from __future__ import absolute_import
 
76
 
75
77
import os
76
 
import string
77
78
import sys
78
 
import re
79
 
 
80
 
 
 
79
 
 
80
import bzrlib
81
81
from bzrlib.decorators import needs_write_lock
82
82
from bzrlib.lazy_import import lazy_import
83
83
lazy_import(globals(), """
87
87
 
88
88
from bzrlib import (
89
89
    atomicfile,
90
 
    bzrdir,
 
90
    controldir,
91
91
    debug,
92
92
    errors,
93
93
    lazy_regex,
 
94
    library_state,
94
95
    lockdir,
95
96
    mail_client,
96
97
    mergetools,
102
103
    urlutils,
103
104
    win32utils,
104
105
    )
 
106
from bzrlib.i18n import gettext
105
107
from bzrlib.util.configobj import configobj
106
108
""")
107
109
from bzrlib import (
108
110
    commands,
109
111
    hooks,
 
112
    lazy_regex,
110
113
    registry,
111
114
    )
112
115
from bzrlib.symbol_versioning import (
149
152
STORE_GLOBAL = 4
150
153
 
151
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
 
152
179
class ConfigObj(configobj.ConfigObj):
153
180
 
154
181
    def __init__(self, infile=None, **kwargs):
414
441
            # add) the final ','
415
442
            l = [l]
416
443
        return l
417
 
        
418
 
    def get_user_option_as_int_from_SI(self,  option_name,  default=None):
 
444
 
 
445
    @deprecated_method(deprecated_in((2, 5, 0)))
 
446
    def get_user_option_as_int_from_SI(self, option_name, default=None):
419
447
        """Get a generic option from a human readable size in SI units, e.g 10MB
420
 
        
 
448
 
421
449
        Accepted suffixes are K,M,G. It is case-insensitive and may be followed
422
450
        by a trailing b (i.e. Kb, MB). This is intended to be practical and not
423
451
        pedantic.
424
 
        
 
452
 
425
453
        :return Integer, expanded to its base-10 value if a proper SI unit is 
426
454
            found. If the option doesn't exist, or isn't a value in 
427
455
            SI units, return default (which defaults to None)
445
473
                        elif m.group(2).lower() == 'g':
446
474
                            val *= 10**9
447
475
                else:
448
 
                    ui.ui_factory.show_warning('Invalid config value for "%s" '
449
 
                                               ' value %r is not an SI unit.'
450
 
                                                % (option_name, val))
 
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))
451
479
                    val = default
452
480
            except TypeError:
453
481
                val = default
454
482
        return val
455
 
        
456
483
 
 
484
    @deprecated_method(deprecated_in((2, 5, 0)))
457
485
    def gpg_signing_command(self):
458
486
        """What program should be used to sign signatures?"""
459
487
        result = self._gpg_signing_command()
465
493
        """See gpg_signing_command()."""
466
494
        return None
467
495
 
 
496
    @deprecated_method(deprecated_in((2, 5, 0)))
468
497
    def log_format(self):
469
498
        """What log format should be used"""
470
499
        result = self._log_format()
489
518
        """See validate_signatures_in_log()."""
490
519
        return None
491
520
 
 
521
    @deprecated_method(deprecated_in((2, 5, 0)))
492
522
    def acceptable_keys(self):
493
523
        """Comma separated list of key patterns acceptable to 
494
524
        verify-signatures command"""
499
529
        """See acceptable_keys()."""
500
530
        return None
501
531
 
 
532
    @deprecated_method(deprecated_in((2, 5, 0)))
502
533
    def post_commit(self):
503
534
        """An ordered list of python functions to call.
504
535
 
530
561
        v = self._get_user_id()
531
562
        if v:
532
563
            return v
533
 
        v = os.environ.get('EMAIL')
534
 
        if v:
535
 
            return v.decode(osutils.get_user_encoding())
536
 
        name, email = _auto_user_id()
537
 
        if name and email:
538
 
            return '%s <%s>' % (name, email)
539
 
        elif email:
540
 
            return email
541
 
        raise errors.NoWhoami()
 
564
        return default_email()
542
565
 
543
566
    def ensure_username(self):
544
567
        """Raise errors.NoWhoami if username is not set.
547
570
        """
548
571
        self.username()
549
572
 
 
573
    @deprecated_method(deprecated_in((2, 5, 0)))
550
574
    def signature_checking(self):
551
575
        """What is the current policy for signature checking?."""
552
576
        policy = self._get_signature_checking()
554
578
            return policy
555
579
        return CHECK_IF_POSSIBLE
556
580
 
 
581
    @deprecated_method(deprecated_in((2, 5, 0)))
557
582
    def signing_policy(self):
558
583
        """What is the current policy for signature checking?."""
559
584
        policy = self._get_signing_policy()
561
586
            return policy
562
587
        return SIGN_WHEN_REQUIRED
563
588
 
 
589
    @deprecated_method(deprecated_in((2, 5, 0)))
564
590
    def signature_needed(self):
565
591
        """Is a signature needed when committing ?."""
566
592
        policy = self._get_signing_policy()
575
601
            return True
576
602
        return False
577
603
 
 
604
    @deprecated_method(deprecated_in((2, 5, 0)))
578
605
    def gpg_signing_key(self):
579
606
        """GPG user-id to sign commits"""
580
607
        key = self.get_user_option('gpg_signing_key')
622
649
        for (oname, value, section, conf_id, parser) in self._get_options():
623
650
            if oname.startswith('bzr.mergetool.'):
624
651
                tool_name = oname[len('bzr.mergetool.'):]
625
 
                tools[tool_name] = value
 
652
                tools[tool_name] = self.get_user_option(oname)
626
653
        trace.mutter('loaded merge tools: %r' % tools)
627
654
        return tools
628
655
 
865
892
        """See Config._get_signature_checking."""
866
893
        policy = self._get_user_option('check_signatures')
867
894
        if policy:
868
 
            return self._string_to_signature_policy(policy)
 
895
            return signature_policy_from_unicode(policy)
869
896
 
870
897
    def _get_signing_policy(self):
871
898
        """See Config._get_signing_policy"""
872
899
        policy = self._get_user_option('create_signatures')
873
900
        if policy:
874
 
            return self._string_to_signing_policy(policy)
 
901
            return signing_policy_from_unicode(policy)
875
902
 
876
903
    def _get_user_id(self):
877
904
        """Get the user id from the 'email' key in the current section."""
922
949
        """See Config.post_commit."""
923
950
        return self._get_user_option('post_commit')
924
951
 
925
 
    def _string_to_signature_policy(self, signature_string):
926
 
        """Convert a string to a signing policy."""
927
 
        if signature_string.lower() == 'check-available':
928
 
            return CHECK_IF_POSSIBLE
929
 
        if signature_string.lower() == 'ignore':
930
 
            return CHECK_NEVER
931
 
        if signature_string.lower() == 'require':
932
 
            return CHECK_ALWAYS
933
 
        raise errors.BzrError("Invalid signatures policy '%s'"
934
 
                              % signature_string)
935
 
 
936
 
    def _string_to_signing_policy(self, signature_string):
937
 
        """Convert a string to a signing policy."""
938
 
        if signature_string.lower() == 'when-required':
939
 
            return SIGN_WHEN_REQUIRED
940
 
        if signature_string.lower() == 'never':
941
 
            return SIGN_NEVER
942
 
        if signature_string.lower() == 'always':
943
 
            return SIGN_ALWAYS
944
 
        raise errors.BzrError("Invalid signing policy '%s'"
945
 
                              % signature_string)
946
 
 
947
952
    def _get_alias(self, value):
948
953
        try:
949
954
            return self._get_parser().get_value("ALIASES",
1393
1398
        e.g. "John Hacker <jhacker@example.com>"
1394
1399
        This is looked up in the email controlfile for the branch.
1395
1400
        """
1396
 
        try:
1397
 
            return (self.branch._transport.get_bytes("email")
1398
 
                    .decode(osutils.get_user_encoding())
1399
 
                    .rstrip("\r\n"))
1400
 
        except errors.NoSuchFile, e:
1401
 
            pass
1402
 
 
1403
1401
        return self._get_best_value('_get_user_id')
1404
1402
 
1405
1403
    def _get_change_editor(self):
1639
1637
        f.close()
1640
1638
 
1641
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
 
1642
1655
def _auto_user_id():
1643
1656
    """Calculate automatic user identification.
1644
1657
 
1833
1846
        :param user: login (optional)
1834
1847
 
1835
1848
        :param path: the absolute path on the server (optional)
1836
 
        
 
1849
 
1837
1850
        :param realm: the http authentication realm (optional)
1838
1851
 
1839
1852
        :return: A dict containing the matching credentials or None.
2278
2291
            return f
2279
2292
        except errors.NoSuchFile:
2280
2293
            return StringIO()
 
2294
        except errors.PermissionDenied, e:
 
2295
            trace.warning("Permission denied while trying to open "
 
2296
                "configuration file %s.", urlutils.unescape_for_display(
 
2297
                urlutils.join(self._transport.base, self._filename), "utf-8"))
 
2298
            return StringIO()
2281
2299
 
2282
2300
    def _external_url(self):
2283
2301
        return urlutils.join(self._transport.external_url(), self._filename)
2314
2332
    encoutered, in which config files it can be stored.
2315
2333
    """
2316
2334
 
2317
 
    def __init__(self, name, default=None, default_from_env=None,
2318
 
                 help=None,
2319
 
                 from_unicode=None, invalid=None):
 
2335
    def __init__(self, name, override_from_env=None,
 
2336
                 default=None, default_from_env=None,
 
2337
                 help=None, from_unicode=None, invalid=None, unquote=True):
2320
2338
        """Build an option definition.
2321
2339
 
2322
2340
        :param name: the name used to refer to the option.
2323
2341
 
 
2342
        :param override_from_env: A list of environment variables which can
 
2343
           provide override any configuration setting.
 
2344
 
2324
2345
        :param default: the default value to use when none exist in the config
2325
2346
            stores. This is either a string that ``from_unicode`` will convert
2326
 
            into the proper type or a python object that can be stringified (so
2327
 
            only the empty list is supported for example).
 
2347
            into the proper type, a callable returning a unicode string so that
 
2348
            ``from_unicode`` can be used on the return value, or a python
 
2349
            object that can be stringified (so only the empty list is supported
 
2350
            for example).
2328
2351
 
2329
2352
        :param default_from_env: A list of environment variables which can
2330
2353
           provide a default value. 'default' will be used only if none of the
2342
2365
            TypeError. Accepted values are: None (ignore invalid values),
2343
2366
            'warning' (emit a warning), 'error' (emit an error message and
2344
2367
            terminates).
 
2368
 
 
2369
        :param unquote: should the unicode value be unquoted before conversion.
 
2370
           This should be used only when the store providing the values cannot
 
2371
           safely unquote them (see http://pad.lv/906897). It is provided so
 
2372
           daughter classes can handle the quoting themselves.
2345
2373
        """
 
2374
        if override_from_env is None:
 
2375
            override_from_env = []
2346
2376
        if default_from_env is None:
2347
2377
            default_from_env = []
2348
2378
        self.name = name
 
2379
        self.override_from_env = override_from_env
2349
2380
        # Convert the default value to a unicode string so all values are
2350
2381
        # strings internally before conversion (via from_unicode) is attempted.
2351
2382
        if default is None:
2356
2387
                raise AssertionError(
2357
2388
                    'Only empty lists are supported as default values')
2358
2389
            self.default = u','
2359
 
        elif isinstance(default, (str, unicode, bool, int)):
 
2390
        elif isinstance(default, (str, unicode, bool, int, float)):
2360
2391
            # Rely on python to convert strings, booleans and integers
2361
2392
            self.default = u'%s' % (default,)
 
2393
        elif callable(default):
 
2394
            self.default = default
2362
2395
        else:
2363
2396
            # other python objects are not expected
2364
2397
            raise AssertionError('%r is not supported as a default value'
2366
2399
        self.default_from_env = default_from_env
2367
2400
        self.help = help
2368
2401
        self.from_unicode = from_unicode
 
2402
        self.unquote = unquote
2369
2403
        if invalid and invalid not in ('warning', 'error'):
2370
2404
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2371
2405
        self.invalid = invalid
2372
2406
 
2373
 
    def convert_from_unicode(self, unicode_value):
 
2407
    def convert_from_unicode(self, store, unicode_value):
 
2408
        if self.unquote and store is not None and unicode_value is not None:
 
2409
            unicode_value = store.unquote(unicode_value)
2374
2410
        if self.from_unicode is None or unicode_value is None:
2375
2411
            # Don't convert or nothing to convert
2376
2412
            return unicode_value
2388
2424
                raise errors.ConfigOptionValueError(self.name, unicode_value)
2389
2425
        return converted
2390
2426
 
 
2427
    def get_override(self):
 
2428
        value = None
 
2429
        for var in self.override_from_env:
 
2430
            try:
 
2431
                # If the env variable is defined, its value takes precedence
 
2432
                value = os.environ[var].decode(osutils.get_user_encoding())
 
2433
                break
 
2434
            except KeyError:
 
2435
                continue
 
2436
        return value
 
2437
 
2391
2438
    def get_default(self):
2392
2439
        value = None
2393
2440
        for var in self.default_from_env:
2394
2441
            try:
2395
2442
                # If the env variable is defined, its value is the default one
2396
 
                value = os.environ[var]
 
2443
                value = os.environ[var].decode(osutils.get_user_encoding())
2397
2444
                break
2398
2445
            except KeyError:
2399
2446
                continue
2400
2447
        if value is None:
2401
2448
            # Otherwise, fallback to the value defined at registration
2402
 
            value = self.default
 
2449
            if callable(self.default):
 
2450
                value = self.default()
 
2451
                if not isinstance(value, unicode):
 
2452
                    raise AssertionError(
 
2453
                    'Callable default values should be unicode')
 
2454
            else:
 
2455
                value = self.default
2403
2456
        return value
2404
2457
 
2405
2458
    def get_help_text(self, additional_see_also=None, plain=True):
2421
2474
    return int(unicode_str)
2422
2475
 
2423
2476
 
2424
 
def list_from_store(unicode_str):
2425
 
    # ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
2426
 
    if isinstance(unicode_str, (str, unicode)):
2427
 
        if unicode_str:
2428
 
            # A single value, most probably the user forgot (or didn't care to
2429
 
            # add) the final ','
2430
 
            l = [unicode_str]
 
2477
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
 
2478
 
 
2479
def int_SI_from_store(unicode_str):
 
2480
    """Convert a human readable size in SI units, e.g 10MB into an integer.
 
2481
 
 
2482
    Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
2483
    by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
2484
    pedantic.
 
2485
 
 
2486
    :return Integer, expanded to its base-10 value if a proper SI unit is 
 
2487
        found, None otherwise.
 
2488
    """
 
2489
    regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
 
2490
    p = re.compile(regexp, re.IGNORECASE)
 
2491
    m = p.match(unicode_str)
 
2492
    val = None
 
2493
    if m is not None:
 
2494
        val, _, unit = m.groups()
 
2495
        val = int(val)
 
2496
        if unit:
 
2497
            try:
 
2498
                coeff = _unit_suffixes[unit.upper()]
 
2499
            except KeyError:
 
2500
                raise ValueError(gettext('{0} is not an SI unit.').format(unit))
 
2501
            val *= coeff
 
2502
    return val
 
2503
 
 
2504
 
 
2505
def float_from_store(unicode_str):
 
2506
    return float(unicode_str)
 
2507
 
 
2508
 
 
2509
# Use a an empty dict to initialize an empty configobj avoiding all
 
2510
# parsing and encoding checks
 
2511
_list_converter_config = configobj.ConfigObj(
 
2512
    {}, encoding='utf-8', list_values=True, interpolation=False)
 
2513
 
 
2514
 
 
2515
class ListOption(Option):
 
2516
 
 
2517
    def __init__(self, name, default=None, default_from_env=None,
 
2518
                 help=None, invalid=None):
 
2519
        """A list Option definition.
 
2520
 
 
2521
        This overrides the base class so the conversion from a unicode string
 
2522
        can take quoting into account.
 
2523
        """
 
2524
        super(ListOption, self).__init__(
 
2525
            name, default=default, default_from_env=default_from_env,
 
2526
            from_unicode=self.from_unicode, help=help,
 
2527
            invalid=invalid, unquote=False)
 
2528
 
 
2529
    def from_unicode(self, unicode_str):
 
2530
        if not isinstance(unicode_str, basestring):
 
2531
            raise TypeError
 
2532
        # Now inject our string directly as unicode. All callers got their
 
2533
        # value from configobj, so values that need to be quoted are already
 
2534
        # properly quoted.
 
2535
        _list_converter_config.reset()
 
2536
        _list_converter_config._parse([u"list=%s" % (unicode_str,)])
 
2537
        maybe_list = _list_converter_config['list']
 
2538
        if isinstance(maybe_list, basestring):
 
2539
            if maybe_list:
 
2540
                # A single value, most probably the user forgot (or didn't care
 
2541
                # to add) the final ','
 
2542
                l = [maybe_list]
 
2543
            else:
 
2544
                # The empty string, convert to empty list
 
2545
                l = []
2431
2546
        else:
2432
 
            # The empty string, convert to empty list
2433
 
            l = []
2434
 
    else:
2435
 
        # We rely on ConfigObj providing us with a list already
2436
 
        l = unicode_str
2437
 
    return l
 
2547
            # We rely on ConfigObj providing us with a list already
 
2548
            l = maybe_list
 
2549
        return l
2438
2550
 
2439
2551
 
2440
2552
class OptionRegistry(registry.Registry):
2481
2593
# Registered options in lexicographical order
2482
2594
 
2483
2595
option_registry.register(
 
2596
    Option('append_revisions_only',
 
2597
           default=None, from_unicode=bool_from_store, invalid='warning',
 
2598
           help='''\
 
2599
Whether to only append revisions to the mainline.
 
2600
 
 
2601
If this is set to true, then it is not possible to change the
 
2602
existing mainline of the branch.
 
2603
'''))
 
2604
option_registry.register(
 
2605
    ListOption('acceptable_keys',
 
2606
           default=None,
 
2607
           help="""\
 
2608
List of GPG key patterns which are acceptable for verification.
 
2609
"""))
 
2610
option_registry.register(
 
2611
    Option('add.maximum_file_size',
 
2612
           default=u'20MB', from_unicode=int_SI_from_store,
 
2613
           help="""\
 
2614
Size above which files should be added manually.
 
2615
 
 
2616
Files below this size are added automatically when using ``bzr add`` without
 
2617
arguments.
 
2618
 
 
2619
A negative value means disable the size check.
 
2620
"""))
 
2621
option_registry.register(
 
2622
    Option('bound',
 
2623
           default=None, from_unicode=bool_from_store,
 
2624
           help="""\
 
2625
Is the branch bound to ``bound_location``.
 
2626
 
 
2627
If set to "True", the branch should act as a checkout, and push each commit to
 
2628
the bound_location.  This option is normally set by ``bind``/``unbind``.
 
2629
 
 
2630
See also: bound_location.
 
2631
"""))
 
2632
option_registry.register(
 
2633
    Option('bound_location',
 
2634
           default=None,
 
2635
           help="""\
 
2636
The location that commits should go to when acting as a checkout.
 
2637
 
 
2638
This option is normally set by ``bind``.
 
2639
 
 
2640
See also: bound.
 
2641
"""))
 
2642
option_registry.register(
 
2643
    Option('branch.fetch_tags', default=False,  from_unicode=bool_from_store,
 
2644
           help="""\
 
2645
Whether revisions associated with tags should be fetched.
 
2646
"""))
 
2647
option_registry.register(
2484
2648
    Option('bzr.workingtree.worth_saving_limit', default=10,
2485
2649
           from_unicode=int_from_store,  invalid='warning',
2486
2650
           help='''\
2493
2657
a file has been touched.
2494
2658
'''))
2495
2659
option_registry.register(
 
2660
    Option('check_signatures', default=CHECK_IF_POSSIBLE,
 
2661
           from_unicode=signature_policy_from_unicode,
 
2662
           help='''\
 
2663
GPG checking policy.
 
2664
 
 
2665
Possible values: require, ignore, check-available (default)
 
2666
 
 
2667
this option will control whether bzr will require good gpg
 
2668
signatures, ignore them, or check them if they are
 
2669
present.
 
2670
'''))
 
2671
option_registry.register(
 
2672
    Option('create_signatures', default=SIGN_WHEN_REQUIRED,
 
2673
           from_unicode=signing_policy_from_unicode,
 
2674
           help='''\
 
2675
GPG Signing policy.
 
2676
 
 
2677
Possible values: always, never, when-required (default)
 
2678
 
 
2679
This option controls whether bzr will always create
 
2680
gpg signatures or not on commits.
 
2681
'''))
 
2682
option_registry.register(
2496
2683
    Option('dirstate.fdatasync', default=True,
2497
2684
           from_unicode=bool_from_store,
2498
2685
           help='''\
2503
2690
should not be lost if the machine crashes.  See also repository.fdatasync.
2504
2691
'''))
2505
2692
option_registry.register(
2506
 
    Option('debug_flags', default=[], from_unicode=list_from_store,
 
2693
    ListOption('debug_flags', default=[],
2507
2694
           help='Debug flags to activate.'))
2508
2695
option_registry.register(
2509
2696
    Option('default_format', default='2a',
2510
2697
           help='Format used when creating branches.'))
2511
2698
option_registry.register(
 
2699
    Option('dpush_strict', default=None,
 
2700
           from_unicode=bool_from_store,
 
2701
           help='''\
 
2702
The default value for ``dpush --strict``.
 
2703
 
 
2704
If present, defines the ``--strict`` option default value for checking
 
2705
uncommitted changes before pushing into a different VCS without any
 
2706
custom bzr metadata.
 
2707
'''))
 
2708
option_registry.register(
2512
2709
    Option('editor',
2513
2710
           help='The command called to launch an editor to enter a message.'))
2514
2711
option_registry.register(
 
2712
    Option('email', override_from_env=['BZR_EMAIL'], default=default_email,
 
2713
           help='The users identity'))
 
2714
option_registry.register(
 
2715
    Option('gpg_signing_command',
 
2716
           default='gpg',
 
2717
           help="""\
 
2718
Program to use use for creating signatures.
 
2719
 
 
2720
This should support at least the -u and --clearsign options.
 
2721
"""))
 
2722
option_registry.register(
 
2723
    Option('gpg_signing_key',
 
2724
           default=None,
 
2725
           help="""\
 
2726
GPG key to use for signing.
 
2727
 
 
2728
This defaults to the first key associated with the users email.
 
2729
"""))
 
2730
option_registry.register(
2515
2731
    Option('ignore_missing_extensions', default=False,
2516
2732
           from_unicode=bool_from_store,
2517
2733
           help='''\
2535
2751
Otherwise, bzr will prompt as normal to break the lock.
2536
2752
'''))
2537
2753
option_registry.register(
 
2754
    Option('log_format', default='long',
 
2755
           help= '''\
 
2756
Log format to use when displaying revisions.
 
2757
 
 
2758
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
 
2759
may be provided by plugins.
 
2760
'''))
 
2761
option_registry.register(
2538
2762
    Option('output_encoding',
2539
2763
           help= 'Unicode encoding for output'
2540
2764
           ' (terminal encoding if not specified).'))
2541
2765
option_registry.register(
 
2766
    Option('parent_location',
 
2767
           default=None,
 
2768
           help="""\
 
2769
The location of the default branch for pull or merge.
 
2770
 
 
2771
This option is normally set when creating a branch, the first ``pull`` or by
 
2772
``pull --remember``.
 
2773
"""))
 
2774
option_registry.register(
 
2775
    Option('post_commit', default=None,
 
2776
           help='''\
 
2777
Post commit functions.
 
2778
 
 
2779
An ordered list of python functions to call, separated by spaces.
 
2780
 
 
2781
Each function takes branch, rev_id as parameters.
 
2782
'''))
 
2783
option_registry.register(
 
2784
    Option('public_branch',
 
2785
           default=None,
 
2786
           help="""\
 
2787
A publically-accessible version of this branch.
 
2788
 
 
2789
This implies that the branch setting this option is not publically-accessible.
 
2790
Used and set by ``bzr send``.
 
2791
"""))
 
2792
option_registry.register(
 
2793
    Option('push_location',
 
2794
           default=None,
 
2795
           help="""\
 
2796
The location of the default branch for push.
 
2797
 
 
2798
This option is normally set by the first ``push`` or ``push --remember``.
 
2799
"""))
 
2800
option_registry.register(
 
2801
    Option('push_strict', default=None,
 
2802
           from_unicode=bool_from_store,
 
2803
           help='''\
 
2804
The default value for ``push --strict``.
 
2805
 
 
2806
If present, defines the ``--strict`` option default value for checking
 
2807
uncommitted changes before sending a merge directive.
 
2808
'''))
 
2809
option_registry.register(
2542
2810
    Option('repository.fdatasync', default=True,
2543
2811
           from_unicode=bool_from_store,
2544
2812
           help='''\
2548
2816
to physical disk.  This is somewhat slower, but means data should not be
2549
2817
lost if the machine crashes.  See also dirstate.fdatasync.
2550
2818
'''))
 
2819
option_registry.register_lazy('smtp_server',
 
2820
    'bzrlib.smtp_connection', 'smtp_server')
 
2821
option_registry.register_lazy('smtp_password',
 
2822
    'bzrlib.smtp_connection', 'smtp_password')
 
2823
option_registry.register_lazy('smtp_username',
 
2824
    'bzrlib.smtp_connection', 'smtp_username')
 
2825
option_registry.register(
 
2826
    Option('selftest.timeout',
 
2827
        default='600',
 
2828
        from_unicode=int_from_store,
 
2829
        help='Abort selftest if one test takes longer than this many seconds',
 
2830
        ))
 
2831
 
 
2832
option_registry.register(
 
2833
    Option('send_strict', default=None,
 
2834
           from_unicode=bool_from_store,
 
2835
           help='''\
 
2836
The default value for ``send --strict``.
 
2837
 
 
2838
If present, defines the ``--strict`` option default value for checking
 
2839
uncommitted changes before sending a bundle.
 
2840
'''))
 
2841
 
 
2842
option_registry.register(
 
2843
    Option('serve.client_timeout',
 
2844
           default=300.0, from_unicode=float_from_store,
 
2845
           help="If we wait for a new request from a client for more than"
 
2846
                " X seconds, consider the client idle, and hangup."))
 
2847
option_registry.register(
 
2848
    Option('stacked_on_location',
 
2849
           default=None,
 
2850
           help="""The location where this branch is stacked on."""))
 
2851
option_registry.register(
 
2852
    Option('submit_branch',
 
2853
           default=None,
 
2854
           help="""\
 
2855
The branch you intend to submit your current work to.
 
2856
 
 
2857
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
 
2858
by the ``submit:`` revision spec.
 
2859
"""))
2551
2860
 
2552
2861
 
2553
2862
class Section(object):
2563
2872
        # We re-use the dict-like object received
2564
2873
        self.options = options
2565
2874
 
2566
 
    def get(self, name, default=None):
 
2875
    def get(self, name, default=None, expand=True):
2567
2876
        return self.options.get(name, default)
2568
2877
 
 
2878
    def iter_option_names(self):
 
2879
        for k in self.options.iterkeys():
 
2880
            yield k
 
2881
 
2569
2882
    def __repr__(self):
2570
2883
        # Mostly for debugging use
2571
2884
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2630
2943
        """
2631
2944
        raise NotImplementedError(self.unload)
2632
2945
 
 
2946
    def quote(self, value):
 
2947
        """Quote a configuration option value for storing purposes.
 
2948
 
 
2949
        This allows Stacks to present values as they will be stored.
 
2950
        """
 
2951
        return value
 
2952
 
 
2953
    def unquote(self, value):
 
2954
        """Unquote a configuration option value into unicode.
 
2955
 
 
2956
        The received value is quoted as stored.
 
2957
        """
 
2958
        return value
 
2959
 
2633
2960
    def save(self):
2634
2961
        """Saves the Store to persistent storage."""
2635
2962
        raise NotImplementedError(self.save)
2640
2967
    def get_sections(self):
2641
2968
        """Returns an ordered iterable of existing sections.
2642
2969
 
2643
 
        :returns: An iterable of (name, dict).
 
2970
        :returns: An iterable of (store, section).
2644
2971
        """
2645
2972
        raise NotImplementedError(self.get_sections)
2646
2973
 
2647
 
    def get_mutable_section(self, section_name=None):
 
2974
    def get_mutable_section(self, section_id=None):
2648
2975
        """Returns the specified mutable section.
2649
2976
 
2650
 
        :param section_name: The section identifier
 
2977
        :param section_id: The section identifier
2651
2978
        """
2652
2979
        raise NotImplementedError(self.get_mutable_section)
2653
2980
 
2657
2984
                                    self.external_url())
2658
2985
 
2659
2986
 
 
2987
class CommandLineStore(Store):
 
2988
    "A store to carry command line overrides for the config options."""
 
2989
 
 
2990
    def __init__(self, opts=None):
 
2991
        super(CommandLineStore, self).__init__()
 
2992
        if opts is None:
 
2993
            opts = {}
 
2994
        self.options = {}
 
2995
        self.id = 'cmdline'
 
2996
 
 
2997
    def _reset(self):
 
2998
        # The dict should be cleared but not replaced so it can be shared.
 
2999
        self.options.clear()
 
3000
 
 
3001
    def _from_cmdline(self, overrides):
 
3002
        # Reset before accepting new definitions
 
3003
        self._reset()
 
3004
        for over in overrides:
 
3005
            try:
 
3006
                name, value = over.split('=', 1)
 
3007
            except ValueError:
 
3008
                raise errors.BzrCommandError(
 
3009
                    gettext("Invalid '%s', should be of the form 'name=value'")
 
3010
                    % (over,))
 
3011
            self.options[name] = value
 
3012
 
 
3013
    def external_url(self):
 
3014
        # Not an url but it makes debugging easier and is never needed
 
3015
        # otherwise
 
3016
        return 'cmdline'
 
3017
 
 
3018
    def get_sections(self):
 
3019
        yield self,  self.readonly_section_class(None, self.options)
 
3020
 
 
3021
 
2660
3022
class IniFileStore(Store):
2661
3023
    """A config Store using ConfigObj for storage.
2662
3024
 
2668
3030
        serialize/deserialize the config file.
2669
3031
    """
2670
3032
 
2671
 
    def __init__(self, transport, file_name):
 
3033
    def __init__(self):
2672
3034
        """A config Store using ConfigObj for storage.
2673
 
 
2674
 
        :param transport: The transport object where the config file is located.
2675
 
 
2676
 
        :param file_name: The config file basename in the transport directory.
2677
3035
        """
2678
3036
        super(IniFileStore, self).__init__()
2679
 
        self.transport = transport
2680
 
        self.file_name = file_name
2681
3037
        self._config_obj = None
2682
3038
 
2683
3039
    def is_loaded(self):
2686
3042
    def unload(self):
2687
3043
        self._config_obj = None
2688
3044
 
 
3045
    def _load_content(self):
 
3046
        """Load the config file bytes.
 
3047
 
 
3048
        This should be provided by subclasses
 
3049
 
 
3050
        :return: Byte string
 
3051
        """
 
3052
        raise NotImplementedError(self._load_content)
 
3053
 
 
3054
    def _save_content(self, content):
 
3055
        """Save the config file bytes.
 
3056
 
 
3057
        This should be provided by subclasses
 
3058
 
 
3059
        :param content: Config file bytes to write
 
3060
        """
 
3061
        raise NotImplementedError(self._save_content)
 
3062
 
2689
3063
    def load(self):
2690
3064
        """Load the store from the associated file."""
2691
3065
        if self.is_loaded():
2692
3066
            return
2693
 
        content = self.transport.get_bytes(self.file_name)
 
3067
        content = self._load_content()
2694
3068
        self._load_from_string(content)
2695
3069
        for hook in ConfigHooks['load']:
2696
3070
            hook(self)
2705
3079
        co_input = StringIO(bytes)
2706
3080
        try:
2707
3081
            # The config files are always stored utf8-encoded
2708
 
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
 
3082
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
 
3083
                                         list_values=False)
2709
3084
        except configobj.ConfigObjError, e:
2710
3085
            self._config_obj = None
2711
3086
            raise errors.ParseConfigError(e.errors, self.external_url())
2718
3093
            return
2719
3094
        out = StringIO()
2720
3095
        self._config_obj.write(out)
2721
 
        self.transport.put_bytes(self.file_name, out.getvalue())
 
3096
        self._save_content(out.getvalue())
2722
3097
        for hook in ConfigHooks['save']:
2723
3098
            hook(self)
2724
3099
 
2725
 
    def external_url(self):
2726
 
        # FIXME: external_url should really accepts an optional relpath
2727
 
        # parameter (bug #750169) :-/ -- vila 2011-04-04
2728
 
        # The following will do in the interim but maybe we don't want to
2729
 
        # expose a path here but rather a config ID and its associated
2730
 
        # object </hand wawe>.
2731
 
        return urlutils.join(self.transport.external_url(), self.file_name)
2732
 
 
2733
3100
    def get_sections(self):
2734
3101
        """Get the configobj section in the file order.
2735
3102
 
2736
 
        :returns: An iterable of (name, dict).
 
3103
        :returns: An iterable of (store, section).
2737
3104
        """
2738
3105
        # We need a loaded store
2739
3106
        try:
2740
3107
            self.load()
2741
 
        except errors.NoSuchFile:
2742
 
            # If the file doesn't exist, there is no sections
 
3108
        except (errors.NoSuchFile, errors.PermissionDenied):
 
3109
            # If the file can't be read, there is no sections
2743
3110
            return
2744
3111
        cobj = self._config_obj
2745
3112
        if cobj.scalars:
2746
 
            yield self.readonly_section_class(None, cobj)
 
3113
            yield self, self.readonly_section_class(None, cobj)
2747
3114
        for section_name in cobj.sections:
2748
 
            yield self.readonly_section_class(section_name, cobj[section_name])
 
3115
            yield (self,
 
3116
                   self.readonly_section_class(section_name,
 
3117
                                               cobj[section_name]))
2749
3118
 
2750
 
    def get_mutable_section(self, section_name=None):
 
3119
    def get_mutable_section(self, section_id=None):
2751
3120
        # We need a loaded store
2752
3121
        try:
2753
3122
            self.load()
2754
3123
        except errors.NoSuchFile:
2755
3124
            # The file doesn't exist, let's pretend it was empty
2756
3125
            self._load_from_string('')
2757
 
        if section_name is None:
 
3126
        if section_id is None:
2758
3127
            section = self._config_obj
2759
3128
        else:
2760
 
            section = self._config_obj.setdefault(section_name, {})
2761
 
        return self.mutable_section_class(section_name, section)
 
3129
            section = self._config_obj.setdefault(section_id, {})
 
3130
        return self.mutable_section_class(section_id, section)
 
3131
 
 
3132
    def quote(self, value):
 
3133
        try:
 
3134
            # configobj conflates automagical list values and quoting
 
3135
            self._config_obj.list_values = True
 
3136
            return self._config_obj._quote(value)
 
3137
        finally:
 
3138
            self._config_obj.list_values = False
 
3139
 
 
3140
    def unquote(self, value):
 
3141
        if value and isinstance(value, basestring):
 
3142
            # _unquote doesn't handle None nor empty strings nor anything that
 
3143
            # is not a string, really.
 
3144
            value = self._config_obj._unquote(value)
 
3145
        return value
 
3146
 
 
3147
 
 
3148
class TransportIniFileStore(IniFileStore):
 
3149
    """IniFileStore that loads files from a transport.
 
3150
    """
 
3151
 
 
3152
    def __init__(self, transport, file_name):
 
3153
        """A Store using a ini file on a Transport
 
3154
 
 
3155
        :param transport: The transport object where the config file is located.
 
3156
        :param file_name: The config file basename in the transport directory.
 
3157
        """
 
3158
        super(TransportIniFileStore, self).__init__()
 
3159
        self.transport = transport
 
3160
        self.file_name = file_name
 
3161
 
 
3162
    def _load_content(self):
 
3163
        try:
 
3164
            return self.transport.get_bytes(self.file_name)
 
3165
        except errors.PermissionDenied:
 
3166
            trace.warning("Permission denied while trying to load "
 
3167
                          "configuration store %s.", self.external_url())
 
3168
            raise
 
3169
 
 
3170
    def _save_content(self, content):
 
3171
        self.transport.put_bytes(self.file_name, content)
 
3172
 
 
3173
    def external_url(self):
 
3174
        # FIXME: external_url should really accepts an optional relpath
 
3175
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
3176
        # The following will do in the interim but maybe we don't want to
 
3177
        # expose a path here but rather a config ID and its associated
 
3178
        # object </hand wawe>.
 
3179
        return urlutils.join(self.transport.external_url(), self.file_name)
2762
3180
 
2763
3181
 
2764
3182
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2767
3185
# they may face the same issue.
2768
3186
 
2769
3187
 
2770
 
class LockableIniFileStore(IniFileStore):
 
3188
class LockableIniFileStore(TransportIniFileStore):
2771
3189
    """A ConfigObjStore using locks on save to ensure store integrity."""
2772
3190
 
2773
3191
    def __init__(self, transport, file_name, lock_dir_name=None):
2823
3241
        t = transport.get_transport_from_path(
2824
3242
            config_dir(), possible_transports=possible_transports)
2825
3243
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
3244
        self.id = 'bazaar'
2826
3245
 
2827
3246
 
2828
3247
class LocationStore(LockableIniFileStore):
2831
3250
        t = transport.get_transport_from_path(
2832
3251
            config_dir(), possible_transports=possible_transports)
2833
3252
        super(LocationStore, self).__init__(t, 'locations.conf')
2834
 
 
2835
 
 
2836
 
class BranchStore(IniFileStore):
 
3253
        self.id = 'locations'
 
3254
 
 
3255
 
 
3256
class BranchStore(TransportIniFileStore):
2837
3257
 
2838
3258
    def __init__(self, branch):
2839
3259
        super(BranchStore, self).__init__(branch.control_transport,
2840
3260
                                          'branch.conf')
2841
3261
        self.branch = branch
 
3262
        self.id = 'branch'
2842
3263
 
2843
3264
    def lock_write(self, token=None):
2844
3265
        return self.branch.lock_write(token)
2861
3282
        super(ControlStore, self).__init__(bzrdir.transport,
2862
3283
                                          'control.conf',
2863
3284
                                           lock_dir_name='branch_lock')
 
3285
        self.id = 'control'
2864
3286
 
2865
3287
 
2866
3288
class SectionMatcher(object):
2867
3289
    """Select sections into a given Store.
2868
3290
 
2869
 
    This intended to be used to postpone getting an iterable of sections from a
2870
 
    store.
 
3291
    This is intended to be used to postpone getting an iterable of sections
 
3292
    from a store.
2871
3293
    """
2872
3294
 
2873
3295
    def __init__(self, store):
2878
3300
        # sections.
2879
3301
        sections = self.store.get_sections()
2880
3302
        # Walk the revisions in the order provided
2881
 
        for s in sections:
 
3303
        for store, s in sections:
2882
3304
            if self.match(s):
2883
 
                yield s
2884
 
 
2885
 
    def match(self, secion):
 
3305
                yield store, s
 
3306
 
 
3307
    def match(self, section):
 
3308
        """Does the proposed section match.
 
3309
 
 
3310
        :param section: A Section object.
 
3311
 
 
3312
        :returns: True if the section matches, False otherwise.
 
3313
        """
2886
3314
        raise NotImplementedError(self.match)
2887
3315
 
2888
3316
 
 
3317
class NameMatcher(SectionMatcher):
 
3318
 
 
3319
    def __init__(self, store, section_id):
 
3320
        super(NameMatcher, self).__init__(store)
 
3321
        self.section_id = section_id
 
3322
 
 
3323
    def match(self, section):
 
3324
        return section.id == self.section_id
 
3325
 
 
3326
 
2889
3327
class LocationSection(Section):
2890
3328
 
2891
3329
    def __init__(self, section, length, extra_path):
2892
3330
        super(LocationSection, self).__init__(section.id, section.options)
2893
3331
        self.length = length
2894
3332
        self.extra_path = extra_path
 
3333
        self.locals = {'relpath': extra_path,
 
3334
                       'basename': urlutils.basename(extra_path)}
2895
3335
 
2896
 
    def get(self, name, default=None):
 
3336
    def get(self, name, default=None, expand=True):
2897
3337
        value = super(LocationSection, self).get(name, default)
2898
 
        if value is not None:
 
3338
        if value is not None and expand:
2899
3339
            policy_name = self.get(name + ':policy', None)
2900
3340
            policy = _policy_value.get(policy_name, POLICY_NONE)
2901
3341
            if policy == POLICY_APPENDPATH:
2902
3342
                value = urlutils.join(value, self.extra_path)
 
3343
            # expand section local options right now (since POLICY_APPENDPATH
 
3344
            # will never add options references, it's ok to expand after it).
 
3345
            chunks = []
 
3346
            for is_ref, chunk in iter_option_refs(value):
 
3347
                if not is_ref:
 
3348
                    chunks.append(chunk)
 
3349
                else:
 
3350
                    ref = chunk[1:-1]
 
3351
                    if ref in self.locals:
 
3352
                        chunks.append(self.locals[ref])
 
3353
                    else:
 
3354
                        chunks.append(chunk)
 
3355
            value = ''.join(chunks)
2903
3356
        return value
2904
3357
 
2905
3358
 
2919
3372
        all_sections = []
2920
3373
        # Filter out the no_name_section so _iter_for_location_by_parts can be
2921
3374
        # used (it assumes all sections have a name).
2922
 
        for section in self.store.get_sections():
 
3375
        for _, section in self.store.get_sections():
2923
3376
            if section.id is None:
2924
3377
                no_name_section = section
2925
3378
            else:
2962
3415
            if ignore:
2963
3416
                break
2964
3417
            # Finally, we have a valid section
2965
 
            yield section
 
3418
            yield self.store, section
 
3419
 
 
3420
 
 
3421
_option_ref_re = lazy_regex.lazy_compile('({[^{}\n]+})')
 
3422
"""Describes an expandable option reference.
 
3423
 
 
3424
We want to match the most embedded reference first.
 
3425
 
 
3426
I.e. for '{{foo}}' we will get '{foo}',
 
3427
for '{bar{baz}}' we will get '{baz}'
 
3428
"""
 
3429
 
 
3430
def iter_option_refs(string):
 
3431
    # Split isolate refs so every other chunk is a ref
 
3432
    is_ref = False
 
3433
    for chunk  in _option_ref_re.split(string):
 
3434
        yield is_ref, chunk
 
3435
        is_ref = not is_ref
2966
3436
 
2967
3437
 
2968
3438
class Stack(object):
2969
3439
    """A stack of configurations where an option can be defined"""
2970
3440
 
2971
 
    def __init__(self, sections_def, store=None, mutable_section_name=None):
 
3441
    def __init__(self, sections_def, store=None, mutable_section_id=None):
2972
3442
        """Creates a stack of sections with an optional store for changes.
2973
3443
 
2974
3444
        :param sections_def: A list of Section or callables that returns an
2978
3448
        :param store: The optional Store where modifications will be
2979
3449
            recorded. If none is specified, no modifications can be done.
2980
3450
 
2981
 
        :param mutable_section_name: The name of the MutableSection where
2982
 
            changes are recorded. This requires the ``store`` parameter to be
 
3451
        :param mutable_section_id: The id of the MutableSection where changes
 
3452
            are recorded. This requires the ``store`` parameter to be
2983
3453
            specified.
2984
3454
        """
2985
3455
        self.sections_def = sections_def
2986
3456
        self.store = store
2987
 
        self.mutable_section_name = mutable_section_name
 
3457
        self.mutable_section_id = mutable_section_id
2988
3458
 
2989
 
    def get(self, name):
 
3459
    def get(self, name, expand=None):
2990
3460
        """Return the *first* option value found in the sections.
2991
3461
 
2992
3462
        This is where we guarantee that sections coming from Store are loaded
2994
3464
        option exists or get its value, which in turn may require to discover
2995
3465
        in which sections it can be defined. Both of these (section and option
2996
3466
        existence) require loading the store (even partially).
 
3467
 
 
3468
        :param name: The queried option.
 
3469
 
 
3470
        :param expand: Whether options references should be expanded.
 
3471
 
 
3472
        :returns: The value of the option.
2997
3473
        """
2998
3474
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
3475
        if expand is None:
 
3476
            expand = _get_expand_default_value()
2999
3477
        value = None
3000
 
        # Ensuring lazy loading is achieved by delaying section matching (which
3001
 
        # implies querying the persistent storage) until it can't be avoided
3002
 
        # anymore by using callables to describe (possibly empty) section
3003
 
        # lists.
3004
 
        for section_or_callable in self.sections_def:
3005
 
            # Each section can expand to multiple ones when a callable is used
3006
 
            if callable(section_or_callable):
3007
 
                sections = section_or_callable()
3008
 
            else:
3009
 
                sections = [section_or_callable]
3010
 
            for section in sections:
3011
 
                value = section.get(name)
3012
 
                if value is not None:
3013
 
                    break
3014
 
            if value is not None:
3015
 
                break
 
3478
        found_store = None # Where the option value has been found
3016
3479
        # If the option is registered, it may provide additional info about
3017
3480
        # value handling
3018
3481
        try:
3020
3483
        except KeyError:
3021
3484
            # Not registered
3022
3485
            opt = None
3023
 
        if opt is not None:
3024
 
            value = opt.convert_from_unicode(value)
3025
 
            if value is None:
3026
 
                # The conversion failed or there was no value to convert,
3027
 
                # fallback to the default value
3028
 
                value = opt.convert_from_unicode(opt.get_default())
 
3486
 
 
3487
        def expand_and_convert(val):
 
3488
            # This may need to be called in different contexts if the value is
 
3489
            # None or ends up being None during expansion or conversion.
 
3490
            if val is not None:
 
3491
                if expand:
 
3492
                    if isinstance(val, basestring):
 
3493
                        val = self._expand_options_in_string(val)
 
3494
                    else:
 
3495
                        trace.warning('Cannot expand "%s":'
 
3496
                                      ' %s does not support option expansion'
 
3497
                                      % (name, type(val)))
 
3498
                if opt is None:
 
3499
                    val = found_store.unquote(val)
 
3500
                else:
 
3501
                    val = opt.convert_from_unicode(found_store, val)
 
3502
            return val
 
3503
 
 
3504
        # First of all, check if the environment can override the configuration
 
3505
        # value
 
3506
        if opt is not None and opt.override_from_env:
 
3507
            value = opt.get_override()
 
3508
            value = expand_and_convert(value)
 
3509
        if value is None:
 
3510
            # Ensuring lazy loading is achieved by delaying section matching
 
3511
            # (which implies querying the persistent storage) until it can't be
 
3512
            # avoided anymore by using callables to describe (possibly empty)
 
3513
            # section lists.
 
3514
            for sections in self.sections_def:
 
3515
                for store, section in sections():
 
3516
                    value = section.get(name)
 
3517
                    if value is not None:
 
3518
                        found_store = store
 
3519
                        break
 
3520
                if value is not None:
 
3521
                    break
 
3522
            value = expand_and_convert(value)
 
3523
            if opt is not None and value is None:
 
3524
                # If the option is registered, it may provide a default value
 
3525
                value = opt.get_default()
 
3526
                value = expand_and_convert(value)
3029
3527
        for hook in ConfigHooks['get']:
3030
3528
            hook(self, name, value)
3031
3529
        return value
3032
3530
 
 
3531
    def expand_options(self, string, env=None):
 
3532
        """Expand option references in the string in the configuration context.
 
3533
 
 
3534
        :param string: The string containing option(s) to expand.
 
3535
 
 
3536
        :param env: An option dict defining additional configuration options or
 
3537
            overriding existing ones.
 
3538
 
 
3539
        :returns: The expanded string.
 
3540
        """
 
3541
        return self._expand_options_in_string(string, env)
 
3542
 
 
3543
    def _expand_options_in_string(self, string, env=None, _refs=None):
 
3544
        """Expand options in the string in the configuration context.
 
3545
 
 
3546
        :param string: The string to be expanded.
 
3547
 
 
3548
        :param env: An option dict defining additional configuration options or
 
3549
            overriding existing ones.
 
3550
 
 
3551
        :param _refs: Private list (FIFO) containing the options being expanded
 
3552
            to detect loops.
 
3553
 
 
3554
        :returns: The expanded string.
 
3555
        """
 
3556
        if string is None:
 
3557
            # Not much to expand there
 
3558
            return None
 
3559
        if _refs is None:
 
3560
            # What references are currently resolved (to detect loops)
 
3561
            _refs = []
 
3562
        result = string
 
3563
        # We need to iterate until no more refs appear ({{foo}} will need two
 
3564
        # iterations for example).
 
3565
        expanded = True
 
3566
        while expanded:
 
3567
            expanded = False
 
3568
            chunks = []
 
3569
            for is_ref, chunk in iter_option_refs(result):
 
3570
                if not is_ref:
 
3571
                    chunks.append(chunk)
 
3572
                else:
 
3573
                    expanded = True
 
3574
                    name = chunk[1:-1]
 
3575
                    if name in _refs:
 
3576
                        raise errors.OptionExpansionLoop(string, _refs)
 
3577
                    _refs.append(name)
 
3578
                    value = self._expand_option(name, env, _refs)
 
3579
                    if value is None:
 
3580
                        raise errors.ExpandingUnknownOption(name, string)
 
3581
                    chunks.append(value)
 
3582
                    _refs.pop()
 
3583
            result = ''.join(chunks)
 
3584
        return result
 
3585
 
 
3586
    def _expand_option(self, name, env, _refs):
 
3587
        if env is not None and name in env:
 
3588
            # Special case, values provided in env takes precedence over
 
3589
            # anything else
 
3590
            value = env[name]
 
3591
        else:
 
3592
            value = self.get(name, expand=False)
 
3593
            value = self._expand_options_in_string(value, env, _refs)
 
3594
        return value
 
3595
 
3033
3596
    def _get_mutable_section(self):
3034
3597
        """Get the MutableSection for the Stack.
3035
3598
 
3036
3599
        This is where we guarantee that the mutable section is lazily loaded:
3037
3600
        this means we won't load the corresponding store before setting a value
3038
3601
        or deleting an option. In practice the store will often be loaded but
3039
 
        this allows helps catching some programming errors.
 
3602
        this helps catching some programming errors.
3040
3603
        """
3041
 
        section = self.store.get_mutable_section(self.mutable_section_name)
3042
 
        return section
 
3604
        store = self.store
 
3605
        section = store.get_mutable_section(self.mutable_section_id)
 
3606
        return store, section
3043
3607
 
3044
3608
    def set(self, name, value):
3045
3609
        """Set a new value for the option."""
3046
 
        section = self._get_mutable_section()
3047
 
        section.set(name, value)
 
3610
        store, section = self._get_mutable_section()
 
3611
        section.set(name, store.quote(value))
3048
3612
        for hook in ConfigHooks['set']:
3049
3613
            hook(self, name, value)
3050
3614
 
3051
3615
    def remove(self, name):
3052
3616
        """Remove an existing option."""
3053
 
        section = self._get_mutable_section()
 
3617
        _, section = self._get_mutable_section()
3054
3618
        section.remove(name)
3055
3619
        for hook in ConfigHooks['remove']:
3056
3620
            hook(self, name)
3059
3623
        # Mostly for debugging use
3060
3624
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
3061
3625
 
 
3626
    def _get_overrides(self):
 
3627
        # Hack around library_state.initialize never called
 
3628
        if bzrlib.global_state is not None:
 
3629
            return bzrlib.global_state.cmdline_overrides.get_sections()
 
3630
        return []
 
3631
 
 
3632
 
 
3633
class MemoryStack(Stack):
 
3634
    """A configuration stack defined from a string.
 
3635
 
 
3636
    This is mainly intended for tests and requires no disk resources.
 
3637
    """
 
3638
 
 
3639
    def __init__(self, content=None):
 
3640
        """Create an in-memory stack from a given content.
 
3641
 
 
3642
        It uses a single store based on configobj and support reading and
 
3643
        writing options.
 
3644
 
 
3645
        :param content: The initial content of the store. If None, the store is
 
3646
            not loaded and ``_load_from_string`` can and should be used if
 
3647
            needed.
 
3648
        """
 
3649
        store = IniFileStore()
 
3650
        if content is not None:
 
3651
            store._load_from_string(content)
 
3652
        super(MemoryStack, self).__init__(
 
3653
            [store.get_sections], store)
 
3654
 
3062
3655
 
3063
3656
class _CompatibleStack(Stack):
3064
3657
    """Place holder for compatibility with previous design.
3069
3662
    One assumption made here is that the daughter classes will all use Stores
3070
3663
    derived from LockableIniFileStore).
3071
3664
 
3072
 
    It implements set() by re-loading the store before applying the
3073
 
    modification and saving it.
 
3665
    It implements set() and remove () by re-loading the store before applying
 
3666
    the modification and saving it.
3074
3667
 
3075
3668
    The long term plan being to implement a single write by store to save
3076
3669
    all modifications, this class should not be used in the interim.
3083
3676
        # Force a write to persistent storage
3084
3677
        self.store.save()
3085
3678
 
 
3679
    def remove(self, name):
 
3680
        # Force a reload
 
3681
        self.store.unload()
 
3682
        super(_CompatibleStack, self).remove(name)
 
3683
        # Force a write to persistent storage
 
3684
        self.store.save()
 
3685
 
3086
3686
 
3087
3687
class GlobalStack(_CompatibleStack):
3088
 
    """Global options only stack."""
 
3688
    """Global options only stack.
 
3689
 
 
3690
    The following sections are queried:
 
3691
 
 
3692
    * command-line overrides,
 
3693
 
 
3694
    * the 'DEFAULT' section in bazaar.conf
 
3695
 
 
3696
    This stack will use the ``DEFAULT`` section in bazaar.conf as its
 
3697
    MutableSection.
 
3698
    """
3089
3699
 
3090
3700
    def __init__(self):
3091
 
        # Get a GlobalStore
3092
3701
        gstore = GlobalStore()
3093
 
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
 
3702
        super(GlobalStack, self).__init__(
 
3703
            [self._get_overrides,
 
3704
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
3705
            gstore, mutable_section_id='DEFAULT')
3094
3706
 
3095
3707
 
3096
3708
class LocationStack(_CompatibleStack):
3097
 
    """Per-location options falling back to global options stack."""
 
3709
    """Per-location options falling back to global options stack.
 
3710
 
 
3711
 
 
3712
    The following sections are queried:
 
3713
 
 
3714
    * command-line overrides,
 
3715
 
 
3716
    * the sections matching ``location`` in ``locations.conf``, the order being
 
3717
      defined by the number of path components in the section glob, higher
 
3718
      numbers first (from most specific section to most generic).
 
3719
 
 
3720
    * the 'DEFAULT' section in bazaar.conf
 
3721
 
 
3722
    This stack will use the ``location`` section in locations.conf as its
 
3723
    MutableSection.
 
3724
    """
3098
3725
 
3099
3726
    def __init__(self, location):
3100
3727
        """Make a new stack for a location and global configuration.
3101
 
        
 
3728
 
3102
3729
        :param location: A URL prefix to """
3103
3730
        lstore = LocationStore()
3104
 
        matcher = LocationMatcher(lstore, location)
 
3731
        if location.startswith('file://'):
 
3732
            location = urlutils.local_path_from_url(location)
3105
3733
        gstore = GlobalStore()
3106
3734
        super(LocationStack, self).__init__(
3107
 
            [matcher.get_sections, gstore.get_sections], lstore)
 
3735
            [self._get_overrides,
 
3736
             LocationMatcher(lstore, location).get_sections,
 
3737
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
3738
            lstore, mutable_section_id=location)
3108
3739
 
3109
3740
 
3110
3741
class BranchStack(_CompatibleStack):
3111
 
    """Per-location options falling back to branch then global options stack."""
 
3742
    """Per-location options falling back to branch then global options stack.
 
3743
 
 
3744
    The following sections are queried:
 
3745
 
 
3746
    * command-line overrides,
 
3747
 
 
3748
    * the sections matching ``location`` in ``locations.conf``, the order being
 
3749
      defined by the number of path components in the section glob, higher
 
3750
      numbers first (from most specific section to most generic),
 
3751
 
 
3752
    * the no-name section in branch.conf,
 
3753
 
 
3754
    * the ``DEFAULT`` section in ``bazaar.conf``.
 
3755
 
 
3756
    This stack will use the no-name section in ``branch.conf`` as its
 
3757
    MutableSection.
 
3758
    """
3112
3759
 
3113
3760
    def __init__(self, branch):
3114
 
        bstore = BranchStore(branch)
3115
3761
        lstore = LocationStore()
3116
 
        matcher = LocationMatcher(lstore, branch.base)
 
3762
        bstore = branch._get_config_store()
3117
3763
        gstore = GlobalStore()
3118
3764
        super(BranchStack, self).__init__(
3119
 
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
 
3765
            [self._get_overrides,
 
3766
             LocationMatcher(lstore, branch.base).get_sections,
 
3767
             NameMatcher(bstore, None).get_sections,
 
3768
             NameMatcher(gstore, 'DEFAULT').get_sections],
3120
3769
            bstore)
3121
3770
        self.branch = branch
3122
3771
 
3124
3773
class RemoteControlStack(_CompatibleStack):
3125
3774
    """Remote control-only options stack."""
3126
3775
 
 
3776
    # FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
 
3777
    # with the stack used for remote bzr dirs. RemoteControlStack only uses
 
3778
    # control.conf and is used only for stack options.
 
3779
 
3127
3780
    def __init__(self, bzrdir):
3128
 
        cstore = ControlStore(bzrdir)
 
3781
        cstore = bzrdir._get_config_store()
3129
3782
        super(RemoteControlStack, self).__init__(
3130
 
            [cstore.get_sections],
 
3783
            [NameMatcher(cstore, None).get_sections],
3131
3784
            cstore)
3132
3785
        self.bzrdir = bzrdir
3133
3786
 
3134
3787
 
3135
 
class RemoteBranchStack(_CompatibleStack):
3136
 
    """Remote branch-only options stack."""
 
3788
class BranchOnlyStack(_CompatibleStack):
 
3789
    """Branch-only options stack."""
 
3790
 
 
3791
    # FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
 
3792
    # stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
 
3793
    # -- vila 2011-12-16
3137
3794
 
3138
3795
    def __init__(self, branch):
3139
 
        bstore = BranchStore(branch)
3140
 
        super(RemoteBranchStack, self).__init__(
3141
 
            [bstore.get_sections],
 
3796
        bstore = branch._get_config_store()
 
3797
        super(BranchOnlyStack, self).__init__(
 
3798
            [NameMatcher(bstore, None).get_sections],
3142
3799
            bstore)
3143
3800
        self.branch = branch
3144
3801
 
3145
3802
 
 
3803
# Use a an empty dict to initialize an empty configobj avoiding all
 
3804
# parsing and encoding checks
 
3805
_quoting_config = configobj.ConfigObj(
 
3806
    {}, encoding='utf-8', interpolation=False, list_values=True)
 
3807
 
3146
3808
class cmd_config(commands.Command):
3147
3809
    __doc__ = """Display, set or remove a configuration option.
3148
3810
 
3164
3826
    takes_options = [
3165
3827
        'directory',
3166
3828
        # FIXME: This should be a registry option so that plugins can register
3167
 
        # their own config files (or not) -- vila 20101002
 
3829
        # their own config files (or not) and will also address
 
3830
        # http://pad.lv/788991 -- vila 20101115
3168
3831
        commands.Option('scope', help='Reduce the scope to the specified'
3169
 
                        ' configuration file',
 
3832
                        ' configuration file.',
3170
3833
                        type=unicode),
3171
3834
        commands.Option('all',
3172
3835
            help='Display all the defined values for the matching options.',
3173
3836
            ),
3174
3837
        commands.Option('remove', help='Remove the option from'
3175
 
                        ' the configuration file'),
 
3838
                        ' the configuration file.'),
3176
3839
        ]
3177
3840
 
3178
3841
    _see_also = ['configuration']
3208
3871
                # Set the option value
3209
3872
                self._set_config_option(name, value, directory, scope)
3210
3873
 
3211
 
    def _get_configs(self, directory, scope=None):
3212
 
        """Iterate the configurations specified by ``directory`` and ``scope``.
 
3874
    def _get_stack(self, directory, scope=None):
 
3875
        """Get the configuration stack specified by ``directory`` and ``scope``.
3213
3876
 
3214
3877
        :param directory: Where the configurations are derived from.
3215
3878
 
3216
3879
        :param scope: A specific config to start from.
3217
3880
        """
 
3881
        # FIXME: scope should allow access to plugin-specific stacks (even
 
3882
        # reduced to the plugin-specific store), related to
 
3883
        # http://pad.lv/788991 -- vila 2011-11-15
3218
3884
        if scope is not None:
3219
3885
            if scope == 'bazaar':
3220
 
                yield GlobalConfig()
 
3886
                return GlobalStack()
3221
3887
            elif scope == 'locations':
3222
 
                yield LocationConfig(directory)
 
3888
                return LocationStack(directory)
3223
3889
            elif scope == 'branch':
3224
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3225
 
                    directory)
3226
 
                yield br.get_config()
 
3890
                (_, br, _) = (
 
3891
                    controldir.ControlDir.open_containing_tree_or_branch(
 
3892
                        directory))
 
3893
                return br.get_config_stack()
 
3894
            raise errors.NoSuchConfig(scope)
3227
3895
        else:
3228
3896
            try:
3229
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3230
 
                    directory)
3231
 
                yield br.get_config()
 
3897
                (_, br, _) = (
 
3898
                    controldir.ControlDir.open_containing_tree_or_branch(
 
3899
                        directory))
 
3900
                return br.get_config_stack()
3232
3901
            except errors.NotBranchError:
3233
 
                yield LocationConfig(directory)
3234
 
                yield GlobalConfig()
 
3902
                return LocationStack(directory)
3235
3903
 
3236
3904
    def _show_value(self, name, directory, scope):
3237
 
        displayed = False
3238
 
        for c in self._get_configs(directory, scope):
3239
 
            if displayed:
3240
 
                break
3241
 
            for (oname, value, section, conf_id, parser) in c._get_options():
3242
 
                if name == oname:
3243
 
                    # Display only the first value and exit
3244
 
 
3245
 
                    # FIXME: We need to use get_user_option to take policies
3246
 
                    # into account and we need to make sure the option exists
3247
 
                    # too (hence the two for loops), this needs a better API
3248
 
                    # -- vila 20101117
3249
 
                    value = c.get_user_option(name)
3250
 
                    # Quote the value appropriately
3251
 
                    value = parser._quote(value)
3252
 
                    self.outf.write('%s\n' % (value,))
3253
 
                    displayed = True
3254
 
                    break
3255
 
        if not displayed:
 
3905
        conf = self._get_stack(directory, scope)
 
3906
        value = conf.get(name, expand=True)
 
3907
        if value is not None:
 
3908
            # Quote the value appropriately
 
3909
            value = _quoting_config._quote(value)
 
3910
            self.outf.write('%s\n' % (value,))
 
3911
        else:
3256
3912
            raise errors.NoSuchConfigOption(name)
3257
3913
 
3258
3914
    def _show_matching_options(self, name, directory, scope):
3261
3917
        # avoid the delay introduced by the lazy regexp.  But, we still do
3262
3918
        # want the nicer errors raised by lazy_regex.
3263
3919
        name._compile_and_collapse()
3264
 
        cur_conf_id = None
 
3920
        cur_store_id = None
3265
3921
        cur_section = None
3266
 
        for c in self._get_configs(directory, scope):
3267
 
            for (oname, value, section, conf_id, parser) in c._get_options():
3268
 
                if name.search(oname):
3269
 
                    if cur_conf_id != conf_id:
3270
 
                        # Explain where the options are defined
3271
 
                        self.outf.write('%s:\n' % (conf_id,))
3272
 
                        cur_conf_id = conf_id
3273
 
                        cur_section = None
3274
 
                    if (section not in (None, 'DEFAULT')
3275
 
                        and cur_section != section):
3276
 
                        # Display the section if it's not the default (or only)
3277
 
                        # one.
3278
 
                        self.outf.write('  [%s]\n' % (section,))
3279
 
                        cur_section = section
3280
 
                    self.outf.write('  %s = %s\n' % (oname, value))
 
3922
        conf = self._get_stack(directory, scope)
 
3923
        for sections in conf.sections_def:
 
3924
            for store, section in sections():
 
3925
                for oname in section.iter_option_names():
 
3926
                    if name.search(oname):
 
3927
                        if cur_store_id != store.id:
 
3928
                            # Explain where the options are defined
 
3929
                            self.outf.write('%s:\n' % (store.id,))
 
3930
                            cur_store_id = store.id
 
3931
                            cur_section = None
 
3932
                        if (section.id is not None
 
3933
                            and cur_section != section.id):
 
3934
                            # Display the section id as it appears in the store
 
3935
                            # (None doesn't appear by definition)
 
3936
                            self.outf.write('  [%s]\n' % (section.id,))
 
3937
                            cur_section = section.id
 
3938
                        value = section.get(oname, expand=False)
 
3939
                        # Since we don't use the stack, we need to restore a
 
3940
                        # proper quoting.
 
3941
                        try:
 
3942
                            opt = option_registry.get(oname)
 
3943
                            value = opt.convert_from_unicode(store, value)
 
3944
                        except KeyError:
 
3945
                            value = store.unquote(value)
 
3946
                        value = _quoting_config._quote(value)
 
3947
                        self.outf.write('  %s = %s\n' % (oname, value))
3281
3948
 
3282
3949
    def _set_config_option(self, name, value, directory, scope):
3283
 
        for conf in self._get_configs(directory, scope):
3284
 
            conf.set_user_option(name, value)
3285
 
            break
3286
 
        else:
3287
 
            raise errors.NoSuchConfig(scope)
 
3950
        conf = self._get_stack(directory, scope)
 
3951
        conf.set(name, value)
3288
3952
 
3289
3953
    def _remove_config_option(self, name, directory, scope):
3290
3954
        if name is None:
3291
3955
            raise errors.BzrCommandError(
3292
3956
                '--remove expects an option to remove.')
3293
 
        removed = False
3294
 
        for conf in self._get_configs(directory, scope):
3295
 
            for (section_name, section, conf_id) in conf._get_sections():
3296
 
                if scope is not None and conf_id != scope:
3297
 
                    # Not the right configuration file
3298
 
                    continue
3299
 
                if name in section:
3300
 
                    if conf_id != conf.config_id():
3301
 
                        conf = self._get_configs(directory, conf_id).next()
3302
 
                    # We use the first section in the first config where the
3303
 
                    # option is defined to remove it
3304
 
                    conf.remove_user_option(name, section_name)
3305
 
                    removed = True
3306
 
                    break
3307
 
            break
3308
 
        else:
3309
 
            raise errors.NoSuchConfig(scope)
3310
 
        if not removed:
 
3957
        conf = self._get_stack(directory, scope)
 
3958
        try:
 
3959
            conf.remove(name)
 
3960
        except KeyError:
3311
3961
            raise errors.NoSuchConfigOption(name)
3312
3962
 
 
3963
 
3313
3964
# Test registries
3314
3965
#
3315
3966
# We need adapters that can build a Store or a Stack in a test context. Test
3318
3969
# ready-to-use store or stack.  Plugins that define new store/stacks can also
3319
3970
# register themselves here to be tested against the tests defined in
3320
3971
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3321
 
# for the same tests.
 
3972
# for the same test.
3322
3973
 
3323
3974
# The registered object should be a callable receiving a test instance
3324
3975
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store