~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2011-08-17 08:40:16 UTC
  • mfrom: (5642.4.6 712474-module-available)
  • Revision ID: pqm@pqm.ubuntu.com-20110817084016-600z65qzqmmt44w7
(vila) ModuleAvailableFeature don't try to imported already imported
 modules. (Vincent Ladeuil)

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
from bzrlib.decorators import needs_write_lock
68
81
from bzrlib.lazy_import import lazy_import
69
82
lazy_import(globals(), """
70
 
import errno
71
 
from fnmatch import fnmatch
 
83
import fnmatch
72
84
import re
73
85
from cStringIO import StringIO
74
86
 
75
 
import bzrlib
76
87
from bzrlib import (
 
88
    atomicfile,
 
89
    bzrdir,
77
90
    debug,
78
91
    errors,
 
92
    lazy_regex,
 
93
    lockdir,
79
94
    mail_client,
 
95
    mergetools,
80
96
    osutils,
81
 
    registry,
82
97
    symbol_versioning,
83
98
    trace,
 
99
    transport,
84
100
    ui,
85
101
    urlutils,
86
102
    win32utils,
87
103
    )
88
104
from bzrlib.util.configobj import configobj
89
105
""")
 
106
from bzrlib import (
 
107
    commands,
 
108
    hooks,
 
109
    registry,
 
110
    )
 
111
from bzrlib.symbol_versioning import (
 
112
    deprecated_in,
 
113
    deprecated_method,
 
114
    )
90
115
 
91
116
 
92
117
CHECK_IF_POSSIBLE=0
122
147
STORE_BRANCH = 3
123
148
STORE_GLOBAL = 4
124
149
 
125
 
_ConfigObj = None
126
 
def ConfigObj(*args, **kwargs):
127
 
    global _ConfigObj
128
 
    if _ConfigObj is None:
129
 
        class ConfigObj(configobj.ConfigObj):
130
 
 
131
 
            def get_bool(self, section, key):
132
 
                return self[section].as_bool(key)
133
 
 
134
 
            def get_value(self, section, name):
135
 
                # Try [] for the old DEFAULT section.
136
 
                if section == "DEFAULT":
137
 
                    try:
138
 
                        return self[name]
139
 
                    except KeyError:
140
 
                        pass
141
 
                return self[section][name]
142
 
        _ConfigObj = ConfigObj
143
 
    return _ConfigObj(*args, **kwargs)
 
150
 
 
151
class ConfigObj(configobj.ConfigObj):
 
152
 
 
153
    def __init__(self, infile=None, **kwargs):
 
154
        # We define our own interpolation mechanism calling it option expansion
 
155
        super(ConfigObj, self).__init__(infile=infile,
 
156
                                        interpolation=False,
 
157
                                        **kwargs)
 
158
 
 
159
    def get_bool(self, section, key):
 
160
        return self[section].as_bool(key)
 
161
 
 
162
    def get_value(self, section, name):
 
163
        # Try [] for the old DEFAULT section.
 
164
        if section == "DEFAULT":
 
165
            try:
 
166
                return self[name]
 
167
            except KeyError:
 
168
                pass
 
169
        return self[section][name]
 
170
 
 
171
 
 
172
# FIXME: Until we can guarantee that each config file is loaded once and
 
173
# only once for a given bzrlib session, we don't want to re-read the file every
 
174
# time we query for an option so we cache the value (bad ! watch out for tests
 
175
# needing to restore the proper value). -- vila 20110219
 
176
_expand_default_value = None
 
177
def _get_expand_default_value():
 
178
    global _expand_default_value
 
179
    if _expand_default_value is not None:
 
180
        return _expand_default_value
 
181
    conf = GlobalConfig()
 
182
    # Note that we must not use None for the expand value below or we'll run
 
183
    # into infinite recursion. Using False really would be quite silly ;)
 
184
    expand = conf.get_user_option_as_bool('bzr.config.expand', expand=True)
 
185
    if expand is None:
 
186
        # This is an opt-in feature, you *really* need to clearly say you want
 
187
        # to activate it !
 
188
        expand = False
 
189
    _expand_default_value = expand
 
190
    return expand
144
191
 
145
192
 
146
193
class Config(object):
149
196
    def __init__(self):
150
197
        super(Config, self).__init__()
151
198
 
 
199
    def config_id(self):
 
200
        """Returns a unique ID for the config."""
 
201
        raise NotImplementedError(self.config_id)
 
202
 
 
203
    @deprecated_method(deprecated_in((2, 4, 0)))
152
204
    def get_editor(self):
153
205
        """Get the users pop up editor."""
154
206
        raise NotImplementedError
161
213
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
162
214
                                             sys.stdout)
163
215
 
164
 
 
165
216
    def get_mail_client(self):
166
217
        """Get a mail client to use"""
167
218
        selected_client = self.get_user_option('mail_client')
178
229
    def _get_signing_policy(self):
179
230
        """Template method to override signature creation policy."""
180
231
 
 
232
    option_ref_re = None
 
233
 
 
234
    def expand_options(self, string, env=None):
 
235
        """Expand option references in the string in the configuration context.
 
236
 
 
237
        :param string: The string containing option to expand.
 
238
 
 
239
        :param env: An option dict defining additional configuration options or
 
240
            overriding existing ones.
 
241
 
 
242
        :returns: The expanded string.
 
243
        """
 
244
        return self._expand_options_in_string(string, env)
 
245
 
 
246
    def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
 
247
        """Expand options in  a list of strings in the configuration context.
 
248
 
 
249
        :param slist: A list of strings.
 
250
 
 
251
        :param env: An option dict defining additional configuration options or
 
252
            overriding existing ones.
 
253
 
 
254
        :param _ref_stack: Private list containing the options being
 
255
            expanded to detect loops.
 
256
 
 
257
        :returns: The flatten list of expanded strings.
 
258
        """
 
259
        # expand options in each value separately flattening lists
 
260
        result = []
 
261
        for s in slist:
 
262
            value = self._expand_options_in_string(s, env, _ref_stack)
 
263
            if isinstance(value, list):
 
264
                result.extend(value)
 
265
            else:
 
266
                result.append(value)
 
267
        return result
 
268
 
 
269
    def _expand_options_in_string(self, string, env=None, _ref_stack=None):
 
270
        """Expand options in the string in the configuration context.
 
271
 
 
272
        :param string: The string to be expanded.
 
273
 
 
274
        :param env: An option dict defining additional configuration options or
 
275
            overriding existing ones.
 
276
 
 
277
        :param _ref_stack: Private list containing the options being
 
278
            expanded to detect loops.
 
279
 
 
280
        :returns: The expanded string.
 
281
        """
 
282
        if string is None:
 
283
            # Not much to expand there
 
284
            return None
 
285
        if _ref_stack is None:
 
286
            # What references are currently resolved (to detect loops)
 
287
            _ref_stack = []
 
288
        if self.option_ref_re is None:
 
289
            # We want to match the most embedded reference first (i.e. for
 
290
            # '{{foo}}' we will get '{foo}',
 
291
            # for '{bar{baz}}' we will get '{baz}'
 
292
            self.option_ref_re = re.compile('({[^{}]+})')
 
293
        result = string
 
294
        # We need to iterate until no more refs appear ({{foo}} will need two
 
295
        # iterations for example).
 
296
        while True:
 
297
            raw_chunks = self.option_ref_re.split(result)
 
298
            if len(raw_chunks) == 1:
 
299
                # Shorcut the trivial case: no refs
 
300
                return result
 
301
            chunks = []
 
302
            list_value = False
 
303
            # Split will isolate refs so that every other chunk is a ref
 
304
            chunk_is_ref = False
 
305
            for chunk in raw_chunks:
 
306
                if not chunk_is_ref:
 
307
                    if chunk:
 
308
                        # Keep only non-empty strings (or we get bogus empty
 
309
                        # slots when a list value is involved).
 
310
                        chunks.append(chunk)
 
311
                    chunk_is_ref = True
 
312
                else:
 
313
                    name = chunk[1:-1]
 
314
                    if name in _ref_stack:
 
315
                        raise errors.OptionExpansionLoop(string, _ref_stack)
 
316
                    _ref_stack.append(name)
 
317
                    value = self._expand_option(name, env, _ref_stack)
 
318
                    if value is None:
 
319
                        raise errors.ExpandingUnknownOption(name, string)
 
320
                    if isinstance(value, list):
 
321
                        list_value = True
 
322
                        chunks.extend(value)
 
323
                    else:
 
324
                        chunks.append(value)
 
325
                    _ref_stack.pop()
 
326
                    chunk_is_ref = False
 
327
            if list_value:
 
328
                # Once a list appears as the result of an expansion, all
 
329
                # callers will get a list result. This allows a consistent
 
330
                # behavior even when some options in the expansion chain
 
331
                # defined as strings (no comma in their value) but their
 
332
                # expanded value is a list.
 
333
                return self._expand_options_in_list(chunks, env, _ref_stack)
 
334
            else:
 
335
                result = ''.join(chunks)
 
336
        return result
 
337
 
 
338
    def _expand_option(self, name, env, _ref_stack):
 
339
        if env is not None and name in env:
 
340
            # Special case, values provided in env takes precedence over
 
341
            # anything else
 
342
            value = env[name]
 
343
        else:
 
344
            # FIXME: This is a limited implementation, what we really need is a
 
345
            # way to query the bzr config for the value of an option,
 
346
            # respecting the scope rules (That is, once we implement fallback
 
347
            # configs, getting the option value should restart from the top
 
348
            # config, not the current one) -- vila 20101222
 
349
            value = self.get_user_option(name, expand=False)
 
350
            if isinstance(value, list):
 
351
                value = self._expand_options_in_list(value, env, _ref_stack)
 
352
            else:
 
353
                value = self._expand_options_in_string(value, env, _ref_stack)
 
354
        return value
 
355
 
181
356
    def _get_user_option(self, option_name):
182
357
        """Template method to provide a user option."""
183
358
        return None
184
359
 
185
 
    def get_user_option(self, option_name):
186
 
        """Get a generic option - no special process, no default."""
187
 
        return self._get_user_option(option_name)
188
 
 
189
 
    def get_user_option_as_bool(self, option_name):
190
 
        """Get a generic option as a boolean - no special process, no default.
191
 
 
 
360
    def get_user_option(self, option_name, expand=None):
 
361
        """Get a generic option - no special process, no default.
 
362
 
 
363
        :param option_name: The queried option.
 
364
 
 
365
        :param expand: Whether options references should be expanded.
 
366
 
 
367
        :returns: The value of the option.
 
368
        """
 
369
        if expand is None:
 
370
            expand = _get_expand_default_value()
 
371
        value = self._get_user_option(option_name)
 
372
        if expand:
 
373
            if isinstance(value, list):
 
374
                value = self._expand_options_in_list(value)
 
375
            elif isinstance(value, dict):
 
376
                trace.warning('Cannot expand "%s":'
 
377
                              ' Dicts do not support option expansion'
 
378
                              % (option_name,))
 
379
            else:
 
380
                value = self._expand_options_in_string(value)
 
381
        for hook in OldConfigHooks['get']:
 
382
            hook(self, option_name, value)
 
383
        return value
 
384
 
 
385
    def get_user_option_as_bool(self, option_name, expand=None, default=None):
 
386
        """Get a generic option as a boolean.
 
387
 
 
388
        :param expand: Allow expanding references to other config values.
 
389
        :param default: Default value if nothing is configured
192
390
        :return None if the option doesn't exist or its value can't be
193
391
            interpreted as a boolean. Returns True or False otherwise.
194
392
        """
195
 
        s = self._get_user_option(option_name)
196
 
        return ui.bool_from_string(s)
 
393
        s = self.get_user_option(option_name, expand=expand)
 
394
        if s is None:
 
395
            # The option doesn't exist
 
396
            return default
 
397
        val = ui.bool_from_string(s)
 
398
        if val is None:
 
399
            # The value can't be interpreted as a boolean
 
400
            trace.warning('Value "%s" is not a boolean for "%s"',
 
401
                          s, option_name)
 
402
        return val
197
403
 
198
 
    def get_user_option_as_list(self, option_name):
 
404
    def get_user_option_as_list(self, option_name, expand=None):
199
405
        """Get a generic option as a list - no special process, no default.
200
406
 
201
407
        :return None if the option doesn't exist. Returns the value as a list
202
408
            otherwise.
203
409
        """
204
 
        l = self._get_user_option(option_name)
 
410
        l = self.get_user_option(option_name, expand=expand)
205
411
        if isinstance(l, (str, unicode)):
206
 
            # A single value, most probably the user forgot the final ','
 
412
            # A single value, most probably the user forgot (or didn't care to
 
413
            # add) the final ','
207
414
            l = [l]
208
415
        return l
209
416
 
229
436
        """See log_format()."""
230
437
        return None
231
438
 
 
439
    def validate_signatures_in_log(self):
 
440
        """Show GPG signature validity in log"""
 
441
        result = self._validate_signatures_in_log()
 
442
        if result == "true":
 
443
            result = True
 
444
        else:
 
445
            result = False
 
446
        return result
 
447
 
 
448
    def _validate_signatures_in_log(self):
 
449
        """See validate_signatures_in_log()."""
 
450
        return None
 
451
 
 
452
    def acceptable_keys(self):
 
453
        """Comma separated list of key patterns acceptable to 
 
454
        verify-signatures command"""
 
455
        result = self._acceptable_keys()
 
456
        return result
 
457
 
 
458
    def _acceptable_keys(self):
 
459
        """See acceptable_keys()."""
 
460
        return None
 
461
 
232
462
    def post_commit(self):
233
463
        """An ordered list of python functions to call.
234
464
 
249
479
 
250
480
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
251
481
 
252
 
        $BZR_EMAIL can be set to override this (as well as the
253
 
        deprecated $BZREMAIL), then
 
482
        $BZR_EMAIL can be set to override this, then
254
483
        the concrete policy type is checked, and finally
255
484
        $EMAIL is examined.
256
 
        If none is found, a reasonable default is (hopefully)
257
 
        created.
258
 
 
259
 
        TODO: Check it's reasonably well-formed.
 
485
        If no username can be found, errors.NoWhoami exception is raised.
260
486
        """
261
487
        v = os.environ.get('BZR_EMAIL')
262
488
        if v:
263
489
            return v.decode(osutils.get_user_encoding())
264
 
 
265
490
        v = self._get_user_id()
266
491
        if v:
267
492
            return v
268
 
 
269
493
        v = os.environ.get('EMAIL')
270
494
        if v:
271
495
            return v.decode(osutils.get_user_encoding())
272
 
 
273
496
        name, email = _auto_user_id()
274
 
        if name:
 
497
        if name and email:
275
498
            return '%s <%s>' % (name, email)
276
 
        else:
 
499
        elif email:
277
500
            return email
 
501
        raise errors.NoWhoami()
 
502
 
 
503
    def ensure_username(self):
 
504
        """Raise errors.NoWhoami if username is not set.
 
505
 
 
506
        This method relies on the username() function raising the error.
 
507
        """
 
508
        self.username()
278
509
 
279
510
    def signature_checking(self):
280
511
        """What is the current policy for signature checking?."""
296
527
        if policy is None:
297
528
            policy = self._get_signature_checking()
298
529
            if policy is not None:
 
530
                #this warning should go away once check_signatures is
 
531
                #implemented (if not before)
299
532
                trace.warning("Please use create_signatures,"
300
533
                              " not check_signatures to set signing policy.")
301
 
            if policy == CHECK_ALWAYS:
302
 
                return True
303
534
        elif policy == SIGN_ALWAYS:
304
535
            return True
305
536
        return False
306
537
 
 
538
    def gpg_signing_key(self):
 
539
        """GPG user-id to sign commits"""
 
540
        key = self.get_user_option('gpg_signing_key')
 
541
        if key == "default" or key == None:
 
542
            return self.user_email()
 
543
        else:
 
544
            return key
 
545
 
307
546
    def get_alias(self, value):
308
547
        return self._get_alias(value)
309
548
 
338
577
        else:
339
578
            return True
340
579
 
 
580
    def get_merge_tools(self):
 
581
        tools = {}
 
582
        for (oname, value, section, conf_id, parser) in self._get_options():
 
583
            if oname.startswith('bzr.mergetool.'):
 
584
                tool_name = oname[len('bzr.mergetool.'):]
 
585
                tools[tool_name] = value
 
586
        trace.mutter('loaded merge tools: %r' % tools)
 
587
        return tools
 
588
 
 
589
    def find_merge_tool(self, name):
 
590
        # We fake a defaults mechanism here by checking if the given name can
 
591
        # be found in the known_merge_tools if it's not found in the config.
 
592
        # This should be done through the proposed config defaults mechanism
 
593
        # when it becomes available in the future.
 
594
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
 
595
                                             expand=False)
 
596
                        or mergetools.known_merge_tools.get(name, None))
 
597
        return command_line
 
598
 
 
599
 
 
600
class _ConfigHooks(hooks.Hooks):
 
601
    """A dict mapping hook names and a list of callables for configs.
 
602
    """
 
603
 
 
604
    def __init__(self):
 
605
        """Create the default hooks.
 
606
 
 
607
        These are all empty initially, because by default nothing should get
 
608
        notified.
 
609
        """
 
610
        super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
 
611
        self.add_hook('load',
 
612
                      'Invoked when a config store is loaded.'
 
613
                      ' The signature is (store).',
 
614
                      (2, 4))
 
615
        self.add_hook('save',
 
616
                      'Invoked when a config store is saved.'
 
617
                      ' The signature is (store).',
 
618
                      (2, 4))
 
619
        # The hooks for config options
 
620
        self.add_hook('get',
 
621
                      'Invoked when a config option is read.'
 
622
                      ' The signature is (stack, name, value).',
 
623
                      (2, 4))
 
624
        self.add_hook('set',
 
625
                      'Invoked when a config option is set.'
 
626
                      ' The signature is (stack, name, value).',
 
627
                      (2, 4))
 
628
        self.add_hook('remove',
 
629
                      'Invoked when a config option is removed.'
 
630
                      ' The signature is (stack, name).',
 
631
                      (2, 4))
 
632
ConfigHooks = _ConfigHooks()
 
633
 
 
634
 
 
635
class _OldConfigHooks(hooks.Hooks):
 
636
    """A dict mapping hook names and a list of callables for configs.
 
637
    """
 
638
 
 
639
    def __init__(self):
 
640
        """Create the default hooks.
 
641
 
 
642
        These are all empty initially, because by default nothing should get
 
643
        notified.
 
644
        """
 
645
        super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
 
646
        self.add_hook('load',
 
647
                      'Invoked when a config store is loaded.'
 
648
                      ' The signature is (config).',
 
649
                      (2, 4))
 
650
        self.add_hook('save',
 
651
                      'Invoked when a config store is saved.'
 
652
                      ' The signature is (config).',
 
653
                      (2, 4))
 
654
        # The hooks for config options
 
655
        self.add_hook('get',
 
656
                      'Invoked when a config option is read.'
 
657
                      ' The signature is (config, name, value).',
 
658
                      (2, 4))
 
659
        self.add_hook('set',
 
660
                      'Invoked when a config option is set.'
 
661
                      ' The signature is (config, name, value).',
 
662
                      (2, 4))
 
663
        self.add_hook('remove',
 
664
                      'Invoked when a config option is removed.'
 
665
                      ' The signature is (config, name).',
 
666
                      (2, 4))
 
667
OldConfigHooks = _OldConfigHooks()
 
668
 
341
669
 
342
670
class IniBasedConfig(Config):
343
671
    """A configuration policy that draws from ini files."""
344
672
 
345
 
    def __init__(self, get_filename):
 
673
    def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
 
674
                 file_name=None):
 
675
        """Base class for configuration files using an ini-like syntax.
 
676
 
 
677
        :param file_name: The configuration file path.
 
678
        """
346
679
        super(IniBasedConfig, self).__init__()
347
 
        self._get_filename = get_filename
 
680
        self.file_name = file_name
 
681
        if symbol_versioning.deprecated_passed(get_filename):
 
682
            symbol_versioning.warn(
 
683
                'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
684
                ' Use file_name instead.',
 
685
                DeprecationWarning,
 
686
                stacklevel=2)
 
687
            if get_filename is not None:
 
688
                self.file_name = get_filename()
 
689
        else:
 
690
            self.file_name = file_name
 
691
        self._content = None
348
692
        self._parser = None
349
693
 
350
 
    def _get_parser(self, file=None):
 
694
    @classmethod
 
695
    def from_string(cls, str_or_unicode, file_name=None, save=False):
 
696
        """Create a config object from a string.
 
697
 
 
698
        :param str_or_unicode: A string representing the file content. This will
 
699
            be utf-8 encoded.
 
700
 
 
701
        :param file_name: The configuration file path.
 
702
 
 
703
        :param _save: Whether the file should be saved upon creation.
 
704
        """
 
705
        conf = cls(file_name=file_name)
 
706
        conf._create_from_string(str_or_unicode, save)
 
707
        return conf
 
708
 
 
709
    def _create_from_string(self, str_or_unicode, save):
 
710
        self._content = StringIO(str_or_unicode.encode('utf-8'))
 
711
        # Some tests use in-memory configs, some other always need the config
 
712
        # file to exist on disk.
 
713
        if save:
 
714
            self._write_config_file()
 
715
 
 
716
    def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
351
717
        if self._parser is not None:
352
718
            return self._parser
353
 
        if file is None:
354
 
            input = self._get_filename()
 
719
        if symbol_versioning.deprecated_passed(file):
 
720
            symbol_versioning.warn(
 
721
                'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
722
                ' Use IniBasedConfig(_content=xxx) instead.',
 
723
                DeprecationWarning,
 
724
                stacklevel=2)
 
725
        if self._content is not None:
 
726
            co_input = self._content
 
727
        elif self.file_name is None:
 
728
            raise AssertionError('We have no content to create the config')
355
729
        else:
356
 
            input = file
 
730
            co_input = self.file_name
357
731
        try:
358
 
            self._parser = ConfigObj(input, encoding='utf-8')
 
732
            self._parser = ConfigObj(co_input, encoding='utf-8')
359
733
        except configobj.ConfigObjError, e:
360
734
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
735
        except UnicodeDecodeError:
 
736
            raise errors.ConfigContentError(self.file_name)
 
737
        # Make sure self.reload() will use the right file name
 
738
        self._parser.filename = self.file_name
 
739
        for hook in OldConfigHooks['load']:
 
740
            hook(self)
361
741
        return self._parser
362
742
 
 
743
    def reload(self):
 
744
        """Reload the config file from disk."""
 
745
        if self.file_name is None:
 
746
            raise AssertionError('We need a file name to reload the config')
 
747
        if self._parser is not None:
 
748
            self._parser.reload()
 
749
        for hook in ConfigHooks['load']:
 
750
            hook(self)
 
751
 
363
752
    def _get_matching_sections(self):
364
753
        """Return an ordered list of (section_name, extra_path) pairs.
365
754
 
376
765
        """Override this to define the section used by the config."""
377
766
        return "DEFAULT"
378
767
 
 
768
    def _get_sections(self, name=None):
 
769
        """Returns an iterator of the sections specified by ``name``.
 
770
 
 
771
        :param name: The section name. If None is supplied, the default
 
772
            configurations are yielded.
 
773
 
 
774
        :return: A tuple (name, section, config_id) for all sections that will
 
775
            be walked by user_get_option() in the 'right' order. The first one
 
776
            is where set_user_option() will update the value.
 
777
        """
 
778
        parser = self._get_parser()
 
779
        if name is not None:
 
780
            yield (name, parser[name], self.config_id())
 
781
        else:
 
782
            # No section name has been given so we fallback to the configobj
 
783
            # itself which holds the variables defined outside of any section.
 
784
            yield (None, parser, self.config_id())
 
785
 
 
786
    def _get_options(self, sections=None):
 
787
        """Return an ordered list of (name, value, section, config_id) tuples.
 
788
 
 
789
        All options are returned with their associated value and the section
 
790
        they appeared in. ``config_id`` is a unique identifier for the
 
791
        configuration file the option is defined in.
 
792
 
 
793
        :param sections: Default to ``_get_matching_sections`` if not
 
794
            specified. This gives a better control to daughter classes about
 
795
            which sections should be searched. This is a list of (name,
 
796
            configobj) tuples.
 
797
        """
 
798
        opts = []
 
799
        if sections is None:
 
800
            parser = self._get_parser()
 
801
            sections = []
 
802
            for (section_name, _) in self._get_matching_sections():
 
803
                try:
 
804
                    section = parser[section_name]
 
805
                except KeyError:
 
806
                    # This could happen for an empty file for which we define a
 
807
                    # DEFAULT section. FIXME: Force callers to provide sections
 
808
                    # instead ? -- vila 20100930
 
809
                    continue
 
810
                sections.append((section_name, section))
 
811
        config_id = self.config_id()
 
812
        for (section_name, section) in sections:
 
813
            for (name, value) in section.iteritems():
 
814
                yield (name, parser._quote(value), section_name,
 
815
                       config_id, parser)
 
816
 
379
817
    def _get_option_policy(self, section, option_name):
380
818
        """Return the policy for the given (section, option_name) pair."""
381
819
        return POLICY_NONE
432
870
        """See Config.log_format."""
433
871
        return self._get_user_option('log_format')
434
872
 
 
873
    def _validate_signatures_in_log(self):
 
874
        """See Config.validate_signatures_in_log."""
 
875
        return self._get_user_option('validate_signatures_in_log')
 
876
 
 
877
    def _acceptable_keys(self):
 
878
        """See Config.acceptable_keys."""
 
879
        return self._get_user_option('acceptable_keys')
 
880
 
435
881
    def _post_commit(self):
436
882
        """See Config.post_commit."""
437
883
        return self._get_user_option('post_commit')
468
914
    def _get_nickname(self):
469
915
        return self.get_user_option('nickname')
470
916
 
471
 
 
472
 
class GlobalConfig(IniBasedConfig):
 
917
    def remove_user_option(self, option_name, section_name=None):
 
918
        """Remove a user option and save the configuration file.
 
919
 
 
920
        :param option_name: The option to be removed.
 
921
 
 
922
        :param section_name: The section the option is defined in, default to
 
923
            the default section.
 
924
        """
 
925
        self.reload()
 
926
        parser = self._get_parser()
 
927
        if section_name is None:
 
928
            section = parser
 
929
        else:
 
930
            section = parser[section_name]
 
931
        try:
 
932
            del section[option_name]
 
933
        except KeyError:
 
934
            raise errors.NoSuchConfigOption(option_name)
 
935
        self._write_config_file()
 
936
        for hook in OldConfigHooks['remove']:
 
937
            hook(self, option_name)
 
938
 
 
939
    def _write_config_file(self):
 
940
        if self.file_name is None:
 
941
            raise AssertionError('We cannot save, self.file_name is None')
 
942
        conf_dir = os.path.dirname(self.file_name)
 
943
        ensure_config_dir_exists(conf_dir)
 
944
        atomic_file = atomicfile.AtomicFile(self.file_name)
 
945
        self._get_parser().write(atomic_file)
 
946
        atomic_file.commit()
 
947
        atomic_file.close()
 
948
        osutils.copy_ownership_from_path(self.file_name)
 
949
        for hook in OldConfigHooks['save']:
 
950
            hook(self)
 
951
 
 
952
 
 
953
class LockableConfig(IniBasedConfig):
 
954
    """A configuration needing explicit locking for access.
 
955
 
 
956
    If several processes try to write the config file, the accesses need to be
 
957
    serialized.
 
958
 
 
959
    Daughter classes should decorate all methods that update a config with the
 
960
    ``@needs_write_lock`` decorator (they call, directly or indirectly, the
 
961
    ``_write_config_file()`` method. These methods (typically ``set_option()``
 
962
    and variants must reload the config file from disk before calling
 
963
    ``_write_config_file()``), this can be achieved by calling the
 
964
    ``self.reload()`` method. Note that the lock scope should cover both the
 
965
    reading and the writing of the config file which is why the decorator can't
 
966
    be applied to ``_write_config_file()`` only.
 
967
 
 
968
    This should be enough to implement the following logic:
 
969
    - lock for exclusive write access,
 
970
    - reload the config file from disk,
 
971
    - set the new value
 
972
    - unlock
 
973
 
 
974
    This logic guarantees that a writer can update a value without erasing an
 
975
    update made by another writer.
 
976
    """
 
977
 
 
978
    lock_name = 'lock'
 
979
 
 
980
    def __init__(self, file_name):
 
981
        super(LockableConfig, self).__init__(file_name=file_name)
 
982
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
 
983
        # FIXME: It doesn't matter that we don't provide possible_transports
 
984
        # below since this is currently used only for local config files ;
 
985
        # local transports are not shared. But if/when we start using
 
986
        # LockableConfig for other kind of transports, we will need to reuse
 
987
        # whatever connection is already established -- vila 20100929
 
988
        self.transport = transport.get_transport(self.dir)
 
989
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
 
990
 
 
991
    def _create_from_string(self, unicode_bytes, save):
 
992
        super(LockableConfig, self)._create_from_string(unicode_bytes, False)
 
993
        if save:
 
994
            # We need to handle the saving here (as opposed to IniBasedConfig)
 
995
            # to be able to lock
 
996
            self.lock_write()
 
997
            self._write_config_file()
 
998
            self.unlock()
 
999
 
 
1000
    def lock_write(self, token=None):
 
1001
        """Takes a write lock in the directory containing the config file.
 
1002
 
 
1003
        If the directory doesn't exist it is created.
 
1004
        """
 
1005
        ensure_config_dir_exists(self.dir)
 
1006
        return self._lock.lock_write(token)
 
1007
 
 
1008
    def unlock(self):
 
1009
        self._lock.unlock()
 
1010
 
 
1011
    def break_lock(self):
 
1012
        self._lock.break_lock()
 
1013
 
 
1014
    @needs_write_lock
 
1015
    def remove_user_option(self, option_name, section_name=None):
 
1016
        super(LockableConfig, self).remove_user_option(option_name,
 
1017
                                                       section_name)
 
1018
 
 
1019
    def _write_config_file(self):
 
1020
        if self._lock is None or not self._lock.is_held:
 
1021
            # NB: if the following exception is raised it probably means a
 
1022
            # missing @needs_write_lock decorator on one of the callers.
 
1023
            raise errors.ObjectNotLocked(self)
 
1024
        super(LockableConfig, self)._write_config_file()
 
1025
 
 
1026
 
 
1027
class GlobalConfig(LockableConfig):
473
1028
    """The configuration that should be used for a specific location."""
474
1029
 
 
1030
    def __init__(self):
 
1031
        super(GlobalConfig, self).__init__(file_name=config_filename())
 
1032
 
 
1033
    def config_id(self):
 
1034
        return 'bazaar'
 
1035
 
 
1036
    @classmethod
 
1037
    def from_string(cls, str_or_unicode, save=False):
 
1038
        """Create a config object from a string.
 
1039
 
 
1040
        :param str_or_unicode: A string representing the file content. This
 
1041
            will be utf-8 encoded.
 
1042
 
 
1043
        :param save: Whether the file should be saved upon creation.
 
1044
        """
 
1045
        conf = cls()
 
1046
        conf._create_from_string(str_or_unicode, save)
 
1047
        return conf
 
1048
 
 
1049
    @deprecated_method(deprecated_in((2, 4, 0)))
475
1050
    def get_editor(self):
476
1051
        return self._get_user_option('editor')
477
1052
 
478
 
    def __init__(self):
479
 
        super(GlobalConfig, self).__init__(config_filename)
480
 
 
 
1053
    @needs_write_lock
481
1054
    def set_user_option(self, option, value):
482
1055
        """Save option and its value in the configuration."""
483
1056
        self._set_option(option, value, 'DEFAULT')
489
1062
        else:
490
1063
            return {}
491
1064
 
 
1065
    @needs_write_lock
492
1066
    def set_alias(self, alias_name, alias_command):
493
1067
        """Save the alias in the configuration."""
494
1068
        self._set_option(alias_name, alias_command, 'ALIASES')
495
1069
 
 
1070
    @needs_write_lock
496
1071
    def unset_alias(self, alias_name):
497
1072
        """Unset an existing alias."""
 
1073
        self.reload()
498
1074
        aliases = self._get_parser().get('ALIASES')
499
1075
        if not aliases or alias_name not in aliases:
500
1076
            raise errors.NoSuchAlias(alias_name)
502
1078
        self._write_config_file()
503
1079
 
504
1080
    def _set_option(self, option, value, section):
505
 
        # FIXME: RBC 20051029 This should refresh the parser and also take a
506
 
        # file lock on bazaar.conf.
507
 
        conf_dir = os.path.dirname(self._get_filename())
508
 
        ensure_config_dir_exists(conf_dir)
 
1081
        self.reload()
509
1082
        self._get_parser().setdefault(section, {})[option] = value
510
1083
        self._write_config_file()
511
 
 
512
 
    def _write_config_file(self):
513
 
        f = open(self._get_filename(), 'wb')
514
 
        self._get_parser().write(f)
515
 
        f.close()
516
 
 
517
 
 
518
 
class LocationConfig(IniBasedConfig):
 
1084
        for hook in OldConfigHooks['set']:
 
1085
            hook(self, option, value)
 
1086
 
 
1087
    def _get_sections(self, name=None):
 
1088
        """See IniBasedConfig._get_sections()."""
 
1089
        parser = self._get_parser()
 
1090
        # We don't give access to options defined outside of any section, we
 
1091
        # used the DEFAULT section by... default.
 
1092
        if name in (None, 'DEFAULT'):
 
1093
            # This could happen for an empty file where the DEFAULT section
 
1094
            # doesn't exist yet. So we force DEFAULT when yielding
 
1095
            name = 'DEFAULT'
 
1096
            if 'DEFAULT' not in parser:
 
1097
               parser['DEFAULT']= {}
 
1098
        yield (name, parser[name], self.config_id())
 
1099
 
 
1100
    @needs_write_lock
 
1101
    def remove_user_option(self, option_name, section_name=None):
 
1102
        if section_name is None:
 
1103
            # We need to force the default section.
 
1104
            section_name = 'DEFAULT'
 
1105
        # We need to avoid the LockableConfig implementation or we'll lock
 
1106
        # twice
 
1107
        super(LockableConfig, self).remove_user_option(option_name,
 
1108
                                                       section_name)
 
1109
 
 
1110
def _iter_for_location_by_parts(sections, location):
 
1111
    """Keep only the sessions matching the specified location.
 
1112
 
 
1113
    :param sections: An iterable of section names.
 
1114
 
 
1115
    :param location: An url or a local path to match against.
 
1116
 
 
1117
    :returns: An iterator of (section, extra_path, nb_parts) where nb is the
 
1118
        number of path components in the section name, section is the section
 
1119
        name and extra_path is the difference between location and the section
 
1120
        name.
 
1121
 
 
1122
    ``location`` will always be a local path and never a 'file://' url but the
 
1123
    section names themselves can be in either form.
 
1124
    """
 
1125
    location_parts = location.rstrip('/').split('/')
 
1126
 
 
1127
    for section in sections:
 
1128
        # location is a local path if possible, so we need to convert 'file://'
 
1129
        # urls in section names to local paths if necessary.
 
1130
 
 
1131
        # This also avoids having file:///path be a more exact
 
1132
        # match than '/path'.
 
1133
 
 
1134
        # FIXME: This still raises an issue if a user defines both file:///path
 
1135
        # *and* /path. Should we raise an error in this case -- vila 20110505
 
1136
 
 
1137
        if section.startswith('file://'):
 
1138
            section_path = urlutils.local_path_from_url(section)
 
1139
        else:
 
1140
            section_path = section
 
1141
        section_parts = section_path.rstrip('/').split('/')
 
1142
 
 
1143
        matched = True
 
1144
        if len(section_parts) > len(location_parts):
 
1145
            # More path components in the section, they can't match
 
1146
            matched = False
 
1147
        else:
 
1148
            # Rely on zip truncating in length to the length of the shortest
 
1149
            # argument sequence.
 
1150
            names = zip(location_parts, section_parts)
 
1151
            for name in names:
 
1152
                if not fnmatch.fnmatch(name[0], name[1]):
 
1153
                    matched = False
 
1154
                    break
 
1155
        if not matched:
 
1156
            continue
 
1157
        # build the path difference between the section and the location
 
1158
        extra_path = '/'.join(location_parts[len(section_parts):])
 
1159
        yield section, extra_path, len(section_parts)
 
1160
 
 
1161
 
 
1162
class LocationConfig(LockableConfig):
519
1163
    """A configuration object that gives the policy for a location."""
520
1164
 
521
1165
    def __init__(self, location):
522
 
        name_generator = locations_config_filename
523
 
        if (not os.path.exists(name_generator()) and
524
 
                os.path.exists(branches_config_filename())):
525
 
            if sys.platform == 'win32':
526
 
                trace.warning('Please rename %s to %s'
527
 
                              % (branches_config_filename(),
528
 
                                 locations_config_filename()))
529
 
            else:
530
 
                trace.warning('Please rename ~/.bazaar/branches.conf'
531
 
                              ' to ~/.bazaar/locations.conf')
532
 
            name_generator = branches_config_filename
533
 
        super(LocationConfig, self).__init__(name_generator)
 
1166
        super(LocationConfig, self).__init__(
 
1167
            file_name=locations_config_filename())
534
1168
        # local file locations are looked up by local path, rather than
535
1169
        # by file url. This is because the config file is a user
536
1170
        # file, and we would rather not expose the user to file urls.
538
1172
            location = urlutils.local_path_from_url(location)
539
1173
        self.location = location
540
1174
 
 
1175
    def config_id(self):
 
1176
        return 'locations'
 
1177
 
 
1178
    @classmethod
 
1179
    def from_string(cls, str_or_unicode, location, save=False):
 
1180
        """Create a config object from a string.
 
1181
 
 
1182
        :param str_or_unicode: A string representing the file content. This will
 
1183
            be utf-8 encoded.
 
1184
 
 
1185
        :param location: The location url to filter the configuration.
 
1186
 
 
1187
        :param save: Whether the file should be saved upon creation.
 
1188
        """
 
1189
        conf = cls(location)
 
1190
        conf._create_from_string(str_or_unicode, save)
 
1191
        return conf
 
1192
 
541
1193
    def _get_matching_sections(self):
542
1194
        """Return an ordered list of section names matching this location."""
543
 
        sections = self._get_parser()
544
 
        location_names = self.location.split('/')
545
 
        if self.location.endswith('/'):
546
 
            del location_names[-1]
547
 
        matches=[]
548
 
        for section in sections:
549
 
            # location is a local path if possible, so we need
550
 
            # to convert 'file://' urls to local paths if necessary.
551
 
            # This also avoids having file:///path be a more exact
552
 
            # match than '/path'.
553
 
            if section.startswith('file://'):
554
 
                section_path = urlutils.local_path_from_url(section)
555
 
            else:
556
 
                section_path = section
557
 
            section_names = section_path.split('/')
558
 
            if section.endswith('/'):
559
 
                del section_names[-1]
560
 
            names = zip(location_names, section_names)
561
 
            matched = True
562
 
            for name in names:
563
 
                if not fnmatch(name[0], name[1]):
564
 
                    matched = False
565
 
                    break
566
 
            if not matched:
567
 
                continue
568
 
            # so, for the common prefix they matched.
569
 
            # if section is longer, no match.
570
 
            if len(section_names) > len(location_names):
571
 
                continue
572
 
            matches.append((len(section_names), section,
573
 
                            '/'.join(location_names[len(section_names):])))
574
 
        matches.sort(reverse=True)
575
 
        sections = []
576
 
        for (length, section, extra_path) in matches:
577
 
            sections.append((section, extra_path))
 
1195
        matches = list(_iter_for_location_by_parts(self._get_parser(),
 
1196
                                                   self.location))
 
1197
        # put the longest (aka more specific) locations first
 
1198
        matches.sort(
 
1199
            key=lambda (section, extra_path, length): (length, section),
 
1200
            reverse=True)
 
1201
        for (section, extra_path, length) in matches:
 
1202
            yield section, extra_path
578
1203
            # should we stop looking for parent configs here?
579
1204
            try:
580
1205
                if self._get_parser()[section].as_bool('ignore_parents'):
581
1206
                    break
582
1207
            except KeyError:
583
1208
                pass
584
 
        return sections
 
1209
 
 
1210
    def _get_sections(self, name=None):
 
1211
        """See IniBasedConfig._get_sections()."""
 
1212
        # We ignore the name here as the only sections handled are named with
 
1213
        # the location path and we don't expose embedded sections either.
 
1214
        parser = self._get_parser()
 
1215
        for name, extra_path in self._get_matching_sections():
 
1216
            yield (name, parser[name], self.config_id())
585
1217
 
586
1218
    def _get_option_policy(self, section, option_name):
587
1219
        """Return the policy for the given (section, option_name) pair."""
631
1263
            if policy_key in self._get_parser()[section]:
632
1264
                del self._get_parser()[section][policy_key]
633
1265
 
 
1266
    @needs_write_lock
634
1267
    def set_user_option(self, option, value, store=STORE_LOCATION):
635
1268
        """Save option and its value in the configuration."""
636
1269
        if store not in [STORE_LOCATION,
638
1271
                         STORE_LOCATION_APPENDPATH]:
639
1272
            raise ValueError('bad storage policy %r for %r' %
640
1273
                (store, option))
641
 
        # FIXME: RBC 20051029 This should refresh the parser and also take a
642
 
        # file lock on locations.conf.
643
 
        conf_dir = os.path.dirname(self._get_filename())
644
 
        ensure_config_dir_exists(conf_dir)
 
1274
        self.reload()
645
1275
        location = self.location
646
1276
        if location.endswith('/'):
647
1277
            location = location[:-1]
648
 
        if (not location in self._get_parser() and
649
 
            not location + '/' in self._get_parser()):
650
 
            self._get_parser()[location]={}
651
 
        elif location + '/' in self._get_parser():
 
1278
        parser = self._get_parser()
 
1279
        if not location in parser and not location + '/' in parser:
 
1280
            parser[location] = {}
 
1281
        elif location + '/' in parser:
652
1282
            location = location + '/'
653
 
        self._get_parser()[location][option]=value
 
1283
        parser[location][option]=value
654
1284
        # the allowed values of store match the config policies
655
1285
        self._set_option_policy(location, option, store)
656
 
        self._get_parser().write(file(self._get_filename(), 'wb'))
 
1286
        self._write_config_file()
 
1287
        for hook in OldConfigHooks['set']:
 
1288
            hook(self, option, value)
657
1289
 
658
1290
 
659
1291
class BranchConfig(Config):
660
1292
    """A configuration object giving the policy for a branch."""
661
1293
 
 
1294
    def __init__(self, branch):
 
1295
        super(BranchConfig, self).__init__()
 
1296
        self._location_config = None
 
1297
        self._branch_data_config = None
 
1298
        self._global_config = None
 
1299
        self.branch = branch
 
1300
        self.option_sources = (self._get_location_config,
 
1301
                               self._get_branch_data_config,
 
1302
                               self._get_global_config)
 
1303
 
 
1304
    def config_id(self):
 
1305
        return 'branch'
 
1306
 
662
1307
    def _get_branch_data_config(self):
663
1308
        if self._branch_data_config is None:
664
1309
            self._branch_data_config = TreeConfig(self.branch)
 
1310
            self._branch_data_config.config_id = self.config_id
665
1311
        return self._branch_data_config
666
1312
 
667
1313
    def _get_location_config(self):
735
1381
                return value
736
1382
        return None
737
1383
 
 
1384
    def _get_sections(self, name=None):
 
1385
        """See IniBasedConfig.get_sections()."""
 
1386
        for source in self.option_sources:
 
1387
            for section in source()._get_sections(name):
 
1388
                yield section
 
1389
 
 
1390
    def _get_options(self, sections=None):
 
1391
        opts = []
 
1392
        # First the locations options
 
1393
        for option in self._get_location_config()._get_options():
 
1394
            yield option
 
1395
        # Then the branch options
 
1396
        branch_config = self._get_branch_data_config()
 
1397
        if sections is None:
 
1398
            sections = [('DEFAULT', branch_config._get_parser())]
 
1399
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
 
1400
        # Config itself has no notion of sections :( -- vila 20101001
 
1401
        config_id = self.config_id()
 
1402
        for (section_name, section) in sections:
 
1403
            for (name, value) in section.iteritems():
 
1404
                yield (name, value, section_name,
 
1405
                       config_id, branch_config._get_parser())
 
1406
        # Then the global options
 
1407
        for option in self._get_global_config()._get_options():
 
1408
            yield option
 
1409
 
738
1410
    def set_user_option(self, name, value, store=STORE_BRANCH,
739
1411
        warn_masked=False):
740
1412
        if store == STORE_BRANCH:
758
1430
                        trace.warning('Value "%s" is masked by "%s" from'
759
1431
                                      ' branch.conf', value, mask_value)
760
1432
 
 
1433
    def remove_user_option(self, option_name, section_name=None):
 
1434
        self._get_branch_data_config().remove_option(option_name, section_name)
 
1435
 
761
1436
    def _gpg_signing_command(self):
762
1437
        """See Config.gpg_signing_command."""
763
1438
        return self._get_safe_value('_gpg_signing_command')
764
1439
 
765
 
    def __init__(self, branch):
766
 
        super(BranchConfig, self).__init__()
767
 
        self._location_config = None
768
 
        self._branch_data_config = None
769
 
        self._global_config = None
770
 
        self.branch = branch
771
 
        self.option_sources = (self._get_location_config,
772
 
                               self._get_branch_data_config,
773
 
                               self._get_global_config)
774
 
 
775
1440
    def _post_commit(self):
776
1441
        """See Config.post_commit."""
777
1442
        return self._get_safe_value('_post_commit')
793
1458
        """See Config.log_format."""
794
1459
        return self._get_best_value('_log_format')
795
1460
 
 
1461
    def _validate_signatures_in_log(self):
 
1462
        """See Config.validate_signatures_in_log."""
 
1463
        return self._get_best_value('_validate_signatures_in_log')
 
1464
 
 
1465
    def _acceptable_keys(self):
 
1466
        """See Config.acceptable_keys."""
 
1467
        return self._get_best_value('_acceptable_keys')
 
1468
 
796
1469
 
797
1470
def ensure_config_dir_exists(path=None):
798
1471
    """Make sure a configuration directory exists.
807
1480
            parent_dir = os.path.dirname(path)
808
1481
            if not os.path.isdir(parent_dir):
809
1482
                trace.mutter('creating config parent directory: %r', parent_dir)
810
 
            os.mkdir(parent_dir)
 
1483
                os.mkdir(parent_dir)
811
1484
        trace.mutter('creating config directory: %r', path)
812
1485
        os.mkdir(path)
 
1486
        osutils.copy_ownership_from_path(path)
813
1487
 
814
1488
 
815
1489
def config_dir():
816
1490
    """Return per-user configuration directory.
817
1491
 
818
 
    By default this is ~/.bazaar/
 
1492
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
 
1493
    and Linux.  On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
 
1494
    that will be used instead.
819
1495
 
820
1496
    TODO: Global option --config-dir to override this.
821
1497
    """
822
1498
    base = os.environ.get('BZR_HOME', None)
823
1499
    if sys.platform == 'win32':
 
1500
        # environ variables on Windows are in user encoding/mbcs. So decode
 
1501
        # before using one
 
1502
        if base is not None:
 
1503
            base = base.decode('mbcs')
824
1504
        if base is None:
825
1505
            base = win32utils.get_appdata_location_unicode()
826
1506
        if base is None:
827
1507
            base = os.environ.get('HOME', None)
 
1508
            if base is not None:
 
1509
                base = base.decode('mbcs')
828
1510
        if base is None:
829
1511
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
830
1512
                                  ' or HOME set')
831
1513
        return osutils.pathjoin(base, 'bazaar', '2.0')
832
1514
    else:
833
 
        # cygwin, linux, and darwin all have a $HOME directory
834
 
        if base is None:
 
1515
        if base is not None:
 
1516
            base = base.decode(osutils._fs_enc)
 
1517
    if sys.platform == 'darwin':
 
1518
        if base is None:
 
1519
            # this takes into account $HOME
 
1520
            base = os.path.expanduser("~")
 
1521
        return osutils.pathjoin(base, '.bazaar')
 
1522
    else:
 
1523
        if base is None:
 
1524
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
 
1525
            if xdg_dir is None:
 
1526
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
 
1527
            xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
 
1528
            if osutils.isdir(xdg_dir):
 
1529
                trace.mutter(
 
1530
                    "Using configuration in XDG directory %s." % xdg_dir)
 
1531
                return xdg_dir
835
1532
            base = os.path.expanduser("~")
836
1533
        return osutils.pathjoin(base, ".bazaar")
837
1534
 
841
1538
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
842
1539
 
843
1540
 
844
 
def branches_config_filename():
845
 
    """Return per-user configuration ini file filename."""
846
 
    return osutils.pathjoin(config_dir(), 'branches.conf')
847
 
 
848
 
 
849
1541
def locations_config_filename():
850
1542
    """Return per-user configuration ini file filename."""
851
1543
    return osutils.pathjoin(config_dir(), 'locations.conf')
888
1580
        return os.path.expanduser('~/.cache')
889
1581
 
890
1582
 
 
1583
def _get_default_mail_domain():
 
1584
    """If possible, return the assumed default email domain.
 
1585
 
 
1586
    :returns: string mail domain, or None.
 
1587
    """
 
1588
    if sys.platform == 'win32':
 
1589
        # No implementation yet; patches welcome
 
1590
        return None
 
1591
    try:
 
1592
        f = open('/etc/mailname')
 
1593
    except (IOError, OSError), e:
 
1594
        return None
 
1595
    try:
 
1596
        domain = f.read().strip()
 
1597
        return domain
 
1598
    finally:
 
1599
        f.close()
 
1600
 
 
1601
 
891
1602
def _auto_user_id():
892
1603
    """Calculate automatic user identification.
893
1604
 
894
 
    Returns (realname, email).
 
1605
    :returns: (realname, email), either of which may be None if they can't be
 
1606
    determined.
895
1607
 
896
1608
    Only used when none is set in the environment or the id file.
897
1609
 
898
 
    This previously used the FQDN as the default domain, but that can
899
 
    be very slow on machines where DNS is broken.  So now we simply
900
 
    use the hostname.
 
1610
    This only returns an email address if we can be fairly sure the 
 
1611
    address is reasonable, ie if /etc/mailname is set on unix.
 
1612
 
 
1613
    This doesn't use the FQDN as the default domain because that may be 
 
1614
    slow, and it doesn't use the hostname alone because that's not normally 
 
1615
    a reasonable address.
901
1616
    """
902
 
    import socket
903
 
 
904
1617
    if sys.platform == 'win32':
905
 
        name = win32utils.get_user_name_unicode()
906
 
        if name is None:
907
 
            raise errors.BzrError("Cannot autodetect user name.\n"
908
 
                                  "Please, set your name with command like:\n"
909
 
                                  'bzr whoami "Your Name <name@domain.com>"')
910
 
        host = win32utils.get_host_name_unicode()
911
 
        if host is None:
912
 
            host = socket.gethostname()
913
 
        return name, (name + '@' + host)
914
 
 
915
 
    try:
916
 
        import pwd
917
 
        uid = os.getuid()
918
 
        try:
919
 
            w = pwd.getpwuid(uid)
920
 
        except KeyError:
921
 
            raise errors.BzrCommandError('Unable to determine your name.  '
922
 
                'Please use "bzr whoami" to set it.')
923
 
 
924
 
        # we try utf-8 first, because on many variants (like Linux),
925
 
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
926
 
        # false positives.  (many users will have their user encoding set to
927
 
        # latin-1, which cannot raise UnicodeError.)
928
 
        try:
929
 
            gecos = w.pw_gecos.decode('utf-8')
930
 
            encoding = 'utf-8'
931
 
        except UnicodeError:
932
 
            try:
933
 
                encoding = osutils.get_user_encoding()
934
 
                gecos = w.pw_gecos.decode(encoding)
935
 
            except UnicodeError:
936
 
                raise errors.BzrCommandError('Unable to determine your name.  '
937
 
                   'Use "bzr whoami" to set it.')
938
 
        try:
939
 
            username = w.pw_name.decode(encoding)
940
 
        except UnicodeError:
941
 
            raise errors.BzrCommandError('Unable to determine your name.  '
942
 
                'Use "bzr whoami" to set it.')
943
 
 
944
 
        comma = gecos.find(',')
945
 
        if comma == -1:
946
 
            realname = gecos
947
 
        else:
948
 
            realname = gecos[:comma]
949
 
        if not realname:
950
 
            realname = username
951
 
 
952
 
    except ImportError:
953
 
        import getpass
954
 
        try:
955
 
            user_encoding = osutils.get_user_encoding()
956
 
            realname = username = getpass.getuser().decode(user_encoding)
957
 
        except UnicodeDecodeError:
958
 
            raise errors.BzrError("Can't decode username as %s." % \
959
 
                    user_encoding)
960
 
 
961
 
    return realname, (username + '@' + socket.gethostname())
 
1618
        # No implementation to reliably determine Windows default mail
 
1619
        # address; please add one.
 
1620
        return None, None
 
1621
 
 
1622
    default_mail_domain = _get_default_mail_domain()
 
1623
    if not default_mail_domain:
 
1624
        return None, None
 
1625
 
 
1626
    import pwd
 
1627
    uid = os.getuid()
 
1628
    try:
 
1629
        w = pwd.getpwuid(uid)
 
1630
    except KeyError:
 
1631
        trace.mutter('no passwd entry for uid %d?' % uid)
 
1632
        return None, None
 
1633
 
 
1634
    # we try utf-8 first, because on many variants (like Linux),
 
1635
    # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
1636
    # false positives.  (many users will have their user encoding set to
 
1637
    # latin-1, which cannot raise UnicodeError.)
 
1638
    try:
 
1639
        gecos = w.pw_gecos.decode('utf-8')
 
1640
        encoding = 'utf-8'
 
1641
    except UnicodeError:
 
1642
        try:
 
1643
            encoding = osutils.get_user_encoding()
 
1644
            gecos = w.pw_gecos.decode(encoding)
 
1645
        except UnicodeError, e:
 
1646
            trace.mutter("cannot decode passwd entry %s" % w)
 
1647
            return None, None
 
1648
    try:
 
1649
        username = w.pw_name.decode(encoding)
 
1650
    except UnicodeError, e:
 
1651
        trace.mutter("cannot decode passwd entry %s" % w)
 
1652
        return None, None
 
1653
 
 
1654
    comma = gecos.find(',')
 
1655
    if comma == -1:
 
1656
        realname = gecos
 
1657
    else:
 
1658
        realname = gecos[:comma]
 
1659
 
 
1660
    return realname, (username + '@' + default_mail_domain)
962
1661
 
963
1662
 
964
1663
def parse_username(username):
1009
1708
 
1010
1709
    def set_option(self, value, name, section=None):
1011
1710
        """Set a per-branch configuration option"""
 
1711
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1712
        # higher levels providing the right lock -- vila 20101004
1012
1713
        self.branch.lock_write()
1013
1714
        try:
1014
1715
            self._config.set_option(value, name, section)
1015
1716
        finally:
1016
1717
            self.branch.unlock()
1017
1718
 
 
1719
    def remove_option(self, option_name, section_name=None):
 
1720
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1721
        # higher levels providing the right lock -- vila 20101004
 
1722
        self.branch.lock_write()
 
1723
        try:
 
1724
            self._config.remove_option(option_name, section_name)
 
1725
        finally:
 
1726
            self.branch.unlock()
 
1727
 
1018
1728
 
1019
1729
class AuthenticationConfig(object):
1020
1730
    """The authentication configuration file based on a ini file.
1046
1756
            self._config = ConfigObj(self._input, encoding='utf-8')
1047
1757
        except configobj.ConfigObjError, e:
1048
1758
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
1759
        except UnicodeError:
 
1760
            raise errors.ConfigContentError(self._filename)
1049
1761
        return self._config
1050
1762
 
1051
1763
    def _save(self):
1052
1764
        """Save the config file, only tests should use it for now."""
1053
1765
        conf_dir = os.path.dirname(self._filename)
1054
1766
        ensure_config_dir_exists(conf_dir)
1055
 
        self._get_config().write(file(self._filename, 'wb'))
 
1767
        f = file(self._filename, 'wb')
 
1768
        try:
 
1769
            self._get_config().write(f)
 
1770
        finally:
 
1771
            f.close()
1056
1772
 
1057
1773
    def _set_option(self, section_name, option_name, value):
1058
1774
        """Set an authentication configuration option"""
1064
1780
        section[option_name] = value
1065
1781
        self._save()
1066
1782
 
1067
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
 
1783
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
1068
1784
                        realm=None):
1069
1785
        """Returns the matching credentials from authentication.conf file.
1070
1786
 
1238
1954
            if ask:
1239
1955
                if prompt is None:
1240
1956
                    # Create a default prompt suitable for most cases
1241
 
                    prompt = scheme.upper() + ' %(host)s username'
 
1957
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
1242
1958
                # Special handling for optional fields in the prompt
1243
1959
                if port is not None:
1244
1960
                    prompt_host = '%s:%d' % (host, port)
1282
1998
        if password is None:
1283
1999
            if prompt is None:
1284
2000
                # Create a default prompt suitable for most cases
1285
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
2001
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
1286
2002
            # Special handling for optional fields in the prompt
1287
2003
            if port is not None:
1288
2004
                prompt_host = '%s:%d' % (host, port)
1406
2122
 
1407
2123
 
1408
2124
class PlainTextCredentialStore(CredentialStore):
1409
 
    """Plain text credential store for the authentication.conf file."""
 
2125
    __doc__ = """Plain text credential store for the authentication.conf file"""
1410
2126
 
1411
2127
    def decode_password(self, credentials):
1412
2128
        """See CredentialStore.decode_password."""
1459
2175
    """A Config that reads/writes a config file on a Transport.
1460
2176
 
1461
2177
    It is a low-level object that considers config data to be name/value pairs
1462
 
    that may be associated with a section.  Assigning meaning to the these
1463
 
    values is done at higher levels like TreeConfig.
 
2178
    that may be associated with a section.  Assigning meaning to these values
 
2179
    is done at higher levels like TreeConfig.
1464
2180
    """
1465
2181
 
1466
2182
    def __init__(self, transport, filename):
1483
2199
                section_obj = configobj[section]
1484
2200
            except KeyError:
1485
2201
                return default
1486
 
        return section_obj.get(name, default)
 
2202
        value = section_obj.get(name, default)
 
2203
        for hook in OldConfigHooks['get']:
 
2204
            hook(self, name, value)
 
2205
        return value
1487
2206
 
1488
2207
    def set_option(self, value, name, section=None):
1489
2208
        """Set the value associated with a named option.
1497
2216
            configobj[name] = value
1498
2217
        else:
1499
2218
            configobj.setdefault(section, {})[name] = value
 
2219
        for hook in OldConfigHooks['set']:
 
2220
            hook(self, name, value)
 
2221
        self._set_configobj(configobj)
 
2222
 
 
2223
    def remove_option(self, option_name, section_name=None):
 
2224
        configobj = self._get_configobj()
 
2225
        if section_name is None:
 
2226
            del configobj[option_name]
 
2227
        else:
 
2228
            del configobj[section_name][option_name]
 
2229
        for hook in OldConfigHooks['remove']:
 
2230
            hook(self, option_name)
1500
2231
        self._set_configobj(configobj)
1501
2232
 
1502
2233
    def _get_config_file(self):
1503
2234
        try:
1504
 
            return StringIO(self._transport.get_bytes(self._filename))
 
2235
            f = StringIO(self._transport.get_bytes(self._filename))
 
2236
            for hook in OldConfigHooks['load']:
 
2237
                hook(self)
 
2238
            return f
1505
2239
        except errors.NoSuchFile:
1506
2240
            return StringIO()
1507
2241
 
 
2242
    def _external_url(self):
 
2243
        return urlutils.join(self._transport.external_url(), self._filename)
 
2244
 
1508
2245
    def _get_configobj(self):
1509
 
        return ConfigObj(self._get_config_file(), encoding='utf-8')
 
2246
        f = self._get_config_file()
 
2247
        try:
 
2248
            try:
 
2249
                conf = ConfigObj(f, encoding='utf-8')
 
2250
            except configobj.ConfigObjError, e:
 
2251
                raise errors.ParseConfigError(e.errors, self._external_url())
 
2252
            except UnicodeDecodeError:
 
2253
                raise errors.ConfigContentError(self._external_url())
 
2254
        finally:
 
2255
            f.close()
 
2256
        return conf
1510
2257
 
1511
2258
    def _set_configobj(self, configobj):
1512
2259
        out_file = StringIO()
1513
2260
        configobj.write(out_file)
1514
2261
        out_file.seek(0)
1515
2262
        self._transport.put_file(self._filename, out_file)
 
2263
        for hook in OldConfigHooks['save']:
 
2264
            hook(self)
 
2265
 
 
2266
 
 
2267
class Option(object):
 
2268
    """An option definition.
 
2269
 
 
2270
    The option *values* are stored in config files and found in sections.
 
2271
 
 
2272
    Here we define various properties about the option itself, its default
 
2273
    value, how to convert it from stores, what to do when invalid values are
 
2274
    encoutered, in which config files it can be stored.
 
2275
    """
 
2276
 
 
2277
    def __init__(self, name, default=None, help=None, from_unicode=None,
 
2278
                 invalid=None):
 
2279
        """Build an option definition.
 
2280
 
 
2281
        :param name: the name used to refer to the option.
 
2282
 
 
2283
        :param default: the default value to use when none exist in the config
 
2284
            stores.
 
2285
 
 
2286
        :param help: a doc string to explain the option to the user.
 
2287
 
 
2288
        :param from_unicode: a callable to convert the unicode string
 
2289
            representing the option value in a store. This is not called for
 
2290
            the default value.
 
2291
 
 
2292
        :param invalid: the action to be taken when an invalid value is
 
2293
            encountered in a store. This is called only when from_unicode is
 
2294
            invoked to convert a string and returns None or raise ValueError or
 
2295
            TypeError. Accepted values are: None (ignore invalid values),
 
2296
            'warning' (emit a warning), 'error' (emit an error message and
 
2297
            terminates).
 
2298
        """
 
2299
        self.name = name
 
2300
        self.default = default
 
2301
        self.help = help
 
2302
        self.from_unicode = from_unicode
 
2303
        if invalid and invalid not in ('warning', 'error'):
 
2304
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
 
2305
        self.invalid = invalid
 
2306
 
 
2307
    def get_default(self):
 
2308
        return self.default
 
2309
 
 
2310
    def get_help_text(self, additional_see_also=None, plain=True):
 
2311
        result = self.help
 
2312
        from bzrlib import help_topics
 
2313
        result += help_topics._format_see_also(additional_see_also)
 
2314
        if plain:
 
2315
            result = help_topics.help_as_plain_text(result)
 
2316
        return result
 
2317
 
 
2318
 
 
2319
# Predefined converters to get proper values from store
 
2320
 
 
2321
def bool_from_store(unicode_str):
 
2322
    return ui.bool_from_string(unicode_str)
 
2323
 
 
2324
 
 
2325
def int_from_store(unicode_str):
 
2326
    return int(unicode_str)
 
2327
 
 
2328
 
 
2329
def list_from_store(unicode_str):
 
2330
    # ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
 
2331
    if isinstance(unicode_str, (str, unicode)):
 
2332
        if unicode_str:
 
2333
            # A single value, most probably the user forgot (or didn't care to
 
2334
            # add) the final ','
 
2335
            l = [unicode_str]
 
2336
        else:
 
2337
            # The empty string, convert to empty list
 
2338
            l = []
 
2339
    else:
 
2340
        # We rely on ConfigObj providing us with a list already
 
2341
        l = unicode_str
 
2342
    return l
 
2343
 
 
2344
 
 
2345
class OptionRegistry(registry.Registry):
 
2346
    """Register config options by their name.
 
2347
 
 
2348
    This overrides ``registry.Registry`` to simplify registration by acquiring
 
2349
    some information from the option object itself.
 
2350
    """
 
2351
 
 
2352
    def register(self, option):
 
2353
        """Register a new option to its name.
 
2354
 
 
2355
        :param option: The option to register. Its name is used as the key.
 
2356
        """
 
2357
        super(OptionRegistry, self).register(option.name, option,
 
2358
                                             help=option.help)
 
2359
 
 
2360
    def register_lazy(self, key, module_name, member_name):
 
2361
        """Register a new option to be loaded on request.
 
2362
 
 
2363
        :param key: the key to request the option later. Since the registration
 
2364
            is lazy, it should be provided and match the option name.
 
2365
 
 
2366
        :param module_name: the python path to the module. Such as 'os.path'.
 
2367
 
 
2368
        :param member_name: the member of the module to return.  If empty or 
 
2369
                None, get() will return the module itself.
 
2370
        """
 
2371
        super(OptionRegistry, self).register_lazy(key,
 
2372
                                                  module_name, member_name)
 
2373
 
 
2374
    def get_help(self, key=None):
 
2375
        """Get the help text associated with the given key"""
 
2376
        option = self.get(key)
 
2377
        the_help = option.help
 
2378
        if callable(the_help):
 
2379
            return the_help(self, key)
 
2380
        return the_help
 
2381
 
 
2382
 
 
2383
option_registry = OptionRegistry()
 
2384
 
 
2385
 
 
2386
# Registered options in lexicographical order
 
2387
 
 
2388
option_registry.register(
 
2389
    Option('bzr.workingtree.worth_saving_limit', default=10,
 
2390
           from_unicode=int_from_store,  invalid='warning',
 
2391
           help='''\
 
2392
How many changes before saving the dirstate.
 
2393
 
 
2394
-1 means that we will never rewrite the dirstate file for only
 
2395
stat-cache changes. Regardless of this setting, we will always rewrite
 
2396
the dirstate file if a file is added/removed/renamed/etc. This flag only
 
2397
affects the behavior of updating the dirstate file after we notice that
 
2398
a file has been touched.
 
2399
'''))
 
2400
option_registry.register(
 
2401
    Option('dirstate.fdatasync', default=True,
 
2402
           from_unicode=bool_from_store,
 
2403
           help='''\
 
2404
Flush dirstate changes onto physical disk?
 
2405
 
 
2406
If true (default), working tree metadata changes are flushed through the
 
2407
OS buffers to physical disk.  This is somewhat slower, but means data
 
2408
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2409
'''))
 
2410
option_registry.register(
 
2411
    Option('debug_flags', default=[], from_unicode=list_from_store,
 
2412
           help='Debug flags to activate.'))
 
2413
option_registry.register(
 
2414
    Option('default_format', default='2a',
 
2415
           help='Format used when creating branches.'))
 
2416
option_registry.register(
 
2417
    Option('editor',
 
2418
           help='The command called to launch an editor to enter a message.'))
 
2419
option_registry.register(
 
2420
    Option('ignore_missing_extensions', default=False,
 
2421
           from_unicode=bool_from_store,
 
2422
           help='''\
 
2423
Control the missing extensions warning display.
 
2424
 
 
2425
The warning will not be emitted if set to True.
 
2426
'''))
 
2427
option_registry.register(
 
2428
    Option('language',
 
2429
           help='Language to translate messages into.'))
 
2430
option_registry.register(
 
2431
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
 
2432
           help='''\
 
2433
Steal locks that appears to be dead.
 
2434
 
 
2435
If set to True, bzr will check if a lock is supposed to be held by an
 
2436
active process from the same user on the same machine. If the user and
 
2437
machine match, but no process with the given PID is active, then bzr
 
2438
will automatically break the stale lock, and create a new lock for
 
2439
this process.
 
2440
Otherwise, bzr will prompt as normal to break the lock.
 
2441
'''))
 
2442
option_registry.register(
 
2443
    Option('output_encoding',
 
2444
           help= 'Unicode encoding for output'
 
2445
           ' (terminal encoding if not specified).'))
 
2446
option_registry.register(
 
2447
    Option('repository.fdatasync', default=True, from_unicode=bool_from_store,
 
2448
           help='''\
 
2449
Flush repository changes onto physical disk?
 
2450
 
 
2451
If true (default), repository changes are flushed through the OS buffers
 
2452
to physical disk.  This is somewhat slower, but means data should not be
 
2453
lost if the machine crashes.  See also dirstate.fdatasync.
 
2454
'''))
 
2455
 
 
2456
 
 
2457
class Section(object):
 
2458
    """A section defines a dict of option name => value.
 
2459
 
 
2460
    This is merely a read-only dict which can add some knowledge about the
 
2461
    options. It is *not* a python dict object though and doesn't try to mimic
 
2462
    its API.
 
2463
    """
 
2464
 
 
2465
    def __init__(self, section_id, options):
 
2466
        self.id = section_id
 
2467
        # We re-use the dict-like object received
 
2468
        self.options = options
 
2469
 
 
2470
    def get(self, name, default=None):
 
2471
        return self.options.get(name, default)
 
2472
 
 
2473
    def __repr__(self):
 
2474
        # Mostly for debugging use
 
2475
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
 
2476
 
 
2477
 
 
2478
_NewlyCreatedOption = object()
 
2479
"""Was the option created during the MutableSection lifetime"""
 
2480
 
 
2481
 
 
2482
class MutableSection(Section):
 
2483
    """A section allowing changes and keeping track of the original values."""
 
2484
 
 
2485
    def __init__(self, section_id, options):
 
2486
        super(MutableSection, self).__init__(section_id, options)
 
2487
        self.orig = {}
 
2488
 
 
2489
    def set(self, name, value):
 
2490
        if name not in self.options:
 
2491
            # This is a new option
 
2492
            self.orig[name] = _NewlyCreatedOption
 
2493
        elif name not in self.orig:
 
2494
            self.orig[name] = self.get(name, None)
 
2495
        self.options[name] = value
 
2496
 
 
2497
    def remove(self, name):
 
2498
        if name not in self.orig:
 
2499
            self.orig[name] = self.get(name, None)
 
2500
        del self.options[name]
 
2501
 
 
2502
 
 
2503
class Store(object):
 
2504
    """Abstract interface to persistent storage for configuration options."""
 
2505
 
 
2506
    readonly_section_class = Section
 
2507
    mutable_section_class = MutableSection
 
2508
 
 
2509
    def is_loaded(self):
 
2510
        """Returns True if the Store has been loaded.
 
2511
 
 
2512
        This is used to implement lazy loading and ensure the persistent
 
2513
        storage is queried only when needed.
 
2514
        """
 
2515
        raise NotImplementedError(self.is_loaded)
 
2516
 
 
2517
    def load(self):
 
2518
        """Loads the Store from persistent storage."""
 
2519
        raise NotImplementedError(self.load)
 
2520
 
 
2521
    def _load_from_string(self, bytes):
 
2522
        """Create a store from a string in configobj syntax.
 
2523
 
 
2524
        :param bytes: A string representing the file content.
 
2525
        """
 
2526
        raise NotImplementedError(self._load_from_string)
 
2527
 
 
2528
    def unload(self):
 
2529
        """Unloads the Store.
 
2530
 
 
2531
        This should make is_loaded() return False. This is used when the caller
 
2532
        knows that the persistent storage has changed or may have change since
 
2533
        the last load.
 
2534
        """
 
2535
        raise NotImplementedError(self.unload)
 
2536
 
 
2537
    def save(self):
 
2538
        """Saves the Store to persistent storage."""
 
2539
        raise NotImplementedError(self.save)
 
2540
 
 
2541
    def external_url(self):
 
2542
        raise NotImplementedError(self.external_url)
 
2543
 
 
2544
    def get_sections(self):
 
2545
        """Returns an ordered iterable of existing sections.
 
2546
 
 
2547
        :returns: An iterable of (name, dict).
 
2548
        """
 
2549
        raise NotImplementedError(self.get_sections)
 
2550
 
 
2551
    def get_mutable_section(self, section_name=None):
 
2552
        """Returns the specified mutable section.
 
2553
 
 
2554
        :param section_name: The section identifier
 
2555
        """
 
2556
        raise NotImplementedError(self.get_mutable_section)
 
2557
 
 
2558
    def __repr__(self):
 
2559
        # Mostly for debugging use
 
2560
        return "<config.%s(%s)>" % (self.__class__.__name__,
 
2561
                                    self.external_url())
 
2562
 
 
2563
 
 
2564
class IniFileStore(Store):
 
2565
    """A config Store using ConfigObj for storage.
 
2566
 
 
2567
    :ivar transport: The transport object where the config file is located.
 
2568
 
 
2569
    :ivar file_name: The config file basename in the transport directory.
 
2570
 
 
2571
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
 
2572
        serialize/deserialize the config file.
 
2573
    """
 
2574
 
 
2575
    def __init__(self, transport, file_name):
 
2576
        """A config Store using ConfigObj for storage.
 
2577
 
 
2578
        :param transport: The transport object where the config file is located.
 
2579
 
 
2580
        :param file_name: The config file basename in the transport directory.
 
2581
        """
 
2582
        super(IniFileStore, self).__init__()
 
2583
        self.transport = transport
 
2584
        self.file_name = file_name
 
2585
        self._config_obj = None
 
2586
 
 
2587
    def is_loaded(self):
 
2588
        return self._config_obj != None
 
2589
 
 
2590
    def unload(self):
 
2591
        self._config_obj = None
 
2592
 
 
2593
    def load(self):
 
2594
        """Load the store from the associated file."""
 
2595
        if self.is_loaded():
 
2596
            return
 
2597
        content = self.transport.get_bytes(self.file_name)
 
2598
        self._load_from_string(content)
 
2599
        for hook in ConfigHooks['load']:
 
2600
            hook(self)
 
2601
 
 
2602
    def _load_from_string(self, bytes):
 
2603
        """Create a config store from a string.
 
2604
 
 
2605
        :param bytes: A string representing the file content.
 
2606
        """
 
2607
        if self.is_loaded():
 
2608
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
 
2609
        co_input = StringIO(bytes)
 
2610
        try:
 
2611
            # The config files are always stored utf8-encoded
 
2612
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
 
2613
        except configobj.ConfigObjError, e:
 
2614
            self._config_obj = None
 
2615
            raise errors.ParseConfigError(e.errors, self.external_url())
 
2616
        except UnicodeDecodeError:
 
2617
            raise errors.ConfigContentError(self.external_url())
 
2618
 
 
2619
    def save(self):
 
2620
        if not self.is_loaded():
 
2621
            # Nothing to save
 
2622
            return
 
2623
        out = StringIO()
 
2624
        self._config_obj.write(out)
 
2625
        self.transport.put_bytes(self.file_name, out.getvalue())
 
2626
        for hook in ConfigHooks['save']:
 
2627
            hook(self)
 
2628
 
 
2629
    def external_url(self):
 
2630
        # FIXME: external_url should really accepts an optional relpath
 
2631
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
2632
        # The following will do in the interim but maybe we don't want to
 
2633
        # expose a path here but rather a config ID and its associated
 
2634
        # object </hand wawe>.
 
2635
        return urlutils.join(self.transport.external_url(), self.file_name)
 
2636
 
 
2637
    def get_sections(self):
 
2638
        """Get the configobj section in the file order.
 
2639
 
 
2640
        :returns: An iterable of (name, dict).
 
2641
        """
 
2642
        # We need a loaded store
 
2643
        try:
 
2644
            self.load()
 
2645
        except errors.NoSuchFile:
 
2646
            # If the file doesn't exist, there is no sections
 
2647
            return
 
2648
        cobj = self._config_obj
 
2649
        if cobj.scalars:
 
2650
            yield self.readonly_section_class(None, cobj)
 
2651
        for section_name in cobj.sections:
 
2652
            yield self.readonly_section_class(section_name, cobj[section_name])
 
2653
 
 
2654
    def get_mutable_section(self, section_name=None):
 
2655
        # We need a loaded store
 
2656
        try:
 
2657
            self.load()
 
2658
        except errors.NoSuchFile:
 
2659
            # The file doesn't exist, let's pretend it was empty
 
2660
            self._load_from_string('')
 
2661
        if section_name is None:
 
2662
            section = self._config_obj
 
2663
        else:
 
2664
            section = self._config_obj.setdefault(section_name, {})
 
2665
        return self.mutable_section_class(section_name, section)
 
2666
 
 
2667
 
 
2668
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
 
2669
# unlockable stores for use with objects that can already ensure the locking
 
2670
# (think branches). If different stores (not based on ConfigObj) are created,
 
2671
# they may face the same issue.
 
2672
 
 
2673
 
 
2674
class LockableIniFileStore(IniFileStore):
 
2675
    """A ConfigObjStore using locks on save to ensure store integrity."""
 
2676
 
 
2677
    def __init__(self, transport, file_name, lock_dir_name=None):
 
2678
        """A config Store using ConfigObj for storage.
 
2679
 
 
2680
        :param transport: The transport object where the config file is located.
 
2681
 
 
2682
        :param file_name: The config file basename in the transport directory.
 
2683
        """
 
2684
        if lock_dir_name is None:
 
2685
            lock_dir_name = 'lock'
 
2686
        self.lock_dir_name = lock_dir_name
 
2687
        super(LockableIniFileStore, self).__init__(transport, file_name)
 
2688
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
 
2689
 
 
2690
    def lock_write(self, token=None):
 
2691
        """Takes a write lock in the directory containing the config file.
 
2692
 
 
2693
        If the directory doesn't exist it is created.
 
2694
        """
 
2695
        # FIXME: This doesn't check the ownership of the created directories as
 
2696
        # ensure_config_dir_exists does. It should if the transport is local
 
2697
        # -- vila 2011-04-06
 
2698
        self.transport.create_prefix()
 
2699
        return self._lock.lock_write(token)
 
2700
 
 
2701
    def unlock(self):
 
2702
        self._lock.unlock()
 
2703
 
 
2704
    def break_lock(self):
 
2705
        self._lock.break_lock()
 
2706
 
 
2707
    @needs_write_lock
 
2708
    def save(self):
 
2709
        # We need to be able to override the undecorated implementation
 
2710
        self.save_without_locking()
 
2711
 
 
2712
    def save_without_locking(self):
 
2713
        super(LockableIniFileStore, self).save()
 
2714
 
 
2715
 
 
2716
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
 
2717
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
 
2718
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
 
2719
 
 
2720
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
 
2721
# functions or a registry will make it easier and clearer for tests, focusing
 
2722
# on the relevant parts of the API that needs testing -- vila 20110503 (based
 
2723
# on a poolie's remark)
 
2724
class GlobalStore(LockableIniFileStore):
 
2725
 
 
2726
    def __init__(self, possible_transports=None):
 
2727
        t = transport.get_transport_from_path(
 
2728
            config_dir(), possible_transports=possible_transports)
 
2729
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
2730
 
 
2731
 
 
2732
class LocationStore(LockableIniFileStore):
 
2733
 
 
2734
    def __init__(self, possible_transports=None):
 
2735
        t = transport.get_transport_from_path(
 
2736
            config_dir(), possible_transports=possible_transports)
 
2737
        super(LocationStore, self).__init__(t, 'locations.conf')
 
2738
 
 
2739
 
 
2740
class BranchStore(IniFileStore):
 
2741
 
 
2742
    def __init__(self, branch):
 
2743
        super(BranchStore, self).__init__(branch.control_transport,
 
2744
                                          'branch.conf')
 
2745
        self.branch = branch
 
2746
 
 
2747
    def lock_write(self, token=None):
 
2748
        return self.branch.lock_write(token)
 
2749
 
 
2750
    def unlock(self):
 
2751
        return self.branch.unlock()
 
2752
 
 
2753
    @needs_write_lock
 
2754
    def save(self):
 
2755
        # We need to be able to override the undecorated implementation
 
2756
        self.save_without_locking()
 
2757
 
 
2758
    def save_without_locking(self):
 
2759
        super(BranchStore, self).save()
 
2760
 
 
2761
 
 
2762
class SectionMatcher(object):
 
2763
    """Select sections into a given Store.
 
2764
 
 
2765
    This intended to be used to postpone getting an iterable of sections from a
 
2766
    store.
 
2767
    """
 
2768
 
 
2769
    def __init__(self, store):
 
2770
        self.store = store
 
2771
 
 
2772
    def get_sections(self):
 
2773
        # This is where we require loading the store so we can see all defined
 
2774
        # sections.
 
2775
        sections = self.store.get_sections()
 
2776
        # Walk the revisions in the order provided
 
2777
        for s in sections:
 
2778
            if self.match(s):
 
2779
                yield s
 
2780
 
 
2781
    def match(self, secion):
 
2782
        raise NotImplementedError(self.match)
 
2783
 
 
2784
 
 
2785
class LocationSection(Section):
 
2786
 
 
2787
    def __init__(self, section, length, extra_path):
 
2788
        super(LocationSection, self).__init__(section.id, section.options)
 
2789
        self.length = length
 
2790
        self.extra_path = extra_path
 
2791
 
 
2792
    def get(self, name, default=None):
 
2793
        value = super(LocationSection, self).get(name, default)
 
2794
        if value is not None:
 
2795
            policy_name = self.get(name + ':policy', None)
 
2796
            policy = _policy_value.get(policy_name, POLICY_NONE)
 
2797
            if policy == POLICY_APPENDPATH:
 
2798
                value = urlutils.join(value, self.extra_path)
 
2799
        return value
 
2800
 
 
2801
 
 
2802
class LocationMatcher(SectionMatcher):
 
2803
 
 
2804
    def __init__(self, store, location):
 
2805
        super(LocationMatcher, self).__init__(store)
 
2806
        if location.startswith('file://'):
 
2807
            location = urlutils.local_path_from_url(location)
 
2808
        self.location = location
 
2809
 
 
2810
    def _get_matching_sections(self):
 
2811
        """Get all sections matching ``location``."""
 
2812
        # We slightly diverge from LocalConfig here by allowing the no-name
 
2813
        # section as the most generic one and the lower priority.
 
2814
        no_name_section = None
 
2815
        sections = []
 
2816
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
2817
        # used (it assumes all sections have a name).
 
2818
        for section in self.store.get_sections():
 
2819
            if section.id is None:
 
2820
                no_name_section = section
 
2821
            else:
 
2822
                sections.append(section)
 
2823
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
2824
        # we have to resync.
 
2825
        filtered_sections = _iter_for_location_by_parts(
 
2826
            [s.id for s in sections], self.location)
 
2827
        iter_sections = iter(sections)
 
2828
        matching_sections = []
 
2829
        if no_name_section is not None:
 
2830
            matching_sections.append(
 
2831
                LocationSection(no_name_section, 0, self.location))
 
2832
        for section_id, extra_path, length in filtered_sections:
 
2833
            # a section id is unique for a given store so it's safe to iterate
 
2834
            # again
 
2835
            section = iter_sections.next()
 
2836
            if section_id == section.id:
 
2837
                matching_sections.append(
 
2838
                    LocationSection(section, length, extra_path))
 
2839
        return matching_sections
 
2840
 
 
2841
    def get_sections(self):
 
2842
        # Override the default implementation as we want to change the order
 
2843
        matching_sections = self._get_matching_sections()
 
2844
        # We want the longest (aka more specific) locations first
 
2845
        sections = sorted(matching_sections,
 
2846
                          key=lambda section: (section.length, section.id),
 
2847
                          reverse=True)
 
2848
        # Sections mentioning 'ignore_parents' restrict the selection
 
2849
        for section in sections:
 
2850
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
 
2851
            ignore = section.get('ignore_parents', None)
 
2852
            if ignore is not None:
 
2853
                ignore = ui.bool_from_string(ignore)
 
2854
            if ignore:
 
2855
                break
 
2856
            # Finally, we have a valid section
 
2857
            yield section
 
2858
 
 
2859
 
 
2860
class Stack(object):
 
2861
    """A stack of configurations where an option can be defined"""
 
2862
 
 
2863
    def __init__(self, sections_def, store=None, mutable_section_name=None):
 
2864
        """Creates a stack of sections with an optional store for changes.
 
2865
 
 
2866
        :param sections_def: A list of Section or callables that returns an
 
2867
            iterable of Section. This defines the Sections for the Stack and
 
2868
            can be called repeatedly if needed.
 
2869
 
 
2870
        :param store: The optional Store where modifications will be
 
2871
            recorded. If none is specified, no modifications can be done.
 
2872
 
 
2873
        :param mutable_section_name: The name of the MutableSection where
 
2874
            changes are recorded. This requires the ``store`` parameter to be
 
2875
            specified.
 
2876
        """
 
2877
        self.sections_def = sections_def
 
2878
        self.store = store
 
2879
        self.mutable_section_name = mutable_section_name
 
2880
 
 
2881
    def get(self, name):
 
2882
        """Return the *first* option value found in the sections.
 
2883
 
 
2884
        This is where we guarantee that sections coming from Store are loaded
 
2885
        lazily: the loading is delayed until we need to either check that an
 
2886
        option exists or get its value, which in turn may require to discover
 
2887
        in which sections it can be defined. Both of these (section and option
 
2888
        existence) require loading the store (even partially).
 
2889
        """
 
2890
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
2891
        value = None
 
2892
        # Ensuring lazy loading is achieved by delaying section matching (which
 
2893
        # implies querying the persistent storage) until it can't be avoided
 
2894
        # anymore by using callables to describe (possibly empty) section
 
2895
        # lists.
 
2896
        for section_or_callable in self.sections_def:
 
2897
            # Each section can expand to multiple ones when a callable is used
 
2898
            if callable(section_or_callable):
 
2899
                sections = section_or_callable()
 
2900
            else:
 
2901
                sections = [section_or_callable]
 
2902
            for section in sections:
 
2903
                value = section.get(name)
 
2904
                if value is not None:
 
2905
                    break
 
2906
            if value is not None:
 
2907
                break
 
2908
        # If the option is registered, it may provide additional info about
 
2909
        # value handling
 
2910
        try:
 
2911
            opt = option_registry.get(name)
 
2912
        except KeyError:
 
2913
            # Not registered
 
2914
            opt = None
 
2915
        if (opt is not None and opt.from_unicode is not None
 
2916
            and value is not None):
 
2917
            # If a value exists and the option provides a converter, use it
 
2918
            try:
 
2919
                converted = opt.from_unicode(value)
 
2920
            except (ValueError, TypeError):
 
2921
                # Invalid values are ignored
 
2922
                converted = None
 
2923
            if converted is None and opt.invalid is not None:
 
2924
                # The conversion failed
 
2925
                if opt.invalid == 'warning':
 
2926
                    trace.warning('Value "%s" is not valid for "%s"',
 
2927
                                  value, name)
 
2928
                elif opt.invalid == 'error':
 
2929
                    raise errors.ConfigOptionValueError(name, value)
 
2930
            value = converted
 
2931
        if value is None:
 
2932
            # If the option is registered, it may provide a default value
 
2933
            if opt is not None:
 
2934
                value = opt.get_default()
 
2935
        for hook in ConfigHooks['get']:
 
2936
            hook(self, name, value)
 
2937
        return value
 
2938
 
 
2939
    def _get_mutable_section(self):
 
2940
        """Get the MutableSection for the Stack.
 
2941
 
 
2942
        This is where we guarantee that the mutable section is lazily loaded:
 
2943
        this means we won't load the corresponding store before setting a value
 
2944
        or deleting an option. In practice the store will often be loaded but
 
2945
        this allows helps catching some programming errors.
 
2946
        """
 
2947
        section = self.store.get_mutable_section(self.mutable_section_name)
 
2948
        return section
 
2949
 
 
2950
    def set(self, name, value):
 
2951
        """Set a new value for the option."""
 
2952
        section = self._get_mutable_section()
 
2953
        section.set(name, value)
 
2954
        for hook in ConfigHooks['set']:
 
2955
            hook(self, name, value)
 
2956
 
 
2957
    def remove(self, name):
 
2958
        """Remove an existing option."""
 
2959
        section = self._get_mutable_section()
 
2960
        section.remove(name)
 
2961
        for hook in ConfigHooks['remove']:
 
2962
            hook(self, name)
 
2963
 
 
2964
    def __repr__(self):
 
2965
        # Mostly for debugging use
 
2966
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
 
2967
 
 
2968
 
 
2969
class _CompatibleStack(Stack):
 
2970
    """Place holder for compatibility with previous design.
 
2971
 
 
2972
    This is intended to ease the transition from the Config-based design to the
 
2973
    Stack-based design and should not be used nor relied upon by plugins.
 
2974
 
 
2975
    One assumption made here is that the daughter classes will all use Stores
 
2976
    derived from LockableIniFileStore).
 
2977
 
 
2978
    It implements set() by re-loading the store before applying the
 
2979
    modification and saving it.
 
2980
 
 
2981
    The long term plan being to implement a single write by store to save
 
2982
    all modifications, this class should not be used in the interim.
 
2983
    """
 
2984
 
 
2985
    def set(self, name, value):
 
2986
        # Force a reload
 
2987
        self.store.unload()
 
2988
        super(_CompatibleStack, self).set(name, value)
 
2989
        # Force a write to persistent storage
 
2990
        self.store.save()
 
2991
 
 
2992
 
 
2993
class GlobalStack(_CompatibleStack):
 
2994
 
 
2995
    def __init__(self):
 
2996
        # Get a GlobalStore
 
2997
        gstore = GlobalStore()
 
2998
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
 
2999
 
 
3000
 
 
3001
class LocationStack(_CompatibleStack):
 
3002
 
 
3003
    def __init__(self, location):
 
3004
        """Make a new stack for a location and global configuration.
 
3005
        
 
3006
        :param location: A URL prefix to """
 
3007
        lstore = LocationStore()
 
3008
        matcher = LocationMatcher(lstore, location)
 
3009
        gstore = GlobalStore()
 
3010
        super(LocationStack, self).__init__(
 
3011
            [matcher.get_sections, gstore.get_sections], lstore)
 
3012
 
 
3013
class BranchStack(_CompatibleStack):
 
3014
 
 
3015
    def __init__(self, branch):
 
3016
        bstore = BranchStore(branch)
 
3017
        lstore = LocationStore()
 
3018
        matcher = LocationMatcher(lstore, branch.base)
 
3019
        gstore = GlobalStore()
 
3020
        super(BranchStack, self).__init__(
 
3021
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
 
3022
            bstore)
 
3023
        self.branch = branch
 
3024
 
 
3025
 
 
3026
class cmd_config(commands.Command):
 
3027
    __doc__ = """Display, set or remove a configuration option.
 
3028
 
 
3029
    Display the active value for a given option.
 
3030
 
 
3031
    If --all is specified, NAME is interpreted as a regular expression and all
 
3032
    matching options are displayed mentioning their scope. The active value
 
3033
    that bzr will take into account is the first one displayed for each option.
 
3034
 
 
3035
    If no NAME is given, --all .* is implied.
 
3036
 
 
3037
    Setting a value is achieved by using name=value without spaces. The value
 
3038
    is set in the most relevant scope and can be checked by displaying the
 
3039
    option again.
 
3040
    """
 
3041
 
 
3042
    takes_args = ['name?']
 
3043
 
 
3044
    takes_options = [
 
3045
        'directory',
 
3046
        # FIXME: This should be a registry option so that plugins can register
 
3047
        # their own config files (or not) -- vila 20101002
 
3048
        commands.Option('scope', help='Reduce the scope to the specified'
 
3049
                        ' configuration file',
 
3050
                        type=unicode),
 
3051
        commands.Option('all',
 
3052
            help='Display all the defined values for the matching options.',
 
3053
            ),
 
3054
        commands.Option('remove', help='Remove the option from'
 
3055
                        ' the configuration file'),
 
3056
        ]
 
3057
 
 
3058
    _see_also = ['configuration']
 
3059
 
 
3060
    @commands.display_command
 
3061
    def run(self, name=None, all=False, directory=None, scope=None,
 
3062
            remove=False):
 
3063
        if directory is None:
 
3064
            directory = '.'
 
3065
        directory = urlutils.normalize_url(directory)
 
3066
        if remove and all:
 
3067
            raise errors.BzrError(
 
3068
                '--all and --remove are mutually exclusive.')
 
3069
        elif remove:
 
3070
            # Delete the option in the given scope
 
3071
            self._remove_config_option(name, directory, scope)
 
3072
        elif name is None:
 
3073
            # Defaults to all options
 
3074
            self._show_matching_options('.*', directory, scope)
 
3075
        else:
 
3076
            try:
 
3077
                name, value = name.split('=', 1)
 
3078
            except ValueError:
 
3079
                # Display the option(s) value(s)
 
3080
                if all:
 
3081
                    self._show_matching_options(name, directory, scope)
 
3082
                else:
 
3083
                    self._show_value(name, directory, scope)
 
3084
            else:
 
3085
                if all:
 
3086
                    raise errors.BzrError(
 
3087
                        'Only one option can be set.')
 
3088
                # Set the option value
 
3089
                self._set_config_option(name, value, directory, scope)
 
3090
 
 
3091
    def _get_configs(self, directory, scope=None):
 
3092
        """Iterate the configurations specified by ``directory`` and ``scope``.
 
3093
 
 
3094
        :param directory: Where the configurations are derived from.
 
3095
 
 
3096
        :param scope: A specific config to start from.
 
3097
        """
 
3098
        if scope is not None:
 
3099
            if scope == 'bazaar':
 
3100
                yield GlobalConfig()
 
3101
            elif scope == 'locations':
 
3102
                yield LocationConfig(directory)
 
3103
            elif scope == 'branch':
 
3104
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
3105
                    directory)
 
3106
                yield br.get_config()
 
3107
        else:
 
3108
            try:
 
3109
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
3110
                    directory)
 
3111
                yield br.get_config()
 
3112
            except errors.NotBranchError:
 
3113
                yield LocationConfig(directory)
 
3114
                yield GlobalConfig()
 
3115
 
 
3116
    def _show_value(self, name, directory, scope):
 
3117
        displayed = False
 
3118
        for c in self._get_configs(directory, scope):
 
3119
            if displayed:
 
3120
                break
 
3121
            for (oname, value, section, conf_id, parser) in c._get_options():
 
3122
                if name == oname:
 
3123
                    # Display only the first value and exit
 
3124
 
 
3125
                    # FIXME: We need to use get_user_option to take policies
 
3126
                    # into account and we need to make sure the option exists
 
3127
                    # too (hence the two for loops), this needs a better API
 
3128
                    # -- vila 20101117
 
3129
                    value = c.get_user_option(name)
 
3130
                    # Quote the value appropriately
 
3131
                    value = parser._quote(value)
 
3132
                    self.outf.write('%s\n' % (value,))
 
3133
                    displayed = True
 
3134
                    break
 
3135
        if not displayed:
 
3136
            raise errors.NoSuchConfigOption(name)
 
3137
 
 
3138
    def _show_matching_options(self, name, directory, scope):
 
3139
        name = lazy_regex.lazy_compile(name)
 
3140
        # We want any error in the regexp to be raised *now* so we need to
 
3141
        # avoid the delay introduced by the lazy regexp.  But, we still do
 
3142
        # want the nicer errors raised by lazy_regex.
 
3143
        name._compile_and_collapse()
 
3144
        cur_conf_id = None
 
3145
        cur_section = None
 
3146
        for c in self._get_configs(directory, scope):
 
3147
            for (oname, value, section, conf_id, parser) in c._get_options():
 
3148
                if name.search(oname):
 
3149
                    if cur_conf_id != conf_id:
 
3150
                        # Explain where the options are defined
 
3151
                        self.outf.write('%s:\n' % (conf_id,))
 
3152
                        cur_conf_id = conf_id
 
3153
                        cur_section = None
 
3154
                    if (section not in (None, 'DEFAULT')
 
3155
                        and cur_section != section):
 
3156
                        # Display the section if it's not the default (or only)
 
3157
                        # one.
 
3158
                        self.outf.write('  [%s]\n' % (section,))
 
3159
                        cur_section = section
 
3160
                    self.outf.write('  %s = %s\n' % (oname, value))
 
3161
 
 
3162
    def _set_config_option(self, name, value, directory, scope):
 
3163
        for conf in self._get_configs(directory, scope):
 
3164
            conf.set_user_option(name, value)
 
3165
            break
 
3166
        else:
 
3167
            raise errors.NoSuchConfig(scope)
 
3168
 
 
3169
    def _remove_config_option(self, name, directory, scope):
 
3170
        if name is None:
 
3171
            raise errors.BzrCommandError(
 
3172
                '--remove expects an option to remove.')
 
3173
        removed = False
 
3174
        for conf in self._get_configs(directory, scope):
 
3175
            for (section_name, section, conf_id) in conf._get_sections():
 
3176
                if scope is not None and conf_id != scope:
 
3177
                    # Not the right configuration file
 
3178
                    continue
 
3179
                if name in section:
 
3180
                    if conf_id != conf.config_id():
 
3181
                        conf = self._get_configs(directory, conf_id).next()
 
3182
                    # We use the first section in the first config where the
 
3183
                    # option is defined to remove it
 
3184
                    conf.remove_user_option(name, section_name)
 
3185
                    removed = True
 
3186
                    break
 
3187
            break
 
3188
        else:
 
3189
            raise errors.NoSuchConfig(scope)
 
3190
        if not removed:
 
3191
            raise errors.NoSuchConfigOption(name)
 
3192
 
 
3193
# Test registries
 
3194
#
 
3195
# We need adapters that can build a Store or a Stack in a test context. Test
 
3196
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
3197
# themselves. The builder will receive a test instance and should return a
 
3198
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
3199
# register themselves here to be tested against the tests defined in
 
3200
# bzrlib.tests.test_config. Note that the builder can be called multiple times
 
3201
# for the same tests.
 
3202
 
 
3203
# The registered object should be a callable receiving a test instance
 
3204
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
3205
# object.
 
3206
test_store_builder_registry = registry.Registry()
 
3207
 
 
3208
# The registered object should be a callable receiving a test instance
 
3209
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
3210
# object.
 
3211
test_stack_builder_registry = registry.Registry()