/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Bastian Bowe
  • Date: 2011-08-08 12:47:07 UTC
  • mto: (6015.14.1 bzr24-filter-809901)
  • mto: This revision was merged to the branch mainline in revision 6066.
  • Revision ID: bastian.bowe@gmail.com-20110808124707-3jegg252r1d804v0
Merged fix regarding error in CHKInventory.filter method from mainline

Show diffs side-by-side

added added

removed removed

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