/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 breezy/config.py

  • Committer: Martin
  • Date: 2017-05-24 20:47:06 UTC
  • mto: This revision was merged to the branch mainline in revision 6635.
  • Revision ID: gzlist@googlemail.com-20170524204706-jvole7jqnplsj8ts
Rename report_delta param from filter to predicate with tests and release notes

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005-2014, 2016 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#            and others
4
4
#
19
19
"""Configuration that affects the behaviour of Bazaar.
20
20
 
21
21
Currently this configuration resides in ~/.bazaar/bazaar.conf
22
 
and ~/.bazaar/locations.conf, which is written to by bzr.
 
22
and ~/.bazaar/locations.conf, which is written to by brz.
23
23
 
24
24
In bazaar.conf the following options may be set:
25
25
[DEFAULT]
29
29
create_signatures=always|never|when-required(default)
30
30
gpg_signing_command=name-of-program
31
31
log_format=name-of-format
 
32
validate_signatures_in_log=true|false(default)
 
33
acceptable_keys=pattern1,pattern2
 
34
gpg_signing_key=amy@example.com
32
35
 
33
36
in locations.conf, you specify the url of a branch and options for it.
34
37
Wildcards may be used - * and ? as normal in shell completion. Options
39
42
email= as above
40
43
check_signatures= as above
41
44
create_signatures= as above.
 
45
validate_signatures_in_log=as above
 
46
acceptable_keys=as above
42
47
 
43
48
explanation of options
44
49
----------------------
45
50
editor - this option sets the pop up editor to use during commits.
46
 
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
email - this option sets the user id brz will use when committing.
 
52
check_signatures - this option will control whether brz will require good gpg
48
53
                   signatures, ignore them, or check them if they are
49
 
                   present.
50
 
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.
 
54
                   present.  Currently it is unused except that check_signatures
 
55
                   turns on create_signatures.
 
56
create_signatures - this option controls whether brz will always create
 
57
                    gpg signatures or not on commits.  There is an unused
 
58
                    option which in future is expected to work if
 
59
                    branch settings require signatures.
53
60
log_format - this option sets the default log format.  Possible values are
54
61
             long, short, line, or a plugin can register new formats.
 
62
validate_signatures_in_log - show GPG signature validity in log output
 
63
acceptable_keys - comma separated list of key patterns acceptable for
 
64
                  verify-signatures command
55
65
 
56
66
In bazaar.conf you can also define aliases in the ALIASES sections, example
57
67
 
62
72
up=pull
63
73
"""
64
74
 
 
75
from __future__ import absolute_import
65
76
import os
66
77
import sys
67
78
 
68
 
from bzrlib.lazy_import import lazy_import
 
79
import configobj
 
80
 
 
81
import breezy
 
82
from .decorators import needs_write_lock
 
83
from .lazy_import import lazy_import
69
84
lazy_import(globals(), """
70
 
import errno
71
 
from fnmatch import fnmatch
 
85
import base64
 
86
import fnmatch
72
87
import re
73
 
from cStringIO import StringIO
74
88
 
75
 
import bzrlib
76
 
from bzrlib import (
 
89
from breezy import (
 
90
    atomicfile,
 
91
    controldir,
77
92
    debug,
 
93
    directory_service,
78
94
    errors,
79
 
    mail_client,
 
95
    lazy_regex,
 
96
    library_state,
 
97
    lockdir,
 
98
    mergetools,
80
99
    osutils,
81
 
    registry,
82
100
    symbol_versioning,
83
101
    trace,
 
102
    transport,
84
103
    ui,
85
104
    urlutils,
86
105
    win32utils,
87
106
    )
88
 
from bzrlib.util.configobj import configobj
 
107
from breezy.i18n import gettext
89
108
""")
 
109
from . import (
 
110
    commands,
 
111
    hooks,
 
112
    lazy_regex,
 
113
    registry,
 
114
    )
 
115
from .sixish import (
 
116
    binary_type,
 
117
    BytesIO,
 
118
    text_type,
 
119
    string_types,
 
120
    )
 
121
from .symbol_versioning import (
 
122
    deprecated_in,
 
123
    deprecated_method,
 
124
    )
90
125
 
91
126
 
92
127
CHECK_IF_POSSIBLE=0
122
157
STORE_BRANCH = 3
123
158
STORE_GLOBAL = 4
124
159
 
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)
 
160
 
 
161
def signature_policy_from_unicode(signature_string):
 
162
    """Convert a string to a signing policy."""
 
163
    if signature_string.lower() == 'check-available':
 
164
        return CHECK_IF_POSSIBLE
 
165
    if signature_string.lower() == 'ignore':
 
166
        return CHECK_NEVER
 
167
    if signature_string.lower() == 'require':
 
168
        return CHECK_ALWAYS
 
169
    raise ValueError("Invalid signatures policy '%s'"
 
170
                     % signature_string)
 
171
 
 
172
 
 
173
def signing_policy_from_unicode(signature_string):
 
174
    """Convert a string to a signing policy."""
 
175
    if signature_string.lower() == 'when-required':
 
176
        return SIGN_WHEN_REQUIRED
 
177
    if signature_string.lower() == 'never':
 
178
        return SIGN_NEVER
 
179
    if signature_string.lower() == 'always':
 
180
        return SIGN_ALWAYS
 
181
    raise ValueError("Invalid signing policy '%s'"
 
182
                     % signature_string)
 
183
 
 
184
 
 
185
def _has_decode_bug():
 
186
    """True if configobj will fail to decode to unicode on Python 2."""
 
187
    if sys.version_info > (3,):
 
188
        return False
 
189
    conf = configobj.ConfigObj()
 
190
    decode = getattr(conf, "_decode", None)
 
191
    if decode:
 
192
        result = decode(b"\xc2\xa7", "utf-8")
 
193
        if isinstance(result[0], str):
 
194
            return True
 
195
    return False
 
196
 
 
197
 
 
198
def _has_triplequote_bug():
 
199
    """True if triple quote logic is reversed, see lp:710410."""
 
200
    conf = configobj.ConfigObj()
 
201
    quote = getattr(conf, "_get_triple_quote", None)
 
202
    if quote and quote('"""') != "'''":
 
203
        return True
 
204
    return False
 
205
 
 
206
 
 
207
class ConfigObj(configobj.ConfigObj):
 
208
 
 
209
    def __init__(self, infile=None, **kwargs):
 
210
        # We define our own interpolation mechanism calling it option expansion
 
211
        super(ConfigObj, self).__init__(infile=infile,
 
212
                                        interpolation=False,
 
213
                                        **kwargs)
 
214
 
 
215
    if _has_decode_bug():
 
216
        def _decode(self, infile, encoding):
 
217
            if isinstance(infile, str) and encoding:
 
218
                return infile.decode(encoding).splitlines(True)
 
219
            return super(ConfigObj, self)._decode(infile, encoding)
 
220
 
 
221
    if _has_triplequote_bug():
 
222
        def _get_triple_quote(self, value):
 
223
            quot = super(ConfigObj, self)._get_triple_quote(value)
 
224
            if quot == configobj.tdquot:
 
225
                return configobj.tsquot
 
226
            return configobj.tdquot
 
227
 
 
228
    def get_bool(self, section, key):
 
229
        return self[section].as_bool(key)
 
230
 
 
231
    def get_value(self, section, name):
 
232
        # Try [] for the old DEFAULT section.
 
233
        if section == "DEFAULT":
 
234
            try:
 
235
                return self[name]
 
236
            except KeyError:
 
237
                pass
 
238
        return self[section][name]
144
239
 
145
240
 
146
241
class Config(object):
149
244
    def __init__(self):
150
245
        super(Config, self).__init__()
151
246
 
152
 
    def get_editor(self):
153
 
        """Get the users pop up editor."""
154
 
        raise NotImplementedError
 
247
    def config_id(self):
 
248
        """Returns a unique ID for the config."""
 
249
        raise NotImplementedError(self.config_id)
155
250
 
156
251
    def get_change_editor(self, old_tree, new_tree):
157
 
        from bzrlib import diff
 
252
        from breezy import diff
158
253
        cmd = self._get_change_editor()
159
254
        if cmd is None:
160
255
            return None
161
256
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
162
257
                                             sys.stdout)
163
258
 
164
 
 
165
 
    def get_mail_client(self):
166
 
        """Get a mail client to use"""
167
 
        selected_client = self.get_user_option('mail_client')
168
 
        _registry = mail_client.mail_client_registry
169
 
        try:
170
 
            mail_client_class = _registry.get(selected_client)
171
 
        except KeyError:
172
 
            raise errors.UnknownMailClient(selected_client)
173
 
        return mail_client_class(self)
174
 
 
175
259
    def _get_signature_checking(self):
176
260
        """Template method to override signature checking policy."""
177
261
 
178
262
    def _get_signing_policy(self):
179
263
        """Template method to override signature creation policy."""
180
264
 
 
265
    option_ref_re = None
 
266
 
 
267
    def expand_options(self, string, env=None):
 
268
        """Expand option references in the string in the configuration context.
 
269
 
 
270
        :param string: The string containing option to expand.
 
271
 
 
272
        :param env: An option dict defining additional configuration options or
 
273
            overriding existing ones.
 
274
 
 
275
        :returns: The expanded string.
 
276
        """
 
277
        return self._expand_options_in_string(string, env)
 
278
 
 
279
    def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
 
280
        """Expand options in  a list of strings in the configuration context.
 
281
 
 
282
        :param slist: A list of strings.
 
283
 
 
284
        :param env: An option dict defining additional configuration options or
 
285
            overriding existing ones.
 
286
 
 
287
        :param _ref_stack: Private list containing the options being
 
288
            expanded to detect loops.
 
289
 
 
290
        :returns: The flatten list of expanded strings.
 
291
        """
 
292
        # expand options in each value separately flattening lists
 
293
        result = []
 
294
        for s in slist:
 
295
            value = self._expand_options_in_string(s, env, _ref_stack)
 
296
            if isinstance(value, list):
 
297
                result.extend(value)
 
298
            else:
 
299
                result.append(value)
 
300
        return result
 
301
 
 
302
    def _expand_options_in_string(self, string, env=None, _ref_stack=None):
 
303
        """Expand options in the string in the configuration context.
 
304
 
 
305
        :param string: The string to be expanded.
 
306
 
 
307
        :param env: An option dict defining additional configuration options or
 
308
            overriding existing ones.
 
309
 
 
310
        :param _ref_stack: Private list containing the options being
 
311
            expanded to detect loops.
 
312
 
 
313
        :returns: The expanded string.
 
314
        """
 
315
        if string is None:
 
316
            # Not much to expand there
 
317
            return None
 
318
        if _ref_stack is None:
 
319
            # What references are currently resolved (to detect loops)
 
320
            _ref_stack = []
 
321
        if self.option_ref_re is None:
 
322
            # We want to match the most embedded reference first (i.e. for
 
323
            # '{{foo}}' we will get '{foo}',
 
324
            # for '{bar{baz}}' we will get '{baz}'
 
325
            self.option_ref_re = re.compile('({[^{}]+})')
 
326
        result = string
 
327
        # We need to iterate until no more refs appear ({{foo}} will need two
 
328
        # iterations for example).
 
329
        while True:
 
330
            raw_chunks = self.option_ref_re.split(result)
 
331
            if len(raw_chunks) == 1:
 
332
                # Shorcut the trivial case: no refs
 
333
                return result
 
334
            chunks = []
 
335
            list_value = False
 
336
            # Split will isolate refs so that every other chunk is a ref
 
337
            chunk_is_ref = False
 
338
            for chunk in raw_chunks:
 
339
                if not chunk_is_ref:
 
340
                    if chunk:
 
341
                        # Keep only non-empty strings (or we get bogus empty
 
342
                        # slots when a list value is involved).
 
343
                        chunks.append(chunk)
 
344
                    chunk_is_ref = True
 
345
                else:
 
346
                    name = chunk[1:-1]
 
347
                    if name in _ref_stack:
 
348
                        raise errors.OptionExpansionLoop(string, _ref_stack)
 
349
                    _ref_stack.append(name)
 
350
                    value = self._expand_option(name, env, _ref_stack)
 
351
                    if value is None:
 
352
                        raise errors.ExpandingUnknownOption(name, string)
 
353
                    if isinstance(value, list):
 
354
                        list_value = True
 
355
                        chunks.extend(value)
 
356
                    else:
 
357
                        chunks.append(value)
 
358
                    _ref_stack.pop()
 
359
                    chunk_is_ref = False
 
360
            if list_value:
 
361
                # Once a list appears as the result of an expansion, all
 
362
                # callers will get a list result. This allows a consistent
 
363
                # behavior even when some options in the expansion chain
 
364
                # defined as strings (no comma in their value) but their
 
365
                # expanded value is a list.
 
366
                return self._expand_options_in_list(chunks, env, _ref_stack)
 
367
            else:
 
368
                result = ''.join(chunks)
 
369
        return result
 
370
 
 
371
    def _expand_option(self, name, env, _ref_stack):
 
372
        if env is not None and name in env:
 
373
            # Special case, values provided in env takes precedence over
 
374
            # anything else
 
375
            value = env[name]
 
376
        else:
 
377
            # FIXME: This is a limited implementation, what we really need is a
 
378
            # way to query the brz config for the value of an option,
 
379
            # respecting the scope rules (That is, once we implement fallback
 
380
            # configs, getting the option value should restart from the top
 
381
            # config, not the current one) -- vila 20101222
 
382
            value = self.get_user_option(name, expand=False)
 
383
            if isinstance(value, list):
 
384
                value = self._expand_options_in_list(value, env, _ref_stack)
 
385
            else:
 
386
                value = self._expand_options_in_string(value, env, _ref_stack)
 
387
        return value
 
388
 
181
389
    def _get_user_option(self, option_name):
182
390
        """Template method to provide a user option."""
183
391
        return None
184
392
 
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
 
 
 
393
    def get_user_option(self, option_name, expand=True):
 
394
        """Get a generic option - no special process, no default.
 
395
 
 
396
        :param option_name: The queried option.
 
397
 
 
398
        :param expand: Whether options references should be expanded.
 
399
 
 
400
        :returns: The value of the option.
 
401
        """
 
402
        value = self._get_user_option(option_name)
 
403
        if expand:
 
404
            if isinstance(value, list):
 
405
                value = self._expand_options_in_list(value)
 
406
            elif isinstance(value, dict):
 
407
                trace.warning('Cannot expand "%s":'
 
408
                              ' Dicts do not support option expansion'
 
409
                              % (option_name,))
 
410
            else:
 
411
                value = self._expand_options_in_string(value)
 
412
        for hook in OldConfigHooks['get']:
 
413
            hook(self, option_name, value)
 
414
        return value
 
415
 
 
416
    def get_user_option_as_bool(self, option_name, expand=None, default=None):
 
417
        """Get a generic option as a boolean.
 
418
 
 
419
        :param expand: Allow expanding references to other config values.
 
420
        :param default: Default value if nothing is configured
192
421
        :return None if the option doesn't exist or its value can't be
193
422
            interpreted as a boolean. Returns True or False otherwise.
194
423
        """
195
 
        s = self._get_user_option(option_name)
 
424
        s = self.get_user_option(option_name, expand=expand)
196
425
        if s is None:
197
426
            # The option doesn't exist
198
 
            return None
 
427
            return default
199
428
        val = ui.bool_from_string(s)
200
429
        if val is None:
201
430
            # The value can't be interpreted as a boolean
203
432
                          s, option_name)
204
433
        return val
205
434
 
206
 
    def get_user_option_as_list(self, option_name):
 
435
    def get_user_option_as_list(self, option_name, expand=None):
207
436
        """Get a generic option as a list - no special process, no default.
208
437
 
209
438
        :return None if the option doesn't exist. Returns the value as a list
210
439
            otherwise.
211
440
        """
212
 
        l = self._get_user_option(option_name)
213
 
        if isinstance(l, (str, unicode)):
214
 
            # A single value, most probably the user forgot the final ','
 
441
        l = self.get_user_option(option_name, expand=expand)
 
442
        if isinstance(l, string_types):
 
443
            # A single value, most probably the user forgot (or didn't care to
 
444
            # add) the final ','
215
445
            l = [l]
216
446
        return l
217
447
 
 
448
    @deprecated_method(deprecated_in((2, 5, 0)))
 
449
    def get_user_option_as_int_from_SI(self, option_name, default=None):
 
450
        """Get a generic option from a human readable size in SI units, e.g 10MB
 
451
 
 
452
        Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
453
        by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
454
        pedantic.
 
455
 
 
456
        :return Integer, expanded to its base-10 value if a proper SI unit is 
 
457
            found. If the option doesn't exist, or isn't a value in 
 
458
            SI units, return default (which defaults to None)
 
459
        """
 
460
        val = self.get_user_option(option_name)
 
461
        if isinstance(val, list):
 
462
            val = val[0]
 
463
        if val is None:
 
464
            val = default
 
465
        else:
 
466
            p = re.compile("^(\d+)([kmg])*b*$", re.IGNORECASE)
 
467
            try:
 
468
                m = p.match(val)
 
469
                if m is not None:
 
470
                    val = int(m.group(1))
 
471
                    if m.group(2) is not None:
 
472
                        if m.group(2).lower() == 'k':
 
473
                            val *= 10**3
 
474
                        elif m.group(2).lower() == 'm':
 
475
                            val *= 10**6
 
476
                        elif m.group(2).lower() == 'g':
 
477
                            val *= 10**9
 
478
                else:
 
479
                    ui.ui_factory.show_warning(gettext('Invalid config value for "{0}" '
 
480
                                               ' value {1!r} is not an SI unit.').format(
 
481
                                                option_name, val))
 
482
                    val = default
 
483
            except TypeError:
 
484
                val = default
 
485
        return val
 
486
 
 
487
    @deprecated_method(deprecated_in((2, 5, 0)))
218
488
    def gpg_signing_command(self):
219
489
        """What program should be used to sign signatures?"""
220
490
        result = self._gpg_signing_command()
226
496
        """See gpg_signing_command()."""
227
497
        return None
228
498
 
 
499
    @deprecated_method(deprecated_in((2, 5, 0)))
229
500
    def log_format(self):
230
501
        """What log format should be used"""
231
502
        result = self._log_format()
237
508
        """See log_format()."""
238
509
        return None
239
510
 
 
511
    def validate_signatures_in_log(self):
 
512
        """Show GPG signature validity in log"""
 
513
        result = self._validate_signatures_in_log()
 
514
        if result == "true":
 
515
            result = True
 
516
        else:
 
517
            result = False
 
518
        return result
 
519
 
 
520
    def _validate_signatures_in_log(self):
 
521
        """See validate_signatures_in_log()."""
 
522
        return None
 
523
 
 
524
    @deprecated_method(deprecated_in((2, 5, 0)))
 
525
    def acceptable_keys(self):
 
526
        """Comma separated list of key patterns acceptable to 
 
527
        verify-signatures command"""
 
528
        result = self._acceptable_keys()
 
529
        return result
 
530
 
 
531
    def _acceptable_keys(self):
 
532
        """See acceptable_keys()."""
 
533
        return None
 
534
 
 
535
    @deprecated_method(deprecated_in((2, 5, 0)))
240
536
    def post_commit(self):
241
537
        """An ordered list of python functions to call.
242
538
 
257
553
 
258
554
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
259
555
 
260
 
        $BZR_EMAIL can be set to override this (as well as the
261
 
        deprecated $BZREMAIL), then
 
556
        $BRZ_EMAIL can be set to override this, then
262
557
        the concrete policy type is checked, and finally
263
558
        $EMAIL is examined.
264
 
        If none is found, a reasonable default is (hopefully)
265
 
        created.
266
 
 
267
 
        TODO: Check it's reasonably well-formed.
 
559
        If no username can be found, errors.NoWhoami exception is raised.
268
560
        """
269
 
        v = os.environ.get('BZR_EMAIL')
 
561
        v = os.environ.get('BRZ_EMAIL')
270
562
        if v:
271
563
            return v.decode(osutils.get_user_encoding())
272
 
 
273
564
        v = self._get_user_id()
274
565
        if v:
275
566
            return v
276
 
 
277
 
        v = os.environ.get('EMAIL')
278
 
        if v:
279
 
            return v.decode(osutils.get_user_encoding())
280
 
 
281
 
        name, email = _auto_user_id()
282
 
        if name:
283
 
            return '%s <%s>' % (name, email)
284
 
        else:
285
 
            return email
286
 
 
 
567
        return default_email()
 
568
 
 
569
    def ensure_username(self):
 
570
        """Raise errors.NoWhoami if username is not set.
 
571
 
 
572
        This method relies on the username() function raising the error.
 
573
        """
 
574
        self.username()
 
575
 
 
576
    @deprecated_method(deprecated_in((2, 5, 0)))
287
577
    def signature_checking(self):
288
578
        """What is the current policy for signature checking?."""
289
579
        policy = self._get_signature_checking()
291
581
            return policy
292
582
        return CHECK_IF_POSSIBLE
293
583
 
 
584
    @deprecated_method(deprecated_in((2, 5, 0)))
294
585
    def signing_policy(self):
295
586
        """What is the current policy for signature checking?."""
296
587
        policy = self._get_signing_policy()
298
589
            return policy
299
590
        return SIGN_WHEN_REQUIRED
300
591
 
 
592
    @deprecated_method(deprecated_in((2, 5, 0)))
301
593
    def signature_needed(self):
302
594
        """Is a signature needed when committing ?."""
303
595
        policy = self._get_signing_policy()
304
596
        if policy is None:
305
597
            policy = self._get_signature_checking()
306
598
            if policy is not None:
 
599
                #this warning should go away once check_signatures is
 
600
                #implemented (if not before)
307
601
                trace.warning("Please use create_signatures,"
308
602
                              " not check_signatures to set signing policy.")
309
 
            if policy == CHECK_ALWAYS:
310
 
                return True
311
603
        elif policy == SIGN_ALWAYS:
312
604
            return True
313
605
        return False
314
606
 
 
607
    @deprecated_method(deprecated_in((2, 5, 0)))
 
608
    def gpg_signing_key(self):
 
609
        """GPG user-id to sign commits"""
 
610
        key = self.get_user_option('gpg_signing_key')
 
611
        if key == "default" or key == None:
 
612
            return self.user_email()
 
613
        else:
 
614
            return key
 
615
 
315
616
    def get_alias(self, value):
316
617
        return self._get_alias(value)
317
618
 
346
647
        else:
347
648
            return True
348
649
 
 
650
    def get_merge_tools(self):
 
651
        tools = {}
 
652
        for (oname, value, section, conf_id, parser) in self._get_options():
 
653
            if oname.startswith('bzr.mergetool.'):
 
654
                tool_name = oname[len('bzr.mergetool.'):]
 
655
                tools[tool_name] = self.get_user_option(oname, False)
 
656
        trace.mutter('loaded merge tools: %r' % tools)
 
657
        return tools
 
658
 
 
659
    def find_merge_tool(self, name):
 
660
        # We fake a defaults mechanism here by checking if the given name can
 
661
        # be found in the known_merge_tools if it's not found in the config.
 
662
        # This should be done through the proposed config defaults mechanism
 
663
        # when it becomes available in the future.
 
664
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
 
665
                                             expand=False)
 
666
                        or mergetools.known_merge_tools.get(name, None))
 
667
        return command_line
 
668
 
 
669
 
 
670
class _ConfigHooks(hooks.Hooks):
 
671
    """A dict mapping hook names and a list of callables for configs.
 
672
    """
 
673
 
 
674
    def __init__(self):
 
675
        """Create the default hooks.
 
676
 
 
677
        These are all empty initially, because by default nothing should get
 
678
        notified.
 
679
        """
 
680
        super(_ConfigHooks, self).__init__('breezy.config', 'ConfigHooks')
 
681
        self.add_hook('load',
 
682
                      'Invoked when a config store is loaded.'
 
683
                      ' The signature is (store).',
 
684
                      (2, 4))
 
685
        self.add_hook('save',
 
686
                      'Invoked when a config store is saved.'
 
687
                      ' The signature is (store).',
 
688
                      (2, 4))
 
689
        # The hooks for config options
 
690
        self.add_hook('get',
 
691
                      'Invoked when a config option is read.'
 
692
                      ' The signature is (stack, name, value).',
 
693
                      (2, 4))
 
694
        self.add_hook('set',
 
695
                      'Invoked when a config option is set.'
 
696
                      ' The signature is (stack, name, value).',
 
697
                      (2, 4))
 
698
        self.add_hook('remove',
 
699
                      'Invoked when a config option is removed.'
 
700
                      ' The signature is (stack, name).',
 
701
                      (2, 4))
 
702
ConfigHooks = _ConfigHooks()
 
703
 
 
704
 
 
705
class _OldConfigHooks(hooks.Hooks):
 
706
    """A dict mapping hook names and a list of callables for configs.
 
707
    """
 
708
 
 
709
    def __init__(self):
 
710
        """Create the default hooks.
 
711
 
 
712
        These are all empty initially, because by default nothing should get
 
713
        notified.
 
714
        """
 
715
        super(_OldConfigHooks, self).__init__('breezy.config', 'OldConfigHooks')
 
716
        self.add_hook('load',
 
717
                      'Invoked when a config store is loaded.'
 
718
                      ' The signature is (config).',
 
719
                      (2, 4))
 
720
        self.add_hook('save',
 
721
                      'Invoked when a config store is saved.'
 
722
                      ' The signature is (config).',
 
723
                      (2, 4))
 
724
        # The hooks for config options
 
725
        self.add_hook('get',
 
726
                      'Invoked when a config option is read.'
 
727
                      ' The signature is (config, name, value).',
 
728
                      (2, 4))
 
729
        self.add_hook('set',
 
730
                      'Invoked when a config option is set.'
 
731
                      ' The signature is (config, name, value).',
 
732
                      (2, 4))
 
733
        self.add_hook('remove',
 
734
                      'Invoked when a config option is removed.'
 
735
                      ' The signature is (config, name).',
 
736
                      (2, 4))
 
737
OldConfigHooks = _OldConfigHooks()
 
738
 
349
739
 
350
740
class IniBasedConfig(Config):
351
741
    """A configuration policy that draws from ini files."""
352
742
 
353
 
    def __init__(self, get_filename):
 
743
    def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
 
744
                 file_name=None):
 
745
        """Base class for configuration files using an ini-like syntax.
 
746
 
 
747
        :param file_name: The configuration file path.
 
748
        """
354
749
        super(IniBasedConfig, self).__init__()
355
 
        self._get_filename = get_filename
 
750
        self.file_name = file_name
 
751
        if symbol_versioning.deprecated_passed(get_filename):
 
752
            symbol_versioning.warn(
 
753
                'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
754
                ' Use file_name instead.',
 
755
                DeprecationWarning,
 
756
                stacklevel=2)
 
757
            if get_filename is not None:
 
758
                self.file_name = get_filename()
 
759
        else:
 
760
            self.file_name = file_name
 
761
        self._content = None
356
762
        self._parser = None
357
763
 
358
 
    def _get_parser(self, file=None):
 
764
    @classmethod
 
765
    def from_string(cls, str_or_unicode, file_name=None, save=False):
 
766
        """Create a config object from a string.
 
767
 
 
768
        :param str_or_unicode: A string representing the file content. This will
 
769
            be utf-8 encoded.
 
770
 
 
771
        :param file_name: The configuration file path.
 
772
 
 
773
        :param _save: Whether the file should be saved upon creation.
 
774
        """
 
775
        conf = cls(file_name=file_name)
 
776
        conf._create_from_string(str_or_unicode, save)
 
777
        return conf
 
778
 
 
779
    def _create_from_string(self, str_or_unicode, save):
 
780
        self._content = BytesIO(str_or_unicode.encode('utf-8'))
 
781
        # Some tests use in-memory configs, some other always need the config
 
782
        # file to exist on disk.
 
783
        if save:
 
784
            self._write_config_file()
 
785
 
 
786
    def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
359
787
        if self._parser is not None:
360
788
            return self._parser
361
 
        if file is None:
362
 
            input = self._get_filename()
 
789
        if symbol_versioning.deprecated_passed(file):
 
790
            symbol_versioning.warn(
 
791
                'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
792
                ' Use IniBasedConfig(_content=xxx) instead.',
 
793
                DeprecationWarning,
 
794
                stacklevel=2)
 
795
        if self._content is not None:
 
796
            co_input = self._content
 
797
        elif self.file_name is None:
 
798
            raise AssertionError('We have no content to create the config')
363
799
        else:
364
 
            input = file
 
800
            co_input = self.file_name
365
801
        try:
366
 
            self._parser = ConfigObj(input, encoding='utf-8')
367
 
        except configobj.ConfigObjError, e:
 
802
            self._parser = ConfigObj(co_input, encoding='utf-8')
 
803
        except configobj.ConfigObjError as e:
368
804
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
805
        except UnicodeDecodeError:
 
806
            raise errors.ConfigContentError(self.file_name)
 
807
        # Make sure self.reload() will use the right file name
 
808
        self._parser.filename = self.file_name
 
809
        for hook in OldConfigHooks['load']:
 
810
            hook(self)
369
811
        return self._parser
370
812
 
 
813
    def reload(self):
 
814
        """Reload the config file from disk."""
 
815
        if self.file_name is None:
 
816
            raise AssertionError('We need a file name to reload the config')
 
817
        if self._parser is not None:
 
818
            self._parser.reload()
 
819
        for hook in ConfigHooks['load']:
 
820
            hook(self)
 
821
 
371
822
    def _get_matching_sections(self):
372
823
        """Return an ordered list of (section_name, extra_path) pairs.
373
824
 
384
835
        """Override this to define the section used by the config."""
385
836
        return "DEFAULT"
386
837
 
 
838
    def _get_sections(self, name=None):
 
839
        """Returns an iterator of the sections specified by ``name``.
 
840
 
 
841
        :param name: The section name. If None is supplied, the default
 
842
            configurations are yielded.
 
843
 
 
844
        :return: A tuple (name, section, config_id) for all sections that will
 
845
            be walked by user_get_option() in the 'right' order. The first one
 
846
            is where set_user_option() will update the value.
 
847
        """
 
848
        parser = self._get_parser()
 
849
        if name is not None:
 
850
            yield (name, parser[name], self.config_id())
 
851
        else:
 
852
            # No section name has been given so we fallback to the configobj
 
853
            # itself which holds the variables defined outside of any section.
 
854
            yield (None, parser, self.config_id())
 
855
 
 
856
    def _get_options(self, sections=None):
 
857
        """Return an ordered list of (name, value, section, config_id) tuples.
 
858
 
 
859
        All options are returned with their associated value and the section
 
860
        they appeared in. ``config_id`` is a unique identifier for the
 
861
        configuration file the option is defined in.
 
862
 
 
863
        :param sections: Default to ``_get_matching_sections`` if not
 
864
            specified. This gives a better control to daughter classes about
 
865
            which sections should be searched. This is a list of (name,
 
866
            configobj) tuples.
 
867
        """
 
868
        opts = []
 
869
        if sections is None:
 
870
            parser = self._get_parser()
 
871
            sections = []
 
872
            for (section_name, _) in self._get_matching_sections():
 
873
                try:
 
874
                    section = parser[section_name]
 
875
                except KeyError:
 
876
                    # This could happen for an empty file for which we define a
 
877
                    # DEFAULT section. FIXME: Force callers to provide sections
 
878
                    # instead ? -- vila 20100930
 
879
                    continue
 
880
                sections.append((section_name, section))
 
881
        config_id = self.config_id()
 
882
        for (section_name, section) in sections:
 
883
            for (name, value) in section.iteritems():
 
884
                yield (name, parser._quote(value), section_name,
 
885
                       config_id, parser)
 
886
 
387
887
    def _get_option_policy(self, section, option_name):
388
888
        """Return the policy for the given (section, option_name) pair."""
389
889
        return POLICY_NONE
395
895
        """See Config._get_signature_checking."""
396
896
        policy = self._get_user_option('check_signatures')
397
897
        if policy:
398
 
            return self._string_to_signature_policy(policy)
 
898
            return signature_policy_from_unicode(policy)
399
899
 
400
900
    def _get_signing_policy(self):
401
901
        """See Config._get_signing_policy"""
402
902
        policy = self._get_user_option('create_signatures')
403
903
        if policy:
404
 
            return self._string_to_signing_policy(policy)
 
904
            return signing_policy_from_unicode(policy)
405
905
 
406
906
    def _get_user_id(self):
407
907
        """Get the user id from the 'email' key in the current section."""
440
940
        """See Config.log_format."""
441
941
        return self._get_user_option('log_format')
442
942
 
 
943
    def _validate_signatures_in_log(self):
 
944
        """See Config.validate_signatures_in_log."""
 
945
        return self._get_user_option('validate_signatures_in_log')
 
946
 
 
947
    def _acceptable_keys(self):
 
948
        """See Config.acceptable_keys."""
 
949
        return self._get_user_option('acceptable_keys')
 
950
 
443
951
    def _post_commit(self):
444
952
        """See Config.post_commit."""
445
953
        return self._get_user_option('post_commit')
446
954
 
447
 
    def _string_to_signature_policy(self, signature_string):
448
 
        """Convert a string to a signing policy."""
449
 
        if signature_string.lower() == 'check-available':
450
 
            return CHECK_IF_POSSIBLE
451
 
        if signature_string.lower() == 'ignore':
452
 
            return CHECK_NEVER
453
 
        if signature_string.lower() == 'require':
454
 
            return CHECK_ALWAYS
455
 
        raise errors.BzrError("Invalid signatures policy '%s'"
456
 
                              % signature_string)
457
 
 
458
 
    def _string_to_signing_policy(self, signature_string):
459
 
        """Convert a string to a signing policy."""
460
 
        if signature_string.lower() == 'when-required':
461
 
            return SIGN_WHEN_REQUIRED
462
 
        if signature_string.lower() == 'never':
463
 
            return SIGN_NEVER
464
 
        if signature_string.lower() == 'always':
465
 
            return SIGN_ALWAYS
466
 
        raise errors.BzrError("Invalid signing policy '%s'"
467
 
                              % signature_string)
468
 
 
469
955
    def _get_alias(self, value):
470
956
        try:
471
957
            return self._get_parser().get_value("ALIASES",
476
962
    def _get_nickname(self):
477
963
        return self.get_user_option('nickname')
478
964
 
479
 
 
480
 
class GlobalConfig(IniBasedConfig):
 
965
    def remove_user_option(self, option_name, section_name=None):
 
966
        """Remove a user option and save the configuration file.
 
967
 
 
968
        :param option_name: The option to be removed.
 
969
 
 
970
        :param section_name: The section the option is defined in, default to
 
971
            the default section.
 
972
        """
 
973
        self.reload()
 
974
        parser = self._get_parser()
 
975
        if section_name is None:
 
976
            section = parser
 
977
        else:
 
978
            section = parser[section_name]
 
979
        try:
 
980
            del section[option_name]
 
981
        except KeyError:
 
982
            raise errors.NoSuchConfigOption(option_name)
 
983
        self._write_config_file()
 
984
        for hook in OldConfigHooks['remove']:
 
985
            hook(self, option_name)
 
986
 
 
987
    def _write_config_file(self):
 
988
        if self.file_name is None:
 
989
            raise AssertionError('We cannot save, self.file_name is None')
 
990
        conf_dir = os.path.dirname(self.file_name)
 
991
        ensure_config_dir_exists(conf_dir)
 
992
        atomic_file = atomicfile.AtomicFile(self.file_name)
 
993
        self._get_parser().write(atomic_file)
 
994
        atomic_file.commit()
 
995
        atomic_file.close()
 
996
        osutils.copy_ownership_from_path(self.file_name)
 
997
        for hook in OldConfigHooks['save']:
 
998
            hook(self)
 
999
 
 
1000
 
 
1001
class LockableConfig(IniBasedConfig):
 
1002
    """A configuration needing explicit locking for access.
 
1003
 
 
1004
    If several processes try to write the config file, the accesses need to be
 
1005
    serialized.
 
1006
 
 
1007
    Daughter classes should decorate all methods that update a config with the
 
1008
    ``@needs_write_lock`` decorator (they call, directly or indirectly, the
 
1009
    ``_write_config_file()`` method. These methods (typically ``set_option()``
 
1010
    and variants must reload the config file from disk before calling
 
1011
    ``_write_config_file()``), this can be achieved by calling the
 
1012
    ``self.reload()`` method. Note that the lock scope should cover both the
 
1013
    reading and the writing of the config file which is why the decorator can't
 
1014
    be applied to ``_write_config_file()`` only.
 
1015
 
 
1016
    This should be enough to implement the following logic:
 
1017
    - lock for exclusive write access,
 
1018
    - reload the config file from disk,
 
1019
    - set the new value
 
1020
    - unlock
 
1021
 
 
1022
    This logic guarantees that a writer can update a value without erasing an
 
1023
    update made by another writer.
 
1024
    """
 
1025
 
 
1026
    lock_name = 'lock'
 
1027
 
 
1028
    def __init__(self, file_name):
 
1029
        super(LockableConfig, self).__init__(file_name=file_name)
 
1030
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
 
1031
        # FIXME: It doesn't matter that we don't provide possible_transports
 
1032
        # below since this is currently used only for local config files ;
 
1033
        # local transports are not shared. But if/when we start using
 
1034
        # LockableConfig for other kind of transports, we will need to reuse
 
1035
        # whatever connection is already established -- vila 20100929
 
1036
        self.transport = transport.get_transport_from_path(self.dir)
 
1037
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
 
1038
 
 
1039
    def _create_from_string(self, unicode_bytes, save):
 
1040
        super(LockableConfig, self)._create_from_string(unicode_bytes, False)
 
1041
        if save:
 
1042
            # We need to handle the saving here (as opposed to IniBasedConfig)
 
1043
            # to be able to lock
 
1044
            self.lock_write()
 
1045
            self._write_config_file()
 
1046
            self.unlock()
 
1047
 
 
1048
    def lock_write(self, token=None):
 
1049
        """Takes a write lock in the directory containing the config file.
 
1050
 
 
1051
        If the directory doesn't exist it is created.
 
1052
        """
 
1053
        ensure_config_dir_exists(self.dir)
 
1054
        return self._lock.lock_write(token)
 
1055
 
 
1056
    def unlock(self):
 
1057
        self._lock.unlock()
 
1058
 
 
1059
    def break_lock(self):
 
1060
        self._lock.break_lock()
 
1061
 
 
1062
    @needs_write_lock
 
1063
    def remove_user_option(self, option_name, section_name=None):
 
1064
        super(LockableConfig, self).remove_user_option(option_name,
 
1065
                                                       section_name)
 
1066
 
 
1067
    def _write_config_file(self):
 
1068
        if self._lock is None or not self._lock.is_held:
 
1069
            # NB: if the following exception is raised it probably means a
 
1070
            # missing @needs_write_lock decorator on one of the callers.
 
1071
            raise errors.ObjectNotLocked(self)
 
1072
        super(LockableConfig, self)._write_config_file()
 
1073
 
 
1074
 
 
1075
class GlobalConfig(LockableConfig):
481
1076
    """The configuration that should be used for a specific location."""
482
1077
 
483
 
    def get_editor(self):
484
 
        return self._get_user_option('editor')
485
 
 
486
1078
    def __init__(self):
487
 
        super(GlobalConfig, self).__init__(config_filename)
488
 
 
 
1079
        super(GlobalConfig, self).__init__(file_name=config_filename())
 
1080
 
 
1081
    def config_id(self):
 
1082
        return 'bazaar'
 
1083
 
 
1084
    @classmethod
 
1085
    def from_string(cls, str_or_unicode, save=False):
 
1086
        """Create a config object from a string.
 
1087
 
 
1088
        :param str_or_unicode: A string representing the file content. This
 
1089
            will be utf-8 encoded.
 
1090
 
 
1091
        :param save: Whether the file should be saved upon creation.
 
1092
        """
 
1093
        conf = cls()
 
1094
        conf._create_from_string(str_or_unicode, save)
 
1095
        return conf
 
1096
 
 
1097
    @needs_write_lock
489
1098
    def set_user_option(self, option, value):
490
1099
        """Save option and its value in the configuration."""
491
1100
        self._set_option(option, value, 'DEFAULT')
497
1106
        else:
498
1107
            return {}
499
1108
 
 
1109
    @needs_write_lock
500
1110
    def set_alias(self, alias_name, alias_command):
501
1111
        """Save the alias in the configuration."""
502
1112
        self._set_option(alias_name, alias_command, 'ALIASES')
503
1113
 
 
1114
    @needs_write_lock
504
1115
    def unset_alias(self, alias_name):
505
1116
        """Unset an existing alias."""
 
1117
        self.reload()
506
1118
        aliases = self._get_parser().get('ALIASES')
507
1119
        if not aliases or alias_name not in aliases:
508
1120
            raise errors.NoSuchAlias(alias_name)
510
1122
        self._write_config_file()
511
1123
 
512
1124
    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)
 
1125
        self.reload()
517
1126
        self._get_parser().setdefault(section, {})[option] = value
518
1127
        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):
 
1128
        for hook in OldConfigHooks['set']:
 
1129
            hook(self, option, value)
 
1130
 
 
1131
    def _get_sections(self, name=None):
 
1132
        """See IniBasedConfig._get_sections()."""
 
1133
        parser = self._get_parser()
 
1134
        # We don't give access to options defined outside of any section, we
 
1135
        # used the DEFAULT section by... default.
 
1136
        if name in (None, 'DEFAULT'):
 
1137
            # This could happen for an empty file where the DEFAULT section
 
1138
            # doesn't exist yet. So we force DEFAULT when yielding
 
1139
            name = 'DEFAULT'
 
1140
            if 'DEFAULT' not in parser:
 
1141
               parser['DEFAULT']= {}
 
1142
        yield (name, parser[name], self.config_id())
 
1143
 
 
1144
    @needs_write_lock
 
1145
    def remove_user_option(self, option_name, section_name=None):
 
1146
        if section_name is None:
 
1147
            # We need to force the default section.
 
1148
            section_name = 'DEFAULT'
 
1149
        # We need to avoid the LockableConfig implementation or we'll lock
 
1150
        # twice
 
1151
        super(LockableConfig, self).remove_user_option(option_name,
 
1152
                                                       section_name)
 
1153
 
 
1154
def _iter_for_location_by_parts(sections, location):
 
1155
    """Keep only the sessions matching the specified location.
 
1156
 
 
1157
    :param sections: An iterable of section names.
 
1158
 
 
1159
    :param location: An url or a local path to match against.
 
1160
 
 
1161
    :returns: An iterator of (section, extra_path, nb_parts) where nb is the
 
1162
        number of path components in the section name, section is the section
 
1163
        name and extra_path is the difference between location and the section
 
1164
        name.
 
1165
 
 
1166
    ``location`` will always be a local path and never a 'file://' url but the
 
1167
    section names themselves can be in either form.
 
1168
    """
 
1169
    location_parts = location.rstrip('/').split('/')
 
1170
 
 
1171
    for section in sections:
 
1172
        # location is a local path if possible, so we need to convert 'file://'
 
1173
        # urls in section names to local paths if necessary.
 
1174
 
 
1175
        # This also avoids having file:///path be a more exact
 
1176
        # match than '/path'.
 
1177
 
 
1178
        # FIXME: This still raises an issue if a user defines both file:///path
 
1179
        # *and* /path. Should we raise an error in this case -- vila 20110505
 
1180
 
 
1181
        if section.startswith('file://'):
 
1182
            section_path = urlutils.local_path_from_url(section)
 
1183
        else:
 
1184
            section_path = section
 
1185
        section_parts = section_path.rstrip('/').split('/')
 
1186
 
 
1187
        matched = True
 
1188
        if len(section_parts) > len(location_parts):
 
1189
            # More path components in the section, they can't match
 
1190
            matched = False
 
1191
        else:
 
1192
            # Rely on zip truncating in length to the length of the shortest
 
1193
            # argument sequence.
 
1194
            for name in zip(location_parts, section_parts):
 
1195
                if not fnmatch.fnmatch(name[0], name[1]):
 
1196
                    matched = False
 
1197
                    break
 
1198
        if not matched:
 
1199
            continue
 
1200
        # build the path difference between the section and the location
 
1201
        extra_path = '/'.join(location_parts[len(section_parts):])
 
1202
        yield section, extra_path, len(section_parts)
 
1203
 
 
1204
 
 
1205
class LocationConfig(LockableConfig):
529
1206
    """A configuration object that gives the policy for a location."""
530
1207
 
531
1208
    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)
 
1209
        super(LocationConfig, self).__init__(
 
1210
            file_name=locations_config_filename())
544
1211
        # local file locations are looked up by local path, rather than
545
1212
        # by file url. This is because the config file is a user
546
1213
        # file, and we would rather not expose the user to file urls.
548
1215
            location = urlutils.local_path_from_url(location)
549
1216
        self.location = location
550
1217
 
 
1218
    def config_id(self):
 
1219
        return 'locations'
 
1220
 
 
1221
    @classmethod
 
1222
    def from_string(cls, str_or_unicode, location, save=False):
 
1223
        """Create a config object from a string.
 
1224
 
 
1225
        :param str_or_unicode: A string representing the file content. This will
 
1226
            be utf-8 encoded.
 
1227
 
 
1228
        :param location: The location url to filter the configuration.
 
1229
 
 
1230
        :param save: Whether the file should be saved upon creation.
 
1231
        """
 
1232
        conf = cls(location)
 
1233
        conf._create_from_string(str_or_unicode, save)
 
1234
        return conf
 
1235
 
551
1236
    def _get_matching_sections(self):
552
1237
        """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))
 
1238
        # put the longest (aka more specific) locations first
 
1239
        matches = sorted(
 
1240
            _iter_for_location_by_parts(self._get_parser(), self.location),
 
1241
            key=lambda match: (match[2], match[0]),
 
1242
            reverse=True)
 
1243
        for (section, extra_path, length) in matches:
 
1244
            yield section, extra_path
588
1245
            # should we stop looking for parent configs here?
589
1246
            try:
590
1247
                if self._get_parser()[section].as_bool('ignore_parents'):
591
1248
                    break
592
1249
            except KeyError:
593
1250
                pass
594
 
        return sections
 
1251
 
 
1252
    def _get_sections(self, name=None):
 
1253
        """See IniBasedConfig._get_sections()."""
 
1254
        # We ignore the name here as the only sections handled are named with
 
1255
        # the location path and we don't expose embedded sections either.
 
1256
        parser = self._get_parser()
 
1257
        for name, extra_path in self._get_matching_sections():
 
1258
            yield (name, parser[name], self.config_id())
595
1259
 
596
1260
    def _get_option_policy(self, section, option_name):
597
1261
        """Return the policy for the given (section, option_name) pair."""
641
1305
            if policy_key in self._get_parser()[section]:
642
1306
                del self._get_parser()[section][policy_key]
643
1307
 
 
1308
    @needs_write_lock
644
1309
    def set_user_option(self, option, value, store=STORE_LOCATION):
645
1310
        """Save option and its value in the configuration."""
646
1311
        if store not in [STORE_LOCATION,
648
1313
                         STORE_LOCATION_APPENDPATH]:
649
1314
            raise ValueError('bad storage policy %r for %r' %
650
1315
                (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)
 
1316
        self.reload()
655
1317
        location = self.location
656
1318
        if location.endswith('/'):
657
1319
            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():
 
1320
        parser = self._get_parser()
 
1321
        if not location in parser and not location + '/' in parser:
 
1322
            parser[location] = {}
 
1323
        elif location + '/' in parser:
662
1324
            location = location + '/'
663
 
        self._get_parser()[location][option]=value
 
1325
        parser[location][option]=value
664
1326
        # the allowed values of store match the config policies
665
1327
        self._set_option_policy(location, option, store)
666
 
        self._get_parser().write(file(self._get_filename(), 'wb'))
 
1328
        self._write_config_file()
 
1329
        for hook in OldConfigHooks['set']:
 
1330
            hook(self, option, value)
667
1331
 
668
1332
 
669
1333
class BranchConfig(Config):
670
1334
    """A configuration object giving the policy for a branch."""
671
1335
 
 
1336
    def __init__(self, branch):
 
1337
        super(BranchConfig, self).__init__()
 
1338
        self._location_config = None
 
1339
        self._branch_data_config = None
 
1340
        self._global_config = None
 
1341
        self.branch = branch
 
1342
        self.option_sources = (self._get_location_config,
 
1343
                               self._get_branch_data_config,
 
1344
                               self._get_global_config)
 
1345
 
 
1346
    def config_id(self):
 
1347
        return 'branch'
 
1348
 
672
1349
    def _get_branch_data_config(self):
673
1350
        if self._branch_data_config is None:
674
1351
            self._branch_data_config = TreeConfig(self.branch)
 
1352
            self._branch_data_config.config_id = self.config_id
675
1353
        return self._branch_data_config
676
1354
 
677
1355
    def _get_location_config(self):
717
1395
        e.g. "John Hacker <jhacker@example.com>"
718
1396
        This is looked up in the email controlfile for the branch.
719
1397
        """
720
 
        try:
721
 
            return (self.branch._transport.get_bytes("email")
722
 
                    .decode(osutils.get_user_encoding())
723
 
                    .rstrip("\r\n"))
724
 
        except errors.NoSuchFile, e:
725
 
            pass
726
 
 
727
1398
        return self._get_best_value('_get_user_id')
728
1399
 
729
1400
    def _get_change_editor(self):
745
1416
                return value
746
1417
        return None
747
1418
 
 
1419
    def _get_sections(self, name=None):
 
1420
        """See IniBasedConfig.get_sections()."""
 
1421
        for source in self.option_sources:
 
1422
            for section in source()._get_sections(name):
 
1423
                yield section
 
1424
 
 
1425
    def _get_options(self, sections=None):
 
1426
        opts = []
 
1427
        # First the locations options
 
1428
        for option in self._get_location_config()._get_options():
 
1429
            yield option
 
1430
        # Then the branch options
 
1431
        branch_config = self._get_branch_data_config()
 
1432
        if sections is None:
 
1433
            sections = [('DEFAULT', branch_config._get_parser())]
 
1434
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
 
1435
        # Config itself has no notion of sections :( -- vila 20101001
 
1436
        config_id = self.config_id()
 
1437
        for (section_name, section) in sections:
 
1438
            for (name, value) in section.iteritems():
 
1439
                yield (name, value, section_name,
 
1440
                       config_id, branch_config._get_parser())
 
1441
        # Then the global options
 
1442
        for option in self._get_global_config()._get_options():
 
1443
            yield option
 
1444
 
748
1445
    def set_user_option(self, name, value, store=STORE_BRANCH,
749
1446
        warn_masked=False):
750
1447
        if store == STORE_BRANCH:
768
1465
                        trace.warning('Value "%s" is masked by "%s" from'
769
1466
                                      ' branch.conf', value, mask_value)
770
1467
 
 
1468
    def remove_user_option(self, option_name, section_name=None):
 
1469
        self._get_branch_data_config().remove_option(option_name, section_name)
 
1470
 
771
1471
    def _gpg_signing_command(self):
772
1472
        """See Config.gpg_signing_command."""
773
1473
        return self._get_safe_value('_gpg_signing_command')
774
1474
 
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
1475
    def _post_commit(self):
786
1476
        """See Config.post_commit."""
787
1477
        return self._get_safe_value('_post_commit')
790
1480
        value = self._get_explicit_nickname()
791
1481
        if value is not None:
792
1482
            return value
 
1483
        if self.branch.name:
 
1484
            return self.branch.name
793
1485
        return urlutils.unescape(self.branch.base.split('/')[-2])
794
1486
 
795
1487
    def has_explicit_nickname(self):
803
1495
        """See Config.log_format."""
804
1496
        return self._get_best_value('_log_format')
805
1497
 
 
1498
    def _validate_signatures_in_log(self):
 
1499
        """See Config.validate_signatures_in_log."""
 
1500
        return self._get_best_value('_validate_signatures_in_log')
 
1501
 
 
1502
    def _acceptable_keys(self):
 
1503
        """See Config.acceptable_keys."""
 
1504
        return self._get_best_value('_acceptable_keys')
 
1505
 
806
1506
 
807
1507
def ensure_config_dir_exists(path=None):
808
1508
    """Make sure a configuration directory exists.
817
1517
            parent_dir = os.path.dirname(path)
818
1518
            if not os.path.isdir(parent_dir):
819
1519
                trace.mutter('creating config parent directory: %r', parent_dir)
820
 
            os.mkdir(parent_dir)
 
1520
                os.mkdir(parent_dir)
821
1521
        trace.mutter('creating config directory: %r', path)
822
1522
        os.mkdir(path)
823
1523
        osutils.copy_ownership_from_path(path)
824
1524
 
825
1525
 
 
1526
def bazaar_config_dir():
 
1527
    """Return per-user configuration directory as unicode string
 
1528
 
 
1529
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
 
1530
    and Linux.  On Mac OS X and Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
 
1531
    that will be used instead.
 
1532
 
 
1533
    TODO: Global option --config-dir to override this.
 
1534
    """
 
1535
    base = osutils.path_from_environ('BZR_HOME')
 
1536
    if sys.platform == 'win32':
 
1537
        if base is None:
 
1538
            base = win32utils.get_appdata_location()
 
1539
        if base is None:
 
1540
            base = win32utils.get_home_location()
 
1541
        # GZ 2012-02-01: Really the two level subdirs only make sense inside
 
1542
        #                APPDATA, but hard to move. See bug 348640 for more.
 
1543
        return osutils.pathjoin(base, 'bazaar', '2.0')
 
1544
    if base is None:
 
1545
        xdg_dir = osutils.path_from_environ('XDG_CONFIG_HOME')
 
1546
        if xdg_dir is None:
 
1547
            xdg_dir = osutils.pathjoin(osutils._get_home_dir(), ".config")
 
1548
        xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
 
1549
        if osutils.isdir(xdg_dir):
 
1550
            trace.mutter(
 
1551
                "Using configuration in XDG directory %s." % xdg_dir)
 
1552
            return xdg_dir
 
1553
        base = osutils._get_home_dir()
 
1554
    return osutils.pathjoin(base, ".bazaar")
 
1555
 
 
1556
 
826
1557
def config_dir():
827
 
    """Return per-user configuration directory.
 
1558
    """Return per-user configuration directory as unicode string
828
1559
 
829
 
    By default this is ~/.bazaar/
 
1560
    By default this is %APPDATA%/breezy on Windows, $XDG_CONFIG_HOME/breezy on
 
1561
    Mac OS X and Linux. If the breezy config directory doesn't exist but
 
1562
    the bazaar one (see bazaar_config_dir()) does, use that instead.
830
1563
 
831
1564
    TODO: Global option --config-dir to override this.
832
1565
    """
833
 
    base = os.environ.get('BZR_HOME', None)
 
1566
    base = osutils.path_from_environ('BRZ_HOME')
834
1567
    if sys.platform == 'win32':
835
1568
        if base is None:
836
 
            base = win32utils.get_appdata_location_unicode()
837
 
        if base is None:
838
 
            base = os.environ.get('HOME', None)
839
 
        if base is None:
840
 
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
841
 
                                  ' or HOME set')
842
 
        return osutils.pathjoin(base, 'bazaar', '2.0')
843
 
    else:
844
 
        # cygwin, linux, and darwin all have a $HOME directory
845
 
        if base is None:
846
 
            base = os.path.expanduser("~")
847
 
        return osutils.pathjoin(base, ".bazaar")
 
1569
            base = win32utils.get_appdata_location()
 
1570
        if base is None:
 
1571
            base = win32utils.get_home_location()
 
1572
        # GZ 2012-02-01: Really the two level subdirs only make sense inside
 
1573
        #                APPDATA, but hard to move. See bug 348640 for more.
 
1574
    if base is None:
 
1575
        base = osutils.path_from_environ('XDG_CONFIG_HOME')
 
1576
        if base is None:
 
1577
            base = osutils.pathjoin(osutils._get_home_dir(), ".config")
 
1578
    breezy_dir = osutils.pathjoin(base, 'breezy')
 
1579
    if osutils.isdir(breezy_dir):
 
1580
        return breezy_dir
 
1581
    # If the breezy directory doesn't exist, but the bazaar one does, use that:
 
1582
    bazaar_dir = bazaar_config_dir()
 
1583
    if osutils.isdir(bazaar_dir):
 
1584
        trace.mutter(
 
1585
            "Using Bazaar configuration directory (%s)", bazaar_dir)
 
1586
        return bazaar_dir
 
1587
    return breezy_dir
848
1588
 
849
1589
 
850
1590
def config_filename():
852
1592
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
853
1593
 
854
1594
 
855
 
def branches_config_filename():
856
 
    """Return per-user configuration ini file filename."""
857
 
    return osutils.pathjoin(config_dir(), 'branches.conf')
858
 
 
859
 
 
860
1595
def locations_config_filename():
861
1596
    """Return per-user configuration ini file filename."""
862
1597
    return osutils.pathjoin(config_dir(), 'locations.conf')
892
1627
def xdg_cache_dir():
893
1628
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
894
1629
    # Possibly this should be different on Windows?
895
 
    e = os.environ.get('XDG_CACHE_DIR', None)
 
1630
    e = os.environ.get('XDG_CACHE_HOME', None)
896
1631
    if e:
897
1632
        return e
898
1633
    else:
899
1634
        return os.path.expanduser('~/.cache')
900
1635
 
901
1636
 
 
1637
def _get_default_mail_domain(mailname_file='/etc/mailname'):
 
1638
    """If possible, return the assumed default email domain.
 
1639
 
 
1640
    :returns: string mail domain, or None.
 
1641
    """
 
1642
    if sys.platform == 'win32':
 
1643
        # No implementation yet; patches welcome
 
1644
        return None
 
1645
    try:
 
1646
        f = open(mailname_file)
 
1647
    except (IOError, OSError) as e:
 
1648
        return None
 
1649
    try:
 
1650
        domain = f.readline().strip()
 
1651
        return domain
 
1652
    finally:
 
1653
        f.close()
 
1654
 
 
1655
 
 
1656
def default_email():
 
1657
    v = os.environ.get('BRZ_EMAIL')
 
1658
    if v:
 
1659
        return v.decode(osutils.get_user_encoding())
 
1660
    v = os.environ.get('EMAIL')
 
1661
    if v:
 
1662
        return v.decode(osutils.get_user_encoding())
 
1663
    name, email = _auto_user_id()
 
1664
    if name and email:
 
1665
        return u'%s <%s>' % (name, email)
 
1666
    elif email:
 
1667
        return email
 
1668
    raise errors.NoWhoami()
 
1669
 
 
1670
 
902
1671
def _auto_user_id():
903
1672
    """Calculate automatic user identification.
904
1673
 
905
 
    Returns (realname, email).
 
1674
    :returns: (realname, email), either of which may be None if they can't be
 
1675
    determined.
906
1676
 
907
1677
    Only used when none is set in the environment or the id file.
908
1678
 
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.
 
1679
    This only returns an email address if we can be fairly sure the 
 
1680
    address is reasonable, ie if /etc/mailname is set on unix.
 
1681
 
 
1682
    This doesn't use the FQDN as the default domain because that may be 
 
1683
    slow, and it doesn't use the hostname alone because that's not normally 
 
1684
    a reasonable address.
912
1685
    """
913
 
    import socket
914
 
 
915
1686
    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())
 
1687
        # No implementation to reliably determine Windows default mail
 
1688
        # address; please add one.
 
1689
        return None, None
 
1690
 
 
1691
    default_mail_domain = _get_default_mail_domain()
 
1692
    if not default_mail_domain:
 
1693
        return None, None
 
1694
 
 
1695
    import pwd
 
1696
    uid = os.getuid()
 
1697
    try:
 
1698
        w = pwd.getpwuid(uid)
 
1699
    except KeyError:
 
1700
        trace.mutter('no passwd entry for uid %d?' % uid)
 
1701
        return None, None
 
1702
 
 
1703
    # we try utf-8 first, because on many variants (like Linux),
 
1704
    # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
1705
    # false positives.  (many users will have their user encoding set to
 
1706
    # latin-1, which cannot raise UnicodeError.)
 
1707
    try:
 
1708
        gecos = w.pw_gecos.decode('utf-8')
 
1709
        encoding = 'utf-8'
 
1710
    except UnicodeError:
 
1711
        try:
 
1712
            encoding = osutils.get_user_encoding()
 
1713
            gecos = w.pw_gecos.decode(encoding)
 
1714
        except UnicodeError as e:
 
1715
            trace.mutter("cannot decode passwd entry %s" % w)
 
1716
            return None, None
 
1717
    try:
 
1718
        username = w.pw_name.decode(encoding)
 
1719
    except UnicodeError as e:
 
1720
        trace.mutter("cannot decode passwd entry %s" % w)
 
1721
        return None, None
 
1722
 
 
1723
    comma = gecos.find(',')
 
1724
    if comma == -1:
 
1725
        realname = gecos
 
1726
    else:
 
1727
        realname = gecos[:comma]
 
1728
 
 
1729
    return realname, (username + '@' + default_mail_domain)
973
1730
 
974
1731
 
975
1732
def parse_username(username):
1020
1777
 
1021
1778
    def set_option(self, value, name, section=None):
1022
1779
        """Set a per-branch configuration option"""
 
1780
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1781
        # higher levels providing the right lock -- vila 20101004
1023
1782
        self.branch.lock_write()
1024
1783
        try:
1025
1784
            self._config.set_option(value, name, section)
1026
1785
        finally:
1027
1786
            self.branch.unlock()
1028
1787
 
 
1788
    def remove_option(self, option_name, section_name=None):
 
1789
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1790
        # higher levels providing the right lock -- vila 20101004
 
1791
        self.branch.lock_write()
 
1792
        try:
 
1793
            self._config.remove_option(option_name, section_name)
 
1794
        finally:
 
1795
            self.branch.unlock()
 
1796
 
1029
1797
 
1030
1798
class AuthenticationConfig(object):
1031
1799
    """The authentication configuration file based on a ini file.
1055
1823
            # Note: the encoding below declares that the file itself is utf-8
1056
1824
            # encoded, but the values in the ConfigObj are always Unicode.
1057
1825
            self._config = ConfigObj(self._input, encoding='utf-8')
1058
 
        except configobj.ConfigObjError, e:
 
1826
        except configobj.ConfigObjError as e:
1059
1827
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
1828
        except UnicodeError:
 
1829
            raise errors.ConfigContentError(self._filename)
1060
1830
        return self._config
1061
1831
 
1062
1832
    def _save(self):
1063
1833
        """Save the config file, only tests should use it for now."""
1064
1834
        conf_dir = os.path.dirname(self._filename)
1065
1835
        ensure_config_dir_exists(conf_dir)
1066
 
        self._get_config().write(file(self._filename, 'wb'))
 
1836
        f = file(self._filename, 'wb')
 
1837
        try:
 
1838
            self._get_config().write(f)
 
1839
        finally:
 
1840
            f.close()
1067
1841
 
1068
1842
    def _set_option(self, section_name, option_name, value):
1069
1843
        """Set an authentication configuration option"""
1075
1849
        section[option_name] = value
1076
1850
        self._save()
1077
1851
 
1078
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
 
1852
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
1079
1853
                        realm=None):
1080
1854
        """Returns the matching credentials from authentication.conf file.
1081
1855
 
1088
1862
        :param user: login (optional)
1089
1863
 
1090
1864
        :param path: the absolute path on the server (optional)
1091
 
        
 
1865
 
1092
1866
        :param realm: the http authentication realm (optional)
1093
1867
 
1094
1868
        :return: A dict containing the matching credentials or None.
1108
1882
        """
1109
1883
        credentials = None
1110
1884
        for auth_def_name, auth_def in self._get_config().items():
1111
 
            if type(auth_def) is not configobj.Section:
 
1885
            if not isinstance(auth_def, configobj.Section):
1112
1886
                raise ValueError("%s defined outside a section" % auth_def_name)
1113
1887
 
1114
1888
            a_scheme, a_host, a_user, a_path = map(
1249
2023
            if ask:
1250
2024
                if prompt is None:
1251
2025
                    # Create a default prompt suitable for most cases
1252
 
                    prompt = scheme.upper() + ' %(host)s username'
 
2026
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
1253
2027
                # Special handling for optional fields in the prompt
1254
2028
                if port is not None:
1255
2029
                    prompt_host = '%s:%d' % (host, port)
1293
2067
        if password is None:
1294
2068
            if prompt is None:
1295
2069
                # Create a default prompt suitable for most cases
1296
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
2070
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
1297
2071
            # Special handling for optional fields in the prompt
1298
2072
            if port is not None:
1299
2073
                prompt_host = '%s:%d' % (host, port)
1318
2092
    A credential store provides access to credentials via the password_encoding
1319
2093
    field in authentication.conf sections.
1320
2094
 
1321
 
    Except for stores provided by bzr itself, most stores are expected to be
 
2095
    Except for stores provided by brz itself, most stores are expected to be
1322
2096
    provided by plugins that will therefore use
1323
2097
    register_lazy(password_encoding, module_name, member_name, help=help,
1324
2098
    fallback=fallback) to install themselves.
1429
2203
credential_store_registry.default_key = 'plain'
1430
2204
 
1431
2205
 
 
2206
class Base64CredentialStore(CredentialStore):
 
2207
    __doc__ = """Base64 credential store for the authentication.conf file"""
 
2208
 
 
2209
    def decode_password(self, credentials):
 
2210
        """See CredentialStore.decode_password."""
 
2211
        # GZ 2012-07-28: Will raise binascii.Error if password is not base64,
 
2212
        #                should probably propogate as something more useful.
 
2213
        return base64.decodestring(credentials['password'])
 
2214
 
 
2215
credential_store_registry.register('base64', Base64CredentialStore,
 
2216
                                   help=Base64CredentialStore.__doc__)
 
2217
 
 
2218
 
1432
2219
class BzrDirConfig(object):
1433
2220
 
1434
2221
    def __init__(self, bzrdir):
1440
2227
 
1441
2228
        It may be set to a location, or None.
1442
2229
 
1443
 
        This policy affects all branches contained by this bzrdir, except for
1444
 
        those under repositories.
 
2230
        This policy affects all branches contained by this control dir, except
 
2231
        for those under repositories.
1445
2232
        """
1446
2233
        if self._config is None:
1447
 
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
 
2234
            raise errors.BzrError("Cannot set configuration in %s"
 
2235
                                  % self._bzrdir)
1448
2236
        if value is None:
1449
2237
            self._config.set_option('', 'default_stack_on')
1450
2238
        else:
1455
2243
 
1456
2244
        This will either be a location, or None.
1457
2245
 
1458
 
        This policy affects all branches contained by this bzrdir, except for
1459
 
        those under repositories.
 
2246
        This policy affects all branches contained by this control dir, except
 
2247
        for those under repositories.
1460
2248
        """
1461
2249
        if self._config is None:
1462
2250
            return None
1470
2258
    """A Config that reads/writes a config file on a Transport.
1471
2259
 
1472
2260
    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.
 
2261
    that may be associated with a section.  Assigning meaning to these values
 
2262
    is done at higher levels like TreeConfig.
1475
2263
    """
1476
2264
 
1477
2265
    def __init__(self, transport, filename):
1494
2282
                section_obj = configobj[section]
1495
2283
            except KeyError:
1496
2284
                return default
1497
 
        return section_obj.get(name, default)
 
2285
        value = section_obj.get(name, default)
 
2286
        for hook in OldConfigHooks['get']:
 
2287
            hook(self, name, value)
 
2288
        return value
1498
2289
 
1499
2290
    def set_option(self, value, name, section=None):
1500
2291
        """Set the value associated with a named option.
1508
2299
            configobj[name] = value
1509
2300
        else:
1510
2301
            configobj.setdefault(section, {})[name] = value
 
2302
        for hook in OldConfigHooks['set']:
 
2303
            hook(self, name, value)
 
2304
        self._set_configobj(configobj)
 
2305
 
 
2306
    def remove_option(self, option_name, section_name=None):
 
2307
        configobj = self._get_configobj()
 
2308
        if section_name is None:
 
2309
            del configobj[option_name]
 
2310
        else:
 
2311
            del configobj[section_name][option_name]
 
2312
        for hook in OldConfigHooks['remove']:
 
2313
            hook(self, option_name)
1511
2314
        self._set_configobj(configobj)
1512
2315
 
1513
2316
    def _get_config_file(self):
1514
2317
        try:
1515
 
            return StringIO(self._transport.get_bytes(self._filename))
 
2318
            f = BytesIO(self._transport.get_bytes(self._filename))
 
2319
            for hook in OldConfigHooks['load']:
 
2320
                hook(self)
 
2321
            return f
1516
2322
        except errors.NoSuchFile:
1517
 
            return StringIO()
 
2323
            return BytesIO()
 
2324
        except errors.PermissionDenied as e:
 
2325
            trace.warning("Permission denied while trying to open "
 
2326
                "configuration file %s.", urlutils.unescape_for_display(
 
2327
                urlutils.join(self._transport.base, self._filename), "utf-8"))
 
2328
            return BytesIO()
 
2329
 
 
2330
    def _external_url(self):
 
2331
        return urlutils.join(self._transport.external_url(), self._filename)
1518
2332
 
1519
2333
    def _get_configobj(self):
1520
 
        return ConfigObj(self._get_config_file(), encoding='utf-8')
 
2334
        f = self._get_config_file()
 
2335
        try:
 
2336
            try:
 
2337
                conf = ConfigObj(f, encoding='utf-8')
 
2338
            except configobj.ConfigObjError as e:
 
2339
                raise errors.ParseConfigError(e.errors, self._external_url())
 
2340
            except UnicodeDecodeError:
 
2341
                raise errors.ConfigContentError(self._external_url())
 
2342
        finally:
 
2343
            f.close()
 
2344
        return conf
1521
2345
 
1522
2346
    def _set_configobj(self, configobj):
1523
 
        out_file = StringIO()
 
2347
        out_file = BytesIO()
1524
2348
        configobj.write(out_file)
1525
2349
        out_file.seek(0)
1526
2350
        self._transport.put_file(self._filename, out_file)
 
2351
        for hook in OldConfigHooks['save']:
 
2352
            hook(self)
 
2353
 
 
2354
 
 
2355
class Option(object):
 
2356
    """An option definition.
 
2357
 
 
2358
    The option *values* are stored in config files and found in sections.
 
2359
 
 
2360
    Here we define various properties about the option itself, its default
 
2361
    value, how to convert it from stores, what to do when invalid values are
 
2362
    encoutered, in which config files it can be stored.
 
2363
    """
 
2364
 
 
2365
    def __init__(self, name, override_from_env=None,
 
2366
                 default=None, default_from_env=None,
 
2367
                 help=None, from_unicode=None, invalid=None, unquote=True):
 
2368
        """Build an option definition.
 
2369
 
 
2370
        :param name: the name used to refer to the option.
 
2371
 
 
2372
        :param override_from_env: A list of environment variables which can
 
2373
           provide override any configuration setting.
 
2374
 
 
2375
        :param default: the default value to use when none exist in the config
 
2376
            stores. This is either a string that ``from_unicode`` will convert
 
2377
            into the proper type, a callable returning a unicode string so that
 
2378
            ``from_unicode`` can be used on the return value, or a python
 
2379
            object that can be stringified (so only the empty list is supported
 
2380
            for example).
 
2381
 
 
2382
        :param default_from_env: A list of environment variables which can
 
2383
           provide a default value. 'default' will be used only if none of the
 
2384
           variables specified here are set in the environment.
 
2385
 
 
2386
        :param help: a doc string to explain the option to the user.
 
2387
 
 
2388
        :param from_unicode: a callable to convert the unicode string
 
2389
            representing the option value in a store or its default value.
 
2390
 
 
2391
        :param invalid: the action to be taken when an invalid value is
 
2392
            encountered in a store. This is called only when from_unicode is
 
2393
            invoked to convert a string and returns None or raise ValueError or
 
2394
            TypeError. Accepted values are: None (ignore invalid values),
 
2395
            'warning' (emit a warning), 'error' (emit an error message and
 
2396
            terminates).
 
2397
 
 
2398
        :param unquote: should the unicode value be unquoted before conversion.
 
2399
           This should be used only when the store providing the values cannot
 
2400
           safely unquote them (see http://pad.lv/906897). It is provided so
 
2401
           daughter classes can handle the quoting themselves.
 
2402
        """
 
2403
        if override_from_env is None:
 
2404
            override_from_env = []
 
2405
        if default_from_env is None:
 
2406
            default_from_env = []
 
2407
        self.name = name
 
2408
        self.override_from_env = override_from_env
 
2409
        # Convert the default value to a unicode string so all values are
 
2410
        # strings internally before conversion (via from_unicode) is attempted.
 
2411
        if default is None:
 
2412
            self.default = None
 
2413
        elif isinstance(default, list):
 
2414
            # Only the empty list is supported
 
2415
            if default:
 
2416
                raise AssertionError(
 
2417
                    'Only empty lists are supported as default values')
 
2418
            self.default = u','
 
2419
        elif isinstance(default, (binary_type, text_type, bool, int, float)):
 
2420
            # Rely on python to convert strings, booleans and integers
 
2421
            self.default = u'%s' % (default,)
 
2422
        elif callable(default):
 
2423
            self.default = default
 
2424
        else:
 
2425
            # other python objects are not expected
 
2426
            raise AssertionError('%r is not supported as a default value'
 
2427
                                 % (default,))
 
2428
        self.default_from_env = default_from_env
 
2429
        self._help = help
 
2430
        self.from_unicode = from_unicode
 
2431
        self.unquote = unquote
 
2432
        if invalid and invalid not in ('warning', 'error'):
 
2433
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
 
2434
        self.invalid = invalid
 
2435
 
 
2436
    @property
 
2437
    def help(self):
 
2438
        return self._help
 
2439
 
 
2440
    def convert_from_unicode(self, store, unicode_value):
 
2441
        if self.unquote and store is not None and unicode_value is not None:
 
2442
            unicode_value = store.unquote(unicode_value)
 
2443
        if self.from_unicode is None or unicode_value is None:
 
2444
            # Don't convert or nothing to convert
 
2445
            return unicode_value
 
2446
        try:
 
2447
            converted = self.from_unicode(unicode_value)
 
2448
        except (ValueError, TypeError):
 
2449
            # Invalid values are ignored
 
2450
            converted = None
 
2451
        if converted is None and self.invalid is not None:
 
2452
            # The conversion failed
 
2453
            if self.invalid == 'warning':
 
2454
                trace.warning('Value "%s" is not valid for "%s"',
 
2455
                              unicode_value, self.name)
 
2456
            elif self.invalid == 'error':
 
2457
                raise errors.ConfigOptionValueError(self.name, unicode_value)
 
2458
        return converted
 
2459
 
 
2460
    def get_override(self):
 
2461
        value = None
 
2462
        for var in self.override_from_env:
 
2463
            try:
 
2464
                # If the env variable is defined, its value takes precedence
 
2465
                value = os.environ[var].decode(osutils.get_user_encoding())
 
2466
                break
 
2467
            except KeyError:
 
2468
                continue
 
2469
        return value
 
2470
 
 
2471
    def get_default(self):
 
2472
        value = None
 
2473
        for var in self.default_from_env:
 
2474
            try:
 
2475
                # If the env variable is defined, its value is the default one
 
2476
                value = os.environ[var].decode(osutils.get_user_encoding())
 
2477
                break
 
2478
            except KeyError:
 
2479
                continue
 
2480
        if value is None:
 
2481
            # Otherwise, fallback to the value defined at registration
 
2482
            if callable(self.default):
 
2483
                value = self.default()
 
2484
                if not isinstance(value, text_type):
 
2485
                    raise AssertionError(
 
2486
                        "Callable default value for '%s' should be unicode"
 
2487
                        % (self.name))
 
2488
            else:
 
2489
                value = self.default
 
2490
        return value
 
2491
 
 
2492
    def get_help_topic(self):
 
2493
        return self.name
 
2494
 
 
2495
    def get_help_text(self, additional_see_also=None, plain=True):
 
2496
        result = self.help
 
2497
        from breezy import help_topics
 
2498
        result += help_topics._format_see_also(additional_see_also)
 
2499
        if plain:
 
2500
            result = help_topics.help_as_plain_text(result)
 
2501
        return result
 
2502
 
 
2503
 
 
2504
# Predefined converters to get proper values from store
 
2505
 
 
2506
def bool_from_store(unicode_str):
 
2507
    return ui.bool_from_string(unicode_str)
 
2508
 
 
2509
 
 
2510
def int_from_store(unicode_str):
 
2511
    return int(unicode_str)
 
2512
 
 
2513
 
 
2514
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
 
2515
 
 
2516
def int_SI_from_store(unicode_str):
 
2517
    """Convert a human readable size in SI units, e.g 10MB into an integer.
 
2518
 
 
2519
    Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
2520
    by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
2521
    pedantic.
 
2522
 
 
2523
    :return Integer, expanded to its base-10 value if a proper SI unit is 
 
2524
        found, None otherwise.
 
2525
    """
 
2526
    regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
 
2527
    p = re.compile(regexp, re.IGNORECASE)
 
2528
    m = p.match(unicode_str)
 
2529
    val = None
 
2530
    if m is not None:
 
2531
        val, _, unit = m.groups()
 
2532
        val = int(val)
 
2533
        if unit:
 
2534
            try:
 
2535
                coeff = _unit_suffixes[unit.upper()]
 
2536
            except KeyError:
 
2537
                raise ValueError(gettext('{0} is not an SI unit.').format(unit))
 
2538
            val *= coeff
 
2539
    return val
 
2540
 
 
2541
 
 
2542
def float_from_store(unicode_str):
 
2543
    return float(unicode_str)
 
2544
 
 
2545
 
 
2546
# Use an empty dict to initialize an empty configobj avoiding all parsing and
 
2547
# encoding checks
 
2548
_list_converter_config = configobj.ConfigObj(
 
2549
    {}, encoding='utf-8', list_values=True, interpolation=False)
 
2550
 
 
2551
 
 
2552
class ListOption(Option):
 
2553
 
 
2554
    def __init__(self, name, default=None, default_from_env=None,
 
2555
                 help=None, invalid=None):
 
2556
        """A list Option definition.
 
2557
 
 
2558
        This overrides the base class so the conversion from a unicode string
 
2559
        can take quoting into account.
 
2560
        """
 
2561
        super(ListOption, self).__init__(
 
2562
            name, default=default, default_from_env=default_from_env,
 
2563
            from_unicode=self.from_unicode, help=help,
 
2564
            invalid=invalid, unquote=False)
 
2565
 
 
2566
    def from_unicode(self, unicode_str):
 
2567
        if not isinstance(unicode_str, string_types):
 
2568
            raise TypeError
 
2569
        # Now inject our string directly as unicode. All callers got their
 
2570
        # value from configobj, so values that need to be quoted are already
 
2571
        # properly quoted.
 
2572
        _list_converter_config.reset()
 
2573
        _list_converter_config._parse([u"list=%s" % (unicode_str,)])
 
2574
        maybe_list = _list_converter_config['list']
 
2575
        if isinstance(maybe_list, string_types):
 
2576
            if maybe_list:
 
2577
                # A single value, most probably the user forgot (or didn't care
 
2578
                # to add) the final ','
 
2579
                l = [maybe_list]
 
2580
            else:
 
2581
                # The empty string, convert to empty list
 
2582
                l = []
 
2583
        else:
 
2584
            # We rely on ConfigObj providing us with a list already
 
2585
            l = maybe_list
 
2586
        return l
 
2587
 
 
2588
 
 
2589
class RegistryOption(Option):
 
2590
    """Option for a choice from a registry."""
 
2591
 
 
2592
    def __init__(self, name, registry, default_from_env=None,
 
2593
                 help=None, invalid=None):
 
2594
        """A registry based Option definition.
 
2595
 
 
2596
        This overrides the base class so the conversion from a unicode string
 
2597
        can take quoting into account.
 
2598
        """
 
2599
        super(RegistryOption, self).__init__(
 
2600
            name, default=lambda: unicode(registry.default_key),
 
2601
            default_from_env=default_from_env,
 
2602
            from_unicode=self.from_unicode, help=help,
 
2603
            invalid=invalid, unquote=False)
 
2604
        self.registry = registry
 
2605
 
 
2606
    def from_unicode(self, unicode_str):
 
2607
        if not isinstance(unicode_str, string_types):
 
2608
            raise TypeError
 
2609
        try:
 
2610
            return self.registry.get(unicode_str)
 
2611
        except KeyError:
 
2612
            raise ValueError(
 
2613
                "Invalid value %s for %s."
 
2614
                "See help for a list of possible values." % (unicode_str,
 
2615
                    self.name))
 
2616
 
 
2617
    @property
 
2618
    def help(self):
 
2619
        ret = [self._help, "\n\nThe following values are supported:\n"]
 
2620
        for key in self.registry.keys():
 
2621
            ret.append(" %s - %s\n" % (key, self.registry.get_help(key)))
 
2622
        return "".join(ret)
 
2623
 
 
2624
 
 
2625
_option_ref_re = lazy_regex.lazy_compile('({[^\d\W](?:\.\w|-\w|\w)*})')
 
2626
"""Describes an expandable option reference.
 
2627
 
 
2628
We want to match the most embedded reference first.
 
2629
 
 
2630
I.e. for '{{foo}}' we will get '{foo}',
 
2631
for '{bar{baz}}' we will get '{baz}'
 
2632
"""
 
2633
 
 
2634
def iter_option_refs(string):
 
2635
    # Split isolate refs so every other chunk is a ref
 
2636
    is_ref = False
 
2637
    for chunk  in _option_ref_re.split(string):
 
2638
        yield is_ref, chunk
 
2639
        is_ref = not is_ref
 
2640
 
 
2641
 
 
2642
class OptionRegistry(registry.Registry):
 
2643
    """Register config options by their name.
 
2644
 
 
2645
    This overrides ``registry.Registry`` to simplify registration by acquiring
 
2646
    some information from the option object itself.
 
2647
    """
 
2648
 
 
2649
    def _check_option_name(self, option_name):
 
2650
        """Ensures an option name is valid.
 
2651
 
 
2652
        :param option_name: The name to validate.
 
2653
        """
 
2654
        if _option_ref_re.match('{%s}' % option_name) is None:
 
2655
            raise errors.IllegalOptionName(option_name)
 
2656
 
 
2657
    def register(self, option):
 
2658
        """Register a new option to its name.
 
2659
 
 
2660
        :param option: The option to register. Its name is used as the key.
 
2661
        """
 
2662
        self._check_option_name(option.name)
 
2663
        super(OptionRegistry, self).register(option.name, option,
 
2664
                                             help=option.help)
 
2665
 
 
2666
    def register_lazy(self, key, module_name, member_name):
 
2667
        """Register a new option to be loaded on request.
 
2668
 
 
2669
        :param key: the key to request the option later. Since the registration
 
2670
            is lazy, it should be provided and match the option name.
 
2671
 
 
2672
        :param module_name: the python path to the module. Such as 'os.path'.
 
2673
 
 
2674
        :param member_name: the member of the module to return.  If empty or 
 
2675
                None, get() will return the module itself.
 
2676
        """
 
2677
        self._check_option_name(key)
 
2678
        super(OptionRegistry, self).register_lazy(key,
 
2679
                                                  module_name, member_name)
 
2680
 
 
2681
    def get_help(self, key=None):
 
2682
        """Get the help text associated with the given key"""
 
2683
        option = self.get(key)
 
2684
        the_help = option.help
 
2685
        if callable(the_help):
 
2686
            return the_help(self, key)
 
2687
        return the_help
 
2688
 
 
2689
 
 
2690
option_registry = OptionRegistry()
 
2691
 
 
2692
 
 
2693
# Registered options in lexicographical order
 
2694
 
 
2695
option_registry.register(
 
2696
    Option('append_revisions_only',
 
2697
           default=None, from_unicode=bool_from_store, invalid='warning',
 
2698
           help='''\
 
2699
Whether to only append revisions to the mainline.
 
2700
 
 
2701
If this is set to true, then it is not possible to change the
 
2702
existing mainline of the branch.
 
2703
'''))
 
2704
option_registry.register(
 
2705
    ListOption('acceptable_keys',
 
2706
           default=None,
 
2707
           help="""\
 
2708
List of GPG key patterns which are acceptable for verification.
 
2709
"""))
 
2710
option_registry.register(
 
2711
    Option('add.maximum_file_size',
 
2712
           default=u'20MB', from_unicode=int_SI_from_store,
 
2713
           help="""\
 
2714
Size above which files should be added manually.
 
2715
 
 
2716
Files below this size are added automatically when using ``bzr add`` without
 
2717
arguments.
 
2718
 
 
2719
A negative value means disable the size check.
 
2720
"""))
 
2721
option_registry.register(
 
2722
    Option('bound',
 
2723
           default=None, from_unicode=bool_from_store,
 
2724
           help="""\
 
2725
Is the branch bound to ``bound_location``.
 
2726
 
 
2727
If set to "True", the branch should act as a checkout, and push each commit to
 
2728
the bound_location.  This option is normally set by ``bind``/``unbind``.
 
2729
 
 
2730
See also: bound_location.
 
2731
"""))
 
2732
option_registry.register(
 
2733
    Option('bound_location',
 
2734
           default=None,
 
2735
           help="""\
 
2736
The location that commits should go to when acting as a checkout.
 
2737
 
 
2738
This option is normally set by ``bind``.
 
2739
 
 
2740
See also: bound.
 
2741
"""))
 
2742
option_registry.register(
 
2743
    Option('branch.fetch_tags', default=False,  from_unicode=bool_from_store,
 
2744
           help="""\
 
2745
Whether revisions associated with tags should be fetched.
 
2746
"""))
 
2747
option_registry.register_lazy(
 
2748
    'bzr.transform.orphan_policy', 'breezy.transform', 'opt_transform_orphan')
 
2749
option_registry.register(
 
2750
    Option('bzr.workingtree.worth_saving_limit', default=10,
 
2751
           from_unicode=int_from_store,  invalid='warning',
 
2752
           help='''\
 
2753
How many changes before saving the dirstate.
 
2754
 
 
2755
-1 means that we will never rewrite the dirstate file for only
 
2756
stat-cache changes. Regardless of this setting, we will always rewrite
 
2757
the dirstate file if a file is added/removed/renamed/etc. This flag only
 
2758
affects the behavior of updating the dirstate file after we notice that
 
2759
a file has been touched.
 
2760
'''))
 
2761
option_registry.register(
 
2762
    Option('bugtracker', default=None,
 
2763
           help='''\
 
2764
Default bug tracker to use.
 
2765
 
 
2766
This bug tracker will be used for example when marking bugs
 
2767
as fixed using ``bzr commit --fixes``, if no explicit
 
2768
bug tracker was specified.
 
2769
'''))
 
2770
option_registry.register(
 
2771
    Option('check_signatures', default=CHECK_IF_POSSIBLE,
 
2772
           from_unicode=signature_policy_from_unicode,
 
2773
           help='''\
 
2774
GPG checking policy.
 
2775
 
 
2776
Possible values: require, ignore, check-available (default)
 
2777
 
 
2778
this option will control whether bzr will require good gpg
 
2779
signatures, ignore them, or check them if they are
 
2780
present.
 
2781
'''))
 
2782
option_registry.register(
 
2783
    Option('child_submit_format',
 
2784
           help='''The preferred format of submissions to this branch.'''))
 
2785
option_registry.register(
 
2786
    Option('child_submit_to',
 
2787
           help='''Where submissions to this branch are mailed to.'''))
 
2788
option_registry.register(
 
2789
    Option('create_signatures', default=SIGN_WHEN_REQUIRED,
 
2790
           from_unicode=signing_policy_from_unicode,
 
2791
           help='''\
 
2792
GPG Signing policy.
 
2793
 
 
2794
Possible values: always, never, when-required (default)
 
2795
 
 
2796
This option controls whether bzr will always create
 
2797
gpg signatures or not on commits.
 
2798
'''))
 
2799
option_registry.register(
 
2800
    Option('dirstate.fdatasync', default=True,
 
2801
           from_unicode=bool_from_store,
 
2802
           help='''\
 
2803
Flush dirstate changes onto physical disk?
 
2804
 
 
2805
If true (default), working tree metadata changes are flushed through the
 
2806
OS buffers to physical disk.  This is somewhat slower, but means data
 
2807
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2808
'''))
 
2809
option_registry.register(
 
2810
    ListOption('debug_flags', default=[],
 
2811
           help='Debug flags to activate.'))
 
2812
option_registry.register(
 
2813
    Option('default_format', default='2a',
 
2814
           help='Format used when creating branches.'))
 
2815
option_registry.register(
 
2816
    Option('dpush_strict', default=None,
 
2817
           from_unicode=bool_from_store,
 
2818
           help='''\
 
2819
The default value for ``dpush --strict``.
 
2820
 
 
2821
If present, defines the ``--strict`` option default value for checking
 
2822
uncommitted changes before pushing into a different VCS without any
 
2823
custom bzr metadata.
 
2824
'''))
 
2825
option_registry.register(
 
2826
    Option('editor',
 
2827
           help='The command called to launch an editor to enter a message.'))
 
2828
option_registry.register(
 
2829
    Option('email', override_from_env=['BRZ_EMAIL'], default=default_email,
 
2830
           help='The users identity'))
 
2831
option_registry.register(
 
2832
    Option('gpg_signing_command',
 
2833
           default='gpg',
 
2834
           help="""\
 
2835
Program to use use for creating signatures.
 
2836
 
 
2837
This should support at least the -u and --clearsign options.
 
2838
"""))
 
2839
option_registry.register(
 
2840
    Option('gpg_signing_key',
 
2841
           default=None,
 
2842
           help="""\
 
2843
GPG key to use for signing.
 
2844
 
 
2845
This defaults to the first key associated with the users email.
 
2846
"""))
 
2847
option_registry.register(
 
2848
    Option('ignore_missing_extensions', default=False,
 
2849
           from_unicode=bool_from_store,
 
2850
           help='''\
 
2851
Control the missing extensions warning display.
 
2852
 
 
2853
The warning will not be emitted if set to True.
 
2854
'''))
 
2855
option_registry.register(
 
2856
    Option('language',
 
2857
           help='Language to translate messages into.'))
 
2858
option_registry.register(
 
2859
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
 
2860
           help='''\
 
2861
Steal locks that appears to be dead.
 
2862
 
 
2863
If set to True, bzr will check if a lock is supposed to be held by an
 
2864
active process from the same user on the same machine. If the user and
 
2865
machine match, but no process with the given PID is active, then bzr
 
2866
will automatically break the stale lock, and create a new lock for
 
2867
this process.
 
2868
Otherwise, bzr will prompt as normal to break the lock.
 
2869
'''))
 
2870
option_registry.register(
 
2871
    Option('log_format', default='long',
 
2872
           help= '''\
 
2873
Log format to use when displaying revisions.
 
2874
 
 
2875
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
 
2876
may be provided by plugins.
 
2877
'''))
 
2878
option_registry.register_lazy('mail_client', 'breezy.mail_client',
 
2879
    'opt_mail_client')
 
2880
option_registry.register(
 
2881
    Option('output_encoding',
 
2882
           help= 'Unicode encoding for output'
 
2883
           ' (terminal encoding if not specified).'))
 
2884
option_registry.register(
 
2885
    Option('parent_location',
 
2886
           default=None,
 
2887
           help="""\
 
2888
The location of the default branch for pull or merge.
 
2889
 
 
2890
This option is normally set when creating a branch, the first ``pull`` or by
 
2891
``pull --remember``.
 
2892
"""))
 
2893
option_registry.register(
 
2894
    Option('post_commit', default=None,
 
2895
           help='''\
 
2896
Post commit functions.
 
2897
 
 
2898
An ordered list of python functions to call, separated by spaces.
 
2899
 
 
2900
Each function takes branch, rev_id as parameters.
 
2901
'''))
 
2902
option_registry.register_lazy('progress_bar', 'breezy.ui.text',
 
2903
                              'opt_progress_bar')
 
2904
option_registry.register(
 
2905
    Option('public_branch',
 
2906
           default=None,
 
2907
           help="""\
 
2908
A publically-accessible version of this branch.
 
2909
 
 
2910
This implies that the branch setting this option is not publically-accessible.
 
2911
Used and set by ``bzr send``.
 
2912
"""))
 
2913
option_registry.register(
 
2914
    Option('push_location',
 
2915
           default=None,
 
2916
           help="""\
 
2917
The location of the default branch for push.
 
2918
 
 
2919
This option is normally set by the first ``push`` or ``push --remember``.
 
2920
"""))
 
2921
option_registry.register(
 
2922
    Option('push_strict', default=None,
 
2923
           from_unicode=bool_from_store,
 
2924
           help='''\
 
2925
The default value for ``push --strict``.
 
2926
 
 
2927
If present, defines the ``--strict`` option default value for checking
 
2928
uncommitted changes before sending a merge directive.
 
2929
'''))
 
2930
option_registry.register(
 
2931
    Option('repository.fdatasync', default=True,
 
2932
           from_unicode=bool_from_store,
 
2933
           help='''\
 
2934
Flush repository changes onto physical disk?
 
2935
 
 
2936
If true (default), repository changes are flushed through the OS buffers
 
2937
to physical disk.  This is somewhat slower, but means data should not be
 
2938
lost if the machine crashes.  See also dirstate.fdatasync.
 
2939
'''))
 
2940
option_registry.register_lazy('smtp_server',
 
2941
    'breezy.smtp_connection', 'smtp_server')
 
2942
option_registry.register_lazy('smtp_password',
 
2943
    'breezy.smtp_connection', 'smtp_password')
 
2944
option_registry.register_lazy('smtp_username',
 
2945
    'breezy.smtp_connection', 'smtp_username')
 
2946
option_registry.register(
 
2947
    Option('selftest.timeout',
 
2948
        default='600',
 
2949
        from_unicode=int_from_store,
 
2950
        help='Abort selftest if one test takes longer than this many seconds',
 
2951
        ))
 
2952
 
 
2953
option_registry.register(
 
2954
    Option('send_strict', default=None,
 
2955
           from_unicode=bool_from_store,
 
2956
           help='''\
 
2957
The default value for ``send --strict``.
 
2958
 
 
2959
If present, defines the ``--strict`` option default value for checking
 
2960
uncommitted changes before sending a bundle.
 
2961
'''))
 
2962
 
 
2963
option_registry.register(
 
2964
    Option('serve.client_timeout',
 
2965
           default=300.0, from_unicode=float_from_store,
 
2966
           help="If we wait for a new request from a client for more than"
 
2967
                " X seconds, consider the client idle, and hangup."))
 
2968
option_registry.register(
 
2969
    Option('stacked_on_location',
 
2970
           default=None,
 
2971
           help="""The location where this branch is stacked on."""))
 
2972
option_registry.register(
 
2973
    Option('submit_branch',
 
2974
           default=None,
 
2975
           help="""\
 
2976
The branch you intend to submit your current work to.
 
2977
 
 
2978
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
 
2979
by the ``submit:`` revision spec.
 
2980
"""))
 
2981
option_registry.register(
 
2982
    Option('submit_to',
 
2983
           help='''Where submissions from this branch are mailed to.'''))
 
2984
option_registry.register(
 
2985
    ListOption('suppress_warnings',
 
2986
           default=[],
 
2987
           help="List of warning classes to suppress."))
 
2988
option_registry.register(
 
2989
    Option('validate_signatures_in_log', default=False,
 
2990
           from_unicode=bool_from_store, invalid='warning',
 
2991
           help='''Whether to validate signatures in brz log.'''))
 
2992
option_registry.register_lazy('ssl.ca_certs',
 
2993
    'breezy.transport.http._urllib2_wrappers', 'opt_ssl_ca_certs')
 
2994
 
 
2995
option_registry.register_lazy('ssl.cert_reqs',
 
2996
    'breezy.transport.http._urllib2_wrappers', 'opt_ssl_cert_reqs')
 
2997
 
 
2998
 
 
2999
class Section(object):
 
3000
    """A section defines a dict of option name => value.
 
3001
 
 
3002
    This is merely a read-only dict which can add some knowledge about the
 
3003
    options. It is *not* a python dict object though and doesn't try to mimic
 
3004
    its API.
 
3005
    """
 
3006
 
 
3007
    def __init__(self, section_id, options):
 
3008
        self.id = section_id
 
3009
        # We re-use the dict-like object received
 
3010
        self.options = options
 
3011
 
 
3012
    def get(self, name, default=None, expand=True):
 
3013
        return self.options.get(name, default)
 
3014
 
 
3015
    def iter_option_names(self):
 
3016
        for k in self.options.iterkeys():
 
3017
            yield k
 
3018
 
 
3019
    def __repr__(self):
 
3020
        # Mostly for debugging use
 
3021
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
 
3022
 
 
3023
 
 
3024
_NewlyCreatedOption = object()
 
3025
"""Was the option created during the MutableSection lifetime"""
 
3026
_DeletedOption = object()
 
3027
"""Was the option deleted during the MutableSection lifetime"""
 
3028
 
 
3029
 
 
3030
class MutableSection(Section):
 
3031
    """A section allowing changes and keeping track of the original values."""
 
3032
 
 
3033
    def __init__(self, section_id, options):
 
3034
        super(MutableSection, self).__init__(section_id, options)
 
3035
        self.reset_changes()
 
3036
 
 
3037
    def set(self, name, value):
 
3038
        if name not in self.options:
 
3039
            # This is a new option
 
3040
            self.orig[name] = _NewlyCreatedOption
 
3041
        elif name not in self.orig:
 
3042
            self.orig[name] = self.get(name, None)
 
3043
        self.options[name] = value
 
3044
 
 
3045
    def remove(self, name):
 
3046
        if name not in self.orig and name in self.options:
 
3047
            self.orig[name] = self.get(name, None)
 
3048
        del self.options[name]
 
3049
 
 
3050
    def reset_changes(self):
 
3051
        self.orig = {}
 
3052
 
 
3053
    def apply_changes(self, dirty, store):
 
3054
        """Apply option value changes.
 
3055
 
 
3056
        ``self`` has been reloaded from the persistent storage. ``dirty``
 
3057
        contains the changes made since the previous loading.
 
3058
 
 
3059
        :param dirty: the mutable section containing the changes.
 
3060
 
 
3061
        :param store: the store containing the section
 
3062
        """
 
3063
        for k, expected in dirty.orig.iteritems():
 
3064
            actual = dirty.get(k, _DeletedOption)
 
3065
            reloaded = self.get(k, _NewlyCreatedOption)
 
3066
            if actual is _DeletedOption:
 
3067
                if k in self.options:
 
3068
                    self.remove(k)
 
3069
            else:
 
3070
                self.set(k, actual)
 
3071
            # Report concurrent updates in an ad-hoc way. This should only
 
3072
            # occurs when different processes try to update the same option
 
3073
            # which is not supported (as in: the config framework is not meant
 
3074
            # to be used as a sharing mechanism).
 
3075
            if expected != reloaded:
 
3076
                if actual is _DeletedOption:
 
3077
                    actual = '<DELETED>'
 
3078
                if reloaded is _NewlyCreatedOption:
 
3079
                    reloaded = '<CREATED>'
 
3080
                if expected is _NewlyCreatedOption:
 
3081
                    expected = '<CREATED>'
 
3082
                # Someone changed the value since we get it from the persistent
 
3083
                # storage.
 
3084
                trace.warning(gettext(
 
3085
                        "Option {0} in section {1} of {2} was changed"
 
3086
                        " from {3} to {4}. The {5} value will be saved.".format(
 
3087
                            k, self.id, store.external_url(), expected,
 
3088
                            reloaded, actual)))
 
3089
        # No need to keep track of these changes
 
3090
        self.reset_changes()
 
3091
 
 
3092
 
 
3093
class Store(object):
 
3094
    """Abstract interface to persistent storage for configuration options."""
 
3095
 
 
3096
    readonly_section_class = Section
 
3097
    mutable_section_class = MutableSection
 
3098
 
 
3099
    def __init__(self):
 
3100
        # Which sections need to be saved (by section id). We use a dict here
 
3101
        # so the dirty sections can be shared by multiple callers.
 
3102
        self.dirty_sections = {}
 
3103
 
 
3104
    def is_loaded(self):
 
3105
        """Returns True if the Store has been loaded.
 
3106
 
 
3107
        This is used to implement lazy loading and ensure the persistent
 
3108
        storage is queried only when needed.
 
3109
        """
 
3110
        raise NotImplementedError(self.is_loaded)
 
3111
 
 
3112
    def load(self):
 
3113
        """Loads the Store from persistent storage."""
 
3114
        raise NotImplementedError(self.load)
 
3115
 
 
3116
    def _load_from_string(self, bytes):
 
3117
        """Create a store from a string in configobj syntax.
 
3118
 
 
3119
        :param bytes: A string representing the file content.
 
3120
        """
 
3121
        raise NotImplementedError(self._load_from_string)
 
3122
 
 
3123
    def unload(self):
 
3124
        """Unloads the Store.
 
3125
 
 
3126
        This should make is_loaded() return False. This is used when the caller
 
3127
        knows that the persistent storage has changed or may have change since
 
3128
        the last load.
 
3129
        """
 
3130
        raise NotImplementedError(self.unload)
 
3131
 
 
3132
    def quote(self, value):
 
3133
        """Quote a configuration option value for storing purposes.
 
3134
 
 
3135
        This allows Stacks to present values as they will be stored.
 
3136
        """
 
3137
        return value
 
3138
 
 
3139
    def unquote(self, value):
 
3140
        """Unquote a configuration option value into unicode.
 
3141
 
 
3142
        The received value is quoted as stored.
 
3143
        """
 
3144
        return value
 
3145
 
 
3146
    def save(self):
 
3147
        """Saves the Store to persistent storage."""
 
3148
        raise NotImplementedError(self.save)
 
3149
 
 
3150
    def _need_saving(self):
 
3151
        for s in self.dirty_sections.values():
 
3152
            if s.orig:
 
3153
                # At least one dirty section contains a modification
 
3154
                return True
 
3155
        return False
 
3156
 
 
3157
    def apply_changes(self, dirty_sections):
 
3158
        """Apply changes from dirty sections while checking for coherency.
 
3159
 
 
3160
        The Store content is discarded and reloaded from persistent storage to
 
3161
        acquire up-to-date values.
 
3162
 
 
3163
        Dirty sections are MutableSection which kept track of the value they
 
3164
        are expected to update.
 
3165
        """
 
3166
        # We need an up-to-date version from the persistent storage, unload the
 
3167
        # store. The reload will occur when needed (triggered by the first
 
3168
        # get_mutable_section() call below.
 
3169
        self.unload()
 
3170
        # Apply the changes from the preserved dirty sections
 
3171
        for section_id, dirty in dirty_sections.iteritems():
 
3172
            clean = self.get_mutable_section(section_id)
 
3173
            clean.apply_changes(dirty, self)
 
3174
        # Everything is clean now
 
3175
        self.dirty_sections = {}
 
3176
 
 
3177
    def save_changes(self):
 
3178
        """Saves the Store to persistent storage if changes occurred.
 
3179
 
 
3180
        Apply the changes recorded in the mutable sections to a store content
 
3181
        refreshed from persistent storage.
 
3182
        """
 
3183
        raise NotImplementedError(self.save_changes)
 
3184
 
 
3185
    def external_url(self):
 
3186
        raise NotImplementedError(self.external_url)
 
3187
 
 
3188
    def get_sections(self):
 
3189
        """Returns an ordered iterable of existing sections.
 
3190
 
 
3191
        :returns: An iterable of (store, section).
 
3192
        """
 
3193
        raise NotImplementedError(self.get_sections)
 
3194
 
 
3195
    def get_mutable_section(self, section_id=None):
 
3196
        """Returns the specified mutable section.
 
3197
 
 
3198
        :param section_id: The section identifier
 
3199
        """
 
3200
        raise NotImplementedError(self.get_mutable_section)
 
3201
 
 
3202
    def __repr__(self):
 
3203
        # Mostly for debugging use
 
3204
        return "<config.%s(%s)>" % (self.__class__.__name__,
 
3205
                                    self.external_url())
 
3206
 
 
3207
 
 
3208
class CommandLineStore(Store):
 
3209
    "A store to carry command line overrides for the config options."""
 
3210
 
 
3211
    def __init__(self, opts=None):
 
3212
        super(CommandLineStore, self).__init__()
 
3213
        if opts is None:
 
3214
            opts = {}
 
3215
        self.options = {}
 
3216
        self.id = 'cmdline'
 
3217
 
 
3218
    def _reset(self):
 
3219
        # The dict should be cleared but not replaced so it can be shared.
 
3220
        self.options.clear()
 
3221
 
 
3222
    def _from_cmdline(self, overrides):
 
3223
        # Reset before accepting new definitions
 
3224
        self._reset()
 
3225
        for over in overrides:
 
3226
            try:
 
3227
                name, value = over.split('=', 1)
 
3228
            except ValueError:
 
3229
                raise errors.BzrCommandError(
 
3230
                    gettext("Invalid '%s', should be of the form 'name=value'")
 
3231
                    % (over,))
 
3232
            self.options[name] = value
 
3233
 
 
3234
    def external_url(self):
 
3235
        # Not an url but it makes debugging easier and is never needed
 
3236
        # otherwise
 
3237
        return 'cmdline'
 
3238
 
 
3239
    def get_sections(self):
 
3240
        yield self,  self.readonly_section_class(None, self.options)
 
3241
 
 
3242
 
 
3243
class IniFileStore(Store):
 
3244
    """A config Store using ConfigObj for storage.
 
3245
 
 
3246
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
 
3247
        serialize/deserialize the config file.
 
3248
    """
 
3249
 
 
3250
    def __init__(self):
 
3251
        """A config Store using ConfigObj for storage.
 
3252
        """
 
3253
        super(IniFileStore, self).__init__()
 
3254
        self._config_obj = None
 
3255
 
 
3256
    def is_loaded(self):
 
3257
        return self._config_obj != None
 
3258
 
 
3259
    def unload(self):
 
3260
        self._config_obj = None
 
3261
        self.dirty_sections = {}
 
3262
 
 
3263
    def _load_content(self):
 
3264
        """Load the config file bytes.
 
3265
 
 
3266
        This should be provided by subclasses
 
3267
 
 
3268
        :return: Byte string
 
3269
        """
 
3270
        raise NotImplementedError(self._load_content)
 
3271
 
 
3272
    def _save_content(self, content):
 
3273
        """Save the config file bytes.
 
3274
 
 
3275
        This should be provided by subclasses
 
3276
 
 
3277
        :param content: Config file bytes to write
 
3278
        """
 
3279
        raise NotImplementedError(self._save_content)
 
3280
 
 
3281
    def load(self):
 
3282
        """Load the store from the associated file."""
 
3283
        if self.is_loaded():
 
3284
            return
 
3285
        content = self._load_content()
 
3286
        self._load_from_string(content)
 
3287
        for hook in ConfigHooks['load']:
 
3288
            hook(self)
 
3289
 
 
3290
    def _load_from_string(self, bytes):
 
3291
        """Create a config store from a string.
 
3292
 
 
3293
        :param bytes: A string representing the file content.
 
3294
        """
 
3295
        if self.is_loaded():
 
3296
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
 
3297
        co_input = BytesIO(bytes)
 
3298
        try:
 
3299
            # The config files are always stored utf8-encoded
 
3300
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
 
3301
                                         list_values=False)
 
3302
        except configobj.ConfigObjError as e:
 
3303
            self._config_obj = None
 
3304
            raise errors.ParseConfigError(e.errors, self.external_url())
 
3305
        except UnicodeDecodeError:
 
3306
            raise errors.ConfigContentError(self.external_url())
 
3307
 
 
3308
    def save_changes(self):
 
3309
        if not self.is_loaded():
 
3310
            # Nothing to save
 
3311
            return
 
3312
        if not self._need_saving():
 
3313
            return
 
3314
        # Preserve the current version
 
3315
        dirty_sections = dict(self.dirty_sections.items())
 
3316
        self.apply_changes(dirty_sections)
 
3317
        # Save to the persistent storage
 
3318
        self.save()
 
3319
 
 
3320
    def save(self):
 
3321
        if not self.is_loaded():
 
3322
            # Nothing to save
 
3323
            return
 
3324
        out = BytesIO()
 
3325
        self._config_obj.write(out)
 
3326
        self._save_content(out.getvalue())
 
3327
        for hook in ConfigHooks['save']:
 
3328
            hook(self)
 
3329
 
 
3330
    def get_sections(self):
 
3331
        """Get the configobj section in the file order.
 
3332
 
 
3333
        :returns: An iterable of (store, section).
 
3334
        """
 
3335
        # We need a loaded store
 
3336
        try:
 
3337
            self.load()
 
3338
        except (errors.NoSuchFile, errors.PermissionDenied):
 
3339
            # If the file can't be read, there is no sections
 
3340
            return
 
3341
        cobj = self._config_obj
 
3342
        if cobj.scalars:
 
3343
            yield self, self.readonly_section_class(None, cobj)
 
3344
        for section_name in cobj.sections:
 
3345
            yield (self,
 
3346
                   self.readonly_section_class(section_name,
 
3347
                                               cobj[section_name]))
 
3348
 
 
3349
    def get_mutable_section(self, section_id=None):
 
3350
        # We need a loaded store
 
3351
        try:
 
3352
            self.load()
 
3353
        except errors.NoSuchFile:
 
3354
            # The file doesn't exist, let's pretend it was empty
 
3355
            self._load_from_string('')
 
3356
        if section_id in self.dirty_sections:
 
3357
            # We already created a mutable section for this id
 
3358
            return self.dirty_sections[section_id]
 
3359
        if section_id is None:
 
3360
            section = self._config_obj
 
3361
        else:
 
3362
            section = self._config_obj.setdefault(section_id, {})
 
3363
        mutable_section = self.mutable_section_class(section_id, section)
 
3364
        # All mutable sections can become dirty
 
3365
        self.dirty_sections[section_id] = mutable_section
 
3366
        return mutable_section
 
3367
 
 
3368
    def quote(self, value):
 
3369
        try:
 
3370
            # configobj conflates automagical list values and quoting
 
3371
            self._config_obj.list_values = True
 
3372
            return self._config_obj._quote(value)
 
3373
        finally:
 
3374
            self._config_obj.list_values = False
 
3375
 
 
3376
    def unquote(self, value):
 
3377
        if value and isinstance(value, string_types):
 
3378
            # _unquote doesn't handle None nor empty strings nor anything that
 
3379
            # is not a string, really.
 
3380
            value = self._config_obj._unquote(value)
 
3381
        return value
 
3382
 
 
3383
    def external_url(self):
 
3384
        # Since an IniFileStore can be used without a file (at least in tests),
 
3385
        # it's better to provide something than raising a NotImplementedError.
 
3386
        # All daughter classes are supposed to provide an implementation
 
3387
        # anyway.
 
3388
        return 'In-Process Store, no URL'
 
3389
 
 
3390
 
 
3391
class TransportIniFileStore(IniFileStore):
 
3392
    """IniFileStore that loads files from a transport.
 
3393
 
 
3394
    :ivar transport: The transport object where the config file is located.
 
3395
 
 
3396
    :ivar file_name: The config file basename in the transport directory.
 
3397
    """
 
3398
 
 
3399
    def __init__(self, transport, file_name):
 
3400
        """A Store using a ini file on a Transport
 
3401
 
 
3402
        :param transport: The transport object where the config file is located.
 
3403
        :param file_name: The config file basename in the transport directory.
 
3404
        """
 
3405
        super(TransportIniFileStore, self).__init__()
 
3406
        self.transport = transport
 
3407
        self.file_name = file_name
 
3408
 
 
3409
    def _load_content(self):
 
3410
        try:
 
3411
            return self.transport.get_bytes(self.file_name)
 
3412
        except errors.PermissionDenied:
 
3413
            trace.warning("Permission denied while trying to load "
 
3414
                          "configuration store %s.", self.external_url())
 
3415
            raise
 
3416
 
 
3417
    def _save_content(self, content):
 
3418
        self.transport.put_bytes(self.file_name, content)
 
3419
 
 
3420
    def external_url(self):
 
3421
        # FIXME: external_url should really accepts an optional relpath
 
3422
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
3423
        # The following will do in the interim but maybe we don't want to
 
3424
        # expose a path here but rather a config ID and its associated
 
3425
        # object </hand wawe>.
 
3426
        return urlutils.join(self.transport.external_url(), self.file_name.encode("ascii"))
 
3427
 
 
3428
 
 
3429
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
 
3430
# unlockable stores for use with objects that can already ensure the locking
 
3431
# (think branches). If different stores (not based on ConfigObj) are created,
 
3432
# they may face the same issue.
 
3433
 
 
3434
 
 
3435
class LockableIniFileStore(TransportIniFileStore):
 
3436
    """A ConfigObjStore using locks on save to ensure store integrity."""
 
3437
 
 
3438
    def __init__(self, transport, file_name, lock_dir_name=None):
 
3439
        """A config Store using ConfigObj for storage.
 
3440
 
 
3441
        :param transport: The transport object where the config file is located.
 
3442
 
 
3443
        :param file_name: The config file basename in the transport directory.
 
3444
        """
 
3445
        if lock_dir_name is None:
 
3446
            lock_dir_name = 'lock'
 
3447
        self.lock_dir_name = lock_dir_name
 
3448
        super(LockableIniFileStore, self).__init__(transport, file_name)
 
3449
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
 
3450
 
 
3451
    def lock_write(self, token=None):
 
3452
        """Takes a write lock in the directory containing the config file.
 
3453
 
 
3454
        If the directory doesn't exist it is created.
 
3455
        """
 
3456
        # FIXME: This doesn't check the ownership of the created directories as
 
3457
        # ensure_config_dir_exists does. It should if the transport is local
 
3458
        # -- vila 2011-04-06
 
3459
        self.transport.create_prefix()
 
3460
        return self._lock.lock_write(token)
 
3461
 
 
3462
    def unlock(self):
 
3463
        self._lock.unlock()
 
3464
 
 
3465
    def break_lock(self):
 
3466
        self._lock.break_lock()
 
3467
 
 
3468
    @needs_write_lock
 
3469
    def save(self):
 
3470
        # We need to be able to override the undecorated implementation
 
3471
        self.save_without_locking()
 
3472
 
 
3473
    def save_without_locking(self):
 
3474
        super(LockableIniFileStore, self).save()
 
3475
 
 
3476
 
 
3477
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
 
3478
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
 
3479
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
 
3480
 
 
3481
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
 
3482
# functions or a registry will make it easier and clearer for tests, focusing
 
3483
# on the relevant parts of the API that needs testing -- vila 20110503 (based
 
3484
# on a poolie's remark)
 
3485
class GlobalStore(LockableIniFileStore):
 
3486
    """A config store for global options.
 
3487
 
 
3488
    There is a single GlobalStore for a given process.
 
3489
    """
 
3490
 
 
3491
    def __init__(self, possible_transports=None):
 
3492
        t = transport.get_transport_from_path(
 
3493
            config_dir(), possible_transports=possible_transports)
 
3494
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
3495
        self.id = 'bazaar'
 
3496
 
 
3497
 
 
3498
class LocationStore(LockableIniFileStore):
 
3499
    """A config store for options specific to a location.
 
3500
 
 
3501
    There is a single LocationStore for a given process.
 
3502
    """
 
3503
 
 
3504
    def __init__(self, possible_transports=None):
 
3505
        t = transport.get_transport_from_path(
 
3506
            config_dir(), possible_transports=possible_transports)
 
3507
        super(LocationStore, self).__init__(t, 'locations.conf')
 
3508
        self.id = 'locations'
 
3509
 
 
3510
 
 
3511
class BranchStore(TransportIniFileStore):
 
3512
    """A config store for branch options.
 
3513
 
 
3514
    There is a single BranchStore for a given branch.
 
3515
    """
 
3516
 
 
3517
    def __init__(self, branch):
 
3518
        super(BranchStore, self).__init__(branch.control_transport,
 
3519
                                          'branch.conf')
 
3520
        self.branch = branch
 
3521
        self.id = 'branch'
 
3522
 
 
3523
 
 
3524
class ControlStore(LockableIniFileStore):
 
3525
 
 
3526
    def __init__(self, bzrdir):
 
3527
        super(ControlStore, self).__init__(bzrdir.transport,
 
3528
                                          'control.conf',
 
3529
                                           lock_dir_name='branch_lock')
 
3530
        self.id = 'control'
 
3531
 
 
3532
 
 
3533
class SectionMatcher(object):
 
3534
    """Select sections into a given Store.
 
3535
 
 
3536
    This is intended to be used to postpone getting an iterable of sections
 
3537
    from a store.
 
3538
    """
 
3539
 
 
3540
    def __init__(self, store):
 
3541
        self.store = store
 
3542
 
 
3543
    def get_sections(self):
 
3544
        # This is where we require loading the store so we can see all defined
 
3545
        # sections.
 
3546
        sections = self.store.get_sections()
 
3547
        # Walk the revisions in the order provided
 
3548
        for store, s in sections:
 
3549
            if self.match(s):
 
3550
                yield store, s
 
3551
 
 
3552
    def match(self, section):
 
3553
        """Does the proposed section match.
 
3554
 
 
3555
        :param section: A Section object.
 
3556
 
 
3557
        :returns: True if the section matches, False otherwise.
 
3558
        """
 
3559
        raise NotImplementedError(self.match)
 
3560
 
 
3561
 
 
3562
class NameMatcher(SectionMatcher):
 
3563
 
 
3564
    def __init__(self, store, section_id):
 
3565
        super(NameMatcher, self).__init__(store)
 
3566
        self.section_id = section_id
 
3567
 
 
3568
    def match(self, section):
 
3569
        return section.id == self.section_id
 
3570
 
 
3571
 
 
3572
class LocationSection(Section):
 
3573
 
 
3574
    def __init__(self, section, extra_path, branch_name=None):
 
3575
        super(LocationSection, self).__init__(section.id, section.options)
 
3576
        self.extra_path = extra_path
 
3577
        if branch_name is None:
 
3578
            branch_name = ''
 
3579
        self.locals = {'relpath': extra_path,
 
3580
                       'basename': urlutils.basename(extra_path),
 
3581
                       'branchname': branch_name}
 
3582
 
 
3583
    def get(self, name, default=None, expand=True):
 
3584
        value = super(LocationSection, self).get(name, default)
 
3585
        if value is not None and expand:
 
3586
            policy_name = self.get(name + ':policy', None)
 
3587
            policy = _policy_value.get(policy_name, POLICY_NONE)
 
3588
            if policy == POLICY_APPENDPATH:
 
3589
                value = urlutils.join(value, self.extra_path)
 
3590
            # expand section local options right now (since POLICY_APPENDPATH
 
3591
            # will never add options references, it's ok to expand after it).
 
3592
            chunks = []
 
3593
            for is_ref, chunk in iter_option_refs(value):
 
3594
                if not is_ref:
 
3595
                    chunks.append(chunk)
 
3596
                else:
 
3597
                    ref = chunk[1:-1]
 
3598
                    if ref in self.locals:
 
3599
                        chunks.append(self.locals[ref])
 
3600
                    else:
 
3601
                        chunks.append(chunk)
 
3602
            value = ''.join(chunks)
 
3603
        return value
 
3604
 
 
3605
 
 
3606
class StartingPathMatcher(SectionMatcher):
 
3607
    """Select sections for a given location respecting the Store order."""
 
3608
 
 
3609
    # FIXME: Both local paths and urls can be used for section names as well as
 
3610
    # ``location`` to stay consistent with ``LocationMatcher`` which itself
 
3611
    # inherited the fuzziness from the previous ``LocationConfig``
 
3612
    # implementation. We probably need to revisit which encoding is allowed for
 
3613
    # both ``location`` and section names and how we normalize
 
3614
    # them. http://pad.lv/85479, http://pad.lv/437009 and http://359320 are
 
3615
    # related too. -- vila 2012-01-04
 
3616
 
 
3617
    def __init__(self, store, location):
 
3618
        super(StartingPathMatcher, self).__init__(store)
 
3619
        if location.startswith('file://'):
 
3620
            location = urlutils.local_path_from_url(location)
 
3621
        self.location = location
 
3622
 
 
3623
    def get_sections(self):
 
3624
        """Get all sections matching ``location`` in the store.
 
3625
 
 
3626
        The most generic sections are described first in the store, then more
 
3627
        specific ones can be provided for reduced scopes.
 
3628
 
 
3629
        The returned section are therefore returned in the reversed order so
 
3630
        the most specific ones can be found first.
 
3631
        """
 
3632
        location_parts = self.location.rstrip('/').split('/')
 
3633
        store = self.store
 
3634
        # Later sections are more specific, they should be returned first
 
3635
        for _, section in reversed(list(store.get_sections())):
 
3636
            if section.id is None:
 
3637
                # The no-name section is always included if present
 
3638
                yield store, LocationSection(section, self.location)
 
3639
                continue
 
3640
            section_path = section.id
 
3641
            if section_path.startswith('file://'):
 
3642
                # the location is already a local path or URL, convert the
 
3643
                # section id to the same format
 
3644
                section_path = urlutils.local_path_from_url(section_path)
 
3645
            if (self.location.startswith(section_path)
 
3646
                or fnmatch.fnmatch(self.location, section_path)):
 
3647
                section_parts = section_path.rstrip('/').split('/')
 
3648
                extra_path = '/'.join(location_parts[len(section_parts):])
 
3649
                yield store, LocationSection(section, extra_path)
 
3650
 
 
3651
 
 
3652
class LocationMatcher(SectionMatcher):
 
3653
 
 
3654
    def __init__(self, store, location):
 
3655
        super(LocationMatcher, self).__init__(store)
 
3656
        url, params = urlutils.split_segment_parameters(location)
 
3657
        if location.startswith('file://'):
 
3658
            location = urlutils.local_path_from_url(location)
 
3659
        self.location = location
 
3660
        branch_name = params.get('branch')
 
3661
        if branch_name is None:
 
3662
            self.branch_name = urlutils.basename(self.location)
 
3663
        else:
 
3664
            self.branch_name = urlutils.unescape(branch_name)
 
3665
 
 
3666
    def _get_matching_sections(self):
 
3667
        """Get all sections matching ``location``."""
 
3668
        # We slightly diverge from LocalConfig here by allowing the no-name
 
3669
        # section as the most generic one and the lower priority.
 
3670
        no_name_section = None
 
3671
        all_sections = []
 
3672
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
3673
        # used (it assumes all sections have a name).
 
3674
        for _, section in self.store.get_sections():
 
3675
            if section.id is None:
 
3676
                no_name_section = section
 
3677
            else:
 
3678
                all_sections.append(section)
 
3679
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
3680
        # we have to resync.
 
3681
        filtered_sections = _iter_for_location_by_parts(
 
3682
            [s.id for s in all_sections], self.location)
 
3683
        iter_all_sections = iter(all_sections)
 
3684
        matching_sections = []
 
3685
        if no_name_section is not None:
 
3686
            matching_sections.append(
 
3687
                (0, LocationSection(no_name_section, self.location)))
 
3688
        for section_id, extra_path, length in filtered_sections:
 
3689
            # a section id is unique for a given store so it's safe to take the
 
3690
            # first matching section while iterating. Also, all filtered
 
3691
            # sections are part of 'all_sections' and will always be found
 
3692
            # there.
 
3693
            while True:
 
3694
                section = iter_all_sections.next()
 
3695
                if section_id == section.id:
 
3696
                    section = LocationSection(section, extra_path,
 
3697
                                              self.branch_name)
 
3698
                    matching_sections.append((length, section))
 
3699
                    break
 
3700
        return matching_sections
 
3701
 
 
3702
    def get_sections(self):
 
3703
        # Override the default implementation as we want to change the order
 
3704
        # We want the longest (aka more specific) locations first
 
3705
        sections = sorted(self._get_matching_sections(),
 
3706
                          key=lambda match: (match[0], match[1].id),
 
3707
                          reverse=True)
 
3708
        # Sections mentioning 'ignore_parents' restrict the selection
 
3709
        for _, section in sections:
 
3710
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
 
3711
            ignore = section.get('ignore_parents', None)
 
3712
            if ignore is not None:
 
3713
                ignore = ui.bool_from_string(ignore)
 
3714
            if ignore:
 
3715
                break
 
3716
            # Finally, we have a valid section
 
3717
            yield self.store, section
 
3718
 
 
3719
 
 
3720
# FIXME: _shared_stores should be an attribute of a library state once a
 
3721
# library_state object is always available.
 
3722
_shared_stores = {}
 
3723
_shared_stores_at_exit_installed = False
 
3724
 
 
3725
class Stack(object):
 
3726
    """A stack of configurations where an option can be defined"""
 
3727
 
 
3728
    def __init__(self, sections_def, store=None, mutable_section_id=None):
 
3729
        """Creates a stack of sections with an optional store for changes.
 
3730
 
 
3731
        :param sections_def: A list of Section or callables that returns an
 
3732
            iterable of Section. This defines the Sections for the Stack and
 
3733
            can be called repeatedly if needed.
 
3734
 
 
3735
        :param store: The optional Store where modifications will be
 
3736
            recorded. If none is specified, no modifications can be done.
 
3737
 
 
3738
        :param mutable_section_id: The id of the MutableSection where changes
 
3739
            are recorded. This requires the ``store`` parameter to be
 
3740
            specified.
 
3741
        """
 
3742
        self.sections_def = sections_def
 
3743
        self.store = store
 
3744
        self.mutable_section_id = mutable_section_id
 
3745
 
 
3746
    def iter_sections(self):
 
3747
        """Iterate all the defined sections."""
 
3748
        # Ensuring lazy loading is achieved by delaying section matching (which
 
3749
        # implies querying the persistent storage) until it can't be avoided
 
3750
        # anymore by using callables to describe (possibly empty) section
 
3751
        # lists.
 
3752
        for sections in self.sections_def:
 
3753
            for store, section in sections():
 
3754
                yield store, section
 
3755
 
 
3756
    def get(self, name, expand=True, convert=True):
 
3757
        """Return the *first* option value found in the sections.
 
3758
 
 
3759
        This is where we guarantee that sections coming from Store are loaded
 
3760
        lazily: the loading is delayed until we need to either check that an
 
3761
        option exists or get its value, which in turn may require to discover
 
3762
        in which sections it can be defined. Both of these (section and option
 
3763
        existence) require loading the store (even partially).
 
3764
 
 
3765
        :param name: The queried option.
 
3766
 
 
3767
        :param expand: Whether options references should be expanded.
 
3768
 
 
3769
        :param convert: Whether the option value should be converted from
 
3770
            unicode (do nothing for non-registered options).
 
3771
 
 
3772
        :returns: The value of the option.
 
3773
        """
 
3774
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
3775
        value = None
 
3776
        found_store = None # Where the option value has been found
 
3777
        # If the option is registered, it may provide additional info about
 
3778
        # value handling
 
3779
        try:
 
3780
            opt = option_registry.get(name)
 
3781
        except KeyError:
 
3782
            # Not registered
 
3783
            opt = None
 
3784
 
 
3785
        def expand_and_convert(val):
 
3786
            # This may need to be called in different contexts if the value is
 
3787
            # None or ends up being None during expansion or conversion.
 
3788
            if val is not None:
 
3789
                if expand:
 
3790
                    if isinstance(val, string_types):
 
3791
                        val = self._expand_options_in_string(val)
 
3792
                    else:
 
3793
                        trace.warning('Cannot expand "%s":'
 
3794
                                      ' %s does not support option expansion'
 
3795
                                      % (name, type(val)))
 
3796
                if opt is None:
 
3797
                    val = found_store.unquote(val)
 
3798
                elif convert:
 
3799
                    val = opt.convert_from_unicode(found_store, val)
 
3800
            return val
 
3801
 
 
3802
        # First of all, check if the environment can override the configuration
 
3803
        # value
 
3804
        if opt is not None and opt.override_from_env:
 
3805
            value = opt.get_override()
 
3806
            value = expand_and_convert(value)
 
3807
        if value is None:
 
3808
            for store, section in self.iter_sections():
 
3809
                value = section.get(name)
 
3810
                if value is not None:
 
3811
                    found_store = store
 
3812
                    break
 
3813
            value = expand_and_convert(value)
 
3814
            if opt is not None and value is None:
 
3815
                # If the option is registered, it may provide a default value
 
3816
                value = opt.get_default()
 
3817
                value = expand_and_convert(value)
 
3818
        for hook in ConfigHooks['get']:
 
3819
            hook(self, name, value)
 
3820
        return value
 
3821
 
 
3822
    def expand_options(self, string, env=None):
 
3823
        """Expand option references in the string in the configuration context.
 
3824
 
 
3825
        :param string: The string containing option(s) to expand.
 
3826
 
 
3827
        :param env: An option dict defining additional configuration options or
 
3828
            overriding existing ones.
 
3829
 
 
3830
        :returns: The expanded string.
 
3831
        """
 
3832
        return self._expand_options_in_string(string, env)
 
3833
 
 
3834
    def _expand_options_in_string(self, string, env=None, _refs=None):
 
3835
        """Expand options in the string in the configuration context.
 
3836
 
 
3837
        :param string: The string to be expanded.
 
3838
 
 
3839
        :param env: An option dict defining additional configuration options or
 
3840
            overriding existing ones.
 
3841
 
 
3842
        :param _refs: Private list (FIFO) containing the options being expanded
 
3843
            to detect loops.
 
3844
 
 
3845
        :returns: The expanded string.
 
3846
        """
 
3847
        if string is None:
 
3848
            # Not much to expand there
 
3849
            return None
 
3850
        if _refs is None:
 
3851
            # What references are currently resolved (to detect loops)
 
3852
            _refs = []
 
3853
        result = string
 
3854
        # We need to iterate until no more refs appear ({{foo}} will need two
 
3855
        # iterations for example).
 
3856
        expanded = True
 
3857
        while expanded:
 
3858
            expanded = False
 
3859
            chunks = []
 
3860
            for is_ref, chunk in iter_option_refs(result):
 
3861
                if not is_ref:
 
3862
                    chunks.append(chunk)
 
3863
                else:
 
3864
                    expanded = True
 
3865
                    name = chunk[1:-1]
 
3866
                    if name in _refs:
 
3867
                        raise errors.OptionExpansionLoop(string, _refs)
 
3868
                    _refs.append(name)
 
3869
                    value = self._expand_option(name, env, _refs)
 
3870
                    if value is None:
 
3871
                        raise errors.ExpandingUnknownOption(name, string)
 
3872
                    chunks.append(value)
 
3873
                    _refs.pop()
 
3874
            result = ''.join(chunks)
 
3875
        return result
 
3876
 
 
3877
    def _expand_option(self, name, env, _refs):
 
3878
        if env is not None and name in env:
 
3879
            # Special case, values provided in env takes precedence over
 
3880
            # anything else
 
3881
            value = env[name]
 
3882
        else:
 
3883
            value = self.get(name, expand=False, convert=False)
 
3884
            value = self._expand_options_in_string(value, env, _refs)
 
3885
        return value
 
3886
 
 
3887
    def _get_mutable_section(self):
 
3888
        """Get the MutableSection for the Stack.
 
3889
 
 
3890
        This is where we guarantee that the mutable section is lazily loaded:
 
3891
        this means we won't load the corresponding store before setting a value
 
3892
        or deleting an option. In practice the store will often be loaded but
 
3893
        this helps catching some programming errors.
 
3894
        """
 
3895
        store = self.store
 
3896
        section = store.get_mutable_section(self.mutable_section_id)
 
3897
        return store, section
 
3898
 
 
3899
    def set(self, name, value):
 
3900
        """Set a new value for the option."""
 
3901
        store, section = self._get_mutable_section()
 
3902
        section.set(name, store.quote(value))
 
3903
        for hook in ConfigHooks['set']:
 
3904
            hook(self, name, value)
 
3905
 
 
3906
    def remove(self, name):
 
3907
        """Remove an existing option."""
 
3908
        _, section = self._get_mutable_section()
 
3909
        section.remove(name)
 
3910
        for hook in ConfigHooks['remove']:
 
3911
            hook(self, name)
 
3912
 
 
3913
    def __repr__(self):
 
3914
        # Mostly for debugging use
 
3915
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
 
3916
 
 
3917
    def _get_overrides(self):
 
3918
        # FIXME: Hack around library_state.initialize never called
 
3919
        if breezy.global_state is not None:
 
3920
            return breezy.global_state.cmdline_overrides.get_sections()
 
3921
        return []
 
3922
 
 
3923
    def get_shared_store(self, store, state=None):
 
3924
        """Get a known shared store.
 
3925
 
 
3926
        Store urls uniquely identify them and are used to ensure a single copy
 
3927
        is shared across all users.
 
3928
 
 
3929
        :param store: The store known to the caller.
 
3930
 
 
3931
        :param state: The library state where the known stores are kept.
 
3932
 
 
3933
        :returns: The store received if it's not a known one, an already known
 
3934
            otherwise.
 
3935
        """
 
3936
        if state is None:
 
3937
            state = breezy.global_state
 
3938
        if state is None:
 
3939
            global _shared_stores_at_exit_installed
 
3940
            stores = _shared_stores
 
3941
            def save_config_changes():
 
3942
                for k, store in stores.items():
 
3943
                    store.save_changes()
 
3944
            if not _shared_stores_at_exit_installed:
 
3945
                # FIXME: Ugly hack waiting for library_state to always be
 
3946
                # available. -- vila 20120731
 
3947
                import atexit
 
3948
                atexit.register(save_config_changes)
 
3949
                _shared_stores_at_exit_installed = True
 
3950
        else:
 
3951
            stores = state.config_stores
 
3952
        url = store.external_url()
 
3953
        try:
 
3954
            return stores[url]
 
3955
        except KeyError:
 
3956
            stores[url] = store
 
3957
            return store
 
3958
 
 
3959
 
 
3960
class MemoryStack(Stack):
 
3961
    """A configuration stack defined from a string.
 
3962
 
 
3963
    This is mainly intended for tests and requires no disk resources.
 
3964
    """
 
3965
 
 
3966
    def __init__(self, content=None):
 
3967
        """Create an in-memory stack from a given content.
 
3968
 
 
3969
        It uses a single store based on configobj and support reading and
 
3970
        writing options.
 
3971
 
 
3972
        :param content: The initial content of the store. If None, the store is
 
3973
            not loaded and ``_load_from_string`` can and should be used if
 
3974
            needed.
 
3975
        """
 
3976
        store = IniFileStore()
 
3977
        if content is not None:
 
3978
            store._load_from_string(content)
 
3979
        super(MemoryStack, self).__init__(
 
3980
            [store.get_sections], store)
 
3981
 
 
3982
 
 
3983
class _CompatibleStack(Stack):
 
3984
    """Place holder for compatibility with previous design.
 
3985
 
 
3986
    This is intended to ease the transition from the Config-based design to the
 
3987
    Stack-based design and should not be used nor relied upon by plugins.
 
3988
 
 
3989
    One assumption made here is that the daughter classes will all use Stores
 
3990
    derived from LockableIniFileStore).
 
3991
 
 
3992
    It implements set() and remove () by re-loading the store before applying
 
3993
    the modification and saving it.
 
3994
 
 
3995
    The long term plan being to implement a single write by store to save
 
3996
    all modifications, this class should not be used in the interim.
 
3997
    """
 
3998
 
 
3999
    def set(self, name, value):
 
4000
        # Force a reload
 
4001
        self.store.unload()
 
4002
        super(_CompatibleStack, self).set(name, value)
 
4003
        # Force a write to persistent storage
 
4004
        self.store.save()
 
4005
 
 
4006
    def remove(self, name):
 
4007
        # Force a reload
 
4008
        self.store.unload()
 
4009
        super(_CompatibleStack, self).remove(name)
 
4010
        # Force a write to persistent storage
 
4011
        self.store.save()
 
4012
 
 
4013
 
 
4014
class GlobalStack(Stack):
 
4015
    """Global options only stack.
 
4016
 
 
4017
    The following sections are queried:
 
4018
 
 
4019
    * command-line overrides,
 
4020
 
 
4021
    * the 'DEFAULT' section in bazaar.conf
 
4022
 
 
4023
    This stack will use the ``DEFAULT`` section in bazaar.conf as its
 
4024
    MutableSection.
 
4025
    """
 
4026
 
 
4027
    def __init__(self):
 
4028
        gstore = self.get_shared_store(GlobalStore())
 
4029
        super(GlobalStack, self).__init__(
 
4030
            [self._get_overrides,
 
4031
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
4032
            gstore, mutable_section_id='DEFAULT')
 
4033
 
 
4034
 
 
4035
class LocationStack(Stack):
 
4036
    """Per-location options falling back to global options stack.
 
4037
 
 
4038
 
 
4039
    The following sections are queried:
 
4040
 
 
4041
    * command-line overrides,
 
4042
 
 
4043
    * the sections matching ``location`` in ``locations.conf``, the order being
 
4044
      defined by the number of path components in the section glob, higher
 
4045
      numbers first (from most specific section to most generic).
 
4046
 
 
4047
    * the 'DEFAULT' section in bazaar.conf
 
4048
 
 
4049
    This stack will use the ``location`` section in locations.conf as its
 
4050
    MutableSection.
 
4051
    """
 
4052
 
 
4053
    def __init__(self, location):
 
4054
        """Make a new stack for a location and global configuration.
 
4055
 
 
4056
        :param location: A URL prefix to """
 
4057
        lstore = self.get_shared_store(LocationStore())
 
4058
        if location.startswith('file://'):
 
4059
            location = urlutils.local_path_from_url(location)
 
4060
        gstore = self.get_shared_store(GlobalStore())
 
4061
        super(LocationStack, self).__init__(
 
4062
            [self._get_overrides,
 
4063
             LocationMatcher(lstore, location).get_sections,
 
4064
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
4065
            lstore, mutable_section_id=location)
 
4066
 
 
4067
 
 
4068
class BranchStack(Stack):
 
4069
    """Per-location options falling back to branch then global options stack.
 
4070
 
 
4071
    The following sections are queried:
 
4072
 
 
4073
    * command-line overrides,
 
4074
 
 
4075
    * the sections matching ``location`` in ``locations.conf``, the order being
 
4076
      defined by the number of path components in the section glob, higher
 
4077
      numbers first (from most specific section to most generic),
 
4078
 
 
4079
    * the no-name section in branch.conf,
 
4080
 
 
4081
    * the ``DEFAULT`` section in ``bazaar.conf``.
 
4082
 
 
4083
    This stack will use the no-name section in ``branch.conf`` as its
 
4084
    MutableSection.
 
4085
    """
 
4086
 
 
4087
    def __init__(self, branch):
 
4088
        lstore = self.get_shared_store(LocationStore())
 
4089
        bstore = branch._get_config_store()
 
4090
        gstore = self.get_shared_store(GlobalStore())
 
4091
        super(BranchStack, self).__init__(
 
4092
            [self._get_overrides,
 
4093
             LocationMatcher(lstore, branch.base).get_sections,
 
4094
             NameMatcher(bstore, None).get_sections,
 
4095
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
4096
            bstore)
 
4097
        self.branch = branch
 
4098
 
 
4099
    def lock_write(self, token=None):
 
4100
        return self.branch.lock_write(token)
 
4101
 
 
4102
    def unlock(self):
 
4103
        return self.branch.unlock()
 
4104
 
 
4105
    @needs_write_lock
 
4106
    def set(self, name, value):
 
4107
        super(BranchStack, self).set(name, value)
 
4108
        # Unlocking the branch will trigger a store.save_changes() so the last
 
4109
        # unlock saves all the changes.
 
4110
 
 
4111
    @needs_write_lock
 
4112
    def remove(self, name):
 
4113
        super(BranchStack, self).remove(name)
 
4114
        # Unlocking the branch will trigger a store.save_changes() so the last
 
4115
        # unlock saves all the changes.
 
4116
 
 
4117
 
 
4118
class RemoteControlStack(Stack):
 
4119
    """Remote control-only options stack."""
 
4120
 
 
4121
    # FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
 
4122
    # with the stack used for remote bzr dirs. RemoteControlStack only uses
 
4123
    # control.conf and is used only for stack options.
 
4124
 
 
4125
    def __init__(self, bzrdir):
 
4126
        cstore = bzrdir._get_config_store()
 
4127
        super(RemoteControlStack, self).__init__(
 
4128
            [NameMatcher(cstore, None).get_sections],
 
4129
            cstore)
 
4130
        self.bzrdir = bzrdir
 
4131
 
 
4132
 
 
4133
class BranchOnlyStack(Stack):
 
4134
    """Branch-only options stack."""
 
4135
 
 
4136
    # FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
 
4137
    # stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
 
4138
    # -- vila 2011-12-16
 
4139
 
 
4140
    def __init__(self, branch):
 
4141
        bstore = branch._get_config_store()
 
4142
        super(BranchOnlyStack, self).__init__(
 
4143
            [NameMatcher(bstore, None).get_sections],
 
4144
            bstore)
 
4145
        self.branch = branch
 
4146
 
 
4147
    def lock_write(self, token=None):
 
4148
        return self.branch.lock_write(token)
 
4149
 
 
4150
    def unlock(self):
 
4151
        return self.branch.unlock()
 
4152
 
 
4153
    @needs_write_lock
 
4154
    def set(self, name, value):
 
4155
        super(BranchOnlyStack, self).set(name, value)
 
4156
        # Force a write to persistent storage
 
4157
        self.store.save_changes()
 
4158
 
 
4159
    @needs_write_lock
 
4160
    def remove(self, name):
 
4161
        super(BranchOnlyStack, self).remove(name)
 
4162
        # Force a write to persistent storage
 
4163
        self.store.save_changes()
 
4164
 
 
4165
 
 
4166
class cmd_config(commands.Command):
 
4167
    __doc__ = """Display, set or remove a configuration option.
 
4168
 
 
4169
    Display the active value for option NAME.
 
4170
 
 
4171
    If --all is specified, NAME is interpreted as a regular expression and all
 
4172
    matching options are displayed mentioning their scope and without resolving
 
4173
    option references in the value). The active value that bzr will take into
 
4174
    account is the first one displayed for each option.
 
4175
 
 
4176
    If NAME is not given, --all .* is implied (all options are displayed for the
 
4177
    current scope).
 
4178
 
 
4179
    Setting a value is achieved by using NAME=value without spaces. The value
 
4180
    is set in the most relevant scope and can be checked by displaying the
 
4181
    option again.
 
4182
 
 
4183
    Removing a value is achieved by using --remove NAME.
 
4184
    """
 
4185
 
 
4186
    takes_args = ['name?']
 
4187
 
 
4188
    takes_options = [
 
4189
        'directory',
 
4190
        # FIXME: This should be a registry option so that plugins can register
 
4191
        # their own config files (or not) and will also address
 
4192
        # http://pad.lv/788991 -- vila 20101115
 
4193
        commands.Option('scope', help='Reduce the scope to the specified'
 
4194
                        ' configuration file.',
 
4195
                        type=text_type),
 
4196
        commands.Option('all',
 
4197
            help='Display all the defined values for the matching options.',
 
4198
            ),
 
4199
        commands.Option('remove', help='Remove the option from'
 
4200
                        ' the configuration file.'),
 
4201
        ]
 
4202
 
 
4203
    _see_also = ['configuration']
 
4204
 
 
4205
    @commands.display_command
 
4206
    def run(self, name=None, all=False, directory=None, scope=None,
 
4207
            remove=False):
 
4208
        if directory is None:
 
4209
            directory = '.'
 
4210
        directory = directory_service.directories.dereference(directory)
 
4211
        directory = urlutils.normalize_url(directory)
 
4212
        if remove and all:
 
4213
            raise errors.BzrError(
 
4214
                '--all and --remove are mutually exclusive.')
 
4215
        elif remove:
 
4216
            # Delete the option in the given scope
 
4217
            self._remove_config_option(name, directory, scope)
 
4218
        elif name is None:
 
4219
            # Defaults to all options
 
4220
            self._show_matching_options('.*', directory, scope)
 
4221
        else:
 
4222
            try:
 
4223
                name, value = name.split('=', 1)
 
4224
            except ValueError:
 
4225
                # Display the option(s) value(s)
 
4226
                if all:
 
4227
                    self._show_matching_options(name, directory, scope)
 
4228
                else:
 
4229
                    self._show_value(name, directory, scope)
 
4230
            else:
 
4231
                if all:
 
4232
                    raise errors.BzrError(
 
4233
                        'Only one option can be set.')
 
4234
                # Set the option value
 
4235
                self._set_config_option(name, value, directory, scope)
 
4236
 
 
4237
    def _get_stack(self, directory, scope=None, write_access=False):
 
4238
        """Get the configuration stack specified by ``directory`` and ``scope``.
 
4239
 
 
4240
        :param directory: Where the configurations are derived from.
 
4241
 
 
4242
        :param scope: A specific config to start from.
 
4243
 
 
4244
        :param write_access: Whether a write access to the stack will be
 
4245
            attempted.
 
4246
        """
 
4247
        # FIXME: scope should allow access to plugin-specific stacks (even
 
4248
        # reduced to the plugin-specific store), related to
 
4249
        # http://pad.lv/788991 -- vila 2011-11-15
 
4250
        if scope is not None:
 
4251
            if scope == 'bazaar':
 
4252
                return GlobalStack()
 
4253
            elif scope == 'locations':
 
4254
                return LocationStack(directory)
 
4255
            elif scope == 'branch':
 
4256
                (_, br, _) = (
 
4257
                    controldir.ControlDir.open_containing_tree_or_branch(
 
4258
                        directory))
 
4259
                if write_access:
 
4260
                    self.add_cleanup(br.lock_write().unlock)
 
4261
                return br.get_config_stack()
 
4262
            raise errors.NoSuchConfig(scope)
 
4263
        else:
 
4264
            try:
 
4265
                (_, br, _) = (
 
4266
                    controldir.ControlDir.open_containing_tree_or_branch(
 
4267
                        directory))
 
4268
                if write_access:
 
4269
                    self.add_cleanup(br.lock_write().unlock)
 
4270
                return br.get_config_stack()
 
4271
            except errors.NotBranchError:
 
4272
                return LocationStack(directory)
 
4273
 
 
4274
    def _quote_multiline(self, value):
 
4275
        if '\n' in value:
 
4276
            value = '"""' + value + '"""'
 
4277
        return value
 
4278
 
 
4279
    def _show_value(self, name, directory, scope):
 
4280
        conf = self._get_stack(directory, scope)
 
4281
        value = conf.get(name, expand=True, convert=False)
 
4282
        if value is not None:
 
4283
            # Quote the value appropriately
 
4284
            value = self._quote_multiline(value)
 
4285
            self.outf.write('%s\n' % (value,))
 
4286
        else:
 
4287
            raise errors.NoSuchConfigOption(name)
 
4288
 
 
4289
    def _show_matching_options(self, name, directory, scope):
 
4290
        name = lazy_regex.lazy_compile(name)
 
4291
        # We want any error in the regexp to be raised *now* so we need to
 
4292
        # avoid the delay introduced by the lazy regexp.  But, we still do
 
4293
        # want the nicer errors raised by lazy_regex.
 
4294
        name._compile_and_collapse()
 
4295
        cur_store_id = None
 
4296
        cur_section = None
 
4297
        conf = self._get_stack(directory, scope)
 
4298
        for store, section in conf.iter_sections():
 
4299
            for oname in section.iter_option_names():
 
4300
                if name.search(oname):
 
4301
                    if cur_store_id != store.id:
 
4302
                        # Explain where the options are defined
 
4303
                        self.outf.write('%s:\n' % (store.id,))
 
4304
                        cur_store_id = store.id
 
4305
                        cur_section = None
 
4306
                    if (section.id is not None and cur_section != section.id):
 
4307
                        # Display the section id as it appears in the store
 
4308
                        # (None doesn't appear by definition)
 
4309
                        self.outf.write('  [%s]\n' % (section.id,))
 
4310
                        cur_section = section.id
 
4311
                    value = section.get(oname, expand=False)
 
4312
                    # Quote the value appropriately
 
4313
                    value = self._quote_multiline(value)
 
4314
                    self.outf.write('  %s = %s\n' % (oname, value))
 
4315
 
 
4316
    def _set_config_option(self, name, value, directory, scope):
 
4317
        conf = self._get_stack(directory, scope, write_access=True)
 
4318
        conf.set(name, value)
 
4319
        # Explicitly save the changes
 
4320
        conf.store.save_changes()
 
4321
 
 
4322
    def _remove_config_option(self, name, directory, scope):
 
4323
        if name is None:
 
4324
            raise errors.BzrCommandError(
 
4325
                '--remove expects an option to remove.')
 
4326
        conf = self._get_stack(directory, scope, write_access=True)
 
4327
        try:
 
4328
            conf.remove(name)
 
4329
            # Explicitly save the changes
 
4330
            conf.store.save_changes()
 
4331
        except KeyError:
 
4332
            raise errors.NoSuchConfigOption(name)
 
4333
 
 
4334
 
 
4335
# Test registries
 
4336
#
 
4337
# We need adapters that can build a Store or a Stack in a test context. Test
 
4338
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
4339
# themselves. The builder will receive a test instance and should return a
 
4340
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
4341
# register themselves here to be tested against the tests defined in
 
4342
# breezy.tests.test_config. Note that the builder can be called multiple times
 
4343
# for the same test.
 
4344
 
 
4345
# The registered object should be a callable receiving a test instance
 
4346
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
4347
# object.
 
4348
test_store_builder_registry = registry.Registry()
 
4349
 
 
4350
# The registered object should be a callable receiving a test instance
 
4351
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
4352
# object.
 
4353
test_stack_builder_registry = registry.Registry()