~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

Abbreviate pack_stat struct format to '>6L'

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
32
35
 
33
36
in locations.conf, you specify the url of a branch and options for it.
34
37
Wildcards may be used - * and ? as normal in shell completion. Options
39
42
email= as above
40
43
check_signatures= as above
41
44
create_signatures= as above.
 
45
validate_signatures_in_log=as above
 
46
acceptable_keys=as above
42
47
 
43
48
explanation of options
44
49
----------------------
45
50
editor - this option sets the pop up editor to use during commits.
46
51
email - this option sets the user id bzr will use when committing.
47
 
check_signatures - this option controls whether bzr will require good gpg
 
52
check_signatures - this option will control whether bzr will require good gpg
48
53
                   signatures, ignore them, or check them if they are
49
 
                   present.
 
54
                   present.  Currently it is unused except that check_signatures
 
55
                   turns on create_signatures.
50
56
create_signatures - this option controls whether bzr will always create
51
 
                    gpg signatures, never create them, or create them if the
52
 
                    branch is configured to require them.
 
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.
53
60
log_format - this option sets the default log format.  Possible values are
54
61
             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
55
65
 
56
66
In bazaar.conf you can also define aliases in the ALIASES sections, example
57
67
 
66
76
import string
67
77
import sys
68
78
 
69
 
from bzrlib import commands
 
79
 
70
80
from bzrlib.decorators import needs_write_lock
71
81
from bzrlib.lazy_import import lazy_import
72
82
lazy_import(globals(), """
74
84
import re
75
85
from cStringIO import StringIO
76
86
 
77
 
import bzrlib
78
87
from bzrlib import (
79
88
    atomicfile,
80
89
    bzrdir,
81
90
    debug,
82
91
    errors,
 
92
    lazy_regex,
83
93
    lockdir,
84
94
    mail_client,
85
95
    mergetools,
86
96
    osutils,
87
 
    registry,
88
97
    symbol_versioning,
89
98
    trace,
90
99
    transport,
94
103
    )
95
104
from bzrlib.util.configobj import configobj
96
105
""")
 
106
from bzrlib import (
 
107
    commands,
 
108
    hooks,
 
109
    lazy_regex,
 
110
    registry,
 
111
    )
 
112
from bzrlib.symbol_versioning import (
 
113
    deprecated_in,
 
114
    deprecated_method,
 
115
    )
97
116
 
98
117
 
99
118
CHECK_IF_POSSIBLE=0
138
157
                                        interpolation=False,
139
158
                                        **kwargs)
140
159
 
141
 
 
142
160
    def get_bool(self, section, key):
143
161
        return self[section].as_bool(key)
144
162
 
152
170
        return self[section][name]
153
171
 
154
172
 
155
 
# FIXME: Until we can guarantee that each config file is loaded once and and
 
173
# FIXME: Until we can guarantee that each config file is loaded once and
156
174
# only once for a given bzrlib session, we don't want to re-read the file every
157
175
# time we query for an option so we cache the value (bad ! watch out for tests
158
 
# needing to restore the proper value).This shouldn't be part of 2.4.0 final,
159
 
# yell at mgz^W vila and the RM if this is still present at that time
160
 
# -- vila 20110219
 
176
# needing to restore the proper value). -- vila 20110219
161
177
_expand_default_value = None
162
178
def _get_expand_default_value():
163
179
    global _expand_default_value
185
201
        """Returns a unique ID for the config."""
186
202
        raise NotImplementedError(self.config_id)
187
203
 
 
204
    @deprecated_method(deprecated_in((2, 4, 0)))
188
205
    def get_editor(self):
189
206
        """Get the users pop up editor."""
190
207
        raise NotImplementedError
197
214
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
198
215
                                             sys.stdout)
199
216
 
200
 
 
201
217
    def get_mail_client(self):
202
218
        """Get a mail client to use"""
203
219
        selected_client = self.get_user_option('mail_client')
363
379
                              % (option_name,))
364
380
            else:
365
381
                value = self._expand_options_in_string(value)
 
382
        for hook in OldConfigHooks['get']:
 
383
            hook(self, option_name, value)
366
384
        return value
367
385
 
368
 
    def get_user_option_as_bool(self, option_name, expand=None):
369
 
        """Get a generic option as a boolean - no special process, no default.
 
386
    def get_user_option_as_bool(self, option_name, expand=None, default=None):
 
387
        """Get a generic option as a boolean.
370
388
 
 
389
        :param expand: Allow expanding references to other config values.
 
390
        :param default: Default value if nothing is configured
371
391
        :return None if the option doesn't exist or its value can't be
372
392
            interpreted as a boolean. Returns True or False otherwise.
373
393
        """
374
394
        s = self.get_user_option(option_name, expand=expand)
375
395
        if s is None:
376
396
            # The option doesn't exist
377
 
            return None
 
397
            return default
378
398
        val = ui.bool_from_string(s)
379
399
        if val is None:
380
400
            # The value can't be interpreted as a boolean
394
414
            # add) the final ','
395
415
            l = [l]
396
416
        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
        
397
456
 
398
457
    def gpg_signing_command(self):
399
458
        """What program should be used to sign signatures?"""
417
476
        """See log_format()."""
418
477
        return None
419
478
 
 
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
 
420
502
    def post_commit(self):
421
503
        """An ordered list of python functions to call.
422
504
 
485
567
        if policy is None:
486
568
            policy = self._get_signature_checking()
487
569
            if policy is not None:
 
570
                #this warning should go away once check_signatures is
 
571
                #implemented (if not before)
488
572
                trace.warning("Please use create_signatures,"
489
573
                              " not check_signatures to set signing policy.")
490
 
            if policy == CHECK_ALWAYS:
491
 
                return True
492
574
        elif policy == SIGN_ALWAYS:
493
575
            return True
494
576
        return False
495
577
 
 
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
 
496
586
    def get_alias(self, value):
497
587
        return self._get_alias(value)
498
588
 
532
622
        for (oname, value, section, conf_id, parser) in self._get_options():
533
623
            if oname.startswith('bzr.mergetool.'):
534
624
                tool_name = oname[len('bzr.mergetool.'):]
535
 
                tools[tool_name] = value
 
625
                tools[tool_name] = self.get_user_option(oname)
536
626
        trace.mutter('loaded merge tools: %r' % tools)
537
627
        return tools
538
628
 
539
629
    def find_merge_tool(self, name):
540
 
        # We fake a defaults mechanism here by checking if the given name can 
 
630
        # We fake a defaults mechanism here by checking if the given name can
541
631
        # be found in the known_merge_tools if it's not found in the config.
542
632
        # This should be done through the proposed config defaults mechanism
543
633
        # when it becomes available in the future.
547
637
        return command_line
548
638
 
549
639
 
 
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
 
550
710
class IniBasedConfig(Config):
551
711
    """A configuration policy that draws from ini files."""
552
712
 
612
772
            self._parser = ConfigObj(co_input, encoding='utf-8')
613
773
        except configobj.ConfigObjError, e:
614
774
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
775
        except UnicodeDecodeError:
 
776
            raise errors.ConfigContentError(self.file_name)
615
777
        # Make sure self.reload() will use the right file name
616
778
        self._parser.filename = self.file_name
 
779
        for hook in OldConfigHooks['load']:
 
780
            hook(self)
617
781
        return self._parser
618
782
 
619
783
    def reload(self):
622
786
            raise AssertionError('We need a file name to reload the config')
623
787
        if self._parser is not None:
624
788
            self._parser.reload()
 
789
        for hook in ConfigHooks['load']:
 
790
            hook(self)
625
791
 
626
792
    def _get_matching_sections(self):
627
793
        """Return an ordered list of (section_name, extra_path) pairs.
744
910
        """See Config.log_format."""
745
911
        return self._get_user_option('log_format')
746
912
 
 
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
 
747
921
    def _post_commit(self):
748
922
        """See Config.post_commit."""
749
923
        return self._get_user_option('post_commit')
799
973
        except KeyError:
800
974
            raise errors.NoSuchConfigOption(option_name)
801
975
        self._write_config_file()
 
976
        for hook in OldConfigHooks['remove']:
 
977
            hook(self, option_name)
802
978
 
803
979
    def _write_config_file(self):
804
980
        if self.file_name is None:
810
986
        atomic_file.commit()
811
987
        atomic_file.close()
812
988
        osutils.copy_ownership_from_path(self.file_name)
 
989
        for hook in OldConfigHooks['save']:
 
990
            hook(self)
813
991
 
814
992
 
815
993
class LockableConfig(IniBasedConfig):
847
1025
        # local transports are not shared. But if/when we start using
848
1026
        # LockableConfig for other kind of transports, we will need to reuse
849
1027
        # whatever connection is already established -- vila 20100929
850
 
        self.transport = transport.get_transport(self.dir)
 
1028
        self.transport = transport.get_transport_from_path(self.dir)
851
1029
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
852
1030
 
853
1031
    def _create_from_string(self, unicode_bytes, save):
908
1086
        conf._create_from_string(str_or_unicode, save)
909
1087
        return conf
910
1088
 
 
1089
    @deprecated_method(deprecated_in((2, 4, 0)))
911
1090
    def get_editor(self):
912
1091
        return self._get_user_option('editor')
913
1092
 
942
1121
        self.reload()
943
1122
        self._get_parser().setdefault(section, {})[option] = value
944
1123
        self._write_config_file()
945
 
 
 
1124
        for hook in OldConfigHooks['set']:
 
1125
            hook(self, option, value)
946
1126
 
947
1127
    def _get_sections(self, name=None):
948
1128
        """See IniBasedConfig._get_sections()."""
978
1158
        number of path components in the section name, section is the section
979
1159
        name and extra_path is the difference between location and the section
980
1160
        name.
 
1161
 
 
1162
    ``location`` will always be a local path and never a 'file://' url but the
 
1163
    section names themselves can be in either form.
981
1164
    """
982
1165
    location_parts = location.rstrip('/').split('/')
983
1166
 
984
1167
    for section in sections:
985
 
        # location is a local path if possible, so we need
986
 
        # to convert 'file://' urls to local paths if necessary.
987
 
 
988
 
        # FIXME: I don't think the above comment is still up to date,
989
 
        # LocationConfig is always instantiated with an url -- vila 2011-04-07
 
1168
        # location is a local path if possible, so we need to convert 'file://'
 
1169
        # urls in section names to local paths if necessary.
990
1170
 
991
1171
        # This also avoids having file:///path be a more exact
992
1172
        # match than '/path'.
993
1173
 
994
 
        # FIXME: Not sure about the above either, but since the path components
995
 
        # are compared in sync, adding two empty components (//) is likely to
996
 
        # trick the comparison and also trick the check on the number of
997
 
        # components, so we *should* take only the relevant part of the url. On
998
 
        # the other hand, this means 'file://' urls *can't* be used in sections
999
 
        # so more work is probably needed -- vila 2011-04-07
 
1174
        # FIXME: This still raises an issue if a user defines both file:///path
 
1175
        # *and* /path. Should we raise an error in this case -- vila 20110505
1000
1176
 
1001
1177
        if section.startswith('file://'):
1002
1178
            section_path = urlutils.local_path_from_url(section)
1148
1324
        # the allowed values of store match the config policies
1149
1325
        self._set_option_policy(location, option, store)
1150
1326
        self._write_config_file()
 
1327
        for hook in OldConfigHooks['set']:
 
1328
            hook(self, option, value)
1151
1329
 
1152
1330
 
1153
1331
class BranchConfig(Config):
1219
1397
            return (self.branch._transport.get_bytes("email")
1220
1398
                    .decode(osutils.get_user_encoding())
1221
1399
                    .rstrip("\r\n"))
1222
 
        except errors.NoSuchFile, e:
 
1400
        except (errors.NoSuchFile, errors.PermissionDenied), e:
1223
1401
            pass
1224
1402
 
1225
1403
        return self._get_best_value('_get_user_id')
1320
1498
        """See Config.log_format."""
1321
1499
        return self._get_best_value('_log_format')
1322
1500
 
 
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
 
1323
1509
 
1324
1510
def ensure_config_dir_exists(path=None):
1325
1511
    """Make sure a configuration directory exists.
1365
1551
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1366
1552
                                  ' or HOME set')
1367
1553
        return osutils.pathjoin(base, 'bazaar', '2.0')
1368
 
    elif sys.platform == 'darwin':
 
1554
    else:
 
1555
        if base is not None:
 
1556
            base = base.decode(osutils._fs_enc)
 
1557
    if sys.platform == 'darwin':
1369
1558
        if base is None:
1370
1559
            # this takes into account $HOME
1371
1560
            base = os.path.expanduser("~")
1372
1561
        return osutils.pathjoin(base, '.bazaar')
1373
1562
    else:
1374
1563
        if base is None:
1375
 
 
1376
1564
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
1377
1565
            if xdg_dir is None:
1378
1566
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
1381
1569
                trace.mutter(
1382
1570
                    "Using configuration in XDG directory %s." % xdg_dir)
1383
1571
                return xdg_dir
1384
 
 
1385
1572
            base = os.path.expanduser("~")
1386
1573
        return osutils.pathjoin(base, ".bazaar")
1387
1574
 
1481
1668
    try:
1482
1669
        w = pwd.getpwuid(uid)
1483
1670
    except KeyError:
1484
 
        mutter('no passwd entry for uid %d?' % uid)
 
1671
        trace.mutter('no passwd entry for uid %d?' % uid)
1485
1672
        return None, None
1486
1673
 
1487
1674
    # we try utf-8 first, because on many variants (like Linux),
1496
1683
            encoding = osutils.get_user_encoding()
1497
1684
            gecos = w.pw_gecos.decode(encoding)
1498
1685
        except UnicodeError, e:
1499
 
            mutter("cannot decode passwd entry %s" % w)
 
1686
            trace.mutter("cannot decode passwd entry %s" % w)
1500
1687
            return None, None
1501
1688
    try:
1502
1689
        username = w.pw_name.decode(encoding)
1503
1690
    except UnicodeError, e:
1504
 
        mutter("cannot decode passwd entry %s" % w)
 
1691
        trace.mutter("cannot decode passwd entry %s" % w)
1505
1692
        return None, None
1506
1693
 
1507
1694
    comma = gecos.find(',')
1609
1796
            self._config = ConfigObj(self._input, encoding='utf-8')
1610
1797
        except configobj.ConfigObjError, e:
1611
1798
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
1799
        except UnicodeError:
 
1800
            raise errors.ConfigContentError(self._filename)
1612
1801
        return self._config
1613
1802
 
1614
1803
    def _save(self):
1631
1820
        section[option_name] = value
1632
1821
        self._save()
1633
1822
 
1634
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
 
1823
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
1635
1824
                        realm=None):
1636
1825
        """Returns the matching credentials from authentication.conf file.
1637
1826
 
1805
1994
            if ask:
1806
1995
                if prompt is None:
1807
1996
                    # Create a default prompt suitable for most cases
1808
 
                    prompt = scheme.upper() + ' %(host)s username'
 
1997
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
1809
1998
                # Special handling for optional fields in the prompt
1810
1999
                if port is not None:
1811
2000
                    prompt_host = '%s:%d' % (host, port)
1849
2038
        if password is None:
1850
2039
            if prompt is None:
1851
2040
                # Create a default prompt suitable for most cases
1852
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
2041
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
1853
2042
            # Special handling for optional fields in the prompt
1854
2043
            if port is not None:
1855
2044
                prompt_host = '%s:%d' % (host, port)
2050
2239
                section_obj = configobj[section]
2051
2240
            except KeyError:
2052
2241
                return default
2053
 
        return section_obj.get(name, default)
 
2242
        value = section_obj.get(name, default)
 
2243
        for hook in OldConfigHooks['get']:
 
2244
            hook(self, name, value)
 
2245
        return value
2054
2246
 
2055
2247
    def set_option(self, value, name, section=None):
2056
2248
        """Set the value associated with a named option.
2064
2256
            configobj[name] = value
2065
2257
        else:
2066
2258
            configobj.setdefault(section, {})[name] = value
 
2259
        for hook in OldConfigHooks['set']:
 
2260
            hook(self, name, value)
2067
2261
        self._set_configobj(configobj)
2068
2262
 
2069
2263
    def remove_option(self, option_name, section_name=None):
2072
2266
            del configobj[option_name]
2073
2267
        else:
2074
2268
            del configobj[section_name][option_name]
 
2269
        for hook in OldConfigHooks['remove']:
 
2270
            hook(self, option_name)
2075
2271
        self._set_configobj(configobj)
2076
2272
 
2077
2273
    def _get_config_file(self):
2078
2274
        try:
2079
 
            return StringIO(self._transport.get_bytes(self._filename))
 
2275
            f = StringIO(self._transport.get_bytes(self._filename))
 
2276
            for hook in OldConfigHooks['load']:
 
2277
                hook(self)
 
2278
            return f
2080
2279
        except errors.NoSuchFile:
2081
2280
            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)
2082
2289
 
2083
2290
    def _get_configobj(self):
2084
2291
        f = self._get_config_file()
2085
2292
        try:
2086
 
            return ConfigObj(f, encoding='utf-8')
 
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())
2087
2299
        finally:
2088
2300
            f.close()
 
2301
        return conf
2089
2302
 
2090
2303
    def _set_configobj(self, configobj):
2091
2304
        out_file = StringIO()
2092
2305
        configobj.write(out_file)
2093
2306
        out_file.seek(0)
2094
2307
        self._transport.put_file(self._filename, out_file)
 
2308
        for hook in OldConfigHooks['save']:
 
2309
            hook(self)
 
2310
 
 
2311
 
 
2312
class Option(object):
 
2313
    """An option definition.
 
2314
 
 
2315
    The option *values* are stored in config files and found in sections.
 
2316
 
 
2317
    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.
 
2320
    """
 
2321
 
 
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 = []
 
2353
        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)):
 
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
 
2395
 
 
2396
    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
# Use a an empty dict to initialize an empty configobj avoiding all
 
2430
# parsing and encoding checks
 
2431
_list_converter_config = configobj.ConfigObj(
 
2432
    {}, encoding='utf-8', list_values=True, interpolation=False)
 
2433
 
 
2434
 
 
2435
def list_from_store(unicode_str):
 
2436
    if not isinstance(unicode_str, basestring):
 
2437
        raise TypeError
 
2438
    # Now inject our string directly as unicode. All callers got their value
 
2439
    # from configobj, so values that need to be quoted are already properly
 
2440
    # quoted.
 
2441
    _list_converter_config.reset()
 
2442
    _list_converter_config._parse([u"list=%s" % (unicode_str,)])
 
2443
    maybe_list = _list_converter_config['list']
 
2444
    # ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
 
2445
    if isinstance(maybe_list, basestring):
 
2446
        if maybe_list:
 
2447
            # A single value, most probably the user forgot (or didn't care to
 
2448
            # add) the final ','
 
2449
            l = [maybe_list]
 
2450
        else:
 
2451
            # The empty string, convert to empty list
 
2452
            l = []
 
2453
    else:
 
2454
        # We rely on ConfigObj providing us with a list already
 
2455
        l = maybe_list
 
2456
    return l
 
2457
 
 
2458
 
 
2459
class OptionRegistry(registry.Registry):
 
2460
    """Register config options by their name.
 
2461
 
 
2462
    This overrides ``registry.Registry`` to simplify registration by acquiring
 
2463
    some information from the option object itself.
 
2464
    """
 
2465
 
 
2466
    def register(self, option):
 
2467
        """Register a new option to its name.
 
2468
 
 
2469
        :param option: The option to register. Its name is used as the key.
 
2470
        """
 
2471
        super(OptionRegistry, self).register(option.name, option,
 
2472
                                             help=option.help)
 
2473
 
 
2474
    def register_lazy(self, key, module_name, member_name):
 
2475
        """Register a new option to be loaded on request.
 
2476
 
 
2477
        :param key: the key to request the option later. Since the registration
 
2478
            is lazy, it should be provided and match the option name.
 
2479
 
 
2480
        :param module_name: the python path to the module. Such as 'os.path'.
 
2481
 
 
2482
        :param member_name: the member of the module to return.  If empty or 
 
2483
                None, get() will return the module itself.
 
2484
        """
 
2485
        super(OptionRegistry, self).register_lazy(key,
 
2486
                                                  module_name, member_name)
 
2487
 
 
2488
    def get_help(self, key=None):
 
2489
        """Get the help text associated with the given key"""
 
2490
        option = self.get(key)
 
2491
        the_help = option.help
 
2492
        if callable(the_help):
 
2493
            return the_help(self, key)
 
2494
        return the_help
 
2495
 
 
2496
 
 
2497
option_registry = OptionRegistry()
 
2498
 
 
2499
 
 
2500
# Registered options in lexicographical order
 
2501
 
 
2502
option_registry.register(
 
2503
    Option('bzr.workingtree.worth_saving_limit', default=10,
 
2504
           from_unicode=int_from_store,  invalid='warning',
 
2505
           help='''\
 
2506
How many changes before saving the dirstate.
 
2507
 
 
2508
-1 means that we will never rewrite the dirstate file for only
 
2509
stat-cache changes. Regardless of this setting, we will always rewrite
 
2510
the dirstate file if a file is added/removed/renamed/etc. This flag only
 
2511
affects the behavior of updating the dirstate file after we notice that
 
2512
a file has been touched.
 
2513
'''))
 
2514
option_registry.register(
 
2515
    Option('dirstate.fdatasync', default=True,
 
2516
           from_unicode=bool_from_store,
 
2517
           help='''\
 
2518
Flush dirstate changes onto physical disk?
 
2519
 
 
2520
If true (default), working tree metadata changes are flushed through the
 
2521
OS buffers to physical disk.  This is somewhat slower, but means data
 
2522
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2523
'''))
 
2524
option_registry.register(
 
2525
    Option('debug_flags', default=[], from_unicode=list_from_store,
 
2526
           help='Debug flags to activate.'))
 
2527
option_registry.register(
 
2528
    Option('default_format', default='2a',
 
2529
           help='Format used when creating branches.'))
 
2530
option_registry.register(
 
2531
    Option('dpush_strict', default=None,
 
2532
           from_unicode=bool_from_store,
 
2533
           help='''\
 
2534
The default value for ``dpush --strict``.
 
2535
 
 
2536
If present, defines the ``--strict`` option default value for checking
 
2537
uncommitted changes before pushing into a different VCS without any
 
2538
custom bzr metadata.
 
2539
'''))
 
2540
option_registry.register(
 
2541
    Option('editor',
 
2542
           help='The command called to launch an editor to enter a message.'))
 
2543
option_registry.register(
 
2544
    Option('ignore_missing_extensions', default=False,
 
2545
           from_unicode=bool_from_store,
 
2546
           help='''\
 
2547
Control the missing extensions warning display.
 
2548
 
 
2549
The warning will not be emitted if set to True.
 
2550
'''))
 
2551
option_registry.register(
 
2552
    Option('language',
 
2553
           help='Language to translate messages into.'))
 
2554
option_registry.register(
 
2555
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
 
2556
           help='''\
 
2557
Steal locks that appears to be dead.
 
2558
 
 
2559
If set to True, bzr will check if a lock is supposed to be held by an
 
2560
active process from the same user on the same machine. If the user and
 
2561
machine match, but no process with the given PID is active, then bzr
 
2562
will automatically break the stale lock, and create a new lock for
 
2563
this process.
 
2564
Otherwise, bzr will prompt as normal to break the lock.
 
2565
'''))
 
2566
option_registry.register(
 
2567
    Option('output_encoding',
 
2568
           help= 'Unicode encoding for output'
 
2569
           ' (terminal encoding if not specified).'))
 
2570
option_registry.register(
 
2571
    Option('push_strict', default=None,
 
2572
           from_unicode=bool_from_store,
 
2573
           help='''\
 
2574
The default value for ``push --strict``.
 
2575
 
 
2576
If present, defines the ``--strict`` option default value for checking
 
2577
uncommitted changes before sending a merge directive.
 
2578
'''))
 
2579
option_registry.register(
 
2580
    Option('repository.fdatasync', default=True,
 
2581
           from_unicode=bool_from_store,
 
2582
           help='''\
 
2583
Flush repository changes onto physical disk?
 
2584
 
 
2585
If true (default), repository changes are flushed through the OS buffers
 
2586
to physical disk.  This is somewhat slower, but means data should not be
 
2587
lost if the machine crashes.  See also dirstate.fdatasync.
 
2588
'''))
 
2589
option_registry.register(
 
2590
    Option('send_strict', default=None,
 
2591
           from_unicode=bool_from_store,
 
2592
           help='''\
 
2593
The default value for ``send --strict``.
 
2594
 
 
2595
If present, defines the ``--strict`` option default value for checking
 
2596
uncommitted changes before pushing.
 
2597
'''))
2095
2598
 
2096
2599
 
2097
2600
class Section(object):
2098
 
    """A section defines a dict of options.
 
2601
    """A section defines a dict of option name => value.
2099
2602
 
2100
2603
    This is merely a read-only dict which can add some knowledge about the
2101
2604
    options. It is *not* a python dict object though and doesn't try to mimic
2158
2661
        """Loads the Store from persistent storage."""
2159
2662
        raise NotImplementedError(self.load)
2160
2663
 
2161
 
    def _load_from_string(self, str_or_unicode):
 
2664
    def _load_from_string(self, bytes):
2162
2665
        """Create a store from a string in configobj syntax.
2163
2666
 
2164
 
        :param str_or_unicode: A string representing the file content. This will
2165
 
            be encoded to suit store needs internally.
2166
 
 
2167
 
        This is for tests and should not be used in production unless a
2168
 
        convincing use case can be demonstrated :)
 
2667
        :param bytes: A string representing the file content.
2169
2668
        """
2170
2669
        raise NotImplementedError(self._load_from_string)
2171
2670
 
 
2671
    def unload(self):
 
2672
        """Unloads the Store.
 
2673
 
 
2674
        This should make is_loaded() return False. This is used when the caller
 
2675
        knows that the persistent storage has changed or may have change since
 
2676
        the last load.
 
2677
        """
 
2678
        raise NotImplementedError(self.unload)
 
2679
 
2172
2680
    def save(self):
2173
2681
        """Saves the Store to persistent storage."""
2174
2682
        raise NotImplementedError(self.save)
2222
2730
    def is_loaded(self):
2223
2731
        return self._config_obj != None
2224
2732
 
 
2733
    def unload(self):
 
2734
        self._config_obj = None
 
2735
 
2225
2736
    def load(self):
2226
2737
        """Load the store from the associated file."""
2227
2738
        if self.is_loaded():
2228
2739
            return
2229
 
        content = self.transport.get_bytes(self.file_name)
 
2740
        try:
 
2741
            content = self.transport.get_bytes(self.file_name)
 
2742
        except errors.PermissionDenied:
 
2743
            trace.warning("Permission denied while trying to load "
 
2744
                          "configuration store %s.", self.external_url())
 
2745
            raise
2230
2746
        self._load_from_string(content)
 
2747
        for hook in ConfigHooks['load']:
 
2748
            hook(self)
2231
2749
 
2232
 
    def _load_from_string(self, str_or_unicode):
 
2750
    def _load_from_string(self, bytes):
2233
2751
        """Create a config store from a string.
2234
2752
 
2235
 
        :param str_or_unicode: A string representing the file content. This will
2236
 
            be utf-8 encoded internally.
2237
 
 
2238
 
        This is for tests and should not be used in production unless a
2239
 
        convincing use case can be demonstrated :)
 
2753
        :param bytes: A string representing the file content.
2240
2754
        """
2241
2755
        if self.is_loaded():
2242
2756
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
2243
 
        co_input = StringIO(str_or_unicode.encode('utf-8'))
 
2757
        co_input = StringIO(bytes)
2244
2758
        try:
2245
2759
            # The config files are always stored utf8-encoded
2246
 
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
 
2760
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
 
2761
                                         list_values=False)
2247
2762
        except configobj.ConfigObjError, e:
2248
2763
            self._config_obj = None
2249
2764
            raise errors.ParseConfigError(e.errors, self.external_url())
 
2765
        except UnicodeDecodeError:
 
2766
            raise errors.ConfigContentError(self.external_url())
2250
2767
 
2251
2768
    def save(self):
2252
2769
        if not self.is_loaded():
2255
2772
        out = StringIO()
2256
2773
        self._config_obj.write(out)
2257
2774
        self.transport.put_bytes(self.file_name, out.getvalue())
 
2775
        for hook in ConfigHooks['save']:
 
2776
            hook(self)
2258
2777
 
2259
2778
    def external_url(self):
2260
2779
        # FIXME: external_url should really accepts an optional relpath
2270
2789
        :returns: An iterable of (name, dict).
2271
2790
        """
2272
2791
        # We need a loaded store
2273
 
        self.load()
 
2792
        try:
 
2793
            self.load()
 
2794
        except (errors.NoSuchFile, errors.PermissionDenied):
 
2795
            # If the file can't be read, there is no sections
 
2796
            return
2274
2797
        cobj = self._config_obj
2275
2798
        if cobj.scalars:
2276
2799
            yield self.readonly_section_class(None, cobj)
2332
2855
 
2333
2856
    @needs_write_lock
2334
2857
    def save(self):
 
2858
        # We need to be able to override the undecorated implementation
 
2859
        self.save_without_locking()
 
2860
 
 
2861
    def save_without_locking(self):
2335
2862
        super(LockableIniFileStore, self).save()
2336
2863
 
2337
2864
 
2346
2873
class GlobalStore(LockableIniFileStore):
2347
2874
 
2348
2875
    def __init__(self, possible_transports=None):
2349
 
        t = transport.get_transport(config_dir(),
2350
 
                                    possible_transports=possible_transports)
 
2876
        t = transport.get_transport_from_path(
 
2877
            config_dir(), possible_transports=possible_transports)
2351
2878
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
2352
2879
 
2353
2880
 
2354
2881
class LocationStore(LockableIniFileStore):
2355
2882
 
2356
2883
    def __init__(self, possible_transports=None):
2357
 
        t = transport.get_transport(config_dir(),
2358
 
                                    possible_transports=possible_transports)
 
2884
        t = transport.get_transport_from_path(
 
2885
            config_dir(), possible_transports=possible_transports)
2359
2886
        super(LocationStore, self).__init__(t, 'locations.conf')
2360
2887
 
2361
2888
 
2364
2891
    def __init__(self, branch):
2365
2892
        super(BranchStore, self).__init__(branch.control_transport,
2366
2893
                                          'branch.conf')
 
2894
        self.branch = branch
 
2895
 
 
2896
    def lock_write(self, token=None):
 
2897
        return self.branch.lock_write(token)
 
2898
 
 
2899
    def unlock(self):
 
2900
        return self.branch.unlock()
 
2901
 
 
2902
    @needs_write_lock
 
2903
    def save(self):
 
2904
        # We need to be able to override the undecorated implementation
 
2905
        self.save_without_locking()
 
2906
 
 
2907
    def save_without_locking(self):
 
2908
        super(BranchStore, self).save()
 
2909
 
 
2910
 
 
2911
class ControlStore(LockableIniFileStore):
 
2912
 
 
2913
    def __init__(self, bzrdir):
 
2914
        super(ControlStore, self).__init__(bzrdir.transport,
 
2915
                                          'control.conf',
 
2916
                                           lock_dir_name='branch_lock')
 
2917
 
2367
2918
 
2368
2919
class SectionMatcher(object):
2369
2920
    """Select sections into a given Store.
2370
2921
 
2371
 
    This intended to be used to postpone getting an iterable of sections from a
2372
 
    store.
 
2922
    This is intended to be used to postpone getting an iterable of sections
 
2923
    from a store.
2373
2924
    """
2374
2925
 
2375
2926
    def __init__(self, store):
2384
2935
            if self.match(s):
2385
2936
                yield s
2386
2937
 
2387
 
    def match(self, secion):
 
2938
    def match(self, section):
 
2939
        """Does the proposed section match.
 
2940
 
 
2941
        :param section: A Section object.
 
2942
 
 
2943
        :returns: True if the section matches, False otherwise.
 
2944
        """
2388
2945
        raise NotImplementedError(self.match)
2389
2946
 
2390
2947
 
 
2948
class NameMatcher(SectionMatcher):
 
2949
 
 
2950
    def __init__(self, store, section_id):
 
2951
        super(NameMatcher, self).__init__(store)
 
2952
        self.section_id = section_id
 
2953
 
 
2954
    def match(self, section):
 
2955
        return section.id == self.section_id
 
2956
 
 
2957
 
2391
2958
class LocationSection(Section):
2392
2959
 
2393
2960
    def __init__(self, section, length, extra_path):
2409
2976
 
2410
2977
    def __init__(self, store, location):
2411
2978
        super(LocationMatcher, self).__init__(store)
 
2979
        if location.startswith('file://'):
 
2980
            location = urlutils.local_path_from_url(location)
2412
2981
        self.location = location
2413
2982
 
2414
 
    def get_sections(self):
2415
 
        # Override the default implementation as we want to change the order
2416
 
 
2417
 
        # The following is a bit hackish but ensures compatibility with
2418
 
        # LocationConfig by reusing the same code
2419
 
        sections = list(self.store.get_sections())
 
2983
    def _get_matching_sections(self):
 
2984
        """Get all sections matching ``location``."""
 
2985
        # We slightly diverge from LocalConfig here by allowing the no-name
 
2986
        # section as the most generic one and the lower priority.
 
2987
        no_name_section = None
 
2988
        all_sections = []
 
2989
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
2990
        # used (it assumes all sections have a name).
 
2991
        for section in self.store.get_sections():
 
2992
            if section.id is None:
 
2993
                no_name_section = section
 
2994
            else:
 
2995
                all_sections.append(section)
 
2996
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
2997
        # we have to resync.
2420
2998
        filtered_sections = _iter_for_location_by_parts(
2421
 
            [s.id for s in sections], self.location)
2422
 
        iter_sections = iter(sections)
 
2999
            [s.id for s in all_sections], self.location)
 
3000
        iter_all_sections = iter(all_sections)
2423
3001
        matching_sections = []
 
3002
        if no_name_section is not None:
 
3003
            matching_sections.append(
 
3004
                LocationSection(no_name_section, 0, self.location))
2424
3005
        for section_id, extra_path, length in filtered_sections:
2425
 
            # a section id is unique for a given store so it's safe to iterate
2426
 
            # again
2427
 
            section = iter_sections.next()
2428
 
            if section_id == section.id:
2429
 
                matching_sections.append(
2430
 
                    LocationSection(section, length, extra_path))
 
3006
            # a section id is unique for a given store so it's safe to take the
 
3007
            # first matching section while iterating. Also, all filtered
 
3008
            # sections are part of 'all_sections' and will always be found
 
3009
            # there.
 
3010
            while True:
 
3011
                section = iter_all_sections.next()
 
3012
                if section_id == section.id:
 
3013
                    matching_sections.append(
 
3014
                        LocationSection(section, length, extra_path))
 
3015
                    break
 
3016
        return matching_sections
 
3017
 
 
3018
    def get_sections(self):
 
3019
        # Override the default implementation as we want to change the order
 
3020
        matching_sections = self._get_matching_sections()
2431
3021
        # We want the longest (aka more specific) locations first
2432
3022
        sections = sorted(matching_sections,
2433
3023
                          key=lambda section: (section.length, section.id),
2447
3037
class Stack(object):
2448
3038
    """A stack of configurations where an option can be defined"""
2449
3039
 
 
3040
    _option_ref_re = lazy_regex.lazy_compile('({[^{}]+})')
 
3041
    """Describes an exandable option reference.
 
3042
 
 
3043
    We want to match the most embedded reference first.
 
3044
 
 
3045
    I.e. for '{{foo}}' we will get '{foo}',
 
3046
    for '{bar{baz}}' we will get '{baz}'
 
3047
    """
 
3048
 
2450
3049
    def __init__(self, sections_def, store=None, mutable_section_name=None):
2451
3050
        """Creates a stack of sections with an optional store for changes.
2452
3051
 
2465
3064
        self.store = store
2466
3065
        self.mutable_section_name = mutable_section_name
2467
3066
 
2468
 
    def get(self, name):
 
3067
    def get(self, name, expand=None):
2469
3068
        """Return the *first* option value found in the sections.
2470
3069
 
2471
3070
        This is where we guarantee that sections coming from Store are loaded
2473
3072
        option exists or get its value, which in turn may require to discover
2474
3073
        in which sections it can be defined. Both of these (section and option
2475
3074
        existence) require loading the store (even partially).
 
3075
 
 
3076
        :param name: The queried option.
 
3077
 
 
3078
        :param expand: Whether options references should be expanded.
 
3079
 
 
3080
        :returns: The value of the option.
2476
3081
        """
2477
3082
        # FIXME: No caching of options nor sections yet -- vila 20110503
2478
 
 
2479
 
        # Ensuring lazy loading is achieved by delaying section matching until
2480
 
        # it can be avoided anymore by using callables to describe (possibly
2481
 
        # empty) section lists.
 
3083
        if expand is None:
 
3084
            expand = _get_expand_default_value()
 
3085
        value = None
 
3086
        # Ensuring lazy loading is achieved by delaying section matching (which
 
3087
        # implies querying the persistent storage) until it can't be avoided
 
3088
        # anymore by using callables to describe (possibly empty) section
 
3089
        # lists.
2482
3090
        for section_or_callable in self.sections_def:
2483
3091
            # Each section can expand to multiple ones when a callable is used
2484
3092
            if callable(section_or_callable):
2488
3096
            for section in sections:
2489
3097
                value = section.get(name)
2490
3098
                if value is not None:
2491
 
                    return value
2492
 
        # No definition was found
2493
 
        return None
 
3099
                    break
 
3100
            if value is not None:
 
3101
                break
 
3102
        # If the option is registered, it may provide additional info about
 
3103
        # value handling
 
3104
        try:
 
3105
            opt = option_registry.get(name)
 
3106
        except KeyError:
 
3107
            # Not registered
 
3108
            opt = None
 
3109
        def expand_and_convert(val):
 
3110
            # This may need to be called twice if the value is None or ends up
 
3111
            # being None during expansion or conversion.
 
3112
            if val is not None:
 
3113
                if expand:
 
3114
                    if isinstance(val, basestring):
 
3115
                        val = self._expand_options_in_string(val)
 
3116
                    else:
 
3117
                        trace.warning('Cannot expand "%s":'
 
3118
                                      ' %s does not support option expansion'
 
3119
                                      % (name, type(val)))
 
3120
                if opt is not None:
 
3121
                    val = opt.convert_from_unicode(val)
 
3122
            return val
 
3123
        value = expand_and_convert(value)
 
3124
        if opt is not None and value is None:
 
3125
            # If the option is registered, it may provide a default value
 
3126
            value = opt.get_default()
 
3127
            value = expand_and_convert(value)
 
3128
        for hook in ConfigHooks['get']:
 
3129
            hook(self, name, value)
 
3130
        return value
 
3131
 
 
3132
    def expand_options(self, string, env=None):
 
3133
        """Expand option references in the string in the configuration context.
 
3134
 
 
3135
        :param string: The string containing option(s) to expand.
 
3136
 
 
3137
        :param env: An option dict defining additional configuration options or
 
3138
            overriding existing ones.
 
3139
 
 
3140
        :returns: The expanded string.
 
3141
        """
 
3142
        return self._expand_options_in_string(string, env)
 
3143
 
 
3144
    def _expand_options_in_string(self, string, env=None, _refs=None):
 
3145
        """Expand options in the string in the configuration context.
 
3146
 
 
3147
        :param string: The string to be expanded.
 
3148
 
 
3149
        :param env: An option dict defining additional configuration options or
 
3150
            overriding existing ones.
 
3151
 
 
3152
        :param _refs: Private list (FIFO) containing the options being expanded
 
3153
            to detect loops.
 
3154
 
 
3155
        :returns: The expanded string.
 
3156
        """
 
3157
        if string is None:
 
3158
            # Not much to expand there
 
3159
            return None
 
3160
        if _refs is None:
 
3161
            # What references are currently resolved (to detect loops)
 
3162
            _refs = []
 
3163
        result = string
 
3164
        # We need to iterate until no more refs appear ({{foo}} will need two
 
3165
        # iterations for example).
 
3166
        while True:
 
3167
            raw_chunks = Stack._option_ref_re.split(result)
 
3168
            if len(raw_chunks) == 1:
 
3169
                # Shorcut the trivial case: no refs
 
3170
                return result
 
3171
            chunks = []
 
3172
            # Split will isolate refs so that every other chunk is a ref
 
3173
            chunk_is_ref = False
 
3174
            for chunk in raw_chunks:
 
3175
                if not chunk_is_ref:
 
3176
                    chunks.append(chunk)
 
3177
                    chunk_is_ref = True
 
3178
                else:
 
3179
                    name = chunk[1:-1]
 
3180
                    if name in _refs:
 
3181
                        raise errors.OptionExpansionLoop(string, _refs)
 
3182
                    _refs.append(name)
 
3183
                    value = self._expand_option(name, env, _refs)
 
3184
                    if value is None:
 
3185
                        raise errors.ExpandingUnknownOption(name, string)
 
3186
                    chunks.append(value)
 
3187
                    _refs.pop()
 
3188
                    chunk_is_ref = False
 
3189
            result = ''.join(chunks)
 
3190
        return result
 
3191
 
 
3192
    def _expand_option(self, name, env, _refs):
 
3193
        if env is not None and name in env:
 
3194
            # Special case, values provided in env takes precedence over
 
3195
            # anything else
 
3196
            value = env[name]
 
3197
        else:
 
3198
            # FIXME: This is a limited implementation, what we really need is a
 
3199
            # way to query the bzr config for the value of an option,
 
3200
            # respecting the scope rules (That is, once we implement fallback
 
3201
            # configs, getting the option value should restart from the top
 
3202
            # config, not the current one) -- vila 20101222
 
3203
            value = self.get(name, expand=False)
 
3204
            value = self._expand_options_in_string(value, env, _refs)
 
3205
        return value
2494
3206
 
2495
3207
    def _get_mutable_section(self):
2496
3208
        """Get the MutableSection for the Stack.
2498
3210
        This is where we guarantee that the mutable section is lazily loaded:
2499
3211
        this means we won't load the corresponding store before setting a value
2500
3212
        or deleting an option. In practice the store will often be loaded but
2501
 
        this allows catching some programming errors.
 
3213
        this allows helps catching some programming errors.
2502
3214
        """
2503
3215
        section = self.store.get_mutable_section(self.mutable_section_name)
2504
3216
        return section
2507
3219
        """Set a new value for the option."""
2508
3220
        section = self._get_mutable_section()
2509
3221
        section.set(name, value)
 
3222
        for hook in ConfigHooks['set']:
 
3223
            hook(self, name, value)
2510
3224
 
2511
3225
    def remove(self, name):
2512
3226
        """Remove an existing option."""
2513
3227
        section = self._get_mutable_section()
2514
3228
        section.remove(name)
 
3229
        for hook in ConfigHooks['remove']:
 
3230
            hook(self, name)
2515
3231
 
2516
3232
    def __repr__(self):
2517
3233
        # Mostly for debugging use
2518
3234
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2519
3235
 
2520
3236
 
 
3237
class _CompatibleStack(Stack):
 
3238
    """Place holder for compatibility with previous design.
 
3239
 
 
3240
    This is intended to ease the transition from the Config-based design to the
 
3241
    Stack-based design and should not be used nor relied upon by plugins.
 
3242
 
 
3243
    One assumption made here is that the daughter classes will all use Stores
 
3244
    derived from LockableIniFileStore).
 
3245
 
 
3246
    It implements set() by re-loading the store before applying the
 
3247
    modification and saving it.
 
3248
 
 
3249
    The long term plan being to implement a single write by store to save
 
3250
    all modifications, this class should not be used in the interim.
 
3251
    """
 
3252
 
 
3253
    def set(self, name, value):
 
3254
        # Force a reload
 
3255
        self.store.unload()
 
3256
        super(_CompatibleStack, self).set(name, value)
 
3257
        # Force a write to persistent storage
 
3258
        self.store.save()
 
3259
 
 
3260
 
 
3261
class GlobalStack(_CompatibleStack):
 
3262
    """Global options only stack."""
 
3263
 
 
3264
    def __init__(self):
 
3265
        # Get a GlobalStore
 
3266
        gstore = GlobalStore()
 
3267
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
 
3268
 
 
3269
 
 
3270
class LocationStack(_CompatibleStack):
 
3271
    """Per-location options falling back to global options stack."""
 
3272
 
 
3273
    def __init__(self, location):
 
3274
        """Make a new stack for a location and global configuration.
 
3275
        
 
3276
        :param location: A URL prefix to """
 
3277
        lstore = LocationStore()
 
3278
        matcher = LocationMatcher(lstore, location)
 
3279
        gstore = GlobalStore()
 
3280
        super(LocationStack, self).__init__(
 
3281
            [matcher.get_sections, gstore.get_sections], lstore)
 
3282
 
 
3283
 
 
3284
class BranchStack(_CompatibleStack):
 
3285
    """Per-location options falling back to branch then global options stack."""
 
3286
 
 
3287
    def __init__(self, branch):
 
3288
        bstore = BranchStore(branch)
 
3289
        lstore = LocationStore()
 
3290
        matcher = LocationMatcher(lstore, branch.base)
 
3291
        gstore = GlobalStore()
 
3292
        super(BranchStack, self).__init__(
 
3293
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
 
3294
            bstore)
 
3295
        self.branch = branch
 
3296
 
 
3297
 
 
3298
class RemoteControlStack(_CompatibleStack):
 
3299
    """Remote control-only options stack."""
 
3300
 
 
3301
    def __init__(self, bzrdir):
 
3302
        cstore = ControlStore(bzrdir)
 
3303
        super(RemoteControlStack, self).__init__(
 
3304
            [cstore.get_sections],
 
3305
            cstore)
 
3306
        self.bzrdir = bzrdir
 
3307
 
 
3308
 
 
3309
class RemoteBranchStack(_CompatibleStack):
 
3310
    """Remote branch-only options stack."""
 
3311
 
 
3312
    def __init__(self, branch):
 
3313
        bstore = BranchStore(branch)
 
3314
        super(RemoteBranchStack, self).__init__(
 
3315
            [bstore.get_sections],
 
3316
            bstore)
 
3317
        self.branch = branch
 
3318
 
 
3319
 
2521
3320
class cmd_config(commands.Command):
2522
3321
    __doc__ = """Display, set or remove a configuration option.
2523
3322
 
2550
3349
                        ' the configuration file'),
2551
3350
        ]
2552
3351
 
 
3352
    _see_also = ['configuration']
 
3353
 
2553
3354
    @commands.display_command
2554
3355
    def run(self, name=None, all=False, directory=None, scope=None,
2555
3356
            remove=False):
2629
3430
            raise errors.NoSuchConfigOption(name)
2630
3431
 
2631
3432
    def _show_matching_options(self, name, directory, scope):
2632
 
        name = re.compile(name)
 
3433
        name = lazy_regex.lazy_compile(name)
2633
3434
        # We want any error in the regexp to be raised *now* so we need to
2634
 
        # avoid the delay introduced by the lazy regexp.
 
3435
        # avoid the delay introduced by the lazy regexp.  But, we still do
 
3436
        # want the nicer errors raised by lazy_regex.
2635
3437
        name._compile_and_collapse()
2636
3438
        cur_conf_id = None
2637
3439
        cur_section = None
2681
3483
            raise errors.NoSuchConfig(scope)
2682
3484
        if not removed:
2683
3485
            raise errors.NoSuchConfigOption(name)
 
3486
 
 
3487
# Test registries
 
3488
#
 
3489
# We need adapters that can build a Store or a Stack in a test context. Test
 
3490
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
3491
# themselves. The builder will receive a test instance and should return a
 
3492
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
3493
# register themselves here to be tested against the tests defined in
 
3494
# bzrlib.tests.test_config. Note that the builder can be called multiple times
 
3495
# for the same tests.
 
3496
 
 
3497
# The registered object should be a callable receiving a test instance
 
3498
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
3499
# object.
 
3500
test_store_builder_registry = registry.Registry()
 
3501
 
 
3502
# The registered object should be a callable receiving a test instance
 
3503
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
3504
# object.
 
3505
test_stack_builder_registry = registry.Registry()