~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Martin von Gagern
  • Date: 2011-06-01 12:53:56 UTC
  • mto: This revision was merged to the branch mainline in revision 6009.
  • Revision ID: martin.vgagern@gmx.net-20110601125356-lwozv2vecea6hxfz
Change from no_decorate to classify as name for the argument.

The command line switch remains as --no-classify, to keep backwards
compatibility.  Users are free to include --no-classify in an alias, and
still use --classify to change back.

Show diffs side-by-side

added added

removed removed

Lines of Context:
29
29
create_signatures=always|never|when-required(default)
30
30
gpg_signing_command=name-of-program
31
31
log_format=name-of-format
32
 
validate_signatures_in_log=true|false(default)
33
 
acceptable_keys=pattern1,pattern2
34
 
gpg_signing_key=amy@example.com
35
32
 
36
33
in locations.conf, you specify the url of a branch and options for it.
37
34
Wildcards may be used - * and ? as normal in shell completion. Options
42
39
email= as above
43
40
check_signatures= as above
44
41
create_signatures= as above.
45
 
validate_signatures_in_log=as above
46
 
acceptable_keys=as above
47
42
 
48
43
explanation of options
49
44
----------------------
50
45
editor - this option sets the pop up editor to use during commits.
51
46
email - this option sets the user id bzr will use when committing.
52
 
check_signatures - this option will control whether bzr will require good gpg
 
47
check_signatures - this option controls whether bzr will require good gpg
53
48
                   signatures, ignore them, or check them if they are
54
 
                   present.  Currently it is unused except that check_signatures
55
 
                   turns on create_signatures.
 
49
                   present.
56
50
create_signatures - this option controls whether bzr will always create
57
 
                    gpg signatures or not on commits.  There is an unused
58
 
                    option which in future is expected to work if               
59
 
                    branch settings require signatures.
 
51
                    gpg signatures, never create them, or create them if the
 
52
                    branch is configured to require them.
60
53
log_format - this option sets the default log format.  Possible values are
61
54
             long, short, line, or a plugin can register new formats.
62
 
validate_signatures_in_log - show GPG signature validity in log output
63
 
acceptable_keys - comma separated list of key patterns acceptable for
64
 
                  verify-signatures command
65
55
 
66
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
67
57
 
75
65
import os
76
66
import string
77
67
import sys
78
 
 
79
 
 
 
68
import weakref
 
69
 
 
70
from bzrlib import commands
80
71
from bzrlib.decorators import needs_write_lock
81
72
from bzrlib.lazy_import import lazy_import
82
73
lazy_import(globals(), """
84
75
import re
85
76
from cStringIO import StringIO
86
77
 
 
78
import bzrlib
87
79
from bzrlib import (
88
80
    atomicfile,
89
81
    bzrdir,
90
82
    debug,
91
83
    errors,
92
 
    lazy_regex,
93
84
    lockdir,
94
85
    mail_client,
95
86
    mergetools,
104
95
from bzrlib.util.configobj import configobj
105
96
""")
106
97
from bzrlib import (
107
 
    commands,
108
 
    hooks,
109
 
    lazy_regex,
110
98
    registry,
111
99
    )
112
100
from bzrlib.symbol_versioning import (
157
145
                                        interpolation=False,
158
146
                                        **kwargs)
159
147
 
 
148
 
160
149
    def get_bool(self, section, key):
161
150
        return self[section].as_bool(key)
162
151
 
170
159
        return self[section][name]
171
160
 
172
161
 
173
 
# FIXME: Until we can guarantee that each config file is loaded once and
 
162
# FIXME: Until we can guarantee that each config file is loaded once and and
174
163
# only once for a given bzrlib session, we don't want to re-read the file every
175
164
# time we query for an option so we cache the value (bad ! watch out for tests
176
 
# needing to restore the proper value). -- vila 20110219
 
165
# needing to restore the proper value).This shouldn't be part of 2.4.0 final,
 
166
# yell at mgz^W vila and the RM if this is still present at that time
 
167
# -- vila 20110219
177
168
_expand_default_value = None
178
169
def _get_expand_default_value():
179
170
    global _expand_default_value
379
370
                              % (option_name,))
380
371
            else:
381
372
                value = self._expand_options_in_string(value)
382
 
        for hook in OldConfigHooks['get']:
383
 
            hook(self, option_name, value)
384
373
        return value
385
374
 
386
 
    def get_user_option_as_bool(self, option_name, expand=None, default=None):
387
 
        """Get a generic option as a boolean.
 
375
    def get_user_option_as_bool(self, option_name, expand=None):
 
376
        """Get a generic option as a boolean - no special process, no default.
388
377
 
389
 
        :param expand: Allow expanding references to other config values.
390
 
        :param default: Default value if nothing is configured
391
378
        :return None if the option doesn't exist or its value can't be
392
379
            interpreted as a boolean. Returns True or False otherwise.
393
380
        """
394
381
        s = self.get_user_option(option_name, expand=expand)
395
382
        if s is None:
396
383
            # The option doesn't exist
397
 
            return default
 
384
            return None
398
385
        val = ui.bool_from_string(s)
399
386
        if val is None:
400
387
            # The value can't be interpreted as a boolean
414
401
            # add) the final ','
415
402
            l = [l]
416
403
        return l
417
 
        
418
 
    def get_user_option_as_int_from_SI(self,  option_name,  default=None):
419
 
        """Get a generic option from a human readable size in SI units, e.g 10MB
420
 
        
421
 
        Accepted suffixes are K,M,G. It is case-insensitive and may be followed
422
 
        by a trailing b (i.e. Kb, MB). This is intended to be practical and not
423
 
        pedantic.
424
 
        
425
 
        :return Integer, expanded to its base-10 value if a proper SI unit is 
426
 
            found. If the option doesn't exist, or isn't a value in 
427
 
            SI units, return default (which defaults to None)
428
 
        """
429
 
        val = self.get_user_option(option_name)
430
 
        if isinstance(val, list):
431
 
            val = val[0]
432
 
        if val is None:
433
 
            val = default
434
 
        else:
435
 
            p = re.compile("^(\d+)([kmg])*b*$", re.IGNORECASE)
436
 
            try:
437
 
                m = p.match(val)
438
 
                if m is not None:
439
 
                    val = int(m.group(1))
440
 
                    if m.group(2) is not None:
441
 
                        if m.group(2).lower() == 'k':
442
 
                            val *= 10**3
443
 
                        elif m.group(2).lower() == 'm':
444
 
                            val *= 10**6
445
 
                        elif m.group(2).lower() == 'g':
446
 
                            val *= 10**9
447
 
                else:
448
 
                    ui.ui_factory.show_warning(gettext('Invalid config value for "{0}" '
449
 
                                               ' value {1!r} is not an SI unit.').format(
450
 
                                                option_name, val))
451
 
                    val = default
452
 
            except TypeError:
453
 
                val = default
454
 
        return val
455
 
        
456
404
 
457
405
    def gpg_signing_command(self):
458
406
        """What program should be used to sign signatures?"""
476
424
        """See log_format()."""
477
425
        return None
478
426
 
479
 
    def validate_signatures_in_log(self):
480
 
        """Show GPG signature validity in log"""
481
 
        result = self._validate_signatures_in_log()
482
 
        if result == "true":
483
 
            result = True
484
 
        else:
485
 
            result = False
486
 
        return result
487
 
 
488
 
    def _validate_signatures_in_log(self):
489
 
        """See validate_signatures_in_log()."""
490
 
        return None
491
 
 
492
 
    def acceptable_keys(self):
493
 
        """Comma separated list of key patterns acceptable to 
494
 
        verify-signatures command"""
495
 
        result = self._acceptable_keys()
496
 
        return result
497
 
 
498
 
    def _acceptable_keys(self):
499
 
        """See acceptable_keys()."""
500
 
        return None
501
 
 
502
427
    def post_commit(self):
503
428
        """An ordered list of python functions to call.
504
429
 
567
492
        if policy is None:
568
493
            policy = self._get_signature_checking()
569
494
            if policy is not None:
570
 
                #this warning should go away once check_signatures is
571
 
                #implemented (if not before)
572
495
                trace.warning("Please use create_signatures,"
573
496
                              " not check_signatures to set signing policy.")
 
497
            if policy == CHECK_ALWAYS:
 
498
                return True
574
499
        elif policy == SIGN_ALWAYS:
575
500
            return True
576
501
        return False
577
502
 
578
 
    def gpg_signing_key(self):
579
 
        """GPG user-id to sign commits"""
580
 
        key = self.get_user_option('gpg_signing_key')
581
 
        if key == "default" or key == None:
582
 
            return self.user_email()
583
 
        else:
584
 
            return key
585
 
 
586
503
    def get_alias(self, value):
587
504
        return self._get_alias(value)
588
505
 
622
539
        for (oname, value, section, conf_id, parser) in self._get_options():
623
540
            if oname.startswith('bzr.mergetool.'):
624
541
                tool_name = oname[len('bzr.mergetool.'):]
625
 
                tools[tool_name] = self.get_user_option(oname)
 
542
                tools[tool_name] = value
626
543
        trace.mutter('loaded merge tools: %r' % tools)
627
544
        return tools
628
545
 
629
546
    def find_merge_tool(self, name):
630
 
        # We fake a defaults mechanism here by checking if the given name can
 
547
        # We fake a defaults mechanism here by checking if the given name can 
631
548
        # be found in the known_merge_tools if it's not found in the config.
632
549
        # This should be done through the proposed config defaults mechanism
633
550
        # when it becomes available in the future.
637
554
        return command_line
638
555
 
639
556
 
640
 
class _ConfigHooks(hooks.Hooks):
641
 
    """A dict mapping hook names and a list of callables for configs.
642
 
    """
643
 
 
644
 
    def __init__(self):
645
 
        """Create the default hooks.
646
 
 
647
 
        These are all empty initially, because by default nothing should get
648
 
        notified.
649
 
        """
650
 
        super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
651
 
        self.add_hook('load',
652
 
                      'Invoked when a config store is loaded.'
653
 
                      ' The signature is (store).',
654
 
                      (2, 4))
655
 
        self.add_hook('save',
656
 
                      'Invoked when a config store is saved.'
657
 
                      ' The signature is (store).',
658
 
                      (2, 4))
659
 
        # The hooks for config options
660
 
        self.add_hook('get',
661
 
                      'Invoked when a config option is read.'
662
 
                      ' The signature is (stack, name, value).',
663
 
                      (2, 4))
664
 
        self.add_hook('set',
665
 
                      'Invoked when a config option is set.'
666
 
                      ' The signature is (stack, name, value).',
667
 
                      (2, 4))
668
 
        self.add_hook('remove',
669
 
                      'Invoked when a config option is removed.'
670
 
                      ' The signature is (stack, name).',
671
 
                      (2, 4))
672
 
ConfigHooks = _ConfigHooks()
673
 
 
674
 
 
675
 
class _OldConfigHooks(hooks.Hooks):
676
 
    """A dict mapping hook names and a list of callables for configs.
677
 
    """
678
 
 
679
 
    def __init__(self):
680
 
        """Create the default hooks.
681
 
 
682
 
        These are all empty initially, because by default nothing should get
683
 
        notified.
684
 
        """
685
 
        super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
686
 
        self.add_hook('load',
687
 
                      'Invoked when a config store is loaded.'
688
 
                      ' The signature is (config).',
689
 
                      (2, 4))
690
 
        self.add_hook('save',
691
 
                      'Invoked when a config store is saved.'
692
 
                      ' The signature is (config).',
693
 
                      (2, 4))
694
 
        # The hooks for config options
695
 
        self.add_hook('get',
696
 
                      'Invoked when a config option is read.'
697
 
                      ' The signature is (config, name, value).',
698
 
                      (2, 4))
699
 
        self.add_hook('set',
700
 
                      'Invoked when a config option is set.'
701
 
                      ' The signature is (config, name, value).',
702
 
                      (2, 4))
703
 
        self.add_hook('remove',
704
 
                      'Invoked when a config option is removed.'
705
 
                      ' The signature is (config, name).',
706
 
                      (2, 4))
707
 
OldConfigHooks = _OldConfigHooks()
708
 
 
709
 
 
710
557
class IniBasedConfig(Config):
711
558
    """A configuration policy that draws from ini files."""
712
559
 
772
619
            self._parser = ConfigObj(co_input, encoding='utf-8')
773
620
        except configobj.ConfigObjError, e:
774
621
            raise errors.ParseConfigError(e.errors, e.config.filename)
775
 
        except UnicodeDecodeError:
776
 
            raise errors.ConfigContentError(self.file_name)
777
622
        # Make sure self.reload() will use the right file name
778
623
        self._parser.filename = self.file_name
779
 
        for hook in OldConfigHooks['load']:
780
 
            hook(self)
781
624
        return self._parser
782
625
 
783
626
    def reload(self):
786
629
            raise AssertionError('We need a file name to reload the config')
787
630
        if self._parser is not None:
788
631
            self._parser.reload()
789
 
        for hook in ConfigHooks['load']:
790
 
            hook(self)
791
632
 
792
633
    def _get_matching_sections(self):
793
634
        """Return an ordered list of (section_name, extra_path) pairs.
910
751
        """See Config.log_format."""
911
752
        return self._get_user_option('log_format')
912
753
 
913
 
    def _validate_signatures_in_log(self):
914
 
        """See Config.validate_signatures_in_log."""
915
 
        return self._get_user_option('validate_signatures_in_log')
916
 
 
917
 
    def _acceptable_keys(self):
918
 
        """See Config.acceptable_keys."""
919
 
        return self._get_user_option('acceptable_keys')
920
 
 
921
754
    def _post_commit(self):
922
755
        """See Config.post_commit."""
923
756
        return self._get_user_option('post_commit')
973
806
        except KeyError:
974
807
            raise errors.NoSuchConfigOption(option_name)
975
808
        self._write_config_file()
976
 
        for hook in OldConfigHooks['remove']:
977
 
            hook(self, option_name)
978
809
 
979
810
    def _write_config_file(self):
980
811
        if self.file_name is None:
986
817
        atomic_file.commit()
987
818
        atomic_file.close()
988
819
        osutils.copy_ownership_from_path(self.file_name)
989
 
        for hook in OldConfigHooks['save']:
990
 
            hook(self)
991
820
 
992
821
 
993
822
class LockableConfig(IniBasedConfig):
1025
854
        # local transports are not shared. But if/when we start using
1026
855
        # LockableConfig for other kind of transports, we will need to reuse
1027
856
        # whatever connection is already established -- vila 20100929
1028
 
        self.transport = transport.get_transport_from_path(self.dir)
 
857
        self.transport = transport.get_transport(self.dir)
1029
858
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
1030
859
 
1031
860
    def _create_from_string(self, unicode_bytes, save):
1121
950
        self.reload()
1122
951
        self._get_parser().setdefault(section, {})[option] = value
1123
952
        self._write_config_file()
1124
 
        for hook in OldConfigHooks['set']:
1125
 
            hook(self, option, value)
 
953
 
1126
954
 
1127
955
    def _get_sections(self, name=None):
1128
956
        """See IniBasedConfig._get_sections()."""
1324
1152
        # the allowed values of store match the config policies
1325
1153
        self._set_option_policy(location, option, store)
1326
1154
        self._write_config_file()
1327
 
        for hook in OldConfigHooks['set']:
1328
 
            hook(self, option, value)
1329
1155
 
1330
1156
 
1331
1157
class BranchConfig(Config):
1397
1223
            return (self.branch._transport.get_bytes("email")
1398
1224
                    .decode(osutils.get_user_encoding())
1399
1225
                    .rstrip("\r\n"))
1400
 
        except (errors.NoSuchFile, errors.PermissionDenied), e:
 
1226
        except errors.NoSuchFile, e:
1401
1227
            pass
1402
1228
 
1403
1229
        return self._get_best_value('_get_user_id')
1498
1324
        """See Config.log_format."""
1499
1325
        return self._get_best_value('_log_format')
1500
1326
 
1501
 
    def _validate_signatures_in_log(self):
1502
 
        """See Config.validate_signatures_in_log."""
1503
 
        return self._get_best_value('_validate_signatures_in_log')
1504
 
 
1505
 
    def _acceptable_keys(self):
1506
 
        """See Config.acceptable_keys."""
1507
 
        return self._get_best_value('_acceptable_keys')
1508
 
 
1509
1327
 
1510
1328
def ensure_config_dir_exists(path=None):
1511
1329
    """Make sure a configuration directory exists.
1551
1369
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1552
1370
                                  ' or HOME set')
1553
1371
        return osutils.pathjoin(base, 'bazaar', '2.0')
1554
 
    else:
1555
 
        if base is not None:
1556
 
            base = base.decode(osutils._fs_enc)
1557
 
    if sys.platform == 'darwin':
 
1372
    elif sys.platform == 'darwin':
1558
1373
        if base is None:
1559
1374
            # this takes into account $HOME
1560
1375
            base = os.path.expanduser("~")
1561
1376
        return osutils.pathjoin(base, '.bazaar')
1562
1377
    else:
1563
1378
        if base is None:
 
1379
 
1564
1380
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
1565
1381
            if xdg_dir is None:
1566
1382
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
1569
1385
                trace.mutter(
1570
1386
                    "Using configuration in XDG directory %s." % xdg_dir)
1571
1387
                return xdg_dir
 
1388
 
1572
1389
            base = os.path.expanduser("~")
1573
1390
        return osutils.pathjoin(base, ".bazaar")
1574
1391
 
1796
1613
            self._config = ConfigObj(self._input, encoding='utf-8')
1797
1614
        except configobj.ConfigObjError, e:
1798
1615
            raise errors.ParseConfigError(e.errors, e.config.filename)
1799
 
        except UnicodeError:
1800
 
            raise errors.ConfigContentError(self._filename)
1801
1616
        return self._config
1802
1617
 
1803
1618
    def _save(self):
1820
1635
        section[option_name] = value
1821
1636
        self._save()
1822
1637
 
1823
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
 
1638
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
1824
1639
                        realm=None):
1825
1640
        """Returns the matching credentials from authentication.conf file.
1826
1641
 
2239
2054
                section_obj = configobj[section]
2240
2055
            except KeyError:
2241
2056
                return default
2242
 
        value = section_obj.get(name, default)
2243
 
        for hook in OldConfigHooks['get']:
2244
 
            hook(self, name, value)
2245
 
        return value
 
2057
        return section_obj.get(name, default)
2246
2058
 
2247
2059
    def set_option(self, value, name, section=None):
2248
2060
        """Set the value associated with a named option.
2256
2068
            configobj[name] = value
2257
2069
        else:
2258
2070
            configobj.setdefault(section, {})[name] = value
2259
 
        for hook in OldConfigHooks['set']:
2260
 
            hook(self, name, value)
2261
2071
        self._set_configobj(configobj)
2262
2072
 
2263
2073
    def remove_option(self, option_name, section_name=None):
2266
2076
            del configobj[option_name]
2267
2077
        else:
2268
2078
            del configobj[section_name][option_name]
2269
 
        for hook in OldConfigHooks['remove']:
2270
 
            hook(self, option_name)
2271
2079
        self._set_configobj(configobj)
2272
2080
 
2273
2081
    def _get_config_file(self):
2274
2082
        try:
2275
 
            f = StringIO(self._transport.get_bytes(self._filename))
2276
 
            for hook in OldConfigHooks['load']:
2277
 
                hook(self)
2278
 
            return f
 
2083
            return StringIO(self._transport.get_bytes(self._filename))
2279
2084
        except errors.NoSuchFile:
2280
2085
            return StringIO()
2281
 
        except errors.PermissionDenied, e:
2282
 
            trace.warning("Permission denied while trying to open "
2283
 
                "configuration file %s.", urlutils.unescape_for_display(
2284
 
                urlutils.join(self._transport.base, self._filename), "utf-8"))
2285
 
            return StringIO()
2286
 
 
2287
 
    def _external_url(self):
2288
 
        return urlutils.join(self._transport.external_url(), self._filename)
2289
2086
 
2290
2087
    def _get_configobj(self):
2291
2088
        f = self._get_config_file()
2292
2089
        try:
2293
 
            try:
2294
 
                conf = ConfigObj(f, encoding='utf-8')
2295
 
            except configobj.ConfigObjError, e:
2296
 
                raise errors.ParseConfigError(e.errors, self._external_url())
2297
 
            except UnicodeDecodeError:
2298
 
                raise errors.ConfigContentError(self._external_url())
 
2090
            return ConfigObj(f, encoding='utf-8')
2299
2091
        finally:
2300
2092
            f.close()
2301
 
        return conf
2302
2093
 
2303
2094
    def _set_configobj(self, configobj):
2304
2095
        out_file = StringIO()
2305
2096
        configobj.write(out_file)
2306
2097
        out_file.seek(0)
2307
2098
        self._transport.put_file(self._filename, out_file)
2308
 
        for hook in OldConfigHooks['save']:
2309
 
            hook(self)
2310
2099
 
2311
2100
 
2312
2101
class Option(object):
2315
2104
    The option *values* are stored in config files and found in sections.
2316
2105
 
2317
2106
    Here we define various properties about the option itself, its default
2318
 
    value, how to convert it from stores, what to do when invalid values are
2319
 
    encoutered, in which config files it can be stored.
 
2107
    value, in which config files it can be stored, etc (TBC).
2320
2108
    """
2321
2109
 
2322
 
    def __init__(self, name, default=None, default_from_env=None,
2323
 
                 help=None,
2324
 
                 from_unicode=None, invalid=None):
2325
 
        """Build an option definition.
2326
 
 
2327
 
        :param name: the name used to refer to the option.
2328
 
 
2329
 
        :param default: the default value to use when none exist in the config
2330
 
            stores. This is either a string that ``from_unicode`` will convert
2331
 
            into the proper type or a python object that can be stringified (so
2332
 
            only the empty list is supported for example).
2333
 
 
2334
 
        :param default_from_env: A list of environment variables which can
2335
 
           provide a default value. 'default' will be used only if none of the
2336
 
           variables specified here are set in the environment.
2337
 
 
2338
 
        :param help: a doc string to explain the option to the user.
2339
 
 
2340
 
        :param from_unicode: a callable to convert the unicode string
2341
 
            representing the option value in a store. This is not called for
2342
 
            the default value.
2343
 
 
2344
 
        :param invalid: the action to be taken when an invalid value is
2345
 
            encountered in a store. This is called only when from_unicode is
2346
 
            invoked to convert a string and returns None or raise ValueError or
2347
 
            TypeError. Accepted values are: None (ignore invalid values),
2348
 
            'warning' (emit a warning), 'error' (emit an error message and
2349
 
            terminates).
2350
 
        """
2351
 
        if default_from_env is None:
2352
 
            default_from_env = []
 
2110
    def __init__(self, name, default=None):
2353
2111
        self.name = name
2354
 
        # Convert the default value to a unicode string so all values are
2355
 
        # strings internally before conversion (via from_unicode) is attempted.
2356
 
        if default is None:
2357
 
            self.default = None
2358
 
        elif isinstance(default, list):
2359
 
            # Only the empty list is supported
2360
 
            if default:
2361
 
                raise AssertionError(
2362
 
                    'Only empty lists are supported as default values')
2363
 
            self.default = u','
2364
 
        elif isinstance(default, (str, unicode, bool, int, float)):
2365
 
            # Rely on python to convert strings, booleans and integers
2366
 
            self.default = u'%s' % (default,)
2367
 
        else:
2368
 
            # other python objects are not expected
2369
 
            raise AssertionError('%r is not supported as a default value'
2370
 
                                 % (default,))
2371
 
        self.default_from_env = default_from_env
2372
 
        self.help = help
2373
 
        self.from_unicode = from_unicode
2374
 
        if invalid and invalid not in ('warning', 'error'):
2375
 
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2376
 
        self.invalid = invalid
2377
 
 
2378
 
    def convert_from_unicode(self, unicode_value):
2379
 
        if self.from_unicode is None or unicode_value is None:
2380
 
            # Don't convert or nothing to convert
2381
 
            return unicode_value
2382
 
        try:
2383
 
            converted = self.from_unicode(unicode_value)
2384
 
        except (ValueError, TypeError):
2385
 
            # Invalid values are ignored
2386
 
            converted = None
2387
 
        if converted is None and self.invalid is not None:
2388
 
            # The conversion failed
2389
 
            if self.invalid == 'warning':
2390
 
                trace.warning('Value "%s" is not valid for "%s"',
2391
 
                              unicode_value, self.name)
2392
 
            elif self.invalid == 'error':
2393
 
                raise errors.ConfigOptionValueError(self.name, unicode_value)
2394
 
        return converted
 
2112
        self.default = default
2395
2113
 
2396
2114
    def get_default(self):
2397
 
        value = None
2398
 
        for var in self.default_from_env:
2399
 
            try:
2400
 
                # If the env variable is defined, its value is the default one
2401
 
                value = os.environ[var]
2402
 
                break
2403
 
            except KeyError:
2404
 
                continue
2405
 
        if value is None:
2406
 
            # Otherwise, fallback to the value defined at registration
2407
 
            value = self.default
2408
 
        return value
2409
 
 
2410
 
    def get_help_text(self, additional_see_also=None, plain=True):
2411
 
        result = self.help
2412
 
        from bzrlib import help_topics
2413
 
        result += help_topics._format_see_also(additional_see_also)
2414
 
        if plain:
2415
 
            result = help_topics.help_as_plain_text(result)
2416
 
        return result
2417
 
 
2418
 
 
2419
 
# Predefined converters to get proper values from store
2420
 
 
2421
 
def bool_from_store(unicode_str):
2422
 
    return ui.bool_from_string(unicode_str)
2423
 
 
2424
 
 
2425
 
def int_from_store(unicode_str):
2426
 
    return int(unicode_str)
2427
 
 
2428
 
 
2429
 
def float_from_store(unicode_str):
2430
 
    return float(unicode_str)
2431
 
 
2432
 
 
2433
 
 
2434
 
# Use a an empty dict to initialize an empty configobj avoiding all
2435
 
# parsing and encoding checks
2436
 
_list_converter_config = configobj.ConfigObj(
2437
 
    {}, encoding='utf-8', list_values=True, interpolation=False)
2438
 
 
2439
 
 
2440
 
def list_from_store(unicode_str):
2441
 
    if not isinstance(unicode_str, basestring):
2442
 
        raise TypeError
2443
 
    # Now inject our string directly as unicode. All callers got their value
2444
 
    # from configobj, so values that need to be quoted are already properly
2445
 
    # quoted.
2446
 
    _list_converter_config.reset()
2447
 
    _list_converter_config._parse([u"list=%s" % (unicode_str,)])
2448
 
    maybe_list = _list_converter_config['list']
2449
 
    # ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
2450
 
    if isinstance(maybe_list, basestring):
2451
 
        if maybe_list:
2452
 
            # A single value, most probably the user forgot (or didn't care to
2453
 
            # add) the final ','
2454
 
            l = [maybe_list]
2455
 
        else:
2456
 
            # The empty string, convert to empty list
2457
 
            l = []
2458
 
    else:
2459
 
        # We rely on ConfigObj providing us with a list already
2460
 
        l = maybe_list
2461
 
    return l
2462
 
 
2463
 
 
2464
 
class OptionRegistry(registry.Registry):
2465
 
    """Register config options by their name.
2466
 
 
2467
 
    This overrides ``registry.Registry`` to simplify registration by acquiring
2468
 
    some information from the option object itself.
2469
 
    """
2470
 
 
2471
 
    def register(self, option):
2472
 
        """Register a new option to its name.
2473
 
 
2474
 
        :param option: The option to register. Its name is used as the key.
2475
 
        """
2476
 
        super(OptionRegistry, self).register(option.name, option,
2477
 
                                             help=option.help)
2478
 
 
2479
 
    def register_lazy(self, key, module_name, member_name):
2480
 
        """Register a new option to be loaded on request.
2481
 
 
2482
 
        :param key: the key to request the option later. Since the registration
2483
 
            is lazy, it should be provided and match the option name.
2484
 
 
2485
 
        :param module_name: the python path to the module. Such as 'os.path'.
2486
 
 
2487
 
        :param member_name: the member of the module to return.  If empty or 
2488
 
                None, get() will return the module itself.
2489
 
        """
2490
 
        super(OptionRegistry, self).register_lazy(key,
2491
 
                                                  module_name, member_name)
2492
 
 
2493
 
    def get_help(self, key=None):
2494
 
        """Get the help text associated with the given key"""
2495
 
        option = self.get(key)
2496
 
        the_help = option.help
2497
 
        if callable(the_help):
2498
 
            return the_help(self, key)
2499
 
        return the_help
2500
 
 
2501
 
 
2502
 
option_registry = OptionRegistry()
2503
 
 
2504
 
 
2505
 
# Registered options in lexicographical order
2506
 
 
2507
 
option_registry.register(
2508
 
    Option('bzr.workingtree.worth_saving_limit', default=10,
2509
 
           from_unicode=int_from_store,  invalid='warning',
2510
 
           help='''\
2511
 
How many changes before saving the dirstate.
2512
 
 
2513
 
-1 means that we will never rewrite the dirstate file for only
2514
 
stat-cache changes. Regardless of this setting, we will always rewrite
2515
 
the dirstate file if a file is added/removed/renamed/etc. This flag only
2516
 
affects the behavior of updating the dirstate file after we notice that
2517
 
a file has been touched.
2518
 
'''))
2519
 
option_registry.register(
2520
 
    Option('dirstate.fdatasync', default=True,
2521
 
           from_unicode=bool_from_store,
2522
 
           help='''\
2523
 
Flush dirstate changes onto physical disk?
2524
 
 
2525
 
If true (default), working tree metadata changes are flushed through the
2526
 
OS buffers to physical disk.  This is somewhat slower, but means data
2527
 
should not be lost if the machine crashes.  See also repository.fdatasync.
2528
 
'''))
2529
 
option_registry.register(
2530
 
    Option('debug_flags', default=[], from_unicode=list_from_store,
2531
 
           help='Debug flags to activate.'))
2532
 
option_registry.register(
2533
 
    Option('default_format', default='2a',
2534
 
           help='Format used when creating branches.'))
2535
 
option_registry.register(
2536
 
    Option('dpush_strict', default=None,
2537
 
           from_unicode=bool_from_store,
2538
 
           help='''\
2539
 
The default value for ``dpush --strict``.
2540
 
 
2541
 
If present, defines the ``--strict`` option default value for checking
2542
 
uncommitted changes before pushing into a different VCS without any
2543
 
custom bzr metadata.
2544
 
'''))
2545
 
option_registry.register(
2546
 
    Option('editor',
2547
 
           help='The command called to launch an editor to enter a message.'))
2548
 
option_registry.register(
2549
 
    Option('ignore_missing_extensions', default=False,
2550
 
           from_unicode=bool_from_store,
2551
 
           help='''\
2552
 
Control the missing extensions warning display.
2553
 
 
2554
 
The warning will not be emitted if set to True.
2555
 
'''))
2556
 
option_registry.register(
2557
 
    Option('language',
2558
 
           help='Language to translate messages into.'))
2559
 
option_registry.register(
2560
 
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2561
 
           help='''\
2562
 
Steal locks that appears to be dead.
2563
 
 
2564
 
If set to True, bzr will check if a lock is supposed to be held by an
2565
 
active process from the same user on the same machine. If the user and
2566
 
machine match, but no process with the given PID is active, then bzr
2567
 
will automatically break the stale lock, and create a new lock for
2568
 
this process.
2569
 
Otherwise, bzr will prompt as normal to break the lock.
2570
 
'''))
2571
 
option_registry.register(
2572
 
    Option('output_encoding',
2573
 
           help= 'Unicode encoding for output'
2574
 
           ' (terminal encoding if not specified).'))
2575
 
option_registry.register(
2576
 
    Option('push_strict', default=None,
2577
 
           from_unicode=bool_from_store,
2578
 
           help='''\
2579
 
The default value for ``push --strict``.
2580
 
 
2581
 
If present, defines the ``--strict`` option default value for checking
2582
 
uncommitted changes before sending a merge directive.
2583
 
'''))
2584
 
option_registry.register(
2585
 
    Option('repository.fdatasync', default=True,
2586
 
           from_unicode=bool_from_store,
2587
 
           help='''\
2588
 
Flush repository changes onto physical disk?
2589
 
 
2590
 
If true (default), repository changes are flushed through the OS buffers
2591
 
to physical disk.  This is somewhat slower, but means data should not be
2592
 
lost if the machine crashes.  See also dirstate.fdatasync.
2593
 
'''))
2594
 
option_registry.register(
2595
 
    Option('send_strict', default=None,
2596
 
           from_unicode=bool_from_store,
2597
 
           help='''\
2598
 
The default value for ``send --strict``.
2599
 
 
2600
 
If present, defines the ``--strict`` option default value for checking
2601
 
uncommitted changes before pushing.
2602
 
'''))
2603
 
 
2604
 
option_registry.register(
2605
 
    Option('serve.client_timeout',
2606
 
           default=300.0, from_unicode=float_from_store,
2607
 
           help="If we wait for a new request from a client for more than"
2608
 
                " X seconds, consider the client idle, and hangup."))
 
2115
        return self.default
 
2116
 
 
2117
 
 
2118
# Options registry
 
2119
 
 
2120
option_registry = registry.Registry()
 
2121
 
 
2122
 
 
2123
option_registry.register(
 
2124
    'editor', Option('editor'),
 
2125
    help='The command called to launch an editor to enter a message.')
2609
2126
 
2610
2127
 
2611
2128
class Section(object):
2672
2189
        """Loads the Store from persistent storage."""
2673
2190
        raise NotImplementedError(self.load)
2674
2191
 
2675
 
    def _load_from_string(self, bytes):
 
2192
    def _load_from_string(self, str_or_unicode):
2676
2193
        """Create a store from a string in configobj syntax.
2677
2194
 
2678
 
        :param bytes: A string representing the file content.
 
2195
        :param str_or_unicode: A string representing the file content. This will
 
2196
            be encoded to suit store needs internally.
 
2197
 
 
2198
        This is for tests and should not be used in production unless a
 
2199
        convincing use case can be demonstrated :)
2679
2200
        """
2680
2201
        raise NotImplementedError(self._load_from_string)
2681
2202
 
2748
2269
        """Load the store from the associated file."""
2749
2270
        if self.is_loaded():
2750
2271
            return
2751
 
        try:
2752
 
            content = self.transport.get_bytes(self.file_name)
2753
 
        except errors.PermissionDenied:
2754
 
            trace.warning("Permission denied while trying to load "
2755
 
                          "configuration store %s.", self.external_url())
2756
 
            raise
 
2272
        content = self.transport.get_bytes(self.file_name)
2757
2273
        self._load_from_string(content)
2758
 
        for hook in ConfigHooks['load']:
2759
 
            hook(self)
2760
2274
 
2761
 
    def _load_from_string(self, bytes):
 
2275
    def _load_from_string(self, str_or_unicode):
2762
2276
        """Create a config store from a string.
2763
2277
 
2764
 
        :param bytes: A string representing the file content.
 
2278
        :param str_or_unicode: A string representing the file content. This will
 
2279
            be utf-8 encoded internally.
 
2280
 
 
2281
        This is for tests and should not be used in production unless a
 
2282
        convincing use case can be demonstrated :)
2765
2283
        """
2766
2284
        if self.is_loaded():
2767
2285
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
2768
 
        co_input = StringIO(bytes)
 
2286
        co_input = StringIO(str_or_unicode.encode('utf-8'))
2769
2287
        try:
2770
2288
            # The config files are always stored utf8-encoded
2771
 
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
2772
 
                                         list_values=False)
 
2289
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
2773
2290
        except configobj.ConfigObjError, e:
2774
2291
            self._config_obj = None
2775
2292
            raise errors.ParseConfigError(e.errors, self.external_url())
2776
 
        except UnicodeDecodeError:
2777
 
            raise errors.ConfigContentError(self.external_url())
2778
2293
 
2779
2294
    def save(self):
2780
2295
        if not self.is_loaded():
2783
2298
        out = StringIO()
2784
2299
        self._config_obj.write(out)
2785
2300
        self.transport.put_bytes(self.file_name, out.getvalue())
2786
 
        for hook in ConfigHooks['save']:
2787
 
            hook(self)
2788
2301
 
2789
2302
    def external_url(self):
2790
2303
        # FIXME: external_url should really accepts an optional relpath
2802
2315
        # We need a loaded store
2803
2316
        try:
2804
2317
            self.load()
2805
 
        except (errors.NoSuchFile, errors.PermissionDenied):
2806
 
            # If the file can't be read, there is no sections
 
2318
        except errors.NoSuchFile:
 
2319
            # If the file doesn't exist, there is no sections
2807
2320
            return
2808
2321
        cobj = self._config_obj
2809
2322
        if cobj.scalars:
2884
2397
class GlobalStore(LockableIniFileStore):
2885
2398
 
2886
2399
    def __init__(self, possible_transports=None):
2887
 
        t = transport.get_transport_from_path(
2888
 
            config_dir(), possible_transports=possible_transports)
 
2400
        t = transport.get_transport(config_dir(),
 
2401
                                    possible_transports=possible_transports)
2889
2402
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
2890
2403
 
2891
2404
 
2892
2405
class LocationStore(LockableIniFileStore):
2893
2406
 
2894
2407
    def __init__(self, possible_transports=None):
2895
 
        t = transport.get_transport_from_path(
2896
 
            config_dir(), possible_transports=possible_transports)
 
2408
        t = transport.get_transport(config_dir(),
 
2409
                                    possible_transports=possible_transports)
2897
2410
        super(LocationStore, self).__init__(t, 'locations.conf')
2898
2411
 
2899
2412
 
2902
2415
    def __init__(self, branch):
2903
2416
        super(BranchStore, self).__init__(branch.control_transport,
2904
2417
                                          'branch.conf')
2905
 
        self.branch = branch
 
2418
        # We don't want to create a cycle here when the BranchStore becomes
 
2419
        # part of an object (roughly a Stack, directly or indirectly) that is
 
2420
        # an attribute of the branch object itself. Since the BranchStore
 
2421
        # cannot exist without a branch, it's safe to make it a weakref.
 
2422
        self.branch_ref = weakref.ref(branch)
 
2423
 
 
2424
    def _get_branch(self):
 
2425
        b = self.branch_ref()
 
2426
        if b is None:
 
2427
            # Programmer error, a branch store can't exist if the branch it
 
2428
            # refers to is dead.
 
2429
            raise AssertionError('Dead branch ref in %r' % (self,))
 
2430
        return b
2906
2431
 
2907
2432
    def lock_write(self, token=None):
2908
 
        return self.branch.lock_write(token)
 
2433
        return self._get_branch().lock_write(token)
2909
2434
 
2910
2435
    def unlock(self):
2911
 
        return self.branch.unlock()
 
2436
        return self._get_branch().unlock()
2912
2437
 
2913
2438
    @needs_write_lock
2914
2439
    def save(self):
2919
2444
        super(BranchStore, self).save()
2920
2445
 
2921
2446
 
2922
 
class ControlStore(LockableIniFileStore):
2923
 
 
2924
 
    def __init__(self, bzrdir):
2925
 
        super(ControlStore, self).__init__(bzrdir.transport,
2926
 
                                          'control.conf',
2927
 
                                           lock_dir_name='branch_lock')
2928
 
 
2929
 
 
2930
2447
class SectionMatcher(object):
2931
2448
    """Select sections into a given Store.
2932
2449
 
2933
 
    This is intended to be used to postpone getting an iterable of sections
2934
 
    from a store.
 
2450
    This intended to be used to postpone getting an iterable of sections from a
 
2451
    store.
2935
2452
    """
2936
2453
 
2937
2454
    def __init__(self, store):
2946
2463
            if self.match(s):
2947
2464
                yield s
2948
2465
 
2949
 
    def match(self, section):
2950
 
        """Does the proposed section match.
2951
 
 
2952
 
        :param section: A Section object.
2953
 
 
2954
 
        :returns: True if the section matches, False otherwise.
2955
 
        """
 
2466
    def match(self, secion):
2956
2467
        raise NotImplementedError(self.match)
2957
2468
 
2958
2469
 
2959
 
class NameMatcher(SectionMatcher):
2960
 
 
2961
 
    def __init__(self, store, section_id):
2962
 
        super(NameMatcher, self).__init__(store)
2963
 
        self.section_id = section_id
2964
 
 
2965
 
    def match(self, section):
2966
 
        return section.id == self.section_id
2967
 
 
2968
 
 
2969
2470
class LocationSection(Section):
2970
2471
 
2971
2472
    def __init__(self, section, length, extra_path):
2996
2497
        # We slightly diverge from LocalConfig here by allowing the no-name
2997
2498
        # section as the most generic one and the lower priority.
2998
2499
        no_name_section = None
2999
 
        all_sections = []
 
2500
        sections = []
3000
2501
        # Filter out the no_name_section so _iter_for_location_by_parts can be
3001
2502
        # used (it assumes all sections have a name).
3002
2503
        for section in self.store.get_sections():
3003
2504
            if section.id is None:
3004
2505
                no_name_section = section
3005
2506
            else:
3006
 
                all_sections.append(section)
 
2507
                sections.append(section)
3007
2508
        # Unfortunately _iter_for_location_by_parts deals with section names so
3008
2509
        # we have to resync.
3009
2510
        filtered_sections = _iter_for_location_by_parts(
3010
 
            [s.id for s in all_sections], self.location)
3011
 
        iter_all_sections = iter(all_sections)
 
2511
            [s.id for s in sections], self.location)
 
2512
        iter_sections = iter(sections)
3012
2513
        matching_sections = []
3013
2514
        if no_name_section is not None:
3014
2515
            matching_sections.append(
3015
2516
                LocationSection(no_name_section, 0, self.location))
3016
2517
        for section_id, extra_path, length in filtered_sections:
3017
 
            # a section id is unique for a given store so it's safe to take the
3018
 
            # first matching section while iterating. Also, all filtered
3019
 
            # sections are part of 'all_sections' and will always be found
3020
 
            # there.
3021
 
            while True:
3022
 
                section = iter_all_sections.next()
3023
 
                if section_id == section.id:
3024
 
                    matching_sections.append(
3025
 
                        LocationSection(section, length, extra_path))
3026
 
                    break
 
2518
            # a section id is unique for a given store so it's safe to iterate
 
2519
            # again
 
2520
            section = iter_sections.next()
 
2521
            if section_id == section.id:
 
2522
                matching_sections.append(
 
2523
                    LocationSection(section, length, extra_path))
3027
2524
        return matching_sections
3028
2525
 
3029
2526
    def get_sections(self):
3048
2545
class Stack(object):
3049
2546
    """A stack of configurations where an option can be defined"""
3050
2547
 
3051
 
    _option_ref_re = lazy_regex.lazy_compile('({[^{}]+})')
3052
 
    """Describes an exandable option reference.
3053
 
 
3054
 
    We want to match the most embedded reference first.
3055
 
 
3056
 
    I.e. for '{{foo}}' we will get '{foo}',
3057
 
    for '{bar{baz}}' we will get '{baz}'
3058
 
    """
3059
 
 
3060
2548
    def __init__(self, sections_def, store=None, mutable_section_name=None):
3061
2549
        """Creates a stack of sections with an optional store for changes.
3062
2550
 
3075
2563
        self.store = store
3076
2564
        self.mutable_section_name = mutable_section_name
3077
2565
 
3078
 
    def get(self, name, expand=None):
 
2566
    def get(self, name):
3079
2567
        """Return the *first* option value found in the sections.
3080
2568
 
3081
2569
        This is where we guarantee that sections coming from Store are loaded
3083
2571
        option exists or get its value, which in turn may require to discover
3084
2572
        in which sections it can be defined. Both of these (section and option
3085
2573
        existence) require loading the store (even partially).
3086
 
 
3087
 
        :param name: The queried option.
3088
 
 
3089
 
        :param expand: Whether options references should be expanded.
3090
 
 
3091
 
        :returns: The value of the option.
3092
2574
        """
3093
2575
        # FIXME: No caching of options nor sections yet -- vila 20110503
3094
 
        if expand is None:
3095
 
            expand = _get_expand_default_value()
3096
2576
        value = None
3097
2577
        # Ensuring lazy loading is achieved by delaying section matching (which
3098
2578
        # implies querying the persistent storage) until it can't be avoided
3110
2590
                    break
3111
2591
            if value is not None:
3112
2592
                break
3113
 
        # If the option is registered, it may provide additional info about
3114
 
        # value handling
3115
 
        try:
3116
 
            opt = option_registry.get(name)
3117
 
        except KeyError:
3118
 
            # Not registered
3119
 
            opt = None
3120
 
        def expand_and_convert(val):
3121
 
            # This may need to be called twice if the value is None or ends up
3122
 
            # being None during expansion or conversion.
3123
 
            if val is not None:
3124
 
                if expand:
3125
 
                    if isinstance(val, basestring):
3126
 
                        val = self._expand_options_in_string(val)
3127
 
                    else:
3128
 
                        trace.warning('Cannot expand "%s":'
3129
 
                                      ' %s does not support option expansion'
3130
 
                                      % (name, type(val)))
3131
 
                if opt is not None:
3132
 
                    val = opt.convert_from_unicode(val)
3133
 
            return val
3134
 
        value = expand_and_convert(value)
3135
 
        if opt is not None and value is None:
 
2593
        if value is None:
3136
2594
            # If the option is registered, it may provide a default value
3137
 
            value = opt.get_default()
3138
 
            value = expand_and_convert(value)
3139
 
        for hook in ConfigHooks['get']:
3140
 
            hook(self, name, value)
3141
 
        return value
3142
 
 
3143
 
    def expand_options(self, string, env=None):
3144
 
        """Expand option references in the string in the configuration context.
3145
 
 
3146
 
        :param string: The string containing option(s) to expand.
3147
 
 
3148
 
        :param env: An option dict defining additional configuration options or
3149
 
            overriding existing ones.
3150
 
 
3151
 
        :returns: The expanded string.
3152
 
        """
3153
 
        return self._expand_options_in_string(string, env)
3154
 
 
3155
 
    def _expand_options_in_string(self, string, env=None, _refs=None):
3156
 
        """Expand options in the string in the configuration context.
3157
 
 
3158
 
        :param string: The string to be expanded.
3159
 
 
3160
 
        :param env: An option dict defining additional configuration options or
3161
 
            overriding existing ones.
3162
 
 
3163
 
        :param _refs: Private list (FIFO) containing the options being expanded
3164
 
            to detect loops.
3165
 
 
3166
 
        :returns: The expanded string.
3167
 
        """
3168
 
        if string is None:
3169
 
            # Not much to expand there
3170
 
            return None
3171
 
        if _refs is None:
3172
 
            # What references are currently resolved (to detect loops)
3173
 
            _refs = []
3174
 
        result = string
3175
 
        # We need to iterate until no more refs appear ({{foo}} will need two
3176
 
        # iterations for example).
3177
 
        while True:
3178
 
            raw_chunks = Stack._option_ref_re.split(result)
3179
 
            if len(raw_chunks) == 1:
3180
 
                # Shorcut the trivial case: no refs
3181
 
                return result
3182
 
            chunks = []
3183
 
            # Split will isolate refs so that every other chunk is a ref
3184
 
            chunk_is_ref = False
3185
 
            for chunk in raw_chunks:
3186
 
                if not chunk_is_ref:
3187
 
                    chunks.append(chunk)
3188
 
                    chunk_is_ref = True
3189
 
                else:
3190
 
                    name = chunk[1:-1]
3191
 
                    if name in _refs:
3192
 
                        raise errors.OptionExpansionLoop(string, _refs)
3193
 
                    _refs.append(name)
3194
 
                    value = self._expand_option(name, env, _refs)
3195
 
                    if value is None:
3196
 
                        raise errors.ExpandingUnknownOption(name, string)
3197
 
                    chunks.append(value)
3198
 
                    _refs.pop()
3199
 
                    chunk_is_ref = False
3200
 
            result = ''.join(chunks)
3201
 
        return result
3202
 
 
3203
 
    def _expand_option(self, name, env, _refs):
3204
 
        if env is not None and name in env:
3205
 
            # Special case, values provided in env takes precedence over
3206
 
            # anything else
3207
 
            value = env[name]
3208
 
        else:
3209
 
            # FIXME: This is a limited implementation, what we really need is a
3210
 
            # way to query the bzr config for the value of an option,
3211
 
            # respecting the scope rules (That is, once we implement fallback
3212
 
            # configs, getting the option value should restart from the top
3213
 
            # config, not the current one) -- vila 20101222
3214
 
            value = self.get(name, expand=False)
3215
 
            value = self._expand_options_in_string(value, env, _refs)
 
2595
            try:
 
2596
                opt = option_registry.get(name)
 
2597
            except KeyError:
 
2598
                # Not registered
 
2599
                opt = None
 
2600
            if opt is not None:
 
2601
                value = opt.get_default()
3216
2602
        return value
3217
2603
 
3218
2604
    def _get_mutable_section(self):
3230
2616
        """Set a new value for the option."""
3231
2617
        section = self._get_mutable_section()
3232
2618
        section.set(name, value)
3233
 
        for hook in ConfigHooks['set']:
3234
 
            hook(self, name, value)
3235
2619
 
3236
2620
    def remove(self, name):
3237
2621
        """Remove an existing option."""
3238
2622
        section = self._get_mutable_section()
3239
2623
        section.remove(name)
3240
 
        for hook in ConfigHooks['remove']:
3241
 
            hook(self, name)
3242
2624
 
3243
2625
    def __repr__(self):
3244
2626
        # Mostly for debugging use
3270
2652
 
3271
2653
 
3272
2654
class GlobalStack(_CompatibleStack):
3273
 
    """Global options only stack."""
3274
2655
 
3275
2656
    def __init__(self):
3276
2657
        # Get a GlobalStore
3279
2660
 
3280
2661
 
3281
2662
class LocationStack(_CompatibleStack):
3282
 
    """Per-location options falling back to global options stack."""
3283
2663
 
3284
2664
    def __init__(self, location):
3285
 
        """Make a new stack for a location and global configuration.
3286
 
        
3287
 
        :param location: A URL prefix to """
3288
2665
        lstore = LocationStore()
3289
2666
        matcher = LocationMatcher(lstore, location)
3290
2667
        gstore = GlobalStore()
3291
2668
        super(LocationStack, self).__init__(
3292
2669
            [matcher.get_sections, gstore.get_sections], lstore)
3293
2670
 
3294
 
 
3295
2671
class BranchStack(_CompatibleStack):
3296
 
    """Per-location options falling back to branch then global options stack."""
3297
2672
 
3298
2673
    def __init__(self, branch):
3299
2674
        bstore = BranchStore(branch)
3306
2681
        self.branch = branch
3307
2682
 
3308
2683
 
3309
 
class RemoteControlStack(_CompatibleStack):
3310
 
    """Remote control-only options stack."""
3311
 
 
3312
 
    def __init__(self, bzrdir):
3313
 
        cstore = ControlStore(bzrdir)
3314
 
        super(RemoteControlStack, self).__init__(
3315
 
            [cstore.get_sections],
3316
 
            cstore)
3317
 
        self.bzrdir = bzrdir
3318
 
 
3319
 
 
3320
 
class RemoteBranchStack(_CompatibleStack):
3321
 
    """Remote branch-only options stack."""
3322
 
 
3323
 
    def __init__(self, branch):
3324
 
        bstore = BranchStore(branch)
3325
 
        super(RemoteBranchStack, self).__init__(
3326
 
            [bstore.get_sections],
3327
 
            bstore)
3328
 
        self.branch = branch
3329
 
 
3330
 
 
3331
2684
class cmd_config(commands.Command):
3332
2685
    __doc__ = """Display, set or remove a configuration option.
3333
2686
 
3360
2713
                        ' the configuration file'),
3361
2714
        ]
3362
2715
 
3363
 
    _see_also = ['configuration']
3364
 
 
3365
2716
    @commands.display_command
3366
2717
    def run(self, name=None, all=False, directory=None, scope=None,
3367
2718
            remove=False):
3441
2792
            raise errors.NoSuchConfigOption(name)
3442
2793
 
3443
2794
    def _show_matching_options(self, name, directory, scope):
3444
 
        name = lazy_regex.lazy_compile(name)
 
2795
        name = re.compile(name)
3445
2796
        # We want any error in the regexp to be raised *now* so we need to
3446
 
        # avoid the delay introduced by the lazy regexp.  But, we still do
3447
 
        # want the nicer errors raised by lazy_regex.
 
2797
        # avoid the delay introduced by the lazy regexp.
3448
2798
        name._compile_and_collapse()
3449
2799
        cur_conf_id = None
3450
2800
        cur_section = None