~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-06-22 17:11:20 UTC
  • mfrom: (4398.8.10 1.16-commit-fulltext)
  • Revision ID: pqm@pqm.ubuntu.com-20090622171120-fuxez9ylfqpxynqn
(jam) Add VF._add_text and reduce memory overhead during commit (see
        bug #109114)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2007, 2008 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
35
32
 
36
33
in locations.conf, you specify the url of a branch and options for it.
37
34
Wildcards may be used - * and ? as normal in shell completion. Options
42
39
email= as above
43
40
check_signatures= as above
44
41
create_signatures= as above.
45
 
validate_signatures_in_log=as above
46
 
acceptable_keys=as above
47
42
 
48
43
explanation of options
49
44
----------------------
50
45
editor - this option sets the pop up editor to use during commits.
51
46
email - this option sets the user id bzr will use when committing.
52
 
check_signatures - this option will control whether bzr will require good gpg
 
47
check_signatures - this option controls whether bzr will require good gpg
53
48
                   signatures, ignore them, or check them if they are
54
 
                   present.  Currently it is unused except that check_signatures
55
 
                   turns on create_signatures.
 
49
                   present.
56
50
create_signatures - this option controls whether bzr will always create
57
 
                    gpg signatures or not on commits.  There is an unused
58
 
                    option which in future is expected to work if               
59
 
                    branch settings require signatures.
 
51
                    gpg signatures, never create them, or create them if the
 
52
                    branch is configured to require them.
60
53
log_format - this option sets the default log format.  Possible values are
61
54
             long, short, line, or a plugin can register new formats.
62
 
validate_signatures_in_log - show GPG signature validity in log output
63
 
acceptable_keys - comma separated list of key patterns acceptable for
64
 
                  verify-signatures command
65
55
 
66
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
67
57
 
73
63
"""
74
64
 
75
65
import os
76
 
import string
77
66
import sys
78
67
 
79
 
 
80
 
from bzrlib.decorators import needs_write_lock
81
68
from bzrlib.lazy_import import lazy_import
82
69
lazy_import(globals(), """
83
 
import fnmatch
 
70
import errno
 
71
from fnmatch import fnmatch
84
72
import re
85
73
from cStringIO import StringIO
86
74
 
 
75
import bzrlib
87
76
from bzrlib import (
88
 
    atomicfile,
89
 
    bzrdir,
90
77
    debug,
91
78
    errors,
92
 
    lazy_regex,
93
 
    lockdir,
94
79
    mail_client,
95
 
    mergetools,
96
80
    osutils,
 
81
    registry,
97
82
    symbol_versioning,
98
83
    trace,
99
 
    transport,
100
84
    ui,
101
85
    urlutils,
102
86
    win32utils,
103
87
    )
104
88
from bzrlib.util.configobj import configobj
105
89
""")
106
 
from bzrlib import (
107
 
    commands,
108
 
    hooks,
109
 
    registry,
110
 
    )
111
 
from bzrlib.symbol_versioning import (
112
 
    deprecated_in,
113
 
    deprecated_method,
114
 
    )
115
90
 
116
91
 
117
92
CHECK_IF_POSSIBLE=0
147
122
STORE_BRANCH = 3
148
123
STORE_GLOBAL = 4
149
124
 
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
 
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)
191
144
 
192
145
 
193
146
class Config(object):
194
147
    """A configuration policy - what username, editor, gpg needs etc."""
195
148
 
196
 
    def __init__(self):
197
 
        super(Config, self).__init__()
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)))
204
149
    def get_editor(self):
205
150
        """Get the users pop up editor."""
206
151
        raise NotImplementedError
207
152
 
208
 
    def get_change_editor(self, old_tree, new_tree):
209
 
        from bzrlib import diff
210
 
        cmd = self._get_change_editor()
211
 
        if cmd is None:
212
 
            return None
213
 
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
214
 
                                             sys.stdout)
215
 
 
216
153
    def get_mail_client(self):
217
154
        """Get a mail client to use"""
218
155
        selected_client = self.get_user_option('mail_client')
229
166
    def _get_signing_policy(self):
230
167
        """Template method to override signature creation policy."""
231
168
 
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
 
 
356
169
    def _get_user_option(self, option_name):
357
170
        """Template method to provide a user option."""
358
171
        return None
359
172
 
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
390
 
        :return None if the option doesn't exist or its value can't be
391
 
            interpreted as a boolean. Returns True or False otherwise.
392
 
        """
393
 
        s = self.get_user_option(option_name, expand=expand)
394
 
        if s is None:
395
 
            # The option doesn't exist
396
 
            return default
397
 
        val = ui.bool_from_string(s)
398
 
        if val is None:
399
 
            # The value can't be interpreted as a boolean
400
 
            trace.warning('Value "%s" is not a boolean for "%s"',
401
 
                          s, option_name)
402
 
        return val
403
 
 
404
 
    def get_user_option_as_list(self, option_name, expand=None):
405
 
        """Get a generic option as a list - no special process, no default.
406
 
 
407
 
        :return None if the option doesn't exist. Returns the value as a list
408
 
            otherwise.
409
 
        """
410
 
        l = self.get_user_option(option_name, expand=expand)
411
 
        if isinstance(l, (str, unicode)):
412
 
            # A single value, most probably the user forgot (or didn't care to
413
 
            # add) the final ','
414
 
            l = [l]
415
 
        return l
 
173
    def get_user_option(self, option_name):
 
174
        """Get a generic option - no special process, no default."""
 
175
        return self._get_user_option(option_name)
416
176
 
417
177
    def gpg_signing_command(self):
418
178
        """What program should be used to sign signatures?"""
436
196
        """See log_format()."""
437
197
        return None
438
198
 
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
 
199
    def __init__(self):
 
200
        super(Config, self).__init__()
461
201
 
462
202
    def post_commit(self):
463
203
        """An ordered list of python functions to call.
479
219
 
480
220
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
481
221
 
482
 
        $BZR_EMAIL can be set to override this, then
 
222
        $BZR_EMAIL can be set to override this (as well as the
 
223
        deprecated $BZREMAIL), then
483
224
        the concrete policy type is checked, and finally
484
225
        $EMAIL is examined.
485
 
        If no username can be found, errors.NoWhoami exception is raised.
 
226
        If none is found, a reasonable default is (hopefully)
 
227
        created.
 
228
 
 
229
        TODO: Check it's reasonably well-formed.
486
230
        """
487
231
        v = os.environ.get('BZR_EMAIL')
488
232
        if v:
489
233
            return v.decode(osutils.get_user_encoding())
 
234
 
490
235
        v = self._get_user_id()
491
236
        if v:
492
237
            return v
 
238
 
493
239
        v = os.environ.get('EMAIL')
494
240
        if v:
495
241
            return v.decode(osutils.get_user_encoding())
 
242
 
496
243
        name, email = _auto_user_id()
497
 
        if name and email:
 
244
        if name:
498
245
            return '%s <%s>' % (name, email)
499
 
        elif email:
 
246
        else:
500
247
            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()
509
248
 
510
249
    def signature_checking(self):
511
250
        """What is the current policy for signature checking?."""
527
266
        if policy is None:
528
267
            policy = self._get_signature_checking()
529
268
            if policy is not None:
530
 
                #this warning should go away once check_signatures is
531
 
                #implemented (if not before)
532
269
                trace.warning("Please use create_signatures,"
533
270
                              " not check_signatures to set signing policy.")
 
271
            if policy == CHECK_ALWAYS:
 
272
                return True
534
273
        elif policy == SIGN_ALWAYS:
535
274
            return True
536
275
        return False
537
276
 
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
 
 
546
277
    def get_alias(self, value):
547
278
        return self._get_alias(value)
548
279
 
564
295
                path = 'bzr'
565
296
            return path
566
297
 
567
 
    def suppress_warning(self, warning):
568
 
        """Should the warning be suppressed or emitted.
569
 
 
570
 
        :param warning: The name of the warning being tested.
571
 
 
572
 
        :returns: True if the warning should be suppressed, False otherwise.
573
 
        """
574
 
        warnings = self.get_user_option_as_list('suppress_warnings')
575
 
        if warnings is None or warning not in warnings:
576
 
            return False
577
 
        else:
578
 
            return True
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
 
 
669
298
 
670
299
class IniBasedConfig(Config):
671
300
    """A configuration policy that draws from ini files."""
672
301
 
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
 
        """
679
 
        super(IniBasedConfig, self).__init__()
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
692
 
        self._parser = None
693
 
 
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):
 
302
    def _get_parser(self, file=None):
717
303
        if self._parser is not None:
718
304
            return self._parser
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')
 
305
        if file is None:
 
306
            input = self._get_filename()
729
307
        else:
730
 
            co_input = self.file_name
 
308
            input = file
731
309
        try:
732
 
            self._parser = ConfigObj(co_input, encoding='utf-8')
 
310
            self._parser = ConfigObj(input, encoding='utf-8')
733
311
        except configobj.ConfigObjError, e:
734
312
            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)
741
313
        return self._parser
742
314
 
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
 
 
752
315
    def _get_matching_sections(self):
753
316
        """Return an ordered list of (section_name, extra_path) pairs.
754
317
 
765
328
        """Override this to define the section used by the config."""
766
329
        return "DEFAULT"
767
330
 
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
 
 
817
331
    def _get_option_policy(self, section, option_name):
818
332
        """Return the policy for the given (section, option_name) pair."""
819
333
        return POLICY_NONE
820
334
 
821
 
    def _get_change_editor(self):
822
 
        return self.get_user_option('change_editor')
823
 
 
824
335
    def _get_signature_checking(self):
825
336
        """See Config._get_signature_checking."""
826
337
        policy = self._get_user_option('check_signatures')
870
381
        """See Config.log_format."""
871
382
        return self._get_user_option('log_format')
872
383
 
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')
 
384
    def __init__(self, get_filename):
 
385
        super(IniBasedConfig, self).__init__()
 
386
        self._get_filename = get_filename
 
387
        self._parser = None
880
388
 
881
389
    def _post_commit(self):
882
390
        """See Config.post_commit."""
914
422
    def _get_nickname(self):
915
423
        return self.get_user_option('nickname')
916
424
 
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):
 
425
 
 
426
class GlobalConfig(IniBasedConfig):
1028
427
    """The configuration that should be used for a specific location."""
1029
428
 
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)))
1050
429
    def get_editor(self):
1051
430
        return self._get_user_option('editor')
1052
431
 
1053
 
    @needs_write_lock
 
432
    def __init__(self):
 
433
        super(GlobalConfig, self).__init__(config_filename)
 
434
 
1054
435
    def set_user_option(self, option, value):
1055
436
        """Save option and its value in the configuration."""
1056
437
        self._set_option(option, value, 'DEFAULT')
1062
443
        else:
1063
444
            return {}
1064
445
 
1065
 
    @needs_write_lock
1066
446
    def set_alias(self, alias_name, alias_command):
1067
447
        """Save the alias in the configuration."""
1068
448
        self._set_option(alias_name, alias_command, 'ALIASES')
1069
449
 
1070
 
    @needs_write_lock
1071
450
    def unset_alias(self, alias_name):
1072
451
        """Unset an existing alias."""
1073
 
        self.reload()
1074
452
        aliases = self._get_parser().get('ALIASES')
1075
453
        if not aliases or alias_name not in aliases:
1076
454
            raise errors.NoSuchAlias(alias_name)
1078
456
        self._write_config_file()
1079
457
 
1080
458
    def _set_option(self, option, value, section):
1081
 
        self.reload()
 
459
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
460
        # file lock on bazaar.conf.
 
461
        conf_dir = os.path.dirname(self._get_filename())
 
462
        ensure_config_dir_exists(conf_dir)
1082
463
        self._get_parser().setdefault(section, {})[option] = value
1083
464
        self._write_config_file()
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):
 
465
 
 
466
    def _write_config_file(self):
 
467
        f = open(self._get_filename(), 'wb')
 
468
        self._get_parser().write(f)
 
469
        f.close()
 
470
 
 
471
 
 
472
class LocationConfig(IniBasedConfig):
1163
473
    """A configuration object that gives the policy for a location."""
1164
474
 
1165
475
    def __init__(self, location):
1166
 
        super(LocationConfig, self).__init__(
1167
 
            file_name=locations_config_filename())
 
476
        name_generator = locations_config_filename
 
477
        if (not os.path.exists(name_generator()) and
 
478
                os.path.exists(branches_config_filename())):
 
479
            if sys.platform == 'win32':
 
480
                trace.warning('Please rename %s to %s'
 
481
                              % (branches_config_filename(),
 
482
                                 locations_config_filename()))
 
483
            else:
 
484
                trace.warning('Please rename ~/.bazaar/branches.conf'
 
485
                              ' to ~/.bazaar/locations.conf')
 
486
            name_generator = branches_config_filename
 
487
        super(LocationConfig, self).__init__(name_generator)
1168
488
        # local file locations are looked up by local path, rather than
1169
489
        # by file url. This is because the config file is a user
1170
490
        # file, and we would rather not expose the user to file urls.
1172
492
            location = urlutils.local_path_from_url(location)
1173
493
        self.location = location
1174
494
 
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
 
 
1193
495
    def _get_matching_sections(self):
1194
496
        """Return an ordered list of section names matching this location."""
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
 
497
        sections = self._get_parser()
 
498
        location_names = self.location.split('/')
 
499
        if self.location.endswith('/'):
 
500
            del location_names[-1]
 
501
        matches=[]
 
502
        for section in sections:
 
503
            # location is a local path if possible, so we need
 
504
            # to convert 'file://' urls to local paths if necessary.
 
505
            # This also avoids having file:///path be a more exact
 
506
            # match than '/path'.
 
507
            if section.startswith('file://'):
 
508
                section_path = urlutils.local_path_from_url(section)
 
509
            else:
 
510
                section_path = section
 
511
            section_names = section_path.split('/')
 
512
            if section.endswith('/'):
 
513
                del section_names[-1]
 
514
            names = zip(location_names, section_names)
 
515
            matched = True
 
516
            for name in names:
 
517
                if not fnmatch(name[0], name[1]):
 
518
                    matched = False
 
519
                    break
 
520
            if not matched:
 
521
                continue
 
522
            # so, for the common prefix they matched.
 
523
            # if section is longer, no match.
 
524
            if len(section_names) > len(location_names):
 
525
                continue
 
526
            matches.append((len(section_names), section,
 
527
                            '/'.join(location_names[len(section_names):])))
 
528
        matches.sort(reverse=True)
 
529
        sections = []
 
530
        for (length, section, extra_path) in matches:
 
531
            sections.append((section, extra_path))
1203
532
            # should we stop looking for parent configs here?
1204
533
            try:
1205
534
                if self._get_parser()[section].as_bool('ignore_parents'):
1206
535
                    break
1207
536
            except KeyError:
1208
537
                pass
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())
 
538
        return sections
1217
539
 
1218
540
    def _get_option_policy(self, section, option_name):
1219
541
        """Return the policy for the given (section, option_name) pair."""
1263
585
            if policy_key in self._get_parser()[section]:
1264
586
                del self._get_parser()[section][policy_key]
1265
587
 
1266
 
    @needs_write_lock
1267
588
    def set_user_option(self, option, value, store=STORE_LOCATION):
1268
589
        """Save option and its value in the configuration."""
1269
590
        if store not in [STORE_LOCATION,
1271
592
                         STORE_LOCATION_APPENDPATH]:
1272
593
            raise ValueError('bad storage policy %r for %r' %
1273
594
                (store, option))
1274
 
        self.reload()
 
595
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
596
        # file lock on locations.conf.
 
597
        conf_dir = os.path.dirname(self._get_filename())
 
598
        ensure_config_dir_exists(conf_dir)
1275
599
        location = self.location
1276
600
        if location.endswith('/'):
1277
601
            location = location[:-1]
1278
 
        parser = self._get_parser()
1279
 
        if not location in parser and not location + '/' in parser:
1280
 
            parser[location] = {}
1281
 
        elif location + '/' in parser:
 
602
        if (not location in self._get_parser() and
 
603
            not location + '/' in self._get_parser()):
 
604
            self._get_parser()[location]={}
 
605
        elif location + '/' in self._get_parser():
1282
606
            location = location + '/'
1283
 
        parser[location][option]=value
 
607
        self._get_parser()[location][option]=value
1284
608
        # the allowed values of store match the config policies
1285
609
        self._set_option_policy(location, option, store)
1286
 
        self._write_config_file()
1287
 
        for hook in OldConfigHooks['set']:
1288
 
            hook(self, option, value)
 
610
        self._get_parser().write(file(self._get_filename(), 'wb'))
1289
611
 
1290
612
 
1291
613
class BranchConfig(Config):
1292
614
    """A configuration object giving the policy for a branch."""
1293
615
 
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
 
 
1307
616
    def _get_branch_data_config(self):
1308
617
        if self._branch_data_config is None:
1309
618
            self._branch_data_config = TreeConfig(self.branch)
1310
 
            self._branch_data_config.config_id = self.config_id
1311
619
        return self._branch_data_config
1312
620
 
1313
621
    def _get_location_config(self):
1362
670
 
1363
671
        return self._get_best_value('_get_user_id')
1364
672
 
1365
 
    def _get_change_editor(self):
1366
 
        return self._get_best_value('_get_change_editor')
1367
 
 
1368
673
    def _get_signature_checking(self):
1369
674
        """See Config._get_signature_checking."""
1370
675
        return self._get_best_value('_get_signature_checking')
1381
686
                return value
1382
687
        return None
1383
688
 
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
 
 
1410
689
    def set_user_option(self, name, value, store=STORE_BRANCH,
1411
690
        warn_masked=False):
1412
691
        if store == STORE_BRANCH:
1430
709
                        trace.warning('Value "%s" is masked by "%s" from'
1431
710
                                      ' branch.conf', value, mask_value)
1432
711
 
1433
 
    def remove_user_option(self, option_name, section_name=None):
1434
 
        self._get_branch_data_config().remove_option(option_name, section_name)
1435
 
 
1436
712
    def _gpg_signing_command(self):
1437
713
        """See Config.gpg_signing_command."""
1438
714
        return self._get_safe_value('_gpg_signing_command')
1439
715
 
 
716
    def __init__(self, branch):
 
717
        super(BranchConfig, self).__init__()
 
718
        self._location_config = None
 
719
        self._branch_data_config = None
 
720
        self._global_config = None
 
721
        self.branch = branch
 
722
        self.option_sources = (self._get_location_config,
 
723
                               self._get_branch_data_config,
 
724
                               self._get_global_config)
 
725
 
1440
726
    def _post_commit(self):
1441
727
        """See Config.post_commit."""
1442
728
        return self._get_safe_value('_post_commit')
1458
744
        """See Config.log_format."""
1459
745
        return self._get_best_value('_log_format')
1460
746
 
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
 
 
1469
747
 
1470
748
def ensure_config_dir_exists(path=None):
1471
749
    """Make sure a configuration directory exists.
1480
758
            parent_dir = os.path.dirname(path)
1481
759
            if not os.path.isdir(parent_dir):
1482
760
                trace.mutter('creating config parent directory: %r', parent_dir)
1483
 
                os.mkdir(parent_dir)
 
761
            os.mkdir(parent_dir)
1484
762
        trace.mutter('creating config directory: %r', path)
1485
763
        os.mkdir(path)
1486
 
        osutils.copy_ownership_from_path(path)
1487
764
 
1488
765
 
1489
766
def config_dir():
1490
767
    """Return per-user configuration directory.
1491
768
 
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.
 
769
    By default this is ~/.bazaar/
1495
770
 
1496
771
    TODO: Global option --config-dir to override this.
1497
772
    """
1498
773
    base = os.environ.get('BZR_HOME', None)
1499
774
    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')
1504
775
        if base is None:
1505
776
            base = win32utils.get_appdata_location_unicode()
1506
777
        if base is None:
1507
778
            base = os.environ.get('HOME', None)
1508
 
            if base is not None:
1509
 
                base = base.decode('mbcs')
1510
779
        if base is None:
1511
780
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1512
781
                                  ' or HOME set')
1513
782
        return osutils.pathjoin(base, 'bazaar', '2.0')
1514
783
    else:
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
 
784
        # cygwin, linux, and darwin all have a $HOME directory
 
785
        if base is None:
1532
786
            base = os.path.expanduser("~")
1533
787
        return osutils.pathjoin(base, ".bazaar")
1534
788
 
1538
792
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
1539
793
 
1540
794
 
 
795
def branches_config_filename():
 
796
    """Return per-user configuration ini file filename."""
 
797
    return osutils.pathjoin(config_dir(), 'branches.conf')
 
798
 
 
799
 
1541
800
def locations_config_filename():
1542
801
    """Return per-user configuration ini file filename."""
1543
802
    return osutils.pathjoin(config_dir(), 'locations.conf')
1553
812
    return osutils.pathjoin(config_dir(), 'ignore')
1554
813
 
1555
814
 
1556
 
def crash_dir():
1557
 
    """Return the directory name to store crash files.
1558
 
 
1559
 
    This doesn't implicitly create it.
1560
 
 
1561
 
    On Windows it's in the config directory; elsewhere it's /var/crash
1562
 
    which may be monitored by apport.  It can be overridden by
1563
 
    $APPORT_CRASH_DIR.
1564
 
    """
1565
 
    if sys.platform == 'win32':
1566
 
        return osutils.pathjoin(config_dir(), 'Crash')
1567
 
    else:
1568
 
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
1569
 
        # 2010-01-31
1570
 
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
1571
 
 
1572
 
 
1573
 
def xdg_cache_dir():
1574
 
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
1575
 
    # Possibly this should be different on Windows?
1576
 
    e = os.environ.get('XDG_CACHE_DIR', None)
1577
 
    if e:
1578
 
        return e
1579
 
    else:
1580
 
        return os.path.expanduser('~/.cache')
1581
 
 
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
 
 
1602
815
def _auto_user_id():
1603
816
    """Calculate automatic user identification.
1604
817
 
1605
 
    :returns: (realname, email), either of which may be None if they can't be
1606
 
    determined.
 
818
    Returns (realname, email).
1607
819
 
1608
820
    Only used when none is set in the environment or the id file.
1609
821
 
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.
 
822
    This previously used the FQDN as the default domain, but that can
 
823
    be very slow on machines where DNS is broken.  So now we simply
 
824
    use the hostname.
1616
825
    """
 
826
    import socket
 
827
 
1617
828
    if sys.platform == 'win32':
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)
 
829
        name = win32utils.get_user_name_unicode()
 
830
        if name is None:
 
831
            raise errors.BzrError("Cannot autodetect user name.\n"
 
832
                                  "Please, set your name with command like:\n"
 
833
                                  'bzr whoami "Your Name <name@domain.com>"')
 
834
        host = win32utils.get_host_name_unicode()
 
835
        if host is None:
 
836
            host = socket.gethostname()
 
837
        return name, (name + '@' + host)
 
838
 
 
839
    try:
 
840
        import pwd
 
841
        uid = os.getuid()
 
842
        try:
 
843
            w = pwd.getpwuid(uid)
 
844
        except KeyError:
 
845
            raise errors.BzrCommandError('Unable to determine your name.  '
 
846
                'Please use "bzr whoami" to set it.')
 
847
 
 
848
        # we try utf-8 first, because on many variants (like Linux),
 
849
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
850
        # false positives.  (many users will have their user encoding set to
 
851
        # latin-1, which cannot raise UnicodeError.)
 
852
        try:
 
853
            gecos = w.pw_gecos.decode('utf-8')
 
854
            encoding = 'utf-8'
 
855
        except UnicodeError:
 
856
            try:
 
857
                encoding = osutils.get_user_encoding()
 
858
                gecos = w.pw_gecos.decode(encoding)
 
859
            except UnicodeError:
 
860
                raise errors.BzrCommandError('Unable to determine your name.  '
 
861
                   'Use "bzr whoami" to set it.')
 
862
        try:
 
863
            username = w.pw_name.decode(encoding)
 
864
        except UnicodeError:
 
865
            raise errors.BzrCommandError('Unable to determine your name.  '
 
866
                'Use "bzr whoami" to set it.')
 
867
 
 
868
        comma = gecos.find(',')
 
869
        if comma == -1:
 
870
            realname = gecos
 
871
        else:
 
872
            realname = gecos[:comma]
 
873
        if not realname:
 
874
            realname = username
 
875
 
 
876
    except ImportError:
 
877
        import getpass
 
878
        try:
 
879
            user_encoding = osutils.get_user_encoding()
 
880
            realname = username = getpass.getuser().decode(user_encoding)
 
881
        except UnicodeDecodeError:
 
882
            raise errors.BzrError("Can't decode username as %s." % \
 
883
                    user_encoding)
 
884
 
 
885
    return realname, (username + '@' + socket.gethostname())
1661
886
 
1662
887
 
1663
888
def parse_username(username):
1708
933
 
1709
934
    def set_option(self, value, name, section=None):
1710
935
        """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
1713
936
        self.branch.lock_write()
1714
937
        try:
1715
938
            self._config.set_option(value, name, section)
1716
939
        finally:
1717
940
            self.branch.unlock()
1718
941
 
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
 
 
1728
942
 
1729
943
class AuthenticationConfig(object):
1730
944
    """The authentication configuration file based on a ini file.
1756
970
            self._config = ConfigObj(self._input, encoding='utf-8')
1757
971
        except configobj.ConfigObjError, e:
1758
972
            raise errors.ParseConfigError(e.errors, e.config.filename)
1759
 
        except UnicodeError:
1760
 
            raise errors.ConfigContentError(self._filename)
1761
973
        return self._config
1762
974
 
1763
975
    def _save(self):
1764
976
        """Save the config file, only tests should use it for now."""
1765
977
        conf_dir = os.path.dirname(self._filename)
1766
978
        ensure_config_dir_exists(conf_dir)
1767
 
        f = file(self._filename, 'wb')
1768
 
        try:
1769
 
            self._get_config().write(f)
1770
 
        finally:
1771
 
            f.close()
 
979
        self._get_config().write(file(self._filename, 'wb'))
1772
980
 
1773
981
    def _set_option(self, section_name, option_name, value):
1774
982
        """Set an authentication configuration option"""
1780
988
        section[option_name] = value
1781
989
        self._save()
1782
990
 
1783
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
 
991
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
1784
992
                        realm=None):
1785
993
        """Returns the matching credentials from authentication.conf file.
1786
994
 
1954
1162
            if ask:
1955
1163
                if prompt is None:
1956
1164
                    # Create a default prompt suitable for most cases
1957
 
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
 
1165
                    prompt = scheme.upper() + ' %(host)s username'
1958
1166
                # Special handling for optional fields in the prompt
1959
1167
                if port is not None:
1960
1168
                    prompt_host = '%s:%d' % (host, port)
1998
1206
        if password is None:
1999
1207
            if prompt is None:
2000
1208
                # Create a default prompt suitable for most cases
2001
 
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
 
1209
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
2002
1210
            # Special handling for optional fields in the prompt
2003
1211
            if port is not None:
2004
1212
                prompt_host = '%s:%d' % (host, port)
2122
1330
 
2123
1331
 
2124
1332
class PlainTextCredentialStore(CredentialStore):
2125
 
    __doc__ = """Plain text credential store for the authentication.conf file"""
 
1333
    """Plain text credential store for the authentication.conf file."""
2126
1334
 
2127
1335
    def decode_password(self, credentials):
2128
1336
        """See CredentialStore.decode_password."""
2175
1383
    """A Config that reads/writes a config file on a Transport.
2176
1384
 
2177
1385
    It is a low-level object that considers config data to be name/value pairs
2178
 
    that may be associated with a section.  Assigning meaning to these values
2179
 
    is done at higher levels like TreeConfig.
 
1386
    that may be associated with a section.  Assigning meaning to the these
 
1387
    values is done at higher levels like TreeConfig.
2180
1388
    """
2181
1389
 
2182
1390
    def __init__(self, transport, filename):
2199
1407
                section_obj = configobj[section]
2200
1408
            except KeyError:
2201
1409
                return default
2202
 
        value = section_obj.get(name, default)
2203
 
        for hook in OldConfigHooks['get']:
2204
 
            hook(self, name, value)
2205
 
        return value
 
1410
        return section_obj.get(name, default)
2206
1411
 
2207
1412
    def set_option(self, value, name, section=None):
2208
1413
        """Set the value associated with a named option.
2216
1421
            configobj[name] = value
2217
1422
        else:
2218
1423
            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)
2231
1424
        self._set_configobj(configobj)
2232
1425
 
2233
1426
    def _get_config_file(self):
2234
1427
        try:
2235
 
            f = StringIO(self._transport.get_bytes(self._filename))
2236
 
            for hook in OldConfigHooks['load']:
2237
 
                hook(self)
2238
 
            return f
 
1428
            return self._transport.get(self._filename)
2239
1429
        except errors.NoSuchFile:
2240
1430
            return StringIO()
2241
1431
 
2242
 
    def _external_url(self):
2243
 
        return urlutils.join(self._transport.external_url(), self._filename)
2244
 
 
2245
1432
    def _get_configobj(self):
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
 
1433
        return ConfigObj(self._get_config_file(), encoding='utf-8')
2257
1434
 
2258
1435
    def _set_configobj(self, configobj):
2259
1436
        out_file = StringIO()
2260
1437
        configobj.write(out_file)
2261
1438
        out_file.seek(0)
2262
1439
        self._transport.put_file(self._filename, out_file)
2263
 
        for hook in OldConfigHooks['save']:
2264
 
            hook(self)
2265
 
 
2266
 
 
2267
 
class Option(object):
2268
 
    """An option definition.
2269
 
 
2270
 
    The option *values* are stored in config files and found in sections.
2271
 
 
2272
 
    Here we define various properties about the option itself, its default
2273
 
    value, how to convert it from stores, what to do when invalid values are
2274
 
    encoutered, in which config files it can be stored.
2275
 
    """
2276
 
 
2277
 
    def __init__(self, name, default=None, help=None, from_unicode=None,
2278
 
                 invalid=None):
2279
 
        """Build an option definition.
2280
 
 
2281
 
        :param name: the name used to refer to the option.
2282
 
 
2283
 
        :param default: the default value to use when none exist in the config
2284
 
            stores.
2285
 
 
2286
 
        :param help: a doc string to explain the option to the user.
2287
 
 
2288
 
        :param from_unicode: a callable to convert the unicode string
2289
 
            representing the option value in a store. This is not called for
2290
 
            the default value.
2291
 
 
2292
 
        :param invalid: the action to be taken when an invalid value is
2293
 
            encountered in a store. This is called only when from_unicode is
2294
 
            invoked to convert a string and returns None or raise ValueError or
2295
 
            TypeError. Accepted values are: None (ignore invalid values),
2296
 
            'warning' (emit a warning), 'error' (emit an error message and
2297
 
            terminates).
2298
 
        """
2299
 
        self.name = name
2300
 
        self.default = default
2301
 
        self.help = help
2302
 
        self.from_unicode = from_unicode
2303
 
        if invalid and invalid not in ('warning', 'error'):
2304
 
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2305
 
        self.invalid = invalid
2306
 
 
2307
 
    def get_default(self):
2308
 
        return self.default
2309
 
 
2310
 
    def get_help_text(self, additional_see_also=None, plain=True):
2311
 
        result = self.help
2312
 
        from bzrlib import help_topics
2313
 
        result += help_topics._format_see_also(additional_see_also)
2314
 
        if plain:
2315
 
            result = help_topics.help_as_plain_text(result)
2316
 
        return result
2317
 
 
2318
 
 
2319
 
# Predefined converters to get proper values from store
2320
 
 
2321
 
def bool_from_store(unicode_str):
2322
 
    return ui.bool_from_string(unicode_str)
2323
 
 
2324
 
 
2325
 
def int_from_store(unicode_str):
2326
 
    return int(unicode_str)
2327
 
 
2328
 
 
2329
 
def list_from_store(unicode_str):
2330
 
    # ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
2331
 
    if isinstance(unicode_str, (str, unicode)):
2332
 
        if unicode_str:
2333
 
            # A single value, most probably the user forgot (or didn't care to
2334
 
            # add) the final ','
2335
 
            l = [unicode_str]
2336
 
        else:
2337
 
            # The empty string, convert to empty list
2338
 
            l = []
2339
 
    else:
2340
 
        # We rely on ConfigObj providing us with a list already
2341
 
        l = unicode_str
2342
 
    return l
2343
 
 
2344
 
 
2345
 
class OptionRegistry(registry.Registry):
2346
 
    """Register config options by their name.
2347
 
 
2348
 
    This overrides ``registry.Registry`` to simplify registration by acquiring
2349
 
    some information from the option object itself.
2350
 
    """
2351
 
 
2352
 
    def register(self, option):
2353
 
        """Register a new option to its name.
2354
 
 
2355
 
        :param option: The option to register. Its name is used as the key.
2356
 
        """
2357
 
        super(OptionRegistry, self).register(option.name, option,
2358
 
                                             help=option.help)
2359
 
 
2360
 
    def register_lazy(self, key, module_name, member_name):
2361
 
        """Register a new option to be loaded on request.
2362
 
 
2363
 
        :param key: the key to request the option later. Since the registration
2364
 
            is lazy, it should be provided and match the option name.
2365
 
 
2366
 
        :param module_name: the python path to the module. Such as 'os.path'.
2367
 
 
2368
 
        :param member_name: the member of the module to return.  If empty or 
2369
 
                None, get() will return the module itself.
2370
 
        """
2371
 
        super(OptionRegistry, self).register_lazy(key,
2372
 
                                                  module_name, member_name)
2373
 
 
2374
 
    def get_help(self, key=None):
2375
 
        """Get the help text associated with the given key"""
2376
 
        option = self.get(key)
2377
 
        the_help = option.help
2378
 
        if callable(the_help):
2379
 
            return the_help(self, key)
2380
 
        return the_help
2381
 
 
2382
 
 
2383
 
option_registry = OptionRegistry()
2384
 
 
2385
 
 
2386
 
# Registered options in lexicographical order
2387
 
 
2388
 
option_registry.register(
2389
 
    Option('bzr.workingtree.worth_saving_limit', default=10,
2390
 
           from_unicode=int_from_store,  invalid='warning',
2391
 
           help='''\
2392
 
How many changes before saving the dirstate.
2393
 
 
2394
 
-1 means that we will never rewrite the dirstate file for only
2395
 
stat-cache changes. Regardless of this setting, we will always rewrite
2396
 
the dirstate file if a file is added/removed/renamed/etc. This flag only
2397
 
affects the behavior of updating the dirstate file after we notice that
2398
 
a file has been touched.
2399
 
'''))
2400
 
option_registry.register(
2401
 
    Option('dirstate.fdatasync', default=True,
2402
 
           from_unicode=bool_from_store,
2403
 
           help='''\
2404
 
Flush dirstate changes onto physical disk?
2405
 
 
2406
 
If true (default), working tree metadata changes are flushed through the
2407
 
OS buffers to physical disk.  This is somewhat slower, but means data
2408
 
should not be lost if the machine crashes.  See also repository.fdatasync.
2409
 
'''))
2410
 
option_registry.register(
2411
 
    Option('debug_flags', default=[], from_unicode=list_from_store,
2412
 
           help='Debug flags to activate.'))
2413
 
option_registry.register(
2414
 
    Option('default_format', default='2a',
2415
 
           help='Format used when creating branches.'))
2416
 
option_registry.register(
2417
 
    Option('editor',
2418
 
           help='The command called to launch an editor to enter a message.'))
2419
 
option_registry.register(
2420
 
    Option('ignore_missing_extensions', default=False,
2421
 
           from_unicode=bool_from_store,
2422
 
           help='''\
2423
 
Control the missing extensions warning display.
2424
 
 
2425
 
The warning will not be emitted if set to True.
2426
 
'''))
2427
 
option_registry.register(
2428
 
    Option('language',
2429
 
           help='Language to translate messages into.'))
2430
 
option_registry.register(
2431
 
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2432
 
           help='''\
2433
 
Steal locks that appears to be dead.
2434
 
 
2435
 
If set to True, bzr will check if a lock is supposed to be held by an
2436
 
active process from the same user on the same machine. If the user and
2437
 
machine match, but no process with the given PID is active, then bzr
2438
 
will automatically break the stale lock, and create a new lock for
2439
 
this process.
2440
 
Otherwise, bzr will prompt as normal to break the lock.
2441
 
'''))
2442
 
option_registry.register(
2443
 
    Option('output_encoding',
2444
 
           help= 'Unicode encoding for output'
2445
 
           ' (terminal encoding if not specified).'))
2446
 
option_registry.register(
2447
 
    Option('repository.fdatasync', default=True, from_unicode=bool_from_store,
2448
 
           help='''\
2449
 
Flush repository changes onto physical disk?
2450
 
 
2451
 
If true (default), repository changes are flushed through the OS buffers
2452
 
to physical disk.  This is somewhat slower, but means data should not be
2453
 
lost if the machine crashes.  See also dirstate.fdatasync.
2454
 
'''))
2455
 
 
2456
 
 
2457
 
class Section(object):
2458
 
    """A section defines a dict of option name => value.
2459
 
 
2460
 
    This is merely a read-only dict which can add some knowledge about the
2461
 
    options. It is *not* a python dict object though and doesn't try to mimic
2462
 
    its API.
2463
 
    """
2464
 
 
2465
 
    def __init__(self, section_id, options):
2466
 
        self.id = section_id
2467
 
        # We re-use the dict-like object received
2468
 
        self.options = options
2469
 
 
2470
 
    def get(self, name, default=None):
2471
 
        return self.options.get(name, default)
2472
 
 
2473
 
    def __repr__(self):
2474
 
        # Mostly for debugging use
2475
 
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2476
 
 
2477
 
 
2478
 
_NewlyCreatedOption = object()
2479
 
"""Was the option created during the MutableSection lifetime"""
2480
 
 
2481
 
 
2482
 
class MutableSection(Section):
2483
 
    """A section allowing changes and keeping track of the original values."""
2484
 
 
2485
 
    def __init__(self, section_id, options):
2486
 
        super(MutableSection, self).__init__(section_id, options)
2487
 
        self.orig = {}
2488
 
 
2489
 
    def set(self, name, value):
2490
 
        if name not in self.options:
2491
 
            # This is a new option
2492
 
            self.orig[name] = _NewlyCreatedOption
2493
 
        elif name not in self.orig:
2494
 
            self.orig[name] = self.get(name, None)
2495
 
        self.options[name] = value
2496
 
 
2497
 
    def remove(self, name):
2498
 
        if name not in self.orig:
2499
 
            self.orig[name] = self.get(name, None)
2500
 
        del self.options[name]
2501
 
 
2502
 
 
2503
 
class Store(object):
2504
 
    """Abstract interface to persistent storage for configuration options."""
2505
 
 
2506
 
    readonly_section_class = Section
2507
 
    mutable_section_class = MutableSection
2508
 
 
2509
 
    def is_loaded(self):
2510
 
        """Returns True if the Store has been loaded.
2511
 
 
2512
 
        This is used to implement lazy loading and ensure the persistent
2513
 
        storage is queried only when needed.
2514
 
        """
2515
 
        raise NotImplementedError(self.is_loaded)
2516
 
 
2517
 
    def load(self):
2518
 
        """Loads the Store from persistent storage."""
2519
 
        raise NotImplementedError(self.load)
2520
 
 
2521
 
    def _load_from_string(self, bytes):
2522
 
        """Create a store from a string in configobj syntax.
2523
 
 
2524
 
        :param bytes: A string representing the file content.
2525
 
        """
2526
 
        raise NotImplementedError(self._load_from_string)
2527
 
 
2528
 
    def unload(self):
2529
 
        """Unloads the Store.
2530
 
 
2531
 
        This should make is_loaded() return False. This is used when the caller
2532
 
        knows that the persistent storage has changed or may have change since
2533
 
        the last load.
2534
 
        """
2535
 
        raise NotImplementedError(self.unload)
2536
 
 
2537
 
    def save(self):
2538
 
        """Saves the Store to persistent storage."""
2539
 
        raise NotImplementedError(self.save)
2540
 
 
2541
 
    def external_url(self):
2542
 
        raise NotImplementedError(self.external_url)
2543
 
 
2544
 
    def get_sections(self):
2545
 
        """Returns an ordered iterable of existing sections.
2546
 
 
2547
 
        :returns: An iterable of (name, dict).
2548
 
        """
2549
 
        raise NotImplementedError(self.get_sections)
2550
 
 
2551
 
    def get_mutable_section(self, section_name=None):
2552
 
        """Returns the specified mutable section.
2553
 
 
2554
 
        :param section_name: The section identifier
2555
 
        """
2556
 
        raise NotImplementedError(self.get_mutable_section)
2557
 
 
2558
 
    def __repr__(self):
2559
 
        # Mostly for debugging use
2560
 
        return "<config.%s(%s)>" % (self.__class__.__name__,
2561
 
                                    self.external_url())
2562
 
 
2563
 
 
2564
 
class IniFileStore(Store):
2565
 
    """A config Store using ConfigObj for storage.
2566
 
 
2567
 
    :ivar transport: The transport object where the config file is located.
2568
 
 
2569
 
    :ivar file_name: The config file basename in the transport directory.
2570
 
 
2571
 
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
2572
 
        serialize/deserialize the config file.
2573
 
    """
2574
 
 
2575
 
    def __init__(self, transport, file_name):
2576
 
        """A config Store using ConfigObj for storage.
2577
 
 
2578
 
        :param transport: The transport object where the config file is located.
2579
 
 
2580
 
        :param file_name: The config file basename in the transport directory.
2581
 
        """
2582
 
        super(IniFileStore, self).__init__()
2583
 
        self.transport = transport
2584
 
        self.file_name = file_name
2585
 
        self._config_obj = None
2586
 
 
2587
 
    def is_loaded(self):
2588
 
        return self._config_obj != None
2589
 
 
2590
 
    def unload(self):
2591
 
        self._config_obj = None
2592
 
 
2593
 
    def load(self):
2594
 
        """Load the store from the associated file."""
2595
 
        if self.is_loaded():
2596
 
            return
2597
 
        content = self.transport.get_bytes(self.file_name)
2598
 
        self._load_from_string(content)
2599
 
        for hook in ConfigHooks['load']:
2600
 
            hook(self)
2601
 
 
2602
 
    def _load_from_string(self, bytes):
2603
 
        """Create a config store from a string.
2604
 
 
2605
 
        :param bytes: A string representing the file content.
2606
 
        """
2607
 
        if self.is_loaded():
2608
 
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
2609
 
        co_input = StringIO(bytes)
2610
 
        try:
2611
 
            # The config files are always stored utf8-encoded
2612
 
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
2613
 
        except configobj.ConfigObjError, e:
2614
 
            self._config_obj = None
2615
 
            raise errors.ParseConfigError(e.errors, self.external_url())
2616
 
        except UnicodeDecodeError:
2617
 
            raise errors.ConfigContentError(self.external_url())
2618
 
 
2619
 
    def save(self):
2620
 
        if not self.is_loaded():
2621
 
            # Nothing to save
2622
 
            return
2623
 
        out = StringIO()
2624
 
        self._config_obj.write(out)
2625
 
        self.transport.put_bytes(self.file_name, out.getvalue())
2626
 
        for hook in ConfigHooks['save']:
2627
 
            hook(self)
2628
 
 
2629
 
    def external_url(self):
2630
 
        # FIXME: external_url should really accepts an optional relpath
2631
 
        # parameter (bug #750169) :-/ -- vila 2011-04-04
2632
 
        # The following will do in the interim but maybe we don't want to
2633
 
        # expose a path here but rather a config ID and its associated
2634
 
        # object </hand wawe>.
2635
 
        return urlutils.join(self.transport.external_url(), self.file_name)
2636
 
 
2637
 
    def get_sections(self):
2638
 
        """Get the configobj section in the file order.
2639
 
 
2640
 
        :returns: An iterable of (name, dict).
2641
 
        """
2642
 
        # We need a loaded store
2643
 
        try:
2644
 
            self.load()
2645
 
        except errors.NoSuchFile:
2646
 
            # If the file doesn't exist, there is no sections
2647
 
            return
2648
 
        cobj = self._config_obj
2649
 
        if cobj.scalars:
2650
 
            yield self.readonly_section_class(None, cobj)
2651
 
        for section_name in cobj.sections:
2652
 
            yield self.readonly_section_class(section_name, cobj[section_name])
2653
 
 
2654
 
    def get_mutable_section(self, section_name=None):
2655
 
        # We need a loaded store
2656
 
        try:
2657
 
            self.load()
2658
 
        except errors.NoSuchFile:
2659
 
            # The file doesn't exist, let's pretend it was empty
2660
 
            self._load_from_string('')
2661
 
        if section_name is None:
2662
 
            section = self._config_obj
2663
 
        else:
2664
 
            section = self._config_obj.setdefault(section_name, {})
2665
 
        return self.mutable_section_class(section_name, section)
2666
 
 
2667
 
 
2668
 
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2669
 
# unlockable stores for use with objects that can already ensure the locking
2670
 
# (think branches). If different stores (not based on ConfigObj) are created,
2671
 
# they may face the same issue.
2672
 
 
2673
 
 
2674
 
class LockableIniFileStore(IniFileStore):
2675
 
    """A ConfigObjStore using locks on save to ensure store integrity."""
2676
 
 
2677
 
    def __init__(self, transport, file_name, lock_dir_name=None):
2678
 
        """A config Store using ConfigObj for storage.
2679
 
 
2680
 
        :param transport: The transport object where the config file is located.
2681
 
 
2682
 
        :param file_name: The config file basename in the transport directory.
2683
 
        """
2684
 
        if lock_dir_name is None:
2685
 
            lock_dir_name = 'lock'
2686
 
        self.lock_dir_name = lock_dir_name
2687
 
        super(LockableIniFileStore, self).__init__(transport, file_name)
2688
 
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2689
 
 
2690
 
    def lock_write(self, token=None):
2691
 
        """Takes a write lock in the directory containing the config file.
2692
 
 
2693
 
        If the directory doesn't exist it is created.
2694
 
        """
2695
 
        # FIXME: This doesn't check the ownership of the created directories as
2696
 
        # ensure_config_dir_exists does. It should if the transport is local
2697
 
        # -- vila 2011-04-06
2698
 
        self.transport.create_prefix()
2699
 
        return self._lock.lock_write(token)
2700
 
 
2701
 
    def unlock(self):
2702
 
        self._lock.unlock()
2703
 
 
2704
 
    def break_lock(self):
2705
 
        self._lock.break_lock()
2706
 
 
2707
 
    @needs_write_lock
2708
 
    def save(self):
2709
 
        # We need to be able to override the undecorated implementation
2710
 
        self.save_without_locking()
2711
 
 
2712
 
    def save_without_locking(self):
2713
 
        super(LockableIniFileStore, self).save()
2714
 
 
2715
 
 
2716
 
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2717
 
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2718
 
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
2719
 
 
2720
 
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2721
 
# functions or a registry will make it easier and clearer for tests, focusing
2722
 
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2723
 
# on a poolie's remark)
2724
 
class GlobalStore(LockableIniFileStore):
2725
 
 
2726
 
    def __init__(self, possible_transports=None):
2727
 
        t = transport.get_transport_from_path(
2728
 
            config_dir(), possible_transports=possible_transports)
2729
 
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
2730
 
 
2731
 
 
2732
 
class LocationStore(LockableIniFileStore):
2733
 
 
2734
 
    def __init__(self, possible_transports=None):
2735
 
        t = transport.get_transport_from_path(
2736
 
            config_dir(), possible_transports=possible_transports)
2737
 
        super(LocationStore, self).__init__(t, 'locations.conf')
2738
 
 
2739
 
 
2740
 
class BranchStore(IniFileStore):
2741
 
 
2742
 
    def __init__(self, branch):
2743
 
        super(BranchStore, self).__init__(branch.control_transport,
2744
 
                                          'branch.conf')
2745
 
        self.branch = branch
2746
 
 
2747
 
    def lock_write(self, token=None):
2748
 
        return self.branch.lock_write(token)
2749
 
 
2750
 
    def unlock(self):
2751
 
        return self.branch.unlock()
2752
 
 
2753
 
    @needs_write_lock
2754
 
    def save(self):
2755
 
        # We need to be able to override the undecorated implementation
2756
 
        self.save_without_locking()
2757
 
 
2758
 
    def save_without_locking(self):
2759
 
        super(BranchStore, self).save()
2760
 
 
2761
 
 
2762
 
class SectionMatcher(object):
2763
 
    """Select sections into a given Store.
2764
 
 
2765
 
    This intended to be used to postpone getting an iterable of sections from a
2766
 
    store.
2767
 
    """
2768
 
 
2769
 
    def __init__(self, store):
2770
 
        self.store = store
2771
 
 
2772
 
    def get_sections(self):
2773
 
        # This is where we require loading the store so we can see all defined
2774
 
        # sections.
2775
 
        sections = self.store.get_sections()
2776
 
        # Walk the revisions in the order provided
2777
 
        for s in sections:
2778
 
            if self.match(s):
2779
 
                yield s
2780
 
 
2781
 
    def match(self, secion):
2782
 
        raise NotImplementedError(self.match)
2783
 
 
2784
 
 
2785
 
class LocationSection(Section):
2786
 
 
2787
 
    def __init__(self, section, length, extra_path):
2788
 
        super(LocationSection, self).__init__(section.id, section.options)
2789
 
        self.length = length
2790
 
        self.extra_path = extra_path
2791
 
 
2792
 
    def get(self, name, default=None):
2793
 
        value = super(LocationSection, self).get(name, default)
2794
 
        if value is not None:
2795
 
            policy_name = self.get(name + ':policy', None)
2796
 
            policy = _policy_value.get(policy_name, POLICY_NONE)
2797
 
            if policy == POLICY_APPENDPATH:
2798
 
                value = urlutils.join(value, self.extra_path)
2799
 
        return value
2800
 
 
2801
 
 
2802
 
class LocationMatcher(SectionMatcher):
2803
 
 
2804
 
    def __init__(self, store, location):
2805
 
        super(LocationMatcher, self).__init__(store)
2806
 
        if location.startswith('file://'):
2807
 
            location = urlutils.local_path_from_url(location)
2808
 
        self.location = location
2809
 
 
2810
 
    def _get_matching_sections(self):
2811
 
        """Get all sections matching ``location``."""
2812
 
        # We slightly diverge from LocalConfig here by allowing the no-name
2813
 
        # section as the most generic one and the lower priority.
2814
 
        no_name_section = None
2815
 
        sections = []
2816
 
        # Filter out the no_name_section so _iter_for_location_by_parts can be
2817
 
        # used (it assumes all sections have a name).
2818
 
        for section in self.store.get_sections():
2819
 
            if section.id is None:
2820
 
                no_name_section = section
2821
 
            else:
2822
 
                sections.append(section)
2823
 
        # Unfortunately _iter_for_location_by_parts deals with section names so
2824
 
        # we have to resync.
2825
 
        filtered_sections = _iter_for_location_by_parts(
2826
 
            [s.id for s in sections], self.location)
2827
 
        iter_sections = iter(sections)
2828
 
        matching_sections = []
2829
 
        if no_name_section is not None:
2830
 
            matching_sections.append(
2831
 
                LocationSection(no_name_section, 0, self.location))
2832
 
        for section_id, extra_path, length in filtered_sections:
2833
 
            # a section id is unique for a given store so it's safe to iterate
2834
 
            # again
2835
 
            section = iter_sections.next()
2836
 
            if section_id == section.id:
2837
 
                matching_sections.append(
2838
 
                    LocationSection(section, length, extra_path))
2839
 
        return matching_sections
2840
 
 
2841
 
    def get_sections(self):
2842
 
        # Override the default implementation as we want to change the order
2843
 
        matching_sections = self._get_matching_sections()
2844
 
        # We want the longest (aka more specific) locations first
2845
 
        sections = sorted(matching_sections,
2846
 
                          key=lambda section: (section.length, section.id),
2847
 
                          reverse=True)
2848
 
        # Sections mentioning 'ignore_parents' restrict the selection
2849
 
        for section in sections:
2850
 
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
2851
 
            ignore = section.get('ignore_parents', None)
2852
 
            if ignore is not None:
2853
 
                ignore = ui.bool_from_string(ignore)
2854
 
            if ignore:
2855
 
                break
2856
 
            # Finally, we have a valid section
2857
 
            yield section
2858
 
 
2859
 
 
2860
 
class Stack(object):
2861
 
    """A stack of configurations where an option can be defined"""
2862
 
 
2863
 
    def __init__(self, sections_def, store=None, mutable_section_name=None):
2864
 
        """Creates a stack of sections with an optional store for changes.
2865
 
 
2866
 
        :param sections_def: A list of Section or callables that returns an
2867
 
            iterable of Section. This defines the Sections for the Stack and
2868
 
            can be called repeatedly if needed.
2869
 
 
2870
 
        :param store: The optional Store where modifications will be
2871
 
            recorded. If none is specified, no modifications can be done.
2872
 
 
2873
 
        :param mutable_section_name: The name of the MutableSection where
2874
 
            changes are recorded. This requires the ``store`` parameter to be
2875
 
            specified.
2876
 
        """
2877
 
        self.sections_def = sections_def
2878
 
        self.store = store
2879
 
        self.mutable_section_name = mutable_section_name
2880
 
 
2881
 
    def get(self, name):
2882
 
        """Return the *first* option value found in the sections.
2883
 
 
2884
 
        This is where we guarantee that sections coming from Store are loaded
2885
 
        lazily: the loading is delayed until we need to either check that an
2886
 
        option exists or get its value, which in turn may require to discover
2887
 
        in which sections it can be defined. Both of these (section and option
2888
 
        existence) require loading the store (even partially).
2889
 
        """
2890
 
        # FIXME: No caching of options nor sections yet -- vila 20110503
2891
 
        value = None
2892
 
        # Ensuring lazy loading is achieved by delaying section matching (which
2893
 
        # implies querying the persistent storage) until it can't be avoided
2894
 
        # anymore by using callables to describe (possibly empty) section
2895
 
        # lists.
2896
 
        for section_or_callable in self.sections_def:
2897
 
            # Each section can expand to multiple ones when a callable is used
2898
 
            if callable(section_or_callable):
2899
 
                sections = section_or_callable()
2900
 
            else:
2901
 
                sections = [section_or_callable]
2902
 
            for section in sections:
2903
 
                value = section.get(name)
2904
 
                if value is not None:
2905
 
                    break
2906
 
            if value is not None:
2907
 
                break
2908
 
        # If the option is registered, it may provide additional info about
2909
 
        # value handling
2910
 
        try:
2911
 
            opt = option_registry.get(name)
2912
 
        except KeyError:
2913
 
            # Not registered
2914
 
            opt = None
2915
 
        if (opt is not None and opt.from_unicode is not None
2916
 
            and value is not None):
2917
 
            # If a value exists and the option provides a converter, use it
2918
 
            try:
2919
 
                converted = opt.from_unicode(value)
2920
 
            except (ValueError, TypeError):
2921
 
                # Invalid values are ignored
2922
 
                converted = None
2923
 
            if converted is None and opt.invalid is not None:
2924
 
                # The conversion failed
2925
 
                if opt.invalid == 'warning':
2926
 
                    trace.warning('Value "%s" is not valid for "%s"',
2927
 
                                  value, name)
2928
 
                elif opt.invalid == 'error':
2929
 
                    raise errors.ConfigOptionValueError(name, value)
2930
 
            value = converted
2931
 
        if value is None:
2932
 
            # If the option is registered, it may provide a default value
2933
 
            if opt is not None:
2934
 
                value = opt.get_default()
2935
 
        for hook in ConfigHooks['get']:
2936
 
            hook(self, name, value)
2937
 
        return value
2938
 
 
2939
 
    def _get_mutable_section(self):
2940
 
        """Get the MutableSection for the Stack.
2941
 
 
2942
 
        This is where we guarantee that the mutable section is lazily loaded:
2943
 
        this means we won't load the corresponding store before setting a value
2944
 
        or deleting an option. In practice the store will often be loaded but
2945
 
        this allows helps catching some programming errors.
2946
 
        """
2947
 
        section = self.store.get_mutable_section(self.mutable_section_name)
2948
 
        return section
2949
 
 
2950
 
    def set(self, name, value):
2951
 
        """Set a new value for the option."""
2952
 
        section = self._get_mutable_section()
2953
 
        section.set(name, value)
2954
 
        for hook in ConfigHooks['set']:
2955
 
            hook(self, name, value)
2956
 
 
2957
 
    def remove(self, name):
2958
 
        """Remove an existing option."""
2959
 
        section = self._get_mutable_section()
2960
 
        section.remove(name)
2961
 
        for hook in ConfigHooks['remove']:
2962
 
            hook(self, name)
2963
 
 
2964
 
    def __repr__(self):
2965
 
        # Mostly for debugging use
2966
 
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2967
 
 
2968
 
 
2969
 
class _CompatibleStack(Stack):
2970
 
    """Place holder for compatibility with previous design.
2971
 
 
2972
 
    This is intended to ease the transition from the Config-based design to the
2973
 
    Stack-based design and should not be used nor relied upon by plugins.
2974
 
 
2975
 
    One assumption made here is that the daughter classes will all use Stores
2976
 
    derived from LockableIniFileStore).
2977
 
 
2978
 
    It implements set() by re-loading the store before applying the
2979
 
    modification and saving it.
2980
 
 
2981
 
    The long term plan being to implement a single write by store to save
2982
 
    all modifications, this class should not be used in the interim.
2983
 
    """
2984
 
 
2985
 
    def set(self, name, value):
2986
 
        # Force a reload
2987
 
        self.store.unload()
2988
 
        super(_CompatibleStack, self).set(name, value)
2989
 
        # Force a write to persistent storage
2990
 
        self.store.save()
2991
 
 
2992
 
 
2993
 
class GlobalStack(_CompatibleStack):
2994
 
 
2995
 
    def __init__(self):
2996
 
        # Get a GlobalStore
2997
 
        gstore = GlobalStore()
2998
 
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
2999
 
 
3000
 
 
3001
 
class LocationStack(_CompatibleStack):
3002
 
 
3003
 
    def __init__(self, location):
3004
 
        """Make a new stack for a location and global configuration.
3005
 
        
3006
 
        :param location: A URL prefix to """
3007
 
        lstore = LocationStore()
3008
 
        matcher = LocationMatcher(lstore, location)
3009
 
        gstore = GlobalStore()
3010
 
        super(LocationStack, self).__init__(
3011
 
            [matcher.get_sections, gstore.get_sections], lstore)
3012
 
 
3013
 
class BranchStack(_CompatibleStack):
3014
 
 
3015
 
    def __init__(self, branch):
3016
 
        bstore = BranchStore(branch)
3017
 
        lstore = LocationStore()
3018
 
        matcher = LocationMatcher(lstore, branch.base)
3019
 
        gstore = GlobalStore()
3020
 
        super(BranchStack, self).__init__(
3021
 
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
3022
 
            bstore)
3023
 
        self.branch = branch
3024
 
 
3025
 
 
3026
 
class cmd_config(commands.Command):
3027
 
    __doc__ = """Display, set or remove a configuration option.
3028
 
 
3029
 
    Display the active value for a given option.
3030
 
 
3031
 
    If --all is specified, NAME is interpreted as a regular expression and all
3032
 
    matching options are displayed mentioning their scope. The active value
3033
 
    that bzr will take into account is the first one displayed for each option.
3034
 
 
3035
 
    If no NAME is given, --all .* is implied.
3036
 
 
3037
 
    Setting a value is achieved by using name=value without spaces. The value
3038
 
    is set in the most relevant scope and can be checked by displaying the
3039
 
    option again.
3040
 
    """
3041
 
 
3042
 
    takes_args = ['name?']
3043
 
 
3044
 
    takes_options = [
3045
 
        'directory',
3046
 
        # FIXME: This should be a registry option so that plugins can register
3047
 
        # their own config files (or not) -- vila 20101002
3048
 
        commands.Option('scope', help='Reduce the scope to the specified'
3049
 
                        ' configuration file',
3050
 
                        type=unicode),
3051
 
        commands.Option('all',
3052
 
            help='Display all the defined values for the matching options.',
3053
 
            ),
3054
 
        commands.Option('remove', help='Remove the option from'
3055
 
                        ' the configuration file'),
3056
 
        ]
3057
 
 
3058
 
    _see_also = ['configuration']
3059
 
 
3060
 
    @commands.display_command
3061
 
    def run(self, name=None, all=False, directory=None, scope=None,
3062
 
            remove=False):
3063
 
        if directory is None:
3064
 
            directory = '.'
3065
 
        directory = urlutils.normalize_url(directory)
3066
 
        if remove and all:
3067
 
            raise errors.BzrError(
3068
 
                '--all and --remove are mutually exclusive.')
3069
 
        elif remove:
3070
 
            # Delete the option in the given scope
3071
 
            self._remove_config_option(name, directory, scope)
3072
 
        elif name is None:
3073
 
            # Defaults to all options
3074
 
            self._show_matching_options('.*', directory, scope)
3075
 
        else:
3076
 
            try:
3077
 
                name, value = name.split('=', 1)
3078
 
            except ValueError:
3079
 
                # Display the option(s) value(s)
3080
 
                if all:
3081
 
                    self._show_matching_options(name, directory, scope)
3082
 
                else:
3083
 
                    self._show_value(name, directory, scope)
3084
 
            else:
3085
 
                if all:
3086
 
                    raise errors.BzrError(
3087
 
                        'Only one option can be set.')
3088
 
                # Set the option value
3089
 
                self._set_config_option(name, value, directory, scope)
3090
 
 
3091
 
    def _get_configs(self, directory, scope=None):
3092
 
        """Iterate the configurations specified by ``directory`` and ``scope``.
3093
 
 
3094
 
        :param directory: Where the configurations are derived from.
3095
 
 
3096
 
        :param scope: A specific config to start from.
3097
 
        """
3098
 
        if scope is not None:
3099
 
            if scope == 'bazaar':
3100
 
                yield GlobalConfig()
3101
 
            elif scope == 'locations':
3102
 
                yield LocationConfig(directory)
3103
 
            elif scope == 'branch':
3104
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3105
 
                    directory)
3106
 
                yield br.get_config()
3107
 
        else:
3108
 
            try:
3109
 
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3110
 
                    directory)
3111
 
                yield br.get_config()
3112
 
            except errors.NotBranchError:
3113
 
                yield LocationConfig(directory)
3114
 
                yield GlobalConfig()
3115
 
 
3116
 
    def _show_value(self, name, directory, scope):
3117
 
        displayed = False
3118
 
        for c in self._get_configs(directory, scope):
3119
 
            if displayed:
3120
 
                break
3121
 
            for (oname, value, section, conf_id, parser) in c._get_options():
3122
 
                if name == oname:
3123
 
                    # Display only the first value and exit
3124
 
 
3125
 
                    # FIXME: We need to use get_user_option to take policies
3126
 
                    # into account and we need to make sure the option exists
3127
 
                    # too (hence the two for loops), this needs a better API
3128
 
                    # -- vila 20101117
3129
 
                    value = c.get_user_option(name)
3130
 
                    # Quote the value appropriately
3131
 
                    value = parser._quote(value)
3132
 
                    self.outf.write('%s\n' % (value,))
3133
 
                    displayed = True
3134
 
                    break
3135
 
        if not displayed:
3136
 
            raise errors.NoSuchConfigOption(name)
3137
 
 
3138
 
    def _show_matching_options(self, name, directory, scope):
3139
 
        name = lazy_regex.lazy_compile(name)
3140
 
        # We want any error in the regexp to be raised *now* so we need to
3141
 
        # avoid the delay introduced by the lazy regexp.  But, we still do
3142
 
        # want the nicer errors raised by lazy_regex.
3143
 
        name._compile_and_collapse()
3144
 
        cur_conf_id = None
3145
 
        cur_section = None
3146
 
        for c in self._get_configs(directory, scope):
3147
 
            for (oname, value, section, conf_id, parser) in c._get_options():
3148
 
                if name.search(oname):
3149
 
                    if cur_conf_id != conf_id:
3150
 
                        # Explain where the options are defined
3151
 
                        self.outf.write('%s:\n' % (conf_id,))
3152
 
                        cur_conf_id = conf_id
3153
 
                        cur_section = None
3154
 
                    if (section not in (None, 'DEFAULT')
3155
 
                        and cur_section != section):
3156
 
                        # Display the section if it's not the default (or only)
3157
 
                        # one.
3158
 
                        self.outf.write('  [%s]\n' % (section,))
3159
 
                        cur_section = section
3160
 
                    self.outf.write('  %s = %s\n' % (oname, value))
3161
 
 
3162
 
    def _set_config_option(self, name, value, directory, scope):
3163
 
        for conf in self._get_configs(directory, scope):
3164
 
            conf.set_user_option(name, value)
3165
 
            break
3166
 
        else:
3167
 
            raise errors.NoSuchConfig(scope)
3168
 
 
3169
 
    def _remove_config_option(self, name, directory, scope):
3170
 
        if name is None:
3171
 
            raise errors.BzrCommandError(
3172
 
                '--remove expects an option to remove.')
3173
 
        removed = False
3174
 
        for conf in self._get_configs(directory, scope):
3175
 
            for (section_name, section, conf_id) in conf._get_sections():
3176
 
                if scope is not None and conf_id != scope:
3177
 
                    # Not the right configuration file
3178
 
                    continue
3179
 
                if name in section:
3180
 
                    if conf_id != conf.config_id():
3181
 
                        conf = self._get_configs(directory, conf_id).next()
3182
 
                    # We use the first section in the first config where the
3183
 
                    # option is defined to remove it
3184
 
                    conf.remove_user_option(name, section_name)
3185
 
                    removed = True
3186
 
                    break
3187
 
            break
3188
 
        else:
3189
 
            raise errors.NoSuchConfig(scope)
3190
 
        if not removed:
3191
 
            raise errors.NoSuchConfigOption(name)
3192
 
 
3193
 
# Test registries
3194
 
#
3195
 
# We need adapters that can build a Store or a Stack in a test context. Test
3196
 
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3197
 
# themselves. The builder will receive a test instance and should return a
3198
 
# ready-to-use store or stack.  Plugins that define new store/stacks can also
3199
 
# register themselves here to be tested against the tests defined in
3200
 
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3201
 
# for the same tests.
3202
 
 
3203
 
# The registered object should be a callable receiving a test instance
3204
 
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3205
 
# object.
3206
 
test_store_builder_registry = registry.Registry()
3207
 
 
3208
 
# The registered object should be a callable receiving a test instance
3209
 
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3210
 
# object.
3211
 
test_stack_builder_registry = registry.Registry()