~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Vincent Ladeuil
  • Date: 2011-10-03 14:34:45 UTC
  • mto: This revision was merged to the branch mainline in revision 6185.
  • Revision ID: v.ladeuil+lp@free.fr-20111003143445-s382csvk1613x0sp
Remove the warning.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#            and others
4
4
#
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
 
63
73
"""
64
74
 
65
75
import os
 
76
import string
66
77
import sys
67
78
 
 
79
 
 
80
import bzrlib
68
81
from bzrlib.decorators import needs_write_lock
69
82
from bzrlib.lazy_import import lazy_import
70
83
lazy_import(globals(), """
71
 
import errno
72
 
from fnmatch import fnmatch
 
84
import fnmatch
73
85
import re
74
86
from cStringIO import StringIO
75
87
 
76
 
import bzrlib
77
88
from bzrlib import (
78
89
    atomicfile,
 
90
    bzrdir,
79
91
    debug,
80
92
    errors,
 
93
    lazy_regex,
 
94
    library_state,
81
95
    lockdir,
82
96
    mail_client,
 
97
    mergetools,
83
98
    osutils,
84
 
    registry,
85
99
    symbol_versioning,
86
100
    trace,
87
101
    transport,
89
103
    urlutils,
90
104
    win32utils,
91
105
    )
 
106
from bzrlib.i18n import gettext
92
107
from bzrlib.util.configobj import configobj
93
108
""")
 
109
from bzrlib import (
 
110
    commands,
 
111
    hooks,
 
112
    lazy_regex,
 
113
    registry,
 
114
    )
 
115
from bzrlib.symbol_versioning import (
 
116
    deprecated_in,
 
117
    deprecated_method,
 
118
    )
94
119
 
95
120
 
96
121
CHECK_IF_POSSIBLE=0
126
151
STORE_BRANCH = 3
127
152
STORE_GLOBAL = 4
128
153
 
129
 
_ConfigObj = None
130
 
def ConfigObj(*args, **kwargs):
131
 
    global _ConfigObj
132
 
    if _ConfigObj is None:
133
 
        class ConfigObj(configobj.ConfigObj):
134
 
 
135
 
            def get_bool(self, section, key):
136
 
                return self[section].as_bool(key)
137
 
 
138
 
            def get_value(self, section, name):
139
 
                # Try [] for the old DEFAULT section.
140
 
                if section == "DEFAULT":
141
 
                    try:
142
 
                        return self[name]
143
 
                    except KeyError:
144
 
                        pass
145
 
                return self[section][name]
146
 
        _ConfigObj = ConfigObj
147
 
    return _ConfigObj(*args, **kwargs)
 
154
 
 
155
class ConfigObj(configobj.ConfigObj):
 
156
 
 
157
    def __init__(self, infile=None, **kwargs):
 
158
        # We define our own interpolation mechanism calling it option expansion
 
159
        super(ConfigObj, self).__init__(infile=infile,
 
160
                                        interpolation=False,
 
161
                                        **kwargs)
 
162
 
 
163
    def get_bool(self, section, key):
 
164
        return self[section].as_bool(key)
 
165
 
 
166
    def get_value(self, section, name):
 
167
        # Try [] for the old DEFAULT section.
 
168
        if section == "DEFAULT":
 
169
            try:
 
170
                return self[name]
 
171
            except KeyError:
 
172
                pass
 
173
        return self[section][name]
 
174
 
 
175
 
 
176
# FIXME: Until we can guarantee that each config file is loaded once and
 
177
# only once for a given bzrlib session, we don't want to re-read the file every
 
178
# time we query for an option so we cache the value (bad ! watch out for tests
 
179
# needing to restore the proper value). -- vila 20110219
 
180
_expand_default_value = None
 
181
def _get_expand_default_value():
 
182
    global _expand_default_value
 
183
    if _expand_default_value is not None:
 
184
        return _expand_default_value
 
185
    conf = GlobalConfig()
 
186
    # Note that we must not use None for the expand value below or we'll run
 
187
    # into infinite recursion. Using False really would be quite silly ;)
 
188
    expand = conf.get_user_option_as_bool('bzr.config.expand', expand=True)
 
189
    if expand is None:
 
190
        # This is an opt-in feature, you *really* need to clearly say you want
 
191
        # to activate it !
 
192
        expand = False
 
193
    _expand_default_value = expand
 
194
    return expand
148
195
 
149
196
 
150
197
class Config(object):
153
200
    def __init__(self):
154
201
        super(Config, self).__init__()
155
202
 
 
203
    def config_id(self):
 
204
        """Returns a unique ID for the config."""
 
205
        raise NotImplementedError(self.config_id)
 
206
 
 
207
    @deprecated_method(deprecated_in((2, 4, 0)))
156
208
    def get_editor(self):
157
209
        """Get the users pop up editor."""
158
210
        raise NotImplementedError
165
217
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
166
218
                                             sys.stdout)
167
219
 
168
 
 
169
220
    def get_mail_client(self):
170
221
        """Get a mail client to use"""
171
222
        selected_client = self.get_user_option('mail_client')
182
233
    def _get_signing_policy(self):
183
234
        """Template method to override signature creation policy."""
184
235
 
 
236
    option_ref_re = None
 
237
 
 
238
    def expand_options(self, string, env=None):
 
239
        """Expand option references in the string in the configuration context.
 
240
 
 
241
        :param string: The string containing option to expand.
 
242
 
 
243
        :param env: An option dict defining additional configuration options or
 
244
            overriding existing ones.
 
245
 
 
246
        :returns: The expanded string.
 
247
        """
 
248
        return self._expand_options_in_string(string, env)
 
249
 
 
250
    def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
 
251
        """Expand options in  a list of strings in the configuration context.
 
252
 
 
253
        :param slist: A list of strings.
 
254
 
 
255
        :param env: An option dict defining additional configuration options or
 
256
            overriding existing ones.
 
257
 
 
258
        :param _ref_stack: Private list containing the options being
 
259
            expanded to detect loops.
 
260
 
 
261
        :returns: The flatten list of expanded strings.
 
262
        """
 
263
        # expand options in each value separately flattening lists
 
264
        result = []
 
265
        for s in slist:
 
266
            value = self._expand_options_in_string(s, env, _ref_stack)
 
267
            if isinstance(value, list):
 
268
                result.extend(value)
 
269
            else:
 
270
                result.append(value)
 
271
        return result
 
272
 
 
273
    def _expand_options_in_string(self, string, env=None, _ref_stack=None):
 
274
        """Expand options in the string in the configuration context.
 
275
 
 
276
        :param string: The string to be expanded.
 
277
 
 
278
        :param env: An option dict defining additional configuration options or
 
279
            overriding existing ones.
 
280
 
 
281
        :param _ref_stack: Private list containing the options being
 
282
            expanded to detect loops.
 
283
 
 
284
        :returns: The expanded string.
 
285
        """
 
286
        if string is None:
 
287
            # Not much to expand there
 
288
            return None
 
289
        if _ref_stack is None:
 
290
            # What references are currently resolved (to detect loops)
 
291
            _ref_stack = []
 
292
        if self.option_ref_re is None:
 
293
            # We want to match the most embedded reference first (i.e. for
 
294
            # '{{foo}}' we will get '{foo}',
 
295
            # for '{bar{baz}}' we will get '{baz}'
 
296
            self.option_ref_re = re.compile('({[^{}]+})')
 
297
        result = string
 
298
        # We need to iterate until no more refs appear ({{foo}} will need two
 
299
        # iterations for example).
 
300
        while True:
 
301
            raw_chunks = self.option_ref_re.split(result)
 
302
            if len(raw_chunks) == 1:
 
303
                # Shorcut the trivial case: no refs
 
304
                return result
 
305
            chunks = []
 
306
            list_value = False
 
307
            # Split will isolate refs so that every other chunk is a ref
 
308
            chunk_is_ref = False
 
309
            for chunk in raw_chunks:
 
310
                if not chunk_is_ref:
 
311
                    if chunk:
 
312
                        # Keep only non-empty strings (or we get bogus empty
 
313
                        # slots when a list value is involved).
 
314
                        chunks.append(chunk)
 
315
                    chunk_is_ref = True
 
316
                else:
 
317
                    name = chunk[1:-1]
 
318
                    if name in _ref_stack:
 
319
                        raise errors.OptionExpansionLoop(string, _ref_stack)
 
320
                    _ref_stack.append(name)
 
321
                    value = self._expand_option(name, env, _ref_stack)
 
322
                    if value is None:
 
323
                        raise errors.ExpandingUnknownOption(name, string)
 
324
                    if isinstance(value, list):
 
325
                        list_value = True
 
326
                        chunks.extend(value)
 
327
                    else:
 
328
                        chunks.append(value)
 
329
                    _ref_stack.pop()
 
330
                    chunk_is_ref = False
 
331
            if list_value:
 
332
                # Once a list appears as the result of an expansion, all
 
333
                # callers will get a list result. This allows a consistent
 
334
                # behavior even when some options in the expansion chain
 
335
                # defined as strings (no comma in their value) but their
 
336
                # expanded value is a list.
 
337
                return self._expand_options_in_list(chunks, env, _ref_stack)
 
338
            else:
 
339
                result = ''.join(chunks)
 
340
        return result
 
341
 
 
342
    def _expand_option(self, name, env, _ref_stack):
 
343
        if env is not None and name in env:
 
344
            # Special case, values provided in env takes precedence over
 
345
            # anything else
 
346
            value = env[name]
 
347
        else:
 
348
            # FIXME: This is a limited implementation, what we really need is a
 
349
            # way to query the bzr config for the value of an option,
 
350
            # respecting the scope rules (That is, once we implement fallback
 
351
            # configs, getting the option value should restart from the top
 
352
            # config, not the current one) -- vila 20101222
 
353
            value = self.get_user_option(name, expand=False)
 
354
            if isinstance(value, list):
 
355
                value = self._expand_options_in_list(value, env, _ref_stack)
 
356
            else:
 
357
                value = self._expand_options_in_string(value, env, _ref_stack)
 
358
        return value
 
359
 
185
360
    def _get_user_option(self, option_name):
186
361
        """Template method to provide a user option."""
187
362
        return None
188
363
 
189
 
    def get_user_option(self, option_name):
190
 
        """Get a generic option - no special process, no default."""
191
 
        return self._get_user_option(option_name)
192
 
 
193
 
    def get_user_option_as_bool(self, option_name):
194
 
        """Get a generic option as a boolean - no special process, no default.
195
 
 
 
364
    def get_user_option(self, option_name, expand=None):
 
365
        """Get a generic option - no special process, no default.
 
366
 
 
367
        :param option_name: The queried option.
 
368
 
 
369
        :param expand: Whether options references should be expanded.
 
370
 
 
371
        :returns: The value of the option.
 
372
        """
 
373
        if expand is None:
 
374
            expand = _get_expand_default_value()
 
375
        value = self._get_user_option(option_name)
 
376
        if expand:
 
377
            if isinstance(value, list):
 
378
                value = self._expand_options_in_list(value)
 
379
            elif isinstance(value, dict):
 
380
                trace.warning('Cannot expand "%s":'
 
381
                              ' Dicts do not support option expansion'
 
382
                              % (option_name,))
 
383
            else:
 
384
                value = self._expand_options_in_string(value)
 
385
        for hook in OldConfigHooks['get']:
 
386
            hook(self, option_name, value)
 
387
        return value
 
388
 
 
389
    def get_user_option_as_bool(self, option_name, expand=None, default=None):
 
390
        """Get a generic option as a boolean.
 
391
 
 
392
        :param expand: Allow expanding references to other config values.
 
393
        :param default: Default value if nothing is configured
196
394
        :return None if the option doesn't exist or its value can't be
197
395
            interpreted as a boolean. Returns True or False otherwise.
198
396
        """
199
 
        s = self._get_user_option(option_name)
 
397
        s = self.get_user_option(option_name, expand=expand)
200
398
        if s is None:
201
399
            # The option doesn't exist
202
 
            return None
 
400
            return default
203
401
        val = ui.bool_from_string(s)
204
402
        if val is None:
205
403
            # The value can't be interpreted as a boolean
207
405
                          s, option_name)
208
406
        return val
209
407
 
210
 
    def get_user_option_as_list(self, option_name):
 
408
    def get_user_option_as_list(self, option_name, expand=None):
211
409
        """Get a generic option as a list - no special process, no default.
212
410
 
213
411
        :return None if the option doesn't exist. Returns the value as a list
214
412
            otherwise.
215
413
        """
216
 
        l = self._get_user_option(option_name)
 
414
        l = self.get_user_option(option_name, expand=expand)
217
415
        if isinstance(l, (str, unicode)):
218
 
            # A single value, most probably the user forgot the final ','
 
416
            # A single value, most probably the user forgot (or didn't care to
 
417
            # add) the final ','
219
418
            l = [l]
220
419
        return l
 
420
        
 
421
    def get_user_option_as_int_from_SI(self,  option_name,  default=None):
 
422
        """Get a generic option from a human readable size in SI units, e.g 10MB
 
423
        
 
424
        Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
425
        by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
426
        pedantic.
 
427
        
 
428
        :return Integer, expanded to its base-10 value if a proper SI unit is 
 
429
            found. If the option doesn't exist, or isn't a value in 
 
430
            SI units, return default (which defaults to None)
 
431
        """
 
432
        val = self.get_user_option(option_name)
 
433
        if isinstance(val, list):
 
434
            val = val[0]
 
435
        if val is None:
 
436
            val = default
 
437
        else:
 
438
            p = re.compile("^(\d+)([kmg])*b*$", re.IGNORECASE)
 
439
            try:
 
440
                m = p.match(val)
 
441
                if m is not None:
 
442
                    val = int(m.group(1))
 
443
                    if m.group(2) is not None:
 
444
                        if m.group(2).lower() == 'k':
 
445
                            val *= 10**3
 
446
                        elif m.group(2).lower() == 'm':
 
447
                            val *= 10**6
 
448
                        elif m.group(2).lower() == 'g':
 
449
                            val *= 10**9
 
450
                else:
 
451
                    ui.ui_factory.show_warning(gettext('Invalid config value for "{0}" '
 
452
                                               ' value {1!r} is not an SI unit.').format(
 
453
                                                option_name, val))
 
454
                    val = default
 
455
            except TypeError:
 
456
                val = default
 
457
        return val
 
458
        
221
459
 
222
460
    def gpg_signing_command(self):
223
461
        """What program should be used to sign signatures?"""
241
479
        """See log_format()."""
242
480
        return None
243
481
 
 
482
    def validate_signatures_in_log(self):
 
483
        """Show GPG signature validity in log"""
 
484
        result = self._validate_signatures_in_log()
 
485
        if result == "true":
 
486
            result = True
 
487
        else:
 
488
            result = False
 
489
        return result
 
490
 
 
491
    def _validate_signatures_in_log(self):
 
492
        """See validate_signatures_in_log()."""
 
493
        return None
 
494
 
 
495
    def acceptable_keys(self):
 
496
        """Comma separated list of key patterns acceptable to 
 
497
        verify-signatures command"""
 
498
        result = self._acceptable_keys()
 
499
        return result
 
500
 
 
501
    def _acceptable_keys(self):
 
502
        """See acceptable_keys()."""
 
503
        return None
 
504
 
244
505
    def post_commit(self):
245
506
        """An ordered list of python functions to call.
246
507
 
265
526
        the concrete policy type is checked, and finally
266
527
        $EMAIL is examined.
267
528
        If no username can be found, errors.NoWhoami exception is raised.
268
 
 
269
 
        TODO: Check it's reasonably well-formed.
270
529
        """
271
530
        v = os.environ.get('BZR_EMAIL')
272
531
        if v:
273
532
            return v.decode(osutils.get_user_encoding())
274
 
 
275
533
        v = self._get_user_id()
276
534
        if v:
277
535
            return v
278
 
 
279
536
        v = os.environ.get('EMAIL')
280
537
        if v:
281
538
            return v.decode(osutils.get_user_encoding())
282
 
 
 
539
        name, email = _auto_user_id()
 
540
        if name and email:
 
541
            return '%s <%s>' % (name, email)
 
542
        elif email:
 
543
            return email
283
544
        raise errors.NoWhoami()
284
545
 
285
546
    def ensure_username(self):
309
570
        if policy is None:
310
571
            policy = self._get_signature_checking()
311
572
            if policy is not None:
 
573
                #this warning should go away once check_signatures is
 
574
                #implemented (if not before)
312
575
                trace.warning("Please use create_signatures,"
313
576
                              " not check_signatures to set signing policy.")
314
 
            if policy == CHECK_ALWAYS:
315
 
                return True
316
577
        elif policy == SIGN_ALWAYS:
317
578
            return True
318
579
        return False
319
580
 
 
581
    def gpg_signing_key(self):
 
582
        """GPG user-id to sign commits"""
 
583
        key = self.get_user_option('gpg_signing_key')
 
584
        if key == "default" or key == None:
 
585
            return self.user_email()
 
586
        else:
 
587
            return key
 
588
 
320
589
    def get_alias(self, value):
321
590
        return self._get_alias(value)
322
591
 
351
620
        else:
352
621
            return True
353
622
 
 
623
    def get_merge_tools(self):
 
624
        tools = {}
 
625
        for (oname, value, section, conf_id, parser) in self._get_options():
 
626
            if oname.startswith('bzr.mergetool.'):
 
627
                tool_name = oname[len('bzr.mergetool.'):]
 
628
                tools[tool_name] = self.get_user_option(oname)
 
629
        trace.mutter('loaded merge tools: %r' % tools)
 
630
        return tools
 
631
 
 
632
    def find_merge_tool(self, name):
 
633
        # We fake a defaults mechanism here by checking if the given name can
 
634
        # be found in the known_merge_tools if it's not found in the config.
 
635
        # This should be done through the proposed config defaults mechanism
 
636
        # when it becomes available in the future.
 
637
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
 
638
                                             expand=False)
 
639
                        or mergetools.known_merge_tools.get(name, None))
 
640
        return command_line
 
641
 
 
642
 
 
643
class _ConfigHooks(hooks.Hooks):
 
644
    """A dict mapping hook names and a list of callables for configs.
 
645
    """
 
646
 
 
647
    def __init__(self):
 
648
        """Create the default hooks.
 
649
 
 
650
        These are all empty initially, because by default nothing should get
 
651
        notified.
 
652
        """
 
653
        super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
 
654
        self.add_hook('load',
 
655
                      'Invoked when a config store is loaded.'
 
656
                      ' The signature is (store).',
 
657
                      (2, 4))
 
658
        self.add_hook('save',
 
659
                      'Invoked when a config store is saved.'
 
660
                      ' The signature is (store).',
 
661
                      (2, 4))
 
662
        # The hooks for config options
 
663
        self.add_hook('get',
 
664
                      'Invoked when a config option is read.'
 
665
                      ' The signature is (stack, name, value).',
 
666
                      (2, 4))
 
667
        self.add_hook('set',
 
668
                      'Invoked when a config option is set.'
 
669
                      ' The signature is (stack, name, value).',
 
670
                      (2, 4))
 
671
        self.add_hook('remove',
 
672
                      'Invoked when a config option is removed.'
 
673
                      ' The signature is (stack, name).',
 
674
                      (2, 4))
 
675
ConfigHooks = _ConfigHooks()
 
676
 
 
677
 
 
678
class _OldConfigHooks(hooks.Hooks):
 
679
    """A dict mapping hook names and a list of callables for configs.
 
680
    """
 
681
 
 
682
    def __init__(self):
 
683
        """Create the default hooks.
 
684
 
 
685
        These are all empty initially, because by default nothing should get
 
686
        notified.
 
687
        """
 
688
        super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
 
689
        self.add_hook('load',
 
690
                      'Invoked when a config store is loaded.'
 
691
                      ' The signature is (config).',
 
692
                      (2, 4))
 
693
        self.add_hook('save',
 
694
                      'Invoked when a config store is saved.'
 
695
                      ' The signature is (config).',
 
696
                      (2, 4))
 
697
        # The hooks for config options
 
698
        self.add_hook('get',
 
699
                      'Invoked when a config option is read.'
 
700
                      ' The signature is (config, name, value).',
 
701
                      (2, 4))
 
702
        self.add_hook('set',
 
703
                      'Invoked when a config option is set.'
 
704
                      ' The signature is (config, name, value).',
 
705
                      (2, 4))
 
706
        self.add_hook('remove',
 
707
                      'Invoked when a config option is removed.'
 
708
                      ' The signature is (config, name).',
 
709
                      (2, 4))
 
710
OldConfigHooks = _OldConfigHooks()
 
711
 
354
712
 
355
713
class IniBasedConfig(Config):
356
714
    """A configuration policy that draws from ini files."""
417
775
            self._parser = ConfigObj(co_input, encoding='utf-8')
418
776
        except configobj.ConfigObjError, e:
419
777
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
778
        except UnicodeDecodeError:
 
779
            raise errors.ConfigContentError(self.file_name)
420
780
        # Make sure self.reload() will use the right file name
421
781
        self._parser.filename = self.file_name
 
782
        for hook in OldConfigHooks['load']:
 
783
            hook(self)
422
784
        return self._parser
423
785
 
424
786
    def reload(self):
427
789
            raise AssertionError('We need a file name to reload the config')
428
790
        if self._parser is not None:
429
791
            self._parser.reload()
 
792
        for hook in ConfigHooks['load']:
 
793
            hook(self)
430
794
 
431
795
    def _get_matching_sections(self):
432
796
        """Return an ordered list of (section_name, extra_path) pairs.
444
808
        """Override this to define the section used by the config."""
445
809
        return "DEFAULT"
446
810
 
 
811
    def _get_sections(self, name=None):
 
812
        """Returns an iterator of the sections specified by ``name``.
 
813
 
 
814
        :param name: The section name. If None is supplied, the default
 
815
            configurations are yielded.
 
816
 
 
817
        :return: A tuple (name, section, config_id) for all sections that will
 
818
            be walked by user_get_option() in the 'right' order. The first one
 
819
            is where set_user_option() will update the value.
 
820
        """
 
821
        parser = self._get_parser()
 
822
        if name is not None:
 
823
            yield (name, parser[name], self.config_id())
 
824
        else:
 
825
            # No section name has been given so we fallback to the configobj
 
826
            # itself which holds the variables defined outside of any section.
 
827
            yield (None, parser, self.config_id())
 
828
 
 
829
    def _get_options(self, sections=None):
 
830
        """Return an ordered list of (name, value, section, config_id) tuples.
 
831
 
 
832
        All options are returned with their associated value and the section
 
833
        they appeared in. ``config_id`` is a unique identifier for the
 
834
        configuration file the option is defined in.
 
835
 
 
836
        :param sections: Default to ``_get_matching_sections`` if not
 
837
            specified. This gives a better control to daughter classes about
 
838
            which sections should be searched. This is a list of (name,
 
839
            configobj) tuples.
 
840
        """
 
841
        opts = []
 
842
        if sections is None:
 
843
            parser = self._get_parser()
 
844
            sections = []
 
845
            for (section_name, _) in self._get_matching_sections():
 
846
                try:
 
847
                    section = parser[section_name]
 
848
                except KeyError:
 
849
                    # This could happen for an empty file for which we define a
 
850
                    # DEFAULT section. FIXME: Force callers to provide sections
 
851
                    # instead ? -- vila 20100930
 
852
                    continue
 
853
                sections.append((section_name, section))
 
854
        config_id = self.config_id()
 
855
        for (section_name, section) in sections:
 
856
            for (name, value) in section.iteritems():
 
857
                yield (name, parser._quote(value), section_name,
 
858
                       config_id, parser)
 
859
 
447
860
    def _get_option_policy(self, section, option_name):
448
861
        """Return the policy for the given (section, option_name) pair."""
449
862
        return POLICY_NONE
500
913
        """See Config.log_format."""
501
914
        return self._get_user_option('log_format')
502
915
 
 
916
    def _validate_signatures_in_log(self):
 
917
        """See Config.validate_signatures_in_log."""
 
918
        return self._get_user_option('validate_signatures_in_log')
 
919
 
 
920
    def _acceptable_keys(self):
 
921
        """See Config.acceptable_keys."""
 
922
        return self._get_user_option('acceptable_keys')
 
923
 
503
924
    def _post_commit(self):
504
925
        """See Config.post_commit."""
505
926
        return self._get_user_option('post_commit')
536
957
    def _get_nickname(self):
537
958
        return self.get_user_option('nickname')
538
959
 
 
960
    def remove_user_option(self, option_name, section_name=None):
 
961
        """Remove a user option and save the configuration file.
 
962
 
 
963
        :param option_name: The option to be removed.
 
964
 
 
965
        :param section_name: The section the option is defined in, default to
 
966
            the default section.
 
967
        """
 
968
        self.reload()
 
969
        parser = self._get_parser()
 
970
        if section_name is None:
 
971
            section = parser
 
972
        else:
 
973
            section = parser[section_name]
 
974
        try:
 
975
            del section[option_name]
 
976
        except KeyError:
 
977
            raise errors.NoSuchConfigOption(option_name)
 
978
        self._write_config_file()
 
979
        for hook in OldConfigHooks['remove']:
 
980
            hook(self, option_name)
 
981
 
539
982
    def _write_config_file(self):
540
983
        if self.file_name is None:
541
984
            raise AssertionError('We cannot save, self.file_name is None')
546
989
        atomic_file.commit()
547
990
        atomic_file.close()
548
991
        osutils.copy_ownership_from_path(self.file_name)
 
992
        for hook in OldConfigHooks['save']:
 
993
            hook(self)
549
994
 
550
995
 
551
996
class LockableConfig(IniBasedConfig):
578
1023
    def __init__(self, file_name):
579
1024
        super(LockableConfig, self).__init__(file_name=file_name)
580
1025
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
581
 
        self.transport = transport.get_transport(self.dir)
582
 
        self._lock = lockdir.LockDir(self.transport, 'lock')
 
1026
        # FIXME: It doesn't matter that we don't provide possible_transports
 
1027
        # below since this is currently used only for local config files ;
 
1028
        # local transports are not shared. But if/when we start using
 
1029
        # LockableConfig for other kind of transports, we will need to reuse
 
1030
        # whatever connection is already established -- vila 20100929
 
1031
        self.transport = transport.get_transport_from_path(self.dir)
 
1032
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
583
1033
 
584
1034
    def _create_from_string(self, unicode_bytes, save):
585
1035
        super(LockableConfig, self)._create_from_string(unicode_bytes, False)
604
1054
    def break_lock(self):
605
1055
        self._lock.break_lock()
606
1056
 
 
1057
    @needs_write_lock
 
1058
    def remove_user_option(self, option_name, section_name=None):
 
1059
        super(LockableConfig, self).remove_user_option(option_name,
 
1060
                                                       section_name)
 
1061
 
607
1062
    def _write_config_file(self):
608
1063
        if self._lock is None or not self._lock.is_held:
609
1064
            # NB: if the following exception is raised it probably means a
618
1073
    def __init__(self):
619
1074
        super(GlobalConfig, self).__init__(file_name=config_filename())
620
1075
 
 
1076
    def config_id(self):
 
1077
        return 'bazaar'
 
1078
 
621
1079
    @classmethod
622
1080
    def from_string(cls, str_or_unicode, save=False):
623
1081
        """Create a config object from a string.
631
1089
        conf._create_from_string(str_or_unicode, save)
632
1090
        return conf
633
1091
 
 
1092
    @deprecated_method(deprecated_in((2, 4, 0)))
634
1093
    def get_editor(self):
635
1094
        return self._get_user_option('editor')
636
1095
 
665
1124
        self.reload()
666
1125
        self._get_parser().setdefault(section, {})[option] = value
667
1126
        self._write_config_file()
 
1127
        for hook in OldConfigHooks['set']:
 
1128
            hook(self, option, value)
 
1129
 
 
1130
    def _get_sections(self, name=None):
 
1131
        """See IniBasedConfig._get_sections()."""
 
1132
        parser = self._get_parser()
 
1133
        # We don't give access to options defined outside of any section, we
 
1134
        # used the DEFAULT section by... default.
 
1135
        if name in (None, 'DEFAULT'):
 
1136
            # This could happen for an empty file where the DEFAULT section
 
1137
            # doesn't exist yet. So we force DEFAULT when yielding
 
1138
            name = 'DEFAULT'
 
1139
            if 'DEFAULT' not in parser:
 
1140
               parser['DEFAULT']= {}
 
1141
        yield (name, parser[name], self.config_id())
 
1142
 
 
1143
    @needs_write_lock
 
1144
    def remove_user_option(self, option_name, section_name=None):
 
1145
        if section_name is None:
 
1146
            # We need to force the default section.
 
1147
            section_name = 'DEFAULT'
 
1148
        # We need to avoid the LockableConfig implementation or we'll lock
 
1149
        # twice
 
1150
        super(LockableConfig, self).remove_user_option(option_name,
 
1151
                                                       section_name)
 
1152
 
 
1153
def _iter_for_location_by_parts(sections, location):
 
1154
    """Keep only the sessions matching the specified location.
 
1155
 
 
1156
    :param sections: An iterable of section names.
 
1157
 
 
1158
    :param location: An url or a local path to match against.
 
1159
 
 
1160
    :returns: An iterator of (section, extra_path, nb_parts) where nb is the
 
1161
        number of path components in the section name, section is the section
 
1162
        name and extra_path is the difference between location and the section
 
1163
        name.
 
1164
 
 
1165
    ``location`` will always be a local path and never a 'file://' url but the
 
1166
    section names themselves can be in either form.
 
1167
    """
 
1168
    location_parts = location.rstrip('/').split('/')
 
1169
 
 
1170
    for section in sections:
 
1171
        # location is a local path if possible, so we need to convert 'file://'
 
1172
        # urls in section names to local paths if necessary.
 
1173
 
 
1174
        # This also avoids having file:///path be a more exact
 
1175
        # match than '/path'.
 
1176
 
 
1177
        # FIXME: This still raises an issue if a user defines both file:///path
 
1178
        # *and* /path. Should we raise an error in this case -- vila 20110505
 
1179
 
 
1180
        if section.startswith('file://'):
 
1181
            section_path = urlutils.local_path_from_url(section)
 
1182
        else:
 
1183
            section_path = section
 
1184
        section_parts = section_path.rstrip('/').split('/')
 
1185
 
 
1186
        matched = True
 
1187
        if len(section_parts) > len(location_parts):
 
1188
            # More path components in the section, they can't match
 
1189
            matched = False
 
1190
        else:
 
1191
            # Rely on zip truncating in length to the length of the shortest
 
1192
            # argument sequence.
 
1193
            names = zip(location_parts, section_parts)
 
1194
            for name in names:
 
1195
                if not fnmatch.fnmatch(name[0], name[1]):
 
1196
                    matched = False
 
1197
                    break
 
1198
        if not matched:
 
1199
            continue
 
1200
        # build the path difference between the section and the location
 
1201
        extra_path = '/'.join(location_parts[len(section_parts):])
 
1202
        yield section, extra_path, len(section_parts)
668
1203
 
669
1204
 
670
1205
class LocationConfig(LockableConfig):
680
1215
            location = urlutils.local_path_from_url(location)
681
1216
        self.location = location
682
1217
 
 
1218
    def config_id(self):
 
1219
        return 'locations'
 
1220
 
683
1221
    @classmethod
684
1222
    def from_string(cls, str_or_unicode, location, save=False):
685
1223
        """Create a config object from a string.
697
1235
 
698
1236
    def _get_matching_sections(self):
699
1237
        """Return an ordered list of section names matching this location."""
700
 
        sections = self._get_parser()
701
 
        location_names = self.location.split('/')
702
 
        if self.location.endswith('/'):
703
 
            del location_names[-1]
704
 
        matches=[]
705
 
        for section in sections:
706
 
            # location is a local path if possible, so we need
707
 
            # to convert 'file://' urls to local paths if necessary.
708
 
            # This also avoids having file:///path be a more exact
709
 
            # match than '/path'.
710
 
            if section.startswith('file://'):
711
 
                section_path = urlutils.local_path_from_url(section)
712
 
            else:
713
 
                section_path = section
714
 
            section_names = section_path.split('/')
715
 
            if section.endswith('/'):
716
 
                del section_names[-1]
717
 
            names = zip(location_names, section_names)
718
 
            matched = True
719
 
            for name in names:
720
 
                if not fnmatch(name[0], name[1]):
721
 
                    matched = False
722
 
                    break
723
 
            if not matched:
724
 
                continue
725
 
            # so, for the common prefix they matched.
726
 
            # if section is longer, no match.
727
 
            if len(section_names) > len(location_names):
728
 
                continue
729
 
            matches.append((len(section_names), section,
730
 
                            '/'.join(location_names[len(section_names):])))
731
 
        matches.sort(reverse=True)
732
 
        sections = []
733
 
        for (length, section, extra_path) in matches:
734
 
            sections.append((section, extra_path))
 
1238
        matches = list(_iter_for_location_by_parts(self._get_parser(),
 
1239
                                                   self.location))
 
1240
        # put the longest (aka more specific) locations first
 
1241
        matches.sort(
 
1242
            key=lambda (section, extra_path, length): (length, section),
 
1243
            reverse=True)
 
1244
        for (section, extra_path, length) in matches:
 
1245
            yield section, extra_path
735
1246
            # should we stop looking for parent configs here?
736
1247
            try:
737
1248
                if self._get_parser()[section].as_bool('ignore_parents'):
738
1249
                    break
739
1250
            except KeyError:
740
1251
                pass
741
 
        return sections
 
1252
 
 
1253
    def _get_sections(self, name=None):
 
1254
        """See IniBasedConfig._get_sections()."""
 
1255
        # We ignore the name here as the only sections handled are named with
 
1256
        # the location path and we don't expose embedded sections either.
 
1257
        parser = self._get_parser()
 
1258
        for name, extra_path in self._get_matching_sections():
 
1259
            yield (name, parser[name], self.config_id())
742
1260
 
743
1261
    def _get_option_policy(self, section, option_name):
744
1262
        """Return the policy for the given (section, option_name) pair."""
809
1327
        # the allowed values of store match the config policies
810
1328
        self._set_option_policy(location, option, store)
811
1329
        self._write_config_file()
 
1330
        for hook in OldConfigHooks['set']:
 
1331
            hook(self, option, value)
812
1332
 
813
1333
 
814
1334
class BranchConfig(Config):
824
1344
                               self._get_branch_data_config,
825
1345
                               self._get_global_config)
826
1346
 
 
1347
    def config_id(self):
 
1348
        return 'branch'
 
1349
 
827
1350
    def _get_branch_data_config(self):
828
1351
        if self._branch_data_config is None:
829
1352
            self._branch_data_config = TreeConfig(self.branch)
 
1353
            self._branch_data_config.config_id = self.config_id
830
1354
        return self._branch_data_config
831
1355
 
832
1356
    def _get_location_config(self):
876
1400
            return (self.branch._transport.get_bytes("email")
877
1401
                    .decode(osutils.get_user_encoding())
878
1402
                    .rstrip("\r\n"))
879
 
        except errors.NoSuchFile, e:
 
1403
        except (errors.NoSuchFile, errors.PermissionDenied), e:
880
1404
            pass
881
1405
 
882
1406
        return self._get_best_value('_get_user_id')
900
1424
                return value
901
1425
        return None
902
1426
 
 
1427
    def _get_sections(self, name=None):
 
1428
        """See IniBasedConfig.get_sections()."""
 
1429
        for source in self.option_sources:
 
1430
            for section in source()._get_sections(name):
 
1431
                yield section
 
1432
 
 
1433
    def _get_options(self, sections=None):
 
1434
        opts = []
 
1435
        # First the locations options
 
1436
        for option in self._get_location_config()._get_options():
 
1437
            yield option
 
1438
        # Then the branch options
 
1439
        branch_config = self._get_branch_data_config()
 
1440
        if sections is None:
 
1441
            sections = [('DEFAULT', branch_config._get_parser())]
 
1442
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
 
1443
        # Config itself has no notion of sections :( -- vila 20101001
 
1444
        config_id = self.config_id()
 
1445
        for (section_name, section) in sections:
 
1446
            for (name, value) in section.iteritems():
 
1447
                yield (name, value, section_name,
 
1448
                       config_id, branch_config._get_parser())
 
1449
        # Then the global options
 
1450
        for option in self._get_global_config()._get_options():
 
1451
            yield option
 
1452
 
903
1453
    def set_user_option(self, name, value, store=STORE_BRANCH,
904
1454
        warn_masked=False):
905
1455
        if store == STORE_BRANCH:
923
1473
                        trace.warning('Value "%s" is masked by "%s" from'
924
1474
                                      ' branch.conf', value, mask_value)
925
1475
 
 
1476
    def remove_user_option(self, option_name, section_name=None):
 
1477
        self._get_branch_data_config().remove_option(option_name, section_name)
 
1478
 
926
1479
    def _gpg_signing_command(self):
927
1480
        """See Config.gpg_signing_command."""
928
1481
        return self._get_safe_value('_gpg_signing_command')
948
1501
        """See Config.log_format."""
949
1502
        return self._get_best_value('_log_format')
950
1503
 
 
1504
    def _validate_signatures_in_log(self):
 
1505
        """See Config.validate_signatures_in_log."""
 
1506
        return self._get_best_value('_validate_signatures_in_log')
 
1507
 
 
1508
    def _acceptable_keys(self):
 
1509
        """See Config.acceptable_keys."""
 
1510
        return self._get_best_value('_acceptable_keys')
 
1511
 
951
1512
 
952
1513
def ensure_config_dir_exists(path=None):
953
1514
    """Make sure a configuration directory exists.
962
1523
            parent_dir = os.path.dirname(path)
963
1524
            if not os.path.isdir(parent_dir):
964
1525
                trace.mutter('creating config parent directory: %r', parent_dir)
965
 
            os.mkdir(parent_dir)
 
1526
                os.mkdir(parent_dir)
966
1527
        trace.mutter('creating config directory: %r', path)
967
1528
        os.mkdir(path)
968
1529
        osutils.copy_ownership_from_path(path)
971
1532
def config_dir():
972
1533
    """Return per-user configuration directory.
973
1534
 
974
 
    By default this is ~/.bazaar/
 
1535
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
 
1536
    and Linux.  On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
 
1537
    that will be used instead.
975
1538
 
976
1539
    TODO: Global option --config-dir to override this.
977
1540
    """
978
1541
    base = os.environ.get('BZR_HOME', None)
979
1542
    if sys.platform == 'win32':
 
1543
        # environ variables on Windows are in user encoding/mbcs. So decode
 
1544
        # before using one
 
1545
        if base is not None:
 
1546
            base = base.decode('mbcs')
980
1547
        if base is None:
981
1548
            base = win32utils.get_appdata_location_unicode()
982
1549
        if base is None:
983
1550
            base = os.environ.get('HOME', None)
 
1551
            if base is not None:
 
1552
                base = base.decode('mbcs')
984
1553
        if base is None:
985
1554
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
986
1555
                                  ' or HOME set')
987
1556
        return osutils.pathjoin(base, 'bazaar', '2.0')
988
1557
    else:
989
 
        if base is None:
 
1558
        if base is not None:
 
1559
            base = base.decode(osutils._fs_enc)
 
1560
    if sys.platform == 'darwin':
 
1561
        if base is None:
 
1562
            # this takes into account $HOME
 
1563
            base = os.path.expanduser("~")
 
1564
        return osutils.pathjoin(base, '.bazaar')
 
1565
    else:
 
1566
        if base is None:
 
1567
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
 
1568
            if xdg_dir is None:
 
1569
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
 
1570
            xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
 
1571
            if osutils.isdir(xdg_dir):
 
1572
                trace.mutter(
 
1573
                    "Using configuration in XDG directory %s." % xdg_dir)
 
1574
                return xdg_dir
990
1575
            base = os.path.expanduser("~")
991
1576
        return osutils.pathjoin(base, ".bazaar")
992
1577
 
1038
1623
        return os.path.expanduser('~/.cache')
1039
1624
 
1040
1625
 
 
1626
def _get_default_mail_domain():
 
1627
    """If possible, return the assumed default email domain.
 
1628
 
 
1629
    :returns: string mail domain, or None.
 
1630
    """
 
1631
    if sys.platform == 'win32':
 
1632
        # No implementation yet; patches welcome
 
1633
        return None
 
1634
    try:
 
1635
        f = open('/etc/mailname')
 
1636
    except (IOError, OSError), e:
 
1637
        return None
 
1638
    try:
 
1639
        domain = f.read().strip()
 
1640
        return domain
 
1641
    finally:
 
1642
        f.close()
 
1643
 
 
1644
 
 
1645
def _auto_user_id():
 
1646
    """Calculate automatic user identification.
 
1647
 
 
1648
    :returns: (realname, email), either of which may be None if they can't be
 
1649
    determined.
 
1650
 
 
1651
    Only used when none is set in the environment or the id file.
 
1652
 
 
1653
    This only returns an email address if we can be fairly sure the 
 
1654
    address is reasonable, ie if /etc/mailname is set on unix.
 
1655
 
 
1656
    This doesn't use the FQDN as the default domain because that may be 
 
1657
    slow, and it doesn't use the hostname alone because that's not normally 
 
1658
    a reasonable address.
 
1659
    """
 
1660
    if sys.platform == 'win32':
 
1661
        # No implementation to reliably determine Windows default mail
 
1662
        # address; please add one.
 
1663
        return None, None
 
1664
 
 
1665
    default_mail_domain = _get_default_mail_domain()
 
1666
    if not default_mail_domain:
 
1667
        return None, None
 
1668
 
 
1669
    import pwd
 
1670
    uid = os.getuid()
 
1671
    try:
 
1672
        w = pwd.getpwuid(uid)
 
1673
    except KeyError:
 
1674
        trace.mutter('no passwd entry for uid %d?' % uid)
 
1675
        return None, None
 
1676
 
 
1677
    # we try utf-8 first, because on many variants (like Linux),
 
1678
    # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
1679
    # false positives.  (many users will have their user encoding set to
 
1680
    # latin-1, which cannot raise UnicodeError.)
 
1681
    try:
 
1682
        gecos = w.pw_gecos.decode('utf-8')
 
1683
        encoding = 'utf-8'
 
1684
    except UnicodeError:
 
1685
        try:
 
1686
            encoding = osutils.get_user_encoding()
 
1687
            gecos = w.pw_gecos.decode(encoding)
 
1688
        except UnicodeError, e:
 
1689
            trace.mutter("cannot decode passwd entry %s" % w)
 
1690
            return None, None
 
1691
    try:
 
1692
        username = w.pw_name.decode(encoding)
 
1693
    except UnicodeError, e:
 
1694
        trace.mutter("cannot decode passwd entry %s" % w)
 
1695
        return None, None
 
1696
 
 
1697
    comma = gecos.find(',')
 
1698
    if comma == -1:
 
1699
        realname = gecos
 
1700
    else:
 
1701
        realname = gecos[:comma]
 
1702
 
 
1703
    return realname, (username + '@' + default_mail_domain)
 
1704
 
 
1705
 
1041
1706
def parse_username(username):
1042
1707
    """Parse e-mail username and return a (name, address) tuple."""
1043
1708
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1086
1751
 
1087
1752
    def set_option(self, value, name, section=None):
1088
1753
        """Set a per-branch configuration option"""
 
1754
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1755
        # higher levels providing the right lock -- vila 20101004
1089
1756
        self.branch.lock_write()
1090
1757
        try:
1091
1758
            self._config.set_option(value, name, section)
1092
1759
        finally:
1093
1760
            self.branch.unlock()
1094
1761
 
 
1762
    def remove_option(self, option_name, section_name=None):
 
1763
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1764
        # higher levels providing the right lock -- vila 20101004
 
1765
        self.branch.lock_write()
 
1766
        try:
 
1767
            self._config.remove_option(option_name, section_name)
 
1768
        finally:
 
1769
            self.branch.unlock()
 
1770
 
1095
1771
 
1096
1772
class AuthenticationConfig(object):
1097
1773
    """The authentication configuration file based on a ini file.
1123
1799
            self._config = ConfigObj(self._input, encoding='utf-8')
1124
1800
        except configobj.ConfigObjError, e:
1125
1801
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
1802
        except UnicodeError:
 
1803
            raise errors.ConfigContentError(self._filename)
1126
1804
        return self._config
1127
1805
 
1128
1806
    def _save(self):
1145
1823
        section[option_name] = value
1146
1824
        self._save()
1147
1825
 
1148
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
 
1826
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
1149
1827
                        realm=None):
1150
1828
        """Returns the matching credentials from authentication.conf file.
1151
1829
 
1319
1997
            if ask:
1320
1998
                if prompt is None:
1321
1999
                    # Create a default prompt suitable for most cases
1322
 
                    prompt = scheme.upper() + ' %(host)s username'
 
2000
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
1323
2001
                # Special handling for optional fields in the prompt
1324
2002
                if port is not None:
1325
2003
                    prompt_host = '%s:%d' % (host, port)
1363
2041
        if password is None:
1364
2042
            if prompt is None:
1365
2043
                # Create a default prompt suitable for most cases
1366
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
2044
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
1367
2045
            # Special handling for optional fields in the prompt
1368
2046
            if port is not None:
1369
2047
                prompt_host = '%s:%d' % (host, port)
1540
2218
    """A Config that reads/writes a config file on a Transport.
1541
2219
 
1542
2220
    It is a low-level object that considers config data to be name/value pairs
1543
 
    that may be associated with a section.  Assigning meaning to the these
1544
 
    values is done at higher levels like TreeConfig.
 
2221
    that may be associated with a section.  Assigning meaning to these values
 
2222
    is done at higher levels like TreeConfig.
1545
2223
    """
1546
2224
 
1547
2225
    def __init__(self, transport, filename):
1564
2242
                section_obj = configobj[section]
1565
2243
            except KeyError:
1566
2244
                return default
1567
 
        return section_obj.get(name, default)
 
2245
        value = section_obj.get(name, default)
 
2246
        for hook in OldConfigHooks['get']:
 
2247
            hook(self, name, value)
 
2248
        return value
1568
2249
 
1569
2250
    def set_option(self, value, name, section=None):
1570
2251
        """Set the value associated with a named option.
1578
2259
            configobj[name] = value
1579
2260
        else:
1580
2261
            configobj.setdefault(section, {})[name] = value
 
2262
        for hook in OldConfigHooks['set']:
 
2263
            hook(self, name, value)
 
2264
        self._set_configobj(configobj)
 
2265
 
 
2266
    def remove_option(self, option_name, section_name=None):
 
2267
        configobj = self._get_configobj()
 
2268
        if section_name is None:
 
2269
            del configobj[option_name]
 
2270
        else:
 
2271
            del configobj[section_name][option_name]
 
2272
        for hook in OldConfigHooks['remove']:
 
2273
            hook(self, option_name)
1581
2274
        self._set_configobj(configobj)
1582
2275
 
1583
2276
    def _get_config_file(self):
1584
2277
        try:
1585
 
            return StringIO(self._transport.get_bytes(self._filename))
 
2278
            f = StringIO(self._transport.get_bytes(self._filename))
 
2279
            for hook in OldConfigHooks['load']:
 
2280
                hook(self)
 
2281
            return f
1586
2282
        except errors.NoSuchFile:
1587
2283
            return StringIO()
 
2284
        except errors.PermissionDenied, e:
 
2285
            trace.warning("Permission denied while trying to open "
 
2286
                "configuration file %s.", urlutils.unescape_for_display(
 
2287
                urlutils.join(self._transport.base, self._filename), "utf-8"))
 
2288
            return StringIO()
 
2289
 
 
2290
    def _external_url(self):
 
2291
        return urlutils.join(self._transport.external_url(), self._filename)
1588
2292
 
1589
2293
    def _get_configobj(self):
1590
2294
        f = self._get_config_file()
1591
2295
        try:
1592
 
            return ConfigObj(f, encoding='utf-8')
 
2296
            try:
 
2297
                conf = ConfigObj(f, encoding='utf-8')
 
2298
            except configobj.ConfigObjError, e:
 
2299
                raise errors.ParseConfigError(e.errors, self._external_url())
 
2300
            except UnicodeDecodeError:
 
2301
                raise errors.ConfigContentError(self._external_url())
1593
2302
        finally:
1594
2303
            f.close()
 
2304
        return conf
1595
2305
 
1596
2306
    def _set_configobj(self, configobj):
1597
2307
        out_file = StringIO()
1598
2308
        configobj.write(out_file)
1599
2309
        out_file.seek(0)
1600
2310
        self._transport.put_file(self._filename, out_file)
 
2311
        for hook in OldConfigHooks['save']:
 
2312
            hook(self)
 
2313
 
 
2314
 
 
2315
class Option(object):
 
2316
    """An option definition.
 
2317
 
 
2318
    The option *values* are stored in config files and found in sections.
 
2319
 
 
2320
    Here we define various properties about the option itself, its default
 
2321
    value, how to convert it from stores, what to do when invalid values are
 
2322
    encoutered, in which config files it can be stored.
 
2323
    """
 
2324
 
 
2325
    def __init__(self, name, default=None, default_from_env=None,
 
2326
                 help=None,
 
2327
                 from_unicode=None, invalid=None):
 
2328
        """Build an option definition.
 
2329
 
 
2330
        :param name: the name used to refer to the option.
 
2331
 
 
2332
        :param default: the default value to use when none exist in the config
 
2333
            stores. This is either a string that ``from_unicode`` will convert
 
2334
            into the proper type or a python object that can be stringified (so
 
2335
            only the empty list is supported for example).
 
2336
 
 
2337
        :param default_from_env: A list of environment variables which can
 
2338
           provide a default value. 'default' will be used only if none of the
 
2339
           variables specified here are set in the environment.
 
2340
 
 
2341
        :param help: a doc string to explain the option to the user.
 
2342
 
 
2343
        :param from_unicode: a callable to convert the unicode string
 
2344
            representing the option value in a store. This is not called for
 
2345
            the default value.
 
2346
 
 
2347
        :param invalid: the action to be taken when an invalid value is
 
2348
            encountered in a store. This is called only when from_unicode is
 
2349
            invoked to convert a string and returns None or raise ValueError or
 
2350
            TypeError. Accepted values are: None (ignore invalid values),
 
2351
            'warning' (emit a warning), 'error' (emit an error message and
 
2352
            terminates).
 
2353
        """
 
2354
        if default_from_env is None:
 
2355
            default_from_env = []
 
2356
        self.name = name
 
2357
        # Convert the default value to a unicode string so all values are
 
2358
        # strings internally before conversion (via from_unicode) is attempted.
 
2359
        if default is None:
 
2360
            self.default = None
 
2361
        elif isinstance(default, list):
 
2362
            # Only the empty list is supported
 
2363
            if default:
 
2364
                raise AssertionError(
 
2365
                    'Only empty lists are supported as default values')
 
2366
            self.default = u','
 
2367
        elif isinstance(default, (str, unicode, bool, int, float)):
 
2368
            # Rely on python to convert strings, booleans and integers
 
2369
            self.default = u'%s' % (default,)
 
2370
        else:
 
2371
            # other python objects are not expected
 
2372
            raise AssertionError('%r is not supported as a default value'
 
2373
                                 % (default,))
 
2374
        self.default_from_env = default_from_env
 
2375
        self.help = help
 
2376
        self.from_unicode = from_unicode
 
2377
        if invalid and invalid not in ('warning', 'error'):
 
2378
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
 
2379
        self.invalid = invalid
 
2380
 
 
2381
    def convert_from_unicode(self, unicode_value):
 
2382
        if self.from_unicode is None or unicode_value is None:
 
2383
            # Don't convert or nothing to convert
 
2384
            return unicode_value
 
2385
        try:
 
2386
            converted = self.from_unicode(unicode_value)
 
2387
        except (ValueError, TypeError):
 
2388
            # Invalid values are ignored
 
2389
            converted = None
 
2390
        if converted is None and self.invalid is not None:
 
2391
            # The conversion failed
 
2392
            if self.invalid == 'warning':
 
2393
                trace.warning('Value "%s" is not valid for "%s"',
 
2394
                              unicode_value, self.name)
 
2395
            elif self.invalid == 'error':
 
2396
                raise errors.ConfigOptionValueError(self.name, unicode_value)
 
2397
        return converted
 
2398
 
 
2399
    def get_default(self):
 
2400
        value = None
 
2401
        for var in self.default_from_env:
 
2402
            try:
 
2403
                # If the env variable is defined, its value is the default one
 
2404
                value = os.environ[var]
 
2405
                break
 
2406
            except KeyError:
 
2407
                continue
 
2408
        if value is None:
 
2409
            # Otherwise, fallback to the value defined at registration
 
2410
            value = self.default
 
2411
        return value
 
2412
 
 
2413
    def get_help_text(self, additional_see_also=None, plain=True):
 
2414
        result = self.help
 
2415
        from bzrlib import help_topics
 
2416
        result += help_topics._format_see_also(additional_see_also)
 
2417
        if plain:
 
2418
            result = help_topics.help_as_plain_text(result)
 
2419
        return result
 
2420
 
 
2421
 
 
2422
# Predefined converters to get proper values from store
 
2423
 
 
2424
def bool_from_store(unicode_str):
 
2425
    return ui.bool_from_string(unicode_str)
 
2426
 
 
2427
 
 
2428
def int_from_store(unicode_str):
 
2429
    return int(unicode_str)
 
2430
 
 
2431
 
 
2432
def float_from_store(unicode_str):
 
2433
    return float(unicode_str)
 
2434
 
 
2435
 
 
2436
 
 
2437
# Use a an empty dict to initialize an empty configobj avoiding all
 
2438
# parsing and encoding checks
 
2439
_list_converter_config = configobj.ConfigObj(
 
2440
    {}, encoding='utf-8', list_values=True, interpolation=False)
 
2441
 
 
2442
 
 
2443
def list_from_store(unicode_str):
 
2444
    if not isinstance(unicode_str, basestring):
 
2445
        raise TypeError
 
2446
    # Now inject our string directly as unicode. All callers got their value
 
2447
    # from configobj, so values that need to be quoted are already properly
 
2448
    # quoted.
 
2449
    _list_converter_config.reset()
 
2450
    _list_converter_config._parse([u"list=%s" % (unicode_str,)])
 
2451
    maybe_list = _list_converter_config['list']
 
2452
    # ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
 
2453
    if isinstance(maybe_list, basestring):
 
2454
        if maybe_list:
 
2455
            # A single value, most probably the user forgot (or didn't care to
 
2456
            # add) the final ','
 
2457
            l = [maybe_list]
 
2458
        else:
 
2459
            # The empty string, convert to empty list
 
2460
            l = []
 
2461
    else:
 
2462
        # We rely on ConfigObj providing us with a list already
 
2463
        l = maybe_list
 
2464
    return l
 
2465
 
 
2466
 
 
2467
class OptionRegistry(registry.Registry):
 
2468
    """Register config options by their name.
 
2469
 
 
2470
    This overrides ``registry.Registry`` to simplify registration by acquiring
 
2471
    some information from the option object itself.
 
2472
    """
 
2473
 
 
2474
    def register(self, option):
 
2475
        """Register a new option to its name.
 
2476
 
 
2477
        :param option: The option to register. Its name is used as the key.
 
2478
        """
 
2479
        super(OptionRegistry, self).register(option.name, option,
 
2480
                                             help=option.help)
 
2481
 
 
2482
    def register_lazy(self, key, module_name, member_name):
 
2483
        """Register a new option to be loaded on request.
 
2484
 
 
2485
        :param key: the key to request the option later. Since the registration
 
2486
            is lazy, it should be provided and match the option name.
 
2487
 
 
2488
        :param module_name: the python path to the module. Such as 'os.path'.
 
2489
 
 
2490
        :param member_name: the member of the module to return.  If empty or 
 
2491
                None, get() will return the module itself.
 
2492
        """
 
2493
        super(OptionRegistry, self).register_lazy(key,
 
2494
                                                  module_name, member_name)
 
2495
 
 
2496
    def get_help(self, key=None):
 
2497
        """Get the help text associated with the given key"""
 
2498
        option = self.get(key)
 
2499
        the_help = option.help
 
2500
        if callable(the_help):
 
2501
            return the_help(self, key)
 
2502
        return the_help
 
2503
 
 
2504
 
 
2505
option_registry = OptionRegistry()
 
2506
 
 
2507
 
 
2508
# Registered options in lexicographical order
 
2509
 
 
2510
option_registry.register(
 
2511
    Option('bzr.workingtree.worth_saving_limit', default=10,
 
2512
           from_unicode=int_from_store,  invalid='warning',
 
2513
           help='''\
 
2514
How many changes before saving the dirstate.
 
2515
 
 
2516
-1 means that we will never rewrite the dirstate file for only
 
2517
stat-cache changes. Regardless of this setting, we will always rewrite
 
2518
the dirstate file if a file is added/removed/renamed/etc. This flag only
 
2519
affects the behavior of updating the dirstate file after we notice that
 
2520
a file has been touched.
 
2521
'''))
 
2522
option_registry.register(
 
2523
    Option('dirstate.fdatasync', default=True,
 
2524
           from_unicode=bool_from_store,
 
2525
           help='''\
 
2526
Flush dirstate changes onto physical disk?
 
2527
 
 
2528
If true (default), working tree metadata changes are flushed through the
 
2529
OS buffers to physical disk.  This is somewhat slower, but means data
 
2530
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2531
'''))
 
2532
option_registry.register(
 
2533
    Option('debug_flags', default=[], from_unicode=list_from_store,
 
2534
           help='Debug flags to activate.'))
 
2535
option_registry.register(
 
2536
    Option('default_format', default='2a',
 
2537
           help='Format used when creating branches.'))
 
2538
option_registry.register(
 
2539
    Option('dpush_strict', default=None,
 
2540
           from_unicode=bool_from_store,
 
2541
           help='''\
 
2542
The default value for ``dpush --strict``.
 
2543
 
 
2544
If present, defines the ``--strict`` option default value for checking
 
2545
uncommitted changes before pushing into a different VCS without any
 
2546
custom bzr metadata.
 
2547
'''))
 
2548
option_registry.register(
 
2549
    Option('editor',
 
2550
           help='The command called to launch an editor to enter a message.'))
 
2551
option_registry.register(
 
2552
    Option('ignore_missing_extensions', default=False,
 
2553
           from_unicode=bool_from_store,
 
2554
           help='''\
 
2555
Control the missing extensions warning display.
 
2556
 
 
2557
The warning will not be emitted if set to True.
 
2558
'''))
 
2559
option_registry.register(
 
2560
    Option('language',
 
2561
           help='Language to translate messages into.'))
 
2562
option_registry.register(
 
2563
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
 
2564
           help='''\
 
2565
Steal locks that appears to be dead.
 
2566
 
 
2567
If set to True, bzr will check if a lock is supposed to be held by an
 
2568
active process from the same user on the same machine. If the user and
 
2569
machine match, but no process with the given PID is active, then bzr
 
2570
will automatically break the stale lock, and create a new lock for
 
2571
this process.
 
2572
Otherwise, bzr will prompt as normal to break the lock.
 
2573
'''))
 
2574
option_registry.register(
 
2575
    Option('output_encoding',
 
2576
           help= 'Unicode encoding for output'
 
2577
           ' (terminal encoding if not specified).'))
 
2578
option_registry.register(
 
2579
    Option('push_strict', default=None,
 
2580
           from_unicode=bool_from_store,
 
2581
           help='''\
 
2582
The default value for ``push --strict``.
 
2583
 
 
2584
If present, defines the ``--strict`` option default value for checking
 
2585
uncommitted changes before sending a merge directive.
 
2586
'''))
 
2587
option_registry.register(
 
2588
    Option('repository.fdatasync', default=True,
 
2589
           from_unicode=bool_from_store,
 
2590
           help='''\
 
2591
Flush repository changes onto physical disk?
 
2592
 
 
2593
If true (default), repository changes are flushed through the OS buffers
 
2594
to physical disk.  This is somewhat slower, but means data should not be
 
2595
lost if the machine crashes.  See also dirstate.fdatasync.
 
2596
'''))
 
2597
option_registry.register(
 
2598
    Option('send_strict', default=None,
 
2599
           from_unicode=bool_from_store,
 
2600
           help='''\
 
2601
The default value for ``send --strict``.
 
2602
 
 
2603
If present, defines the ``--strict`` option default value for checking
 
2604
uncommitted changes before pushing.
 
2605
'''))
 
2606
 
 
2607
option_registry.register(
 
2608
    Option('serve.client_timeout',
 
2609
           default=300.0, from_unicode=float_from_store,
 
2610
           help="If we wait for a new request from a client for more than"
 
2611
                " X seconds, consider the client idle, and hangup."))
 
2612
 
 
2613
 
 
2614
class Section(object):
 
2615
    """A section defines a dict of option name => value.
 
2616
 
 
2617
    This is merely a read-only dict which can add some knowledge about the
 
2618
    options. It is *not* a python dict object though and doesn't try to mimic
 
2619
    its API.
 
2620
    """
 
2621
 
 
2622
    def __init__(self, section_id, options):
 
2623
        self.id = section_id
 
2624
        # We re-use the dict-like object received
 
2625
        self.options = options
 
2626
 
 
2627
    def get(self, name, default=None):
 
2628
        return self.options.get(name, default)
 
2629
 
 
2630
    def __repr__(self):
 
2631
        # Mostly for debugging use
 
2632
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
 
2633
 
 
2634
 
 
2635
_NewlyCreatedOption = object()
 
2636
"""Was the option created during the MutableSection lifetime"""
 
2637
 
 
2638
 
 
2639
class MutableSection(Section):
 
2640
    """A section allowing changes and keeping track of the original values."""
 
2641
 
 
2642
    def __init__(self, section_id, options):
 
2643
        super(MutableSection, self).__init__(section_id, options)
 
2644
        self.orig = {}
 
2645
 
 
2646
    def set(self, name, value):
 
2647
        if name not in self.options:
 
2648
            # This is a new option
 
2649
            self.orig[name] = _NewlyCreatedOption
 
2650
        elif name not in self.orig:
 
2651
            self.orig[name] = self.get(name, None)
 
2652
        self.options[name] = value
 
2653
 
 
2654
    def remove(self, name):
 
2655
        if name not in self.orig:
 
2656
            self.orig[name] = self.get(name, None)
 
2657
        del self.options[name]
 
2658
 
 
2659
 
 
2660
class CommandLineSection(MutableSection):
 
2661
    """A section used to carry command line overrides for the config options."""
 
2662
 
 
2663
    def __init__(self, opts=None):
 
2664
        if opts is None:
 
2665
            opts = {}
 
2666
        super(CommandLineSection, self).__init__('cmdline-overrides', opts)
 
2667
 
 
2668
    def _reset(self):
 
2669
        # The dict should be cleared but not replaced so it can be shared.
 
2670
        self.options.clear()
 
2671
 
 
2672
    def _from_cmdline(self, overrides):
 
2673
        # Reset before accepting new definitions
 
2674
        self._reset()
 
2675
        for over in overrides:
 
2676
            try:
 
2677
                name, value = over.split('=', 1)
 
2678
            except ValueError:
 
2679
                raise errors.BzrCommandError(
 
2680
                    gettext("Invalid '%s', should be of the form 'name=value'")
 
2681
                    % (over,))
 
2682
            self.set(name, value)
 
2683
 
 
2684
 
 
2685
class Store(object):
 
2686
    """Abstract interface to persistent storage for configuration options."""
 
2687
 
 
2688
    readonly_section_class = Section
 
2689
    mutable_section_class = MutableSection
 
2690
 
 
2691
    def is_loaded(self):
 
2692
        """Returns True if the Store has been loaded.
 
2693
 
 
2694
        This is used to implement lazy loading and ensure the persistent
 
2695
        storage is queried only when needed.
 
2696
        """
 
2697
        raise NotImplementedError(self.is_loaded)
 
2698
 
 
2699
    def load(self):
 
2700
        """Loads the Store from persistent storage."""
 
2701
        raise NotImplementedError(self.load)
 
2702
 
 
2703
    def _load_from_string(self, bytes):
 
2704
        """Create a store from a string in configobj syntax.
 
2705
 
 
2706
        :param bytes: A string representing the file content.
 
2707
        """
 
2708
        raise NotImplementedError(self._load_from_string)
 
2709
 
 
2710
    def unload(self):
 
2711
        """Unloads the Store.
 
2712
 
 
2713
        This should make is_loaded() return False. This is used when the caller
 
2714
        knows that the persistent storage has changed or may have change since
 
2715
        the last load.
 
2716
        """
 
2717
        raise NotImplementedError(self.unload)
 
2718
 
 
2719
    def save(self):
 
2720
        """Saves the Store to persistent storage."""
 
2721
        raise NotImplementedError(self.save)
 
2722
 
 
2723
    def external_url(self):
 
2724
        raise NotImplementedError(self.external_url)
 
2725
 
 
2726
    def get_sections(self):
 
2727
        """Returns an ordered iterable of existing sections.
 
2728
 
 
2729
        :returns: An iterable of (name, dict).
 
2730
        """
 
2731
        raise NotImplementedError(self.get_sections)
 
2732
 
 
2733
    def get_mutable_section(self, section_name=None):
 
2734
        """Returns the specified mutable section.
 
2735
 
 
2736
        :param section_name: The section identifier
 
2737
        """
 
2738
        raise NotImplementedError(self.get_mutable_section)
 
2739
 
 
2740
    def __repr__(self):
 
2741
        # Mostly for debugging use
 
2742
        return "<config.%s(%s)>" % (self.__class__.__name__,
 
2743
                                    self.external_url())
 
2744
 
 
2745
 
 
2746
class IniFileStore(Store):
 
2747
    """A config Store using ConfigObj for storage.
 
2748
 
 
2749
    :ivar transport: The transport object where the config file is located.
 
2750
 
 
2751
    :ivar file_name: The config file basename in the transport directory.
 
2752
 
 
2753
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
 
2754
        serialize/deserialize the config file.
 
2755
    """
 
2756
 
 
2757
    def __init__(self, transport, file_name):
 
2758
        """A config Store using ConfigObj for storage.
 
2759
 
 
2760
        :param transport: The transport object where the config file is located.
 
2761
 
 
2762
        :param file_name: The config file basename in the transport directory.
 
2763
        """
 
2764
        super(IniFileStore, self).__init__()
 
2765
        self.transport = transport
 
2766
        self.file_name = file_name
 
2767
        self._config_obj = None
 
2768
 
 
2769
    def is_loaded(self):
 
2770
        return self._config_obj != None
 
2771
 
 
2772
    def unload(self):
 
2773
        self._config_obj = None
 
2774
 
 
2775
    def load(self):
 
2776
        """Load the store from the associated file."""
 
2777
        if self.is_loaded():
 
2778
            return
 
2779
        try:
 
2780
            content = self.transport.get_bytes(self.file_name)
 
2781
        except errors.PermissionDenied:
 
2782
            trace.warning("Permission denied while trying to load "
 
2783
                          "configuration store %s.", self.external_url())
 
2784
            raise
 
2785
        self._load_from_string(content)
 
2786
        for hook in ConfigHooks['load']:
 
2787
            hook(self)
 
2788
 
 
2789
    def _load_from_string(self, bytes):
 
2790
        """Create a config store from a string.
 
2791
 
 
2792
        :param bytes: A string representing the file content.
 
2793
        """
 
2794
        if self.is_loaded():
 
2795
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
 
2796
        co_input = StringIO(bytes)
 
2797
        try:
 
2798
            # The config files are always stored utf8-encoded
 
2799
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
 
2800
                                         list_values=False)
 
2801
        except configobj.ConfigObjError, e:
 
2802
            self._config_obj = None
 
2803
            raise errors.ParseConfigError(e.errors, self.external_url())
 
2804
        except UnicodeDecodeError:
 
2805
            raise errors.ConfigContentError(self.external_url())
 
2806
 
 
2807
    def save(self):
 
2808
        if not self.is_loaded():
 
2809
            # Nothing to save
 
2810
            return
 
2811
        out = StringIO()
 
2812
        self._config_obj.write(out)
 
2813
        self.transport.put_bytes(self.file_name, out.getvalue())
 
2814
        for hook in ConfigHooks['save']:
 
2815
            hook(self)
 
2816
 
 
2817
    def external_url(self):
 
2818
        # FIXME: external_url should really accepts an optional relpath
 
2819
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
2820
        # The following will do in the interim but maybe we don't want to
 
2821
        # expose a path here but rather a config ID and its associated
 
2822
        # object </hand wawe>.
 
2823
        return urlutils.join(self.transport.external_url(), self.file_name)
 
2824
 
 
2825
    def get_sections(self):
 
2826
        """Get the configobj section in the file order.
 
2827
 
 
2828
        :returns: An iterable of (name, dict).
 
2829
        """
 
2830
        # We need a loaded store
 
2831
        try:
 
2832
            self.load()
 
2833
        except (errors.NoSuchFile, errors.PermissionDenied):
 
2834
            # If the file can't be read, there is no sections
 
2835
            return
 
2836
        cobj = self._config_obj
 
2837
        if cobj.scalars:
 
2838
            yield self.readonly_section_class(None, cobj)
 
2839
        for section_name in cobj.sections:
 
2840
            yield self.readonly_section_class(section_name, cobj[section_name])
 
2841
 
 
2842
    def get_mutable_section(self, section_name=None):
 
2843
        # We need a loaded store
 
2844
        try:
 
2845
            self.load()
 
2846
        except errors.NoSuchFile:
 
2847
            # The file doesn't exist, let's pretend it was empty
 
2848
            self._load_from_string('')
 
2849
        if section_name is None:
 
2850
            section = self._config_obj
 
2851
        else:
 
2852
            section = self._config_obj.setdefault(section_name, {})
 
2853
        return self.mutable_section_class(section_name, section)
 
2854
 
 
2855
 
 
2856
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
 
2857
# unlockable stores for use with objects that can already ensure the locking
 
2858
# (think branches). If different stores (not based on ConfigObj) are created,
 
2859
# they may face the same issue.
 
2860
 
 
2861
 
 
2862
class LockableIniFileStore(IniFileStore):
 
2863
    """A ConfigObjStore using locks on save to ensure store integrity."""
 
2864
 
 
2865
    def __init__(self, transport, file_name, lock_dir_name=None):
 
2866
        """A config Store using ConfigObj for storage.
 
2867
 
 
2868
        :param transport: The transport object where the config file is located.
 
2869
 
 
2870
        :param file_name: The config file basename in the transport directory.
 
2871
        """
 
2872
        if lock_dir_name is None:
 
2873
            lock_dir_name = 'lock'
 
2874
        self.lock_dir_name = lock_dir_name
 
2875
        super(LockableIniFileStore, self).__init__(transport, file_name)
 
2876
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
 
2877
 
 
2878
    def lock_write(self, token=None):
 
2879
        """Takes a write lock in the directory containing the config file.
 
2880
 
 
2881
        If the directory doesn't exist it is created.
 
2882
        """
 
2883
        # FIXME: This doesn't check the ownership of the created directories as
 
2884
        # ensure_config_dir_exists does. It should if the transport is local
 
2885
        # -- vila 2011-04-06
 
2886
        self.transport.create_prefix()
 
2887
        return self._lock.lock_write(token)
 
2888
 
 
2889
    def unlock(self):
 
2890
        self._lock.unlock()
 
2891
 
 
2892
    def break_lock(self):
 
2893
        self._lock.break_lock()
 
2894
 
 
2895
    @needs_write_lock
 
2896
    def save(self):
 
2897
        # We need to be able to override the undecorated implementation
 
2898
        self.save_without_locking()
 
2899
 
 
2900
    def save_without_locking(self):
 
2901
        super(LockableIniFileStore, self).save()
 
2902
 
 
2903
 
 
2904
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
 
2905
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
 
2906
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
 
2907
 
 
2908
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
 
2909
# functions or a registry will make it easier and clearer for tests, focusing
 
2910
# on the relevant parts of the API that needs testing -- vila 20110503 (based
 
2911
# on a poolie's remark)
 
2912
class GlobalStore(LockableIniFileStore):
 
2913
 
 
2914
    def __init__(self, possible_transports=None):
 
2915
        t = transport.get_transport_from_path(
 
2916
            config_dir(), possible_transports=possible_transports)
 
2917
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
2918
 
 
2919
 
 
2920
class LocationStore(LockableIniFileStore):
 
2921
 
 
2922
    def __init__(self, possible_transports=None):
 
2923
        t = transport.get_transport_from_path(
 
2924
            config_dir(), possible_transports=possible_transports)
 
2925
        super(LocationStore, self).__init__(t, 'locations.conf')
 
2926
 
 
2927
 
 
2928
class BranchStore(IniFileStore):
 
2929
 
 
2930
    def __init__(self, branch):
 
2931
        super(BranchStore, self).__init__(branch.control_transport,
 
2932
                                          'branch.conf')
 
2933
        self.branch = branch
 
2934
 
 
2935
    def lock_write(self, token=None):
 
2936
        return self.branch.lock_write(token)
 
2937
 
 
2938
    def unlock(self):
 
2939
        return self.branch.unlock()
 
2940
 
 
2941
    @needs_write_lock
 
2942
    def save(self):
 
2943
        # We need to be able to override the undecorated implementation
 
2944
        self.save_without_locking()
 
2945
 
 
2946
    def save_without_locking(self):
 
2947
        super(BranchStore, self).save()
 
2948
 
 
2949
 
 
2950
class ControlStore(LockableIniFileStore):
 
2951
 
 
2952
    def __init__(self, bzrdir):
 
2953
        super(ControlStore, self).__init__(bzrdir.transport,
 
2954
                                          'control.conf',
 
2955
                                           lock_dir_name='branch_lock')
 
2956
 
 
2957
 
 
2958
class SectionMatcher(object):
 
2959
    """Select sections into a given Store.
 
2960
 
 
2961
    This is intended to be used to postpone getting an iterable of sections
 
2962
    from a store.
 
2963
    """
 
2964
 
 
2965
    def __init__(self, store):
 
2966
        self.store = store
 
2967
 
 
2968
    def get_sections(self):
 
2969
        # This is where we require loading the store so we can see all defined
 
2970
        # sections.
 
2971
        sections = self.store.get_sections()
 
2972
        # Walk the revisions in the order provided
 
2973
        for s in sections:
 
2974
            if self.match(s):
 
2975
                yield s
 
2976
 
 
2977
    def match(self, section):
 
2978
        """Does the proposed section match.
 
2979
 
 
2980
        :param section: A Section object.
 
2981
 
 
2982
        :returns: True if the section matches, False otherwise.
 
2983
        """
 
2984
        raise NotImplementedError(self.match)
 
2985
 
 
2986
 
 
2987
class NameMatcher(SectionMatcher):
 
2988
 
 
2989
    def __init__(self, store, section_id):
 
2990
        super(NameMatcher, self).__init__(store)
 
2991
        self.section_id = section_id
 
2992
 
 
2993
    def match(self, section):
 
2994
        return section.id == self.section_id
 
2995
 
 
2996
 
 
2997
class LocationSection(Section):
 
2998
 
 
2999
    def __init__(self, section, length, extra_path):
 
3000
        super(LocationSection, self).__init__(section.id, section.options)
 
3001
        self.length = length
 
3002
        self.extra_path = extra_path
 
3003
 
 
3004
    def get(self, name, default=None):
 
3005
        value = super(LocationSection, self).get(name, default)
 
3006
        if value is not None:
 
3007
            policy_name = self.get(name + ':policy', None)
 
3008
            policy = _policy_value.get(policy_name, POLICY_NONE)
 
3009
            if policy == POLICY_APPENDPATH:
 
3010
                value = urlutils.join(value, self.extra_path)
 
3011
        return value
 
3012
 
 
3013
 
 
3014
class LocationMatcher(SectionMatcher):
 
3015
 
 
3016
    def __init__(self, store, location):
 
3017
        super(LocationMatcher, self).__init__(store)
 
3018
        if location.startswith('file://'):
 
3019
            location = urlutils.local_path_from_url(location)
 
3020
        self.location = location
 
3021
 
 
3022
    def _get_matching_sections(self):
 
3023
        """Get all sections matching ``location``."""
 
3024
        # We slightly diverge from LocalConfig here by allowing the no-name
 
3025
        # section as the most generic one and the lower priority.
 
3026
        no_name_section = None
 
3027
        all_sections = []
 
3028
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
3029
        # used (it assumes all sections have a name).
 
3030
        for section in self.store.get_sections():
 
3031
            if section.id is None:
 
3032
                no_name_section = section
 
3033
            else:
 
3034
                all_sections.append(section)
 
3035
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
3036
        # we have to resync.
 
3037
        filtered_sections = _iter_for_location_by_parts(
 
3038
            [s.id for s in all_sections], self.location)
 
3039
        iter_all_sections = iter(all_sections)
 
3040
        matching_sections = []
 
3041
        if no_name_section is not None:
 
3042
            matching_sections.append(
 
3043
                LocationSection(no_name_section, 0, self.location))
 
3044
        for section_id, extra_path, length in filtered_sections:
 
3045
            # a section id is unique for a given store so it's safe to take the
 
3046
            # first matching section while iterating. Also, all filtered
 
3047
            # sections are part of 'all_sections' and will always be found
 
3048
            # there.
 
3049
            while True:
 
3050
                section = iter_all_sections.next()
 
3051
                if section_id == section.id:
 
3052
                    matching_sections.append(
 
3053
                        LocationSection(section, length, extra_path))
 
3054
                    break
 
3055
        return matching_sections
 
3056
 
 
3057
    def get_sections(self):
 
3058
        # Override the default implementation as we want to change the order
 
3059
        matching_sections = self._get_matching_sections()
 
3060
        # We want the longest (aka more specific) locations first
 
3061
        sections = sorted(matching_sections,
 
3062
                          key=lambda section: (section.length, section.id),
 
3063
                          reverse=True)
 
3064
        # Sections mentioning 'ignore_parents' restrict the selection
 
3065
        for section in sections:
 
3066
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
 
3067
            ignore = section.get('ignore_parents', None)
 
3068
            if ignore is not None:
 
3069
                ignore = ui.bool_from_string(ignore)
 
3070
            if ignore:
 
3071
                break
 
3072
            # Finally, we have a valid section
 
3073
            yield section
 
3074
 
 
3075
 
 
3076
class Stack(object):
 
3077
    """A stack of configurations where an option can be defined"""
 
3078
 
 
3079
    _option_ref_re = lazy_regex.lazy_compile('({[^{}]+})')
 
3080
    """Describes an exandable option reference.
 
3081
 
 
3082
    We want to match the most embedded reference first.
 
3083
 
 
3084
    I.e. for '{{foo}}' we will get '{foo}',
 
3085
    for '{bar{baz}}' we will get '{baz}'
 
3086
    """
 
3087
 
 
3088
    def __init__(self, sections_def, store=None, mutable_section_name=None):
 
3089
        """Creates a stack of sections with an optional store for changes.
 
3090
 
 
3091
        :param sections_def: A list of Section or callables that returns an
 
3092
            iterable of Section. This defines the Sections for the Stack and
 
3093
            can be called repeatedly if needed.
 
3094
 
 
3095
        :param store: The optional Store where modifications will be
 
3096
            recorded. If none is specified, no modifications can be done.
 
3097
 
 
3098
        :param mutable_section_name: The name of the MutableSection where
 
3099
            changes are recorded. This requires the ``store`` parameter to be
 
3100
            specified.
 
3101
        """
 
3102
        self.sections_def = sections_def
 
3103
        self.store = store
 
3104
        self.mutable_section_name = mutable_section_name
 
3105
 
 
3106
    def get(self, name, expand=None):
 
3107
        """Return the *first* option value found in the sections.
 
3108
 
 
3109
        This is where we guarantee that sections coming from Store are loaded
 
3110
        lazily: the loading is delayed until we need to either check that an
 
3111
        option exists or get its value, which in turn may require to discover
 
3112
        in which sections it can be defined. Both of these (section and option
 
3113
        existence) require loading the store (even partially).
 
3114
 
 
3115
        :param name: The queried option.
 
3116
 
 
3117
        :param expand: Whether options references should be expanded.
 
3118
 
 
3119
        :returns: The value of the option.
 
3120
        """
 
3121
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
3122
        if expand is None:
 
3123
            expand = _get_expand_default_value()
 
3124
        value = None
 
3125
        # Ensuring lazy loading is achieved by delaying section matching (which
 
3126
        # implies querying the persistent storage) until it can't be avoided
 
3127
        # anymore by using callables to describe (possibly empty) section
 
3128
        # lists.
 
3129
        for section_or_callable in self.sections_def:
 
3130
            # Each section can expand to multiple ones when a callable is used
 
3131
            if callable(section_or_callable):
 
3132
                sections = section_or_callable()
 
3133
            else:
 
3134
                sections = [section_or_callable]
 
3135
            for section in sections:
 
3136
                value = section.get(name)
 
3137
                if value is not None:
 
3138
                    break
 
3139
            if value is not None:
 
3140
                break
 
3141
        # If the option is registered, it may provide additional info about
 
3142
        # value handling
 
3143
        try:
 
3144
            opt = option_registry.get(name)
 
3145
        except KeyError:
 
3146
            # Not registered
 
3147
            opt = None
 
3148
        def expand_and_convert(val):
 
3149
            # This may need to be called twice if the value is None or ends up
 
3150
            # being None during expansion or conversion.
 
3151
            if val is not None:
 
3152
                if expand:
 
3153
                    if isinstance(val, basestring):
 
3154
                        val = self._expand_options_in_string(val)
 
3155
                    else:
 
3156
                        trace.warning('Cannot expand "%s":'
 
3157
                                      ' %s does not support option expansion'
 
3158
                                      % (name, type(val)))
 
3159
                if opt is not None:
 
3160
                    val = opt.convert_from_unicode(val)
 
3161
            return val
 
3162
        value = expand_and_convert(value)
 
3163
        if opt is not None and value is None:
 
3164
            # If the option is registered, it may provide a default value
 
3165
            value = opt.get_default()
 
3166
            value = expand_and_convert(value)
 
3167
        for hook in ConfigHooks['get']:
 
3168
            hook(self, name, value)
 
3169
        return value
 
3170
 
 
3171
    def expand_options(self, string, env=None):
 
3172
        """Expand option references in the string in the configuration context.
 
3173
 
 
3174
        :param string: The string containing option(s) to expand.
 
3175
 
 
3176
        :param env: An option dict defining additional configuration options or
 
3177
            overriding existing ones.
 
3178
 
 
3179
        :returns: The expanded string.
 
3180
        """
 
3181
        return self._expand_options_in_string(string, env)
 
3182
 
 
3183
    def _expand_options_in_string(self, string, env=None, _refs=None):
 
3184
        """Expand options in the string in the configuration context.
 
3185
 
 
3186
        :param string: The string to be expanded.
 
3187
 
 
3188
        :param env: An option dict defining additional configuration options or
 
3189
            overriding existing ones.
 
3190
 
 
3191
        :param _refs: Private list (FIFO) containing the options being expanded
 
3192
            to detect loops.
 
3193
 
 
3194
        :returns: The expanded string.
 
3195
        """
 
3196
        if string is None:
 
3197
            # Not much to expand there
 
3198
            return None
 
3199
        if _refs is None:
 
3200
            # What references are currently resolved (to detect loops)
 
3201
            _refs = []
 
3202
        result = string
 
3203
        # We need to iterate until no more refs appear ({{foo}} will need two
 
3204
        # iterations for example).
 
3205
        while True:
 
3206
            raw_chunks = Stack._option_ref_re.split(result)
 
3207
            if len(raw_chunks) == 1:
 
3208
                # Shorcut the trivial case: no refs
 
3209
                return result
 
3210
            chunks = []
 
3211
            # Split will isolate refs so that every other chunk is a ref
 
3212
            chunk_is_ref = False
 
3213
            for chunk in raw_chunks:
 
3214
                if not chunk_is_ref:
 
3215
                    chunks.append(chunk)
 
3216
                    chunk_is_ref = True
 
3217
                else:
 
3218
                    name = chunk[1:-1]
 
3219
                    if name in _refs:
 
3220
                        raise errors.OptionExpansionLoop(string, _refs)
 
3221
                    _refs.append(name)
 
3222
                    value = self._expand_option(name, env, _refs)
 
3223
                    if value is None:
 
3224
                        raise errors.ExpandingUnknownOption(name, string)
 
3225
                    chunks.append(value)
 
3226
                    _refs.pop()
 
3227
                    chunk_is_ref = False
 
3228
            result = ''.join(chunks)
 
3229
        return result
 
3230
 
 
3231
    def _expand_option(self, name, env, _refs):
 
3232
        if env is not None and name in env:
 
3233
            # Special case, values provided in env takes precedence over
 
3234
            # anything else
 
3235
            value = env[name]
 
3236
        else:
 
3237
            # FIXME: This is a limited implementation, what we really need is a
 
3238
            # way to query the bzr config for the value of an option,
 
3239
            # respecting the scope rules (That is, once we implement fallback
 
3240
            # configs, getting the option value should restart from the top
 
3241
            # config, not the current one) -- vila 20101222
 
3242
            value = self.get(name, expand=False)
 
3243
            value = self._expand_options_in_string(value, env, _refs)
 
3244
        return value
 
3245
 
 
3246
    def _get_mutable_section(self):
 
3247
        """Get the MutableSection for the Stack.
 
3248
 
 
3249
        This is where we guarantee that the mutable section is lazily loaded:
 
3250
        this means we won't load the corresponding store before setting a value
 
3251
        or deleting an option. In practice the store will often be loaded but
 
3252
        this allows helps catching some programming errors.
 
3253
        """
 
3254
        section = self.store.get_mutable_section(self.mutable_section_name)
 
3255
        return section
 
3256
 
 
3257
    def set(self, name, value):
 
3258
        """Set a new value for the option."""
 
3259
        section = self._get_mutable_section()
 
3260
        section.set(name, value)
 
3261
        for hook in ConfigHooks['set']:
 
3262
            hook(self, name, value)
 
3263
 
 
3264
    def remove(self, name):
 
3265
        """Remove an existing option."""
 
3266
        section = self._get_mutable_section()
 
3267
        section.remove(name)
 
3268
        for hook in ConfigHooks['remove']:
 
3269
            hook(self, name)
 
3270
 
 
3271
    def __repr__(self):
 
3272
        # Mostly for debugging use
 
3273
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
 
3274
 
 
3275
    def _get_overrides(self):
 
3276
        # Hack around library_state.initialize never called
 
3277
        if bzrlib.global_state is not None:
 
3278
            return [bzrlib.global_state.cmdline_overrides]
 
3279
        return []
 
3280
 
 
3281
 
 
3282
class _CompatibleStack(Stack):
 
3283
    """Place holder for compatibility with previous design.
 
3284
 
 
3285
    This is intended to ease the transition from the Config-based design to the
 
3286
    Stack-based design and should not be used nor relied upon by plugins.
 
3287
 
 
3288
    One assumption made here is that the daughter classes will all use Stores
 
3289
    derived from LockableIniFileStore).
 
3290
 
 
3291
    It implements set() by re-loading the store before applying the
 
3292
    modification and saving it.
 
3293
 
 
3294
    The long term plan being to implement a single write by store to save
 
3295
    all modifications, this class should not be used in the interim.
 
3296
    """
 
3297
 
 
3298
    def set(self, name, value):
 
3299
        # Force a reload
 
3300
        self.store.unload()
 
3301
        super(_CompatibleStack, self).set(name, value)
 
3302
        # Force a write to persistent storage
 
3303
        self.store.save()
 
3304
 
 
3305
 
 
3306
class GlobalStack(_CompatibleStack):
 
3307
    """Global options only stack."""
 
3308
 
 
3309
    def __init__(self):
 
3310
        # Get a GlobalStore
 
3311
        gstore = GlobalStore()
 
3312
        super(GlobalStack, self).__init__(
 
3313
            [self._get_overrides, gstore.get_sections],
 
3314
            gstore)
 
3315
 
 
3316
 
 
3317
class LocationStack(_CompatibleStack):
 
3318
    """Per-location options falling back to global options stack."""
 
3319
 
 
3320
    def __init__(self, location):
 
3321
        """Make a new stack for a location and global configuration.
 
3322
        
 
3323
        :param location: A URL prefix to """
 
3324
        lstore = LocationStore()
 
3325
        matcher = LocationMatcher(lstore, location)
 
3326
        gstore = GlobalStore()
 
3327
        super(LocationStack, self).__init__(
 
3328
            [self._get_overrides,
 
3329
             matcher.get_sections, gstore.get_sections],
 
3330
            lstore)
 
3331
 
 
3332
 
 
3333
class BranchStack(_CompatibleStack):
 
3334
    """Per-location options falling back to branch then global options stack."""
 
3335
 
 
3336
    def __init__(self, branch):
 
3337
        bstore = BranchStore(branch)
 
3338
        lstore = LocationStore()
 
3339
        matcher = LocationMatcher(lstore, branch.base)
 
3340
        gstore = GlobalStore()
 
3341
        super(BranchStack, self).__init__(
 
3342
            [self._get_overrides,
 
3343
             matcher.get_sections, bstore.get_sections, gstore.get_sections],
 
3344
            bstore)
 
3345
        self.branch = branch
 
3346
 
 
3347
 
 
3348
class RemoteControlStack(_CompatibleStack):
 
3349
    """Remote control-only options stack."""
 
3350
 
 
3351
    def __init__(self, bzrdir):
 
3352
        cstore = ControlStore(bzrdir)
 
3353
        super(RemoteControlStack, self).__init__(
 
3354
            [cstore.get_sections],
 
3355
            cstore)
 
3356
        self.bzrdir = bzrdir
 
3357
 
 
3358
 
 
3359
class RemoteBranchStack(_CompatibleStack):
 
3360
    """Remote branch-only options stack."""
 
3361
 
 
3362
    def __init__(self, branch):
 
3363
        bstore = BranchStore(branch)
 
3364
        super(RemoteBranchStack, self).__init__(
 
3365
            [bstore.get_sections],
 
3366
            bstore)
 
3367
        self.branch = branch
 
3368
 
 
3369
 
 
3370
class cmd_config(commands.Command):
 
3371
    __doc__ = """Display, set or remove a configuration option.
 
3372
 
 
3373
    Display the active value for a given option.
 
3374
 
 
3375
    If --all is specified, NAME is interpreted as a regular expression and all
 
3376
    matching options are displayed mentioning their scope. The active value
 
3377
    that bzr will take into account is the first one displayed for each option.
 
3378
 
 
3379
    If no NAME is given, --all .* is implied.
 
3380
 
 
3381
    Setting a value is achieved by using name=value without spaces. The value
 
3382
    is set in the most relevant scope and can be checked by displaying the
 
3383
    option again.
 
3384
    """
 
3385
 
 
3386
    takes_args = ['name?']
 
3387
 
 
3388
    takes_options = [
 
3389
        'directory',
 
3390
        # FIXME: This should be a registry option so that plugins can register
 
3391
        # their own config files (or not) -- vila 20101002
 
3392
        commands.Option('scope', help='Reduce the scope to the specified'
 
3393
                        ' configuration file',
 
3394
                        type=unicode),
 
3395
        commands.Option('all',
 
3396
            help='Display all the defined values for the matching options.',
 
3397
            ),
 
3398
        commands.Option('remove', help='Remove the option from'
 
3399
                        ' the configuration file'),
 
3400
        ]
 
3401
 
 
3402
    _see_also = ['configuration']
 
3403
 
 
3404
    @commands.display_command
 
3405
    def run(self, name=None, all=False, directory=None, scope=None,
 
3406
            remove=False):
 
3407
        if directory is None:
 
3408
            directory = '.'
 
3409
        directory = urlutils.normalize_url(directory)
 
3410
        if remove and all:
 
3411
            raise errors.BzrError(
 
3412
                '--all and --remove are mutually exclusive.')
 
3413
        elif remove:
 
3414
            # Delete the option in the given scope
 
3415
            self._remove_config_option(name, directory, scope)
 
3416
        elif name is None:
 
3417
            # Defaults to all options
 
3418
            self._show_matching_options('.*', directory, scope)
 
3419
        else:
 
3420
            try:
 
3421
                name, value = name.split('=', 1)
 
3422
            except ValueError:
 
3423
                # Display the option(s) value(s)
 
3424
                if all:
 
3425
                    self._show_matching_options(name, directory, scope)
 
3426
                else:
 
3427
                    self._show_value(name, directory, scope)
 
3428
            else:
 
3429
                if all:
 
3430
                    raise errors.BzrError(
 
3431
                        'Only one option can be set.')
 
3432
                # Set the option value
 
3433
                self._set_config_option(name, value, directory, scope)
 
3434
 
 
3435
    def _get_configs(self, directory, scope=None):
 
3436
        """Iterate the configurations specified by ``directory`` and ``scope``.
 
3437
 
 
3438
        :param directory: Where the configurations are derived from.
 
3439
 
 
3440
        :param scope: A specific config to start from.
 
3441
        """
 
3442
        if scope is not None:
 
3443
            if scope == 'bazaar':
 
3444
                yield GlobalConfig()
 
3445
            elif scope == 'locations':
 
3446
                yield LocationConfig(directory)
 
3447
            elif scope == 'branch':
 
3448
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
3449
                    directory)
 
3450
                yield br.get_config()
 
3451
        else:
 
3452
            try:
 
3453
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
3454
                    directory)
 
3455
                yield br.get_config()
 
3456
            except errors.NotBranchError:
 
3457
                yield LocationConfig(directory)
 
3458
                yield GlobalConfig()
 
3459
 
 
3460
    def _show_value(self, name, directory, scope):
 
3461
        displayed = False
 
3462
        for c in self._get_configs(directory, scope):
 
3463
            if displayed:
 
3464
                break
 
3465
            for (oname, value, section, conf_id, parser) in c._get_options():
 
3466
                if name == oname:
 
3467
                    # Display only the first value and exit
 
3468
 
 
3469
                    # FIXME: We need to use get_user_option to take policies
 
3470
                    # into account and we need to make sure the option exists
 
3471
                    # too (hence the two for loops), this needs a better API
 
3472
                    # -- vila 20101117
 
3473
                    value = c.get_user_option(name)
 
3474
                    # Quote the value appropriately
 
3475
                    value = parser._quote(value)
 
3476
                    self.outf.write('%s\n' % (value,))
 
3477
                    displayed = True
 
3478
                    break
 
3479
        if not displayed:
 
3480
            raise errors.NoSuchConfigOption(name)
 
3481
 
 
3482
    def _show_matching_options(self, name, directory, scope):
 
3483
        name = lazy_regex.lazy_compile(name)
 
3484
        # We want any error in the regexp to be raised *now* so we need to
 
3485
        # avoid the delay introduced by the lazy regexp.  But, we still do
 
3486
        # want the nicer errors raised by lazy_regex.
 
3487
        name._compile_and_collapse()
 
3488
        cur_conf_id = None
 
3489
        cur_section = None
 
3490
        for c in self._get_configs(directory, scope):
 
3491
            for (oname, value, section, conf_id, parser) in c._get_options():
 
3492
                if name.search(oname):
 
3493
                    if cur_conf_id != conf_id:
 
3494
                        # Explain where the options are defined
 
3495
                        self.outf.write('%s:\n' % (conf_id,))
 
3496
                        cur_conf_id = conf_id
 
3497
                        cur_section = None
 
3498
                    if (section not in (None, 'DEFAULT')
 
3499
                        and cur_section != section):
 
3500
                        # Display the section if it's not the default (or only)
 
3501
                        # one.
 
3502
                        self.outf.write('  [%s]\n' % (section,))
 
3503
                        cur_section = section
 
3504
                    self.outf.write('  %s = %s\n' % (oname, value))
 
3505
 
 
3506
    def _set_config_option(self, name, value, directory, scope):
 
3507
        for conf in self._get_configs(directory, scope):
 
3508
            conf.set_user_option(name, value)
 
3509
            break
 
3510
        else:
 
3511
            raise errors.NoSuchConfig(scope)
 
3512
 
 
3513
    def _remove_config_option(self, name, directory, scope):
 
3514
        if name is None:
 
3515
            raise errors.BzrCommandError(
 
3516
                '--remove expects an option to remove.')
 
3517
        removed = False
 
3518
        for conf in self._get_configs(directory, scope):
 
3519
            for (section_name, section, conf_id) in conf._get_sections():
 
3520
                if scope is not None and conf_id != scope:
 
3521
                    # Not the right configuration file
 
3522
                    continue
 
3523
                if name in section:
 
3524
                    if conf_id != conf.config_id():
 
3525
                        conf = self._get_configs(directory, conf_id).next()
 
3526
                    # We use the first section in the first config where the
 
3527
                    # option is defined to remove it
 
3528
                    conf.remove_user_option(name, section_name)
 
3529
                    removed = True
 
3530
                    break
 
3531
            break
 
3532
        else:
 
3533
            raise errors.NoSuchConfig(scope)
 
3534
        if not removed:
 
3535
            raise errors.NoSuchConfigOption(name)
 
3536
 
 
3537
# Test registries
 
3538
#
 
3539
# We need adapters that can build a Store or a Stack in a test context. Test
 
3540
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
3541
# themselves. The builder will receive a test instance and should return a
 
3542
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
3543
# register themselves here to be tested against the tests defined in
 
3544
# bzrlib.tests.test_config. Note that the builder can be called multiple times
 
3545
# for the same tests.
 
3546
 
 
3547
# The registered object should be a callable receiving a test instance
 
3548
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
3549
# object.
 
3550
test_store_builder_registry = registry.Registry()
 
3551
 
 
3552
# The registered object should be a callable receiving a test instance
 
3553
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
3554
# object.
 
3555
test_stack_builder_registry = registry.Registry()