/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Jelmer Vernooij
  • Date: 2011-08-17 09:27:29 UTC
  • mto: This revision was merged to the branch mainline in revision 6085.
  • Revision ID: jelmer@samba.org-20110817092729-1sg4zs7ckiucqe6n
Use utf8 as encoding for urls passed to note().

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)
 
393
        s = self.get_user_option(option_name, expand=expand)
196
394
        if s is None:
197
395
            # The option doesn't exist
198
 
            return None
 
396
            return default
199
397
        val = ui.bool_from_string(s)
200
398
        if val is None:
201
399
            # The value can't be interpreted as a boolean
203
401
                          s, option_name)
204
402
        return val
205
403
 
206
 
    def get_user_option_as_list(self, option_name):
 
404
    def get_user_option_as_list(self, option_name, expand=None):
207
405
        """Get a generic option as a list - no special process, no default.
208
406
 
209
407
        :return None if the option doesn't exist. Returns the value as a list
210
408
            otherwise.
211
409
        """
212
 
        l = self._get_user_option(option_name)
 
410
        l = self.get_user_option(option_name, expand=expand)
213
411
        if isinstance(l, (str, unicode)):
214
 
            # 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 ','
215
414
            l = [l]
216
415
        return l
217
416
 
237
436
        """See log_format()."""
238
437
        return None
239
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
 
240
462
    def post_commit(self):
241
463
        """An ordered list of python functions to call.
242
464
 
257
479
 
258
480
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
259
481
 
260
 
        $BZR_EMAIL can be set to override this (as well as the
261
 
        deprecated $BZREMAIL), then
 
482
        $BZR_EMAIL can be set to override this, then
262
483
        the concrete policy type is checked, and finally
263
484
        $EMAIL is examined.
264
 
        If none is found, a reasonable default is (hopefully)
265
 
        created.
266
 
 
267
 
        TODO: Check it's reasonably well-formed.
 
485
        If no username can be found, errors.NoWhoami exception is raised.
268
486
        """
269
487
        v = os.environ.get('BZR_EMAIL')
270
488
        if v:
271
489
            return v.decode(osutils.get_user_encoding())
272
 
 
273
490
        v = self._get_user_id()
274
491
        if v:
275
492
            return v
276
 
 
277
493
        v = os.environ.get('EMAIL')
278
494
        if v:
279
495
            return v.decode(osutils.get_user_encoding())
280
 
 
281
496
        name, email = _auto_user_id()
282
 
        if name:
 
497
        if name and email:
283
498
            return '%s <%s>' % (name, email)
284
 
        else:
 
499
        elif email:
285
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()
286
509
 
287
510
    def signature_checking(self):
288
511
        """What is the current policy for signature checking?."""
304
527
        if policy is None:
305
528
            policy = self._get_signature_checking()
306
529
            if policy is not None:
 
530
                #this warning should go away once check_signatures is
 
531
                #implemented (if not before)
307
532
                trace.warning("Please use create_signatures,"
308
533
                              " not check_signatures to set signing policy.")
309
 
            if policy == CHECK_ALWAYS:
310
 
                return True
311
534
        elif policy == SIGN_ALWAYS:
312
535
            return True
313
536
        return False
314
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
 
315
546
    def get_alias(self, value):
316
547
        return self._get_alias(value)
317
548
 
346
577
        else:
347
578
            return True
348
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
 
349
669
 
350
670
class IniBasedConfig(Config):
351
671
    """A configuration policy that draws from ini files."""
352
672
 
353
 
    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
        """
354
679
        super(IniBasedConfig, self).__init__()
355
 
        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
356
692
        self._parser = None
357
693
 
358
 
    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):
359
717
        if self._parser is not None:
360
718
            return self._parser
361
 
        if file is None:
362
 
            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')
363
729
        else:
364
 
            input = file
 
730
            co_input = self.file_name
365
731
        try:
366
 
            self._parser = ConfigObj(input, encoding='utf-8')
 
732
            self._parser = ConfigObj(co_input, encoding='utf-8')
367
733
        except configobj.ConfigObjError, e:
368
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)
369
741
        return self._parser
370
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
 
371
752
    def _get_matching_sections(self):
372
753
        """Return an ordered list of (section_name, extra_path) pairs.
373
754
 
384
765
        """Override this to define the section used by the config."""
385
766
        return "DEFAULT"
386
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
 
387
817
    def _get_option_policy(self, section, option_name):
388
818
        """Return the policy for the given (section, option_name) pair."""
389
819
        return POLICY_NONE
440
870
        """See Config.log_format."""
441
871
        return self._get_user_option('log_format')
442
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
 
443
881
    def _post_commit(self):
444
882
        """See Config.post_commit."""
445
883
        return self._get_user_option('post_commit')
476
914
    def _get_nickname(self):
477
915
        return self.get_user_option('nickname')
478
916
 
479
 
 
480
 
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):
481
1028
    """The configuration that should be used for a specific location."""
482
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)))
483
1050
    def get_editor(self):
484
1051
        return self._get_user_option('editor')
485
1052
 
486
 
    def __init__(self):
487
 
        super(GlobalConfig, self).__init__(config_filename)
488
 
 
 
1053
    @needs_write_lock
489
1054
    def set_user_option(self, option, value):
490
1055
        """Save option and its value in the configuration."""
491
1056
        self._set_option(option, value, 'DEFAULT')
497
1062
        else:
498
1063
            return {}
499
1064
 
 
1065
    @needs_write_lock
500
1066
    def set_alias(self, alias_name, alias_command):
501
1067
        """Save the alias in the configuration."""
502
1068
        self._set_option(alias_name, alias_command, 'ALIASES')
503
1069
 
 
1070
    @needs_write_lock
504
1071
    def unset_alias(self, alias_name):
505
1072
        """Unset an existing alias."""
 
1073
        self.reload()
506
1074
        aliases = self._get_parser().get('ALIASES')
507
1075
        if not aliases or alias_name not in aliases:
508
1076
            raise errors.NoSuchAlias(alias_name)
510
1078
        self._write_config_file()
511
1079
 
512
1080
    def _set_option(self, option, value, section):
513
 
        # FIXME: RBC 20051029 This should refresh the parser and also take a
514
 
        # file lock on bazaar.conf.
515
 
        conf_dir = os.path.dirname(self._get_filename())
516
 
        ensure_config_dir_exists(conf_dir)
 
1081
        self.reload()
517
1082
        self._get_parser().setdefault(section, {})[option] = value
518
1083
        self._write_config_file()
519
 
 
520
 
    def _write_config_file(self):
521
 
        path = self._get_filename()
522
 
        f = open(path, 'wb')
523
 
        osutils.copy_ownership_from_path(path)
524
 
        self._get_parser().write(f)
525
 
        f.close()
526
 
 
527
 
 
528
 
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):
529
1163
    """A configuration object that gives the policy for a location."""
530
1164
 
531
1165
    def __init__(self, location):
532
 
        name_generator = locations_config_filename
533
 
        if (not os.path.exists(name_generator()) and
534
 
                os.path.exists(branches_config_filename())):
535
 
            if sys.platform == 'win32':
536
 
                trace.warning('Please rename %s to %s'
537
 
                              % (branches_config_filename(),
538
 
                                 locations_config_filename()))
539
 
            else:
540
 
                trace.warning('Please rename ~/.bazaar/branches.conf'
541
 
                              ' to ~/.bazaar/locations.conf')
542
 
            name_generator = branches_config_filename
543
 
        super(LocationConfig, self).__init__(name_generator)
 
1166
        super(LocationConfig, self).__init__(
 
1167
            file_name=locations_config_filename())
544
1168
        # local file locations are looked up by local path, rather than
545
1169
        # by file url. This is because the config file is a user
546
1170
        # file, and we would rather not expose the user to file urls.
548
1172
            location = urlutils.local_path_from_url(location)
549
1173
        self.location = location
550
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
 
551
1193
    def _get_matching_sections(self):
552
1194
        """Return an ordered list of section names matching this location."""
553
 
        sections = self._get_parser()
554
 
        location_names = self.location.split('/')
555
 
        if self.location.endswith('/'):
556
 
            del location_names[-1]
557
 
        matches=[]
558
 
        for section in sections:
559
 
            # location is a local path if possible, so we need
560
 
            # to convert 'file://' urls to local paths if necessary.
561
 
            # This also avoids having file:///path be a more exact
562
 
            # match than '/path'.
563
 
            if section.startswith('file://'):
564
 
                section_path = urlutils.local_path_from_url(section)
565
 
            else:
566
 
                section_path = section
567
 
            section_names = section_path.split('/')
568
 
            if section.endswith('/'):
569
 
                del section_names[-1]
570
 
            names = zip(location_names, section_names)
571
 
            matched = True
572
 
            for name in names:
573
 
                if not fnmatch(name[0], name[1]):
574
 
                    matched = False
575
 
                    break
576
 
            if not matched:
577
 
                continue
578
 
            # so, for the common prefix they matched.
579
 
            # if section is longer, no match.
580
 
            if len(section_names) > len(location_names):
581
 
                continue
582
 
            matches.append((len(section_names), section,
583
 
                            '/'.join(location_names[len(section_names):])))
584
 
        matches.sort(reverse=True)
585
 
        sections = []
586
 
        for (length, section, extra_path) in matches:
587
 
            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
588
1203
            # should we stop looking for parent configs here?
589
1204
            try:
590
1205
                if self._get_parser()[section].as_bool('ignore_parents'):
591
1206
                    break
592
1207
            except KeyError:
593
1208
                pass
594
 
        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())
595
1217
 
596
1218
    def _get_option_policy(self, section, option_name):
597
1219
        """Return the policy for the given (section, option_name) pair."""
641
1263
            if policy_key in self._get_parser()[section]:
642
1264
                del self._get_parser()[section][policy_key]
643
1265
 
 
1266
    @needs_write_lock
644
1267
    def set_user_option(self, option, value, store=STORE_LOCATION):
645
1268
        """Save option and its value in the configuration."""
646
1269
        if store not in [STORE_LOCATION,
648
1271
                         STORE_LOCATION_APPENDPATH]:
649
1272
            raise ValueError('bad storage policy %r for %r' %
650
1273
                (store, option))
651
 
        # FIXME: RBC 20051029 This should refresh the parser and also take a
652
 
        # file lock on locations.conf.
653
 
        conf_dir = os.path.dirname(self._get_filename())
654
 
        ensure_config_dir_exists(conf_dir)
 
1274
        self.reload()
655
1275
        location = self.location
656
1276
        if location.endswith('/'):
657
1277
            location = location[:-1]
658
 
        if (not location in self._get_parser() and
659
 
            not location + '/' in self._get_parser()):
660
 
            self._get_parser()[location]={}
661
 
        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:
662
1282
            location = location + '/'
663
 
        self._get_parser()[location][option]=value
 
1283
        parser[location][option]=value
664
1284
        # the allowed values of store match the config policies
665
1285
        self._set_option_policy(location, option, store)
666
 
        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)
667
1289
 
668
1290
 
669
1291
class BranchConfig(Config):
670
1292
    """A configuration object giving the policy for a branch."""
671
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
 
672
1307
    def _get_branch_data_config(self):
673
1308
        if self._branch_data_config is None:
674
1309
            self._branch_data_config = TreeConfig(self.branch)
 
1310
            self._branch_data_config.config_id = self.config_id
675
1311
        return self._branch_data_config
676
1312
 
677
1313
    def _get_location_config(self):
745
1381
                return value
746
1382
        return None
747
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
 
748
1410
    def set_user_option(self, name, value, store=STORE_BRANCH,
749
1411
        warn_masked=False):
750
1412
        if store == STORE_BRANCH:
768
1430
                        trace.warning('Value "%s" is masked by "%s" from'
769
1431
                                      ' branch.conf', value, mask_value)
770
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
 
771
1436
    def _gpg_signing_command(self):
772
1437
        """See Config.gpg_signing_command."""
773
1438
        return self._get_safe_value('_gpg_signing_command')
774
1439
 
775
 
    def __init__(self, branch):
776
 
        super(BranchConfig, self).__init__()
777
 
        self._location_config = None
778
 
        self._branch_data_config = None
779
 
        self._global_config = None
780
 
        self.branch = branch
781
 
        self.option_sources = (self._get_location_config,
782
 
                               self._get_branch_data_config,
783
 
                               self._get_global_config)
784
 
 
785
1440
    def _post_commit(self):
786
1441
        """See Config.post_commit."""
787
1442
        return self._get_safe_value('_post_commit')
803
1458
        """See Config.log_format."""
804
1459
        return self._get_best_value('_log_format')
805
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
 
806
1469
 
807
1470
def ensure_config_dir_exists(path=None):
808
1471
    """Make sure a configuration directory exists.
817
1480
            parent_dir = os.path.dirname(path)
818
1481
            if not os.path.isdir(parent_dir):
819
1482
                trace.mutter('creating config parent directory: %r', parent_dir)
820
 
            os.mkdir(parent_dir)
 
1483
                os.mkdir(parent_dir)
821
1484
        trace.mutter('creating config directory: %r', path)
822
1485
        os.mkdir(path)
823
1486
        osutils.copy_ownership_from_path(path)
826
1489
def config_dir():
827
1490
    """Return per-user configuration directory.
828
1491
 
829
 
    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.
830
1495
 
831
1496
    TODO: Global option --config-dir to override this.
832
1497
    """
833
1498
    base = os.environ.get('BZR_HOME', None)
834
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')
835
1504
        if base is None:
836
1505
            base = win32utils.get_appdata_location_unicode()
837
1506
        if base is None:
838
1507
            base = os.environ.get('HOME', None)
 
1508
            if base is not None:
 
1509
                base = base.decode('mbcs')
839
1510
        if base is None:
840
1511
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
841
1512
                                  ' or HOME set')
842
1513
        return osutils.pathjoin(base, 'bazaar', '2.0')
843
1514
    else:
844
 
        # cygwin, linux, and darwin all have a $HOME directory
845
 
        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
846
1532
            base = os.path.expanduser("~")
847
1533
        return osutils.pathjoin(base, ".bazaar")
848
1534
 
852
1538
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
853
1539
 
854
1540
 
855
 
def branches_config_filename():
856
 
    """Return per-user configuration ini file filename."""
857
 
    return osutils.pathjoin(config_dir(), 'branches.conf')
858
 
 
859
 
 
860
1541
def locations_config_filename():
861
1542
    """Return per-user configuration ini file filename."""
862
1543
    return osutils.pathjoin(config_dir(), 'locations.conf')
899
1580
        return os.path.expanduser('~/.cache')
900
1581
 
901
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
 
902
1602
def _auto_user_id():
903
1603
    """Calculate automatic user identification.
904
1604
 
905
 
    Returns (realname, email).
 
1605
    :returns: (realname, email), either of which may be None if they can't be
 
1606
    determined.
906
1607
 
907
1608
    Only used when none is set in the environment or the id file.
908
1609
 
909
 
    This previously used the FQDN as the default domain, but that can
910
 
    be very slow on machines where DNS is broken.  So now we simply
911
 
    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.
912
1616
    """
913
 
    import socket
914
 
 
915
1617
    if sys.platform == 'win32':
916
 
        name = win32utils.get_user_name_unicode()
917
 
        if name is None:
918
 
            raise errors.BzrError("Cannot autodetect user name.\n"
919
 
                                  "Please, set your name with command like:\n"
920
 
                                  'bzr whoami "Your Name <name@domain.com>"')
921
 
        host = win32utils.get_host_name_unicode()
922
 
        if host is None:
923
 
            host = socket.gethostname()
924
 
        return name, (name + '@' + host)
925
 
 
926
 
    try:
927
 
        import pwd
928
 
        uid = os.getuid()
929
 
        try:
930
 
            w = pwd.getpwuid(uid)
931
 
        except KeyError:
932
 
            raise errors.BzrCommandError('Unable to determine your name.  '
933
 
                'Please use "bzr whoami" to set it.')
934
 
 
935
 
        # we try utf-8 first, because on many variants (like Linux),
936
 
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
937
 
        # false positives.  (many users will have their user encoding set to
938
 
        # latin-1, which cannot raise UnicodeError.)
939
 
        try:
940
 
            gecos = w.pw_gecos.decode('utf-8')
941
 
            encoding = 'utf-8'
942
 
        except UnicodeError:
943
 
            try:
944
 
                encoding = osutils.get_user_encoding()
945
 
                gecos = w.pw_gecos.decode(encoding)
946
 
            except UnicodeError:
947
 
                raise errors.BzrCommandError('Unable to determine your name.  '
948
 
                   'Use "bzr whoami" to set it.')
949
 
        try:
950
 
            username = w.pw_name.decode(encoding)
951
 
        except UnicodeError:
952
 
            raise errors.BzrCommandError('Unable to determine your name.  '
953
 
                'Use "bzr whoami" to set it.')
954
 
 
955
 
        comma = gecos.find(',')
956
 
        if comma == -1:
957
 
            realname = gecos
958
 
        else:
959
 
            realname = gecos[:comma]
960
 
        if not realname:
961
 
            realname = username
962
 
 
963
 
    except ImportError:
964
 
        import getpass
965
 
        try:
966
 
            user_encoding = osutils.get_user_encoding()
967
 
            realname = username = getpass.getuser().decode(user_encoding)
968
 
        except UnicodeDecodeError:
969
 
            raise errors.BzrError("Can't decode username as %s." % \
970
 
                    user_encoding)
971
 
 
972
 
    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)
973
1661
 
974
1662
 
975
1663
def parse_username(username):
1020
1708
 
1021
1709
    def set_option(self, value, name, section=None):
1022
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
1023
1713
        self.branch.lock_write()
1024
1714
        try:
1025
1715
            self._config.set_option(value, name, section)
1026
1716
        finally:
1027
1717
            self.branch.unlock()
1028
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
 
1029
1728
 
1030
1729
class AuthenticationConfig(object):
1031
1730
    """The authentication configuration file based on a ini file.
1057
1756
            self._config = ConfigObj(self._input, encoding='utf-8')
1058
1757
        except configobj.ConfigObjError, e:
1059
1758
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
1759
        except UnicodeError:
 
1760
            raise errors.ConfigContentError(self._filename)
1060
1761
        return self._config
1061
1762
 
1062
1763
    def _save(self):
1063
1764
        """Save the config file, only tests should use it for now."""
1064
1765
        conf_dir = os.path.dirname(self._filename)
1065
1766
        ensure_config_dir_exists(conf_dir)
1066
 
        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()
1067
1772
 
1068
1773
    def _set_option(self, section_name, option_name, value):
1069
1774
        """Set an authentication configuration option"""
1075
1780
        section[option_name] = value
1076
1781
        self._save()
1077
1782
 
1078
 
    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,
1079
1784
                        realm=None):
1080
1785
        """Returns the matching credentials from authentication.conf file.
1081
1786
 
1249
1954
            if ask:
1250
1955
                if prompt is None:
1251
1956
                    # Create a default prompt suitable for most cases
1252
 
                    prompt = scheme.upper() + ' %(host)s username'
 
1957
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
1253
1958
                # Special handling for optional fields in the prompt
1254
1959
                if port is not None:
1255
1960
                    prompt_host = '%s:%d' % (host, port)
1293
1998
        if password is None:
1294
1999
            if prompt is None:
1295
2000
                # Create a default prompt suitable for most cases
1296
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
2001
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
1297
2002
            # Special handling for optional fields in the prompt
1298
2003
            if port is not None:
1299
2004
                prompt_host = '%s:%d' % (host, port)
1470
2175
    """A Config that reads/writes a config file on a Transport.
1471
2176
 
1472
2177
    It is a low-level object that considers config data to be name/value pairs
1473
 
    that may be associated with a section.  Assigning meaning to the these
1474
 
    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.
1475
2180
    """
1476
2181
 
1477
2182
    def __init__(self, transport, filename):
1494
2199
                section_obj = configobj[section]
1495
2200
            except KeyError:
1496
2201
                return default
1497
 
        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
1498
2206
 
1499
2207
    def set_option(self, value, name, section=None):
1500
2208
        """Set the value associated with a named option.
1508
2216
            configobj[name] = value
1509
2217
        else:
1510
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)
1511
2231
        self._set_configobj(configobj)
1512
2232
 
1513
2233
    def _get_config_file(self):
1514
2234
        try:
1515
 
            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
1516
2239
        except errors.NoSuchFile:
1517
2240
            return StringIO()
1518
2241
 
 
2242
    def _external_url(self):
 
2243
        return urlutils.join(self._transport.external_url(), self._filename)
 
2244
 
1519
2245
    def _get_configobj(self):
1520
 
        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
1521
2257
 
1522
2258
    def _set_configobj(self, configobj):
1523
2259
        out_file = StringIO()
1524
2260
        configobj.write(out_file)
1525
2261
        out_file.seek(0)
1526
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('dirstate.fdatasync', default=True, from_unicode=bool_from_store,
 
2390
           help='''\
 
2391
Flush dirstate changes onto physical disk?
 
2392
 
 
2393
If true (default), working tree metadata changes are flushed through the
 
2394
OS buffers to physical disk.  This is somewhat slower, but means data
 
2395
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2396
'''))
 
2397
option_registry.register(
 
2398
    Option('default_format', default='2a',
 
2399
           help='Format used when creating branches.'))
 
2400
option_registry.register(
 
2401
    Option('editor',
 
2402
           help='The command called to launch an editor to enter a message.'))
 
2403
option_registry.register(
 
2404
    Option('language',
 
2405
           help='Language to translate messages into.'))
 
2406
option_registry.register(
 
2407
    Option('output_encoding',
 
2408
           help= 'Unicode encoding for output'
 
2409
           ' (terminal encoding if not specified).'))
 
2410
option_registry.register(
 
2411
    Option('repository.fdatasync', default=True, from_unicode=bool_from_store,
 
2412
           help='''\
 
2413
Flush repository changes onto physical disk?
 
2414
 
 
2415
If true (default), repository changes are flushed through the OS buffers
 
2416
to physical disk.  This is somewhat slower, but means data should not be
 
2417
lost if the machine crashes.  See also dirstate.fdatasync.
 
2418
'''))
 
2419
 
 
2420
 
 
2421
class Section(object):
 
2422
    """A section defines a dict of option name => value.
 
2423
 
 
2424
    This is merely a read-only dict which can add some knowledge about the
 
2425
    options. It is *not* a python dict object though and doesn't try to mimic
 
2426
    its API.
 
2427
    """
 
2428
 
 
2429
    def __init__(self, section_id, options):
 
2430
        self.id = section_id
 
2431
        # We re-use the dict-like object received
 
2432
        self.options = options
 
2433
 
 
2434
    def get(self, name, default=None):
 
2435
        return self.options.get(name, default)
 
2436
 
 
2437
    def __repr__(self):
 
2438
        # Mostly for debugging use
 
2439
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
 
2440
 
 
2441
 
 
2442
_NewlyCreatedOption = object()
 
2443
"""Was the option created during the MutableSection lifetime"""
 
2444
 
 
2445
 
 
2446
class MutableSection(Section):
 
2447
    """A section allowing changes and keeping track of the original values."""
 
2448
 
 
2449
    def __init__(self, section_id, options):
 
2450
        super(MutableSection, self).__init__(section_id, options)
 
2451
        self.orig = {}
 
2452
 
 
2453
    def set(self, name, value):
 
2454
        if name not in self.options:
 
2455
            # This is a new option
 
2456
            self.orig[name] = _NewlyCreatedOption
 
2457
        elif name not in self.orig:
 
2458
            self.orig[name] = self.get(name, None)
 
2459
        self.options[name] = value
 
2460
 
 
2461
    def remove(self, name):
 
2462
        if name not in self.orig:
 
2463
            self.orig[name] = self.get(name, None)
 
2464
        del self.options[name]
 
2465
 
 
2466
 
 
2467
class Store(object):
 
2468
    """Abstract interface to persistent storage for configuration options."""
 
2469
 
 
2470
    readonly_section_class = Section
 
2471
    mutable_section_class = MutableSection
 
2472
 
 
2473
    def is_loaded(self):
 
2474
        """Returns True if the Store has been loaded.
 
2475
 
 
2476
        This is used to implement lazy loading and ensure the persistent
 
2477
        storage is queried only when needed.
 
2478
        """
 
2479
        raise NotImplementedError(self.is_loaded)
 
2480
 
 
2481
    def load(self):
 
2482
        """Loads the Store from persistent storage."""
 
2483
        raise NotImplementedError(self.load)
 
2484
 
 
2485
    def _load_from_string(self, bytes):
 
2486
        """Create a store from a string in configobj syntax.
 
2487
 
 
2488
        :param bytes: A string representing the file content.
 
2489
        """
 
2490
        raise NotImplementedError(self._load_from_string)
 
2491
 
 
2492
    def unload(self):
 
2493
        """Unloads the Store.
 
2494
 
 
2495
        This should make is_loaded() return False. This is used when the caller
 
2496
        knows that the persistent storage has changed or may have change since
 
2497
        the last load.
 
2498
        """
 
2499
        raise NotImplementedError(self.unload)
 
2500
 
 
2501
    def save(self):
 
2502
        """Saves the Store to persistent storage."""
 
2503
        raise NotImplementedError(self.save)
 
2504
 
 
2505
    def external_url(self):
 
2506
        raise NotImplementedError(self.external_url)
 
2507
 
 
2508
    def get_sections(self):
 
2509
        """Returns an ordered iterable of existing sections.
 
2510
 
 
2511
        :returns: An iterable of (name, dict).
 
2512
        """
 
2513
        raise NotImplementedError(self.get_sections)
 
2514
 
 
2515
    def get_mutable_section(self, section_name=None):
 
2516
        """Returns the specified mutable section.
 
2517
 
 
2518
        :param section_name: The section identifier
 
2519
        """
 
2520
        raise NotImplementedError(self.get_mutable_section)
 
2521
 
 
2522
    def __repr__(self):
 
2523
        # Mostly for debugging use
 
2524
        return "<config.%s(%s)>" % (self.__class__.__name__,
 
2525
                                    self.external_url())
 
2526
 
 
2527
 
 
2528
class IniFileStore(Store):
 
2529
    """A config Store using ConfigObj for storage.
 
2530
 
 
2531
    :ivar transport: The transport object where the config file is located.
 
2532
 
 
2533
    :ivar file_name: The config file basename in the transport directory.
 
2534
 
 
2535
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
 
2536
        serialize/deserialize the config file.
 
2537
    """
 
2538
 
 
2539
    def __init__(self, transport, file_name):
 
2540
        """A config Store using ConfigObj for storage.
 
2541
 
 
2542
        :param transport: The transport object where the config file is located.
 
2543
 
 
2544
        :param file_name: The config file basename in the transport directory.
 
2545
        """
 
2546
        super(IniFileStore, self).__init__()
 
2547
        self.transport = transport
 
2548
        self.file_name = file_name
 
2549
        self._config_obj = None
 
2550
 
 
2551
    def is_loaded(self):
 
2552
        return self._config_obj != None
 
2553
 
 
2554
    def unload(self):
 
2555
        self._config_obj = None
 
2556
 
 
2557
    def load(self):
 
2558
        """Load the store from the associated file."""
 
2559
        if self.is_loaded():
 
2560
            return
 
2561
        content = self.transport.get_bytes(self.file_name)
 
2562
        self._load_from_string(content)
 
2563
        for hook in ConfigHooks['load']:
 
2564
            hook(self)
 
2565
 
 
2566
    def _load_from_string(self, bytes):
 
2567
        """Create a config store from a string.
 
2568
 
 
2569
        :param bytes: A string representing the file content.
 
2570
        """
 
2571
        if self.is_loaded():
 
2572
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
 
2573
        co_input = StringIO(bytes)
 
2574
        try:
 
2575
            # The config files are always stored utf8-encoded
 
2576
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
 
2577
        except configobj.ConfigObjError, e:
 
2578
            self._config_obj = None
 
2579
            raise errors.ParseConfigError(e.errors, self.external_url())
 
2580
        except UnicodeDecodeError:
 
2581
            raise errors.ConfigContentError(self.external_url())
 
2582
 
 
2583
    def save(self):
 
2584
        if not self.is_loaded():
 
2585
            # Nothing to save
 
2586
            return
 
2587
        out = StringIO()
 
2588
        self._config_obj.write(out)
 
2589
        self.transport.put_bytes(self.file_name, out.getvalue())
 
2590
        for hook in ConfigHooks['save']:
 
2591
            hook(self)
 
2592
 
 
2593
    def external_url(self):
 
2594
        # FIXME: external_url should really accepts an optional relpath
 
2595
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
2596
        # The following will do in the interim but maybe we don't want to
 
2597
        # expose a path here but rather a config ID and its associated
 
2598
        # object </hand wawe>.
 
2599
        return urlutils.join(self.transport.external_url(), self.file_name)
 
2600
 
 
2601
    def get_sections(self):
 
2602
        """Get the configobj section in the file order.
 
2603
 
 
2604
        :returns: An iterable of (name, dict).
 
2605
        """
 
2606
        # We need a loaded store
 
2607
        try:
 
2608
            self.load()
 
2609
        except errors.NoSuchFile:
 
2610
            # If the file doesn't exist, there is no sections
 
2611
            return
 
2612
        cobj = self._config_obj
 
2613
        if cobj.scalars:
 
2614
            yield self.readonly_section_class(None, cobj)
 
2615
        for section_name in cobj.sections:
 
2616
            yield self.readonly_section_class(section_name, cobj[section_name])
 
2617
 
 
2618
    def get_mutable_section(self, section_name=None):
 
2619
        # We need a loaded store
 
2620
        try:
 
2621
            self.load()
 
2622
        except errors.NoSuchFile:
 
2623
            # The file doesn't exist, let's pretend it was empty
 
2624
            self._load_from_string('')
 
2625
        if section_name is None:
 
2626
            section = self._config_obj
 
2627
        else:
 
2628
            section = self._config_obj.setdefault(section_name, {})
 
2629
        return self.mutable_section_class(section_name, section)
 
2630
 
 
2631
 
 
2632
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
 
2633
# unlockable stores for use with objects that can already ensure the locking
 
2634
# (think branches). If different stores (not based on ConfigObj) are created,
 
2635
# they may face the same issue.
 
2636
 
 
2637
 
 
2638
class LockableIniFileStore(IniFileStore):
 
2639
    """A ConfigObjStore using locks on save to ensure store integrity."""
 
2640
 
 
2641
    def __init__(self, transport, file_name, lock_dir_name=None):
 
2642
        """A config Store using ConfigObj for storage.
 
2643
 
 
2644
        :param transport: The transport object where the config file is located.
 
2645
 
 
2646
        :param file_name: The config file basename in the transport directory.
 
2647
        """
 
2648
        if lock_dir_name is None:
 
2649
            lock_dir_name = 'lock'
 
2650
        self.lock_dir_name = lock_dir_name
 
2651
        super(LockableIniFileStore, self).__init__(transport, file_name)
 
2652
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
 
2653
 
 
2654
    def lock_write(self, token=None):
 
2655
        """Takes a write lock in the directory containing the config file.
 
2656
 
 
2657
        If the directory doesn't exist it is created.
 
2658
        """
 
2659
        # FIXME: This doesn't check the ownership of the created directories as
 
2660
        # ensure_config_dir_exists does. It should if the transport is local
 
2661
        # -- vila 2011-04-06
 
2662
        self.transport.create_prefix()
 
2663
        return self._lock.lock_write(token)
 
2664
 
 
2665
    def unlock(self):
 
2666
        self._lock.unlock()
 
2667
 
 
2668
    def break_lock(self):
 
2669
        self._lock.break_lock()
 
2670
 
 
2671
    @needs_write_lock
 
2672
    def save(self):
 
2673
        # We need to be able to override the undecorated implementation
 
2674
        self.save_without_locking()
 
2675
 
 
2676
    def save_without_locking(self):
 
2677
        super(LockableIniFileStore, self).save()
 
2678
 
 
2679
 
 
2680
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
 
2681
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
 
2682
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
 
2683
 
 
2684
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
 
2685
# functions or a registry will make it easier and clearer for tests, focusing
 
2686
# on the relevant parts of the API that needs testing -- vila 20110503 (based
 
2687
# on a poolie's remark)
 
2688
class GlobalStore(LockableIniFileStore):
 
2689
 
 
2690
    def __init__(self, possible_transports=None):
 
2691
        t = transport.get_transport_from_path(
 
2692
            config_dir(), possible_transports=possible_transports)
 
2693
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
2694
 
 
2695
 
 
2696
class LocationStore(LockableIniFileStore):
 
2697
 
 
2698
    def __init__(self, possible_transports=None):
 
2699
        t = transport.get_transport_from_path(
 
2700
            config_dir(), possible_transports=possible_transports)
 
2701
        super(LocationStore, self).__init__(t, 'locations.conf')
 
2702
 
 
2703
 
 
2704
class BranchStore(IniFileStore):
 
2705
 
 
2706
    def __init__(self, branch):
 
2707
        super(BranchStore, self).__init__(branch.control_transport,
 
2708
                                          'branch.conf')
 
2709
        self.branch = branch
 
2710
 
 
2711
    def lock_write(self, token=None):
 
2712
        return self.branch.lock_write(token)
 
2713
 
 
2714
    def unlock(self):
 
2715
        return self.branch.unlock()
 
2716
 
 
2717
    @needs_write_lock
 
2718
    def save(self):
 
2719
        # We need to be able to override the undecorated implementation
 
2720
        self.save_without_locking()
 
2721
 
 
2722
    def save_without_locking(self):
 
2723
        super(BranchStore, self).save()
 
2724
 
 
2725
 
 
2726
class SectionMatcher(object):
 
2727
    """Select sections into a given Store.
 
2728
 
 
2729
    This intended to be used to postpone getting an iterable of sections from a
 
2730
    store.
 
2731
    """
 
2732
 
 
2733
    def __init__(self, store):
 
2734
        self.store = store
 
2735
 
 
2736
    def get_sections(self):
 
2737
        # This is where we require loading the store so we can see all defined
 
2738
        # sections.
 
2739
        sections = self.store.get_sections()
 
2740
        # Walk the revisions in the order provided
 
2741
        for s in sections:
 
2742
            if self.match(s):
 
2743
                yield s
 
2744
 
 
2745
    def match(self, secion):
 
2746
        raise NotImplementedError(self.match)
 
2747
 
 
2748
 
 
2749
class LocationSection(Section):
 
2750
 
 
2751
    def __init__(self, section, length, extra_path):
 
2752
        super(LocationSection, self).__init__(section.id, section.options)
 
2753
        self.length = length
 
2754
        self.extra_path = extra_path
 
2755
 
 
2756
    def get(self, name, default=None):
 
2757
        value = super(LocationSection, self).get(name, default)
 
2758
        if value is not None:
 
2759
            policy_name = self.get(name + ':policy', None)
 
2760
            policy = _policy_value.get(policy_name, POLICY_NONE)
 
2761
            if policy == POLICY_APPENDPATH:
 
2762
                value = urlutils.join(value, self.extra_path)
 
2763
        return value
 
2764
 
 
2765
 
 
2766
class LocationMatcher(SectionMatcher):
 
2767
 
 
2768
    def __init__(self, store, location):
 
2769
        super(LocationMatcher, self).__init__(store)
 
2770
        if location.startswith('file://'):
 
2771
            location = urlutils.local_path_from_url(location)
 
2772
        self.location = location
 
2773
 
 
2774
    def _get_matching_sections(self):
 
2775
        """Get all sections matching ``location``."""
 
2776
        # We slightly diverge from LocalConfig here by allowing the no-name
 
2777
        # section as the most generic one and the lower priority.
 
2778
        no_name_section = None
 
2779
        sections = []
 
2780
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
2781
        # used (it assumes all sections have a name).
 
2782
        for section in self.store.get_sections():
 
2783
            if section.id is None:
 
2784
                no_name_section = section
 
2785
            else:
 
2786
                sections.append(section)
 
2787
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
2788
        # we have to resync.
 
2789
        filtered_sections = _iter_for_location_by_parts(
 
2790
            [s.id for s in sections], self.location)
 
2791
        iter_sections = iter(sections)
 
2792
        matching_sections = []
 
2793
        if no_name_section is not None:
 
2794
            matching_sections.append(
 
2795
                LocationSection(no_name_section, 0, self.location))
 
2796
        for section_id, extra_path, length in filtered_sections:
 
2797
            # a section id is unique for a given store so it's safe to iterate
 
2798
            # again
 
2799
            section = iter_sections.next()
 
2800
            if section_id == section.id:
 
2801
                matching_sections.append(
 
2802
                    LocationSection(section, length, extra_path))
 
2803
        return matching_sections
 
2804
 
 
2805
    def get_sections(self):
 
2806
        # Override the default implementation as we want to change the order
 
2807
        matching_sections = self._get_matching_sections()
 
2808
        # We want the longest (aka more specific) locations first
 
2809
        sections = sorted(matching_sections,
 
2810
                          key=lambda section: (section.length, section.id),
 
2811
                          reverse=True)
 
2812
        # Sections mentioning 'ignore_parents' restrict the selection
 
2813
        for section in sections:
 
2814
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
 
2815
            ignore = section.get('ignore_parents', None)
 
2816
            if ignore is not None:
 
2817
                ignore = ui.bool_from_string(ignore)
 
2818
            if ignore:
 
2819
                break
 
2820
            # Finally, we have a valid section
 
2821
            yield section
 
2822
 
 
2823
 
 
2824
class Stack(object):
 
2825
    """A stack of configurations where an option can be defined"""
 
2826
 
 
2827
    def __init__(self, sections_def, store=None, mutable_section_name=None):
 
2828
        """Creates a stack of sections with an optional store for changes.
 
2829
 
 
2830
        :param sections_def: A list of Section or callables that returns an
 
2831
            iterable of Section. This defines the Sections for the Stack and
 
2832
            can be called repeatedly if needed.
 
2833
 
 
2834
        :param store: The optional Store where modifications will be
 
2835
            recorded. If none is specified, no modifications can be done.
 
2836
 
 
2837
        :param mutable_section_name: The name of the MutableSection where
 
2838
            changes are recorded. This requires the ``store`` parameter to be
 
2839
            specified.
 
2840
        """
 
2841
        self.sections_def = sections_def
 
2842
        self.store = store
 
2843
        self.mutable_section_name = mutable_section_name
 
2844
 
 
2845
    def get(self, name):
 
2846
        """Return the *first* option value found in the sections.
 
2847
 
 
2848
        This is where we guarantee that sections coming from Store are loaded
 
2849
        lazily: the loading is delayed until we need to either check that an
 
2850
        option exists or get its value, which in turn may require to discover
 
2851
        in which sections it can be defined. Both of these (section and option
 
2852
        existence) require loading the store (even partially).
 
2853
        """
 
2854
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
2855
        value = None
 
2856
        # Ensuring lazy loading is achieved by delaying section matching (which
 
2857
        # implies querying the persistent storage) until it can't be avoided
 
2858
        # anymore by using callables to describe (possibly empty) section
 
2859
        # lists.
 
2860
        for section_or_callable in self.sections_def:
 
2861
            # Each section can expand to multiple ones when a callable is used
 
2862
            if callable(section_or_callable):
 
2863
                sections = section_or_callable()
 
2864
            else:
 
2865
                sections = [section_or_callable]
 
2866
            for section in sections:
 
2867
                value = section.get(name)
 
2868
                if value is not None:
 
2869
                    break
 
2870
            if value is not None:
 
2871
                break
 
2872
        # If the option is registered, it may provide additional info about
 
2873
        # value handling
 
2874
        try:
 
2875
            opt = option_registry.get(name)
 
2876
        except KeyError:
 
2877
            # Not registered
 
2878
            opt = None
 
2879
        if (opt is not None and opt.from_unicode is not None
 
2880
            and value is not None):
 
2881
            # If a value exists and the option provides a converter, use it
 
2882
            try:
 
2883
                converted = opt.from_unicode(value)
 
2884
            except (ValueError, TypeError):
 
2885
                # Invalid values are ignored
 
2886
                converted = None
 
2887
            if converted is None and opt.invalid is not None:
 
2888
                # The conversion failed
 
2889
                if opt.invalid == 'warning':
 
2890
                    trace.warning('Value "%s" is not valid for "%s"',
 
2891
                                  value, name)
 
2892
                elif opt.invalid == 'error':
 
2893
                    raise errors.ConfigOptionValueError(name, value)
 
2894
            value = converted
 
2895
        if value is None:
 
2896
            # If the option is registered, it may provide a default value
 
2897
            if opt is not None:
 
2898
                value = opt.get_default()
 
2899
        for hook in ConfigHooks['get']:
 
2900
            hook(self, name, value)
 
2901
        return value
 
2902
 
 
2903
    def _get_mutable_section(self):
 
2904
        """Get the MutableSection for the Stack.
 
2905
 
 
2906
        This is where we guarantee that the mutable section is lazily loaded:
 
2907
        this means we won't load the corresponding store before setting a value
 
2908
        or deleting an option. In practice the store will often be loaded but
 
2909
        this allows helps catching some programming errors.
 
2910
        """
 
2911
        section = self.store.get_mutable_section(self.mutable_section_name)
 
2912
        return section
 
2913
 
 
2914
    def set(self, name, value):
 
2915
        """Set a new value for the option."""
 
2916
        section = self._get_mutable_section()
 
2917
        section.set(name, value)
 
2918
        for hook in ConfigHooks['set']:
 
2919
            hook(self, name, value)
 
2920
 
 
2921
    def remove(self, name):
 
2922
        """Remove an existing option."""
 
2923
        section = self._get_mutable_section()
 
2924
        section.remove(name)
 
2925
        for hook in ConfigHooks['remove']:
 
2926
            hook(self, name)
 
2927
 
 
2928
    def __repr__(self):
 
2929
        # Mostly for debugging use
 
2930
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
 
2931
 
 
2932
 
 
2933
class _CompatibleStack(Stack):
 
2934
    """Place holder for compatibility with previous design.
 
2935
 
 
2936
    This is intended to ease the transition from the Config-based design to the
 
2937
    Stack-based design and should not be used nor relied upon by plugins.
 
2938
 
 
2939
    One assumption made here is that the daughter classes will all use Stores
 
2940
    derived from LockableIniFileStore).
 
2941
 
 
2942
    It implements set() by re-loading the store before applying the
 
2943
    modification and saving it.
 
2944
 
 
2945
    The long term plan being to implement a single write by store to save
 
2946
    all modifications, this class should not be used in the interim.
 
2947
    """
 
2948
 
 
2949
    def set(self, name, value):
 
2950
        # Force a reload
 
2951
        self.store.unload()
 
2952
        super(_CompatibleStack, self).set(name, value)
 
2953
        # Force a write to persistent storage
 
2954
        self.store.save()
 
2955
 
 
2956
 
 
2957
class GlobalStack(_CompatibleStack):
 
2958
 
 
2959
    def __init__(self):
 
2960
        # Get a GlobalStore
 
2961
        gstore = GlobalStore()
 
2962
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
 
2963
 
 
2964
 
 
2965
class LocationStack(_CompatibleStack):
 
2966
 
 
2967
    def __init__(self, location):
 
2968
        """Make a new stack for a location and global configuration.
 
2969
        
 
2970
        :param location: A URL prefix to """
 
2971
        lstore = LocationStore()
 
2972
        matcher = LocationMatcher(lstore, location)
 
2973
        gstore = GlobalStore()
 
2974
        super(LocationStack, self).__init__(
 
2975
            [matcher.get_sections, gstore.get_sections], lstore)
 
2976
 
 
2977
class BranchStack(_CompatibleStack):
 
2978
 
 
2979
    def __init__(self, branch):
 
2980
        bstore = BranchStore(branch)
 
2981
        lstore = LocationStore()
 
2982
        matcher = LocationMatcher(lstore, branch.base)
 
2983
        gstore = GlobalStore()
 
2984
        super(BranchStack, self).__init__(
 
2985
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
 
2986
            bstore)
 
2987
        self.branch = branch
 
2988
 
 
2989
 
 
2990
class cmd_config(commands.Command):
 
2991
    __doc__ = """Display, set or remove a configuration option.
 
2992
 
 
2993
    Display the active value for a given option.
 
2994
 
 
2995
    If --all is specified, NAME is interpreted as a regular expression and all
 
2996
    matching options are displayed mentioning their scope. The active value
 
2997
    that bzr will take into account is the first one displayed for each option.
 
2998
 
 
2999
    If no NAME is given, --all .* is implied.
 
3000
 
 
3001
    Setting a value is achieved by using name=value without spaces. The value
 
3002
    is set in the most relevant scope and can be checked by displaying the
 
3003
    option again.
 
3004
    """
 
3005
 
 
3006
    takes_args = ['name?']
 
3007
 
 
3008
    takes_options = [
 
3009
        'directory',
 
3010
        # FIXME: This should be a registry option so that plugins can register
 
3011
        # their own config files (or not) -- vila 20101002
 
3012
        commands.Option('scope', help='Reduce the scope to the specified'
 
3013
                        ' configuration file',
 
3014
                        type=unicode),
 
3015
        commands.Option('all',
 
3016
            help='Display all the defined values for the matching options.',
 
3017
            ),
 
3018
        commands.Option('remove', help='Remove the option from'
 
3019
                        ' the configuration file'),
 
3020
        ]
 
3021
 
 
3022
    _see_also = ['configuration']
 
3023
 
 
3024
    @commands.display_command
 
3025
    def run(self, name=None, all=False, directory=None, scope=None,
 
3026
            remove=False):
 
3027
        if directory is None:
 
3028
            directory = '.'
 
3029
        directory = urlutils.normalize_url(directory)
 
3030
        if remove and all:
 
3031
            raise errors.BzrError(
 
3032
                '--all and --remove are mutually exclusive.')
 
3033
        elif remove:
 
3034
            # Delete the option in the given scope
 
3035
            self._remove_config_option(name, directory, scope)
 
3036
        elif name is None:
 
3037
            # Defaults to all options
 
3038
            self._show_matching_options('.*', directory, scope)
 
3039
        else:
 
3040
            try:
 
3041
                name, value = name.split('=', 1)
 
3042
            except ValueError:
 
3043
                # Display the option(s) value(s)
 
3044
                if all:
 
3045
                    self._show_matching_options(name, directory, scope)
 
3046
                else:
 
3047
                    self._show_value(name, directory, scope)
 
3048
            else:
 
3049
                if all:
 
3050
                    raise errors.BzrError(
 
3051
                        'Only one option can be set.')
 
3052
                # Set the option value
 
3053
                self._set_config_option(name, value, directory, scope)
 
3054
 
 
3055
    def _get_configs(self, directory, scope=None):
 
3056
        """Iterate the configurations specified by ``directory`` and ``scope``.
 
3057
 
 
3058
        :param directory: Where the configurations are derived from.
 
3059
 
 
3060
        :param scope: A specific config to start from.
 
3061
        """
 
3062
        if scope is not None:
 
3063
            if scope == 'bazaar':
 
3064
                yield GlobalConfig()
 
3065
            elif scope == 'locations':
 
3066
                yield LocationConfig(directory)
 
3067
            elif scope == 'branch':
 
3068
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
3069
                    directory)
 
3070
                yield br.get_config()
 
3071
        else:
 
3072
            try:
 
3073
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
3074
                    directory)
 
3075
                yield br.get_config()
 
3076
            except errors.NotBranchError:
 
3077
                yield LocationConfig(directory)
 
3078
                yield GlobalConfig()
 
3079
 
 
3080
    def _show_value(self, name, directory, scope):
 
3081
        displayed = False
 
3082
        for c in self._get_configs(directory, scope):
 
3083
            if displayed:
 
3084
                break
 
3085
            for (oname, value, section, conf_id, parser) in c._get_options():
 
3086
                if name == oname:
 
3087
                    # Display only the first value and exit
 
3088
 
 
3089
                    # FIXME: We need to use get_user_option to take policies
 
3090
                    # into account and we need to make sure the option exists
 
3091
                    # too (hence the two for loops), this needs a better API
 
3092
                    # -- vila 20101117
 
3093
                    value = c.get_user_option(name)
 
3094
                    # Quote the value appropriately
 
3095
                    value = parser._quote(value)
 
3096
                    self.outf.write('%s\n' % (value,))
 
3097
                    displayed = True
 
3098
                    break
 
3099
        if not displayed:
 
3100
            raise errors.NoSuchConfigOption(name)
 
3101
 
 
3102
    def _show_matching_options(self, name, directory, scope):
 
3103
        name = lazy_regex.lazy_compile(name)
 
3104
        # We want any error in the regexp to be raised *now* so we need to
 
3105
        # avoid the delay introduced by the lazy regexp.  But, we still do
 
3106
        # want the nicer errors raised by lazy_regex.
 
3107
        name._compile_and_collapse()
 
3108
        cur_conf_id = None
 
3109
        cur_section = None
 
3110
        for c in self._get_configs(directory, scope):
 
3111
            for (oname, value, section, conf_id, parser) in c._get_options():
 
3112
                if name.search(oname):
 
3113
                    if cur_conf_id != conf_id:
 
3114
                        # Explain where the options are defined
 
3115
                        self.outf.write('%s:\n' % (conf_id,))
 
3116
                        cur_conf_id = conf_id
 
3117
                        cur_section = None
 
3118
                    if (section not in (None, 'DEFAULT')
 
3119
                        and cur_section != section):
 
3120
                        # Display the section if it's not the default (or only)
 
3121
                        # one.
 
3122
                        self.outf.write('  [%s]\n' % (section,))
 
3123
                        cur_section = section
 
3124
                    self.outf.write('  %s = %s\n' % (oname, value))
 
3125
 
 
3126
    def _set_config_option(self, name, value, directory, scope):
 
3127
        for conf in self._get_configs(directory, scope):
 
3128
            conf.set_user_option(name, value)
 
3129
            break
 
3130
        else:
 
3131
            raise errors.NoSuchConfig(scope)
 
3132
 
 
3133
    def _remove_config_option(self, name, directory, scope):
 
3134
        if name is None:
 
3135
            raise errors.BzrCommandError(
 
3136
                '--remove expects an option to remove.')
 
3137
        removed = False
 
3138
        for conf in self._get_configs(directory, scope):
 
3139
            for (section_name, section, conf_id) in conf._get_sections():
 
3140
                if scope is not None and conf_id != scope:
 
3141
                    # Not the right configuration file
 
3142
                    continue
 
3143
                if name in section:
 
3144
                    if conf_id != conf.config_id():
 
3145
                        conf = self._get_configs(directory, conf_id).next()
 
3146
                    # We use the first section in the first config where the
 
3147
                    # option is defined to remove it
 
3148
                    conf.remove_user_option(name, section_name)
 
3149
                    removed = True
 
3150
                    break
 
3151
            break
 
3152
        else:
 
3153
            raise errors.NoSuchConfig(scope)
 
3154
        if not removed:
 
3155
            raise errors.NoSuchConfigOption(name)
 
3156
 
 
3157
# Test registries
 
3158
#
 
3159
# We need adapters that can build a Store or a Stack in a test context. Test
 
3160
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
3161
# themselves. The builder will receive a test instance and should return a
 
3162
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
3163
# register themselves here to be tested against the tests defined in
 
3164
# bzrlib.tests.test_config. Note that the builder can be called multiple times
 
3165
# for the same tests.
 
3166
 
 
3167
# The registered object should be a callable receiving a test instance
 
3168
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
3169
# object.
 
3170
test_store_builder_registry = registry.Registry()
 
3171
 
 
3172
# The registered object should be a callable receiving a test instance
 
3173
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
3174
# object.
 
3175
test_stack_builder_registry = registry.Registry()