/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-23 14:08:03 UTC
  • mto: (6625.4.6 integration-bisect)
  • mto: This revision was merged to the branch mainline in revision 6629.
  • Revision ID: gzlist@googlemail.com-20170523140803-1bayist4qbqgvku8
Drop custom load_tests implementation and use unittest signature

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
            names = zip(location_parts, section_parts)
 
1195
            for name in names:
 
1196
                if not fnmatch.fnmatch(name[0], name[1]):
 
1197
                    matched = False
 
1198
                    break
 
1199
        if not matched:
 
1200
            continue
 
1201
        # build the path difference between the section and the location
 
1202
        extra_path = '/'.join(location_parts[len(section_parts):])
 
1203
        yield section, extra_path, len(section_parts)
 
1204
 
 
1205
 
 
1206
class LocationConfig(LockableConfig):
529
1207
    """A configuration object that gives the policy for a location."""
530
1208
 
531
1209
    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)
 
1210
        super(LocationConfig, self).__init__(
 
1211
            file_name=locations_config_filename())
544
1212
        # local file locations are looked up by local path, rather than
545
1213
        # by file url. This is because the config file is a user
546
1214
        # file, and we would rather not expose the user to file urls.
548
1216
            location = urlutils.local_path_from_url(location)
549
1217
        self.location = location
550
1218
 
 
1219
    def config_id(self):
 
1220
        return 'locations'
 
1221
 
 
1222
    @classmethod
 
1223
    def from_string(cls, str_or_unicode, location, save=False):
 
1224
        """Create a config object from a string.
 
1225
 
 
1226
        :param str_or_unicode: A string representing the file content. This will
 
1227
            be utf-8 encoded.
 
1228
 
 
1229
        :param location: The location url to filter the configuration.
 
1230
 
 
1231
        :param save: Whether the file should be saved upon creation.
 
1232
        """
 
1233
        conf = cls(location)
 
1234
        conf._create_from_string(str_or_unicode, save)
 
1235
        return conf
 
1236
 
551
1237
    def _get_matching_sections(self):
552
1238
        """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))
 
1239
        # put the longest (aka more specific) locations first
 
1240
        matches = sorted(
 
1241
            _iter_for_location_by_parts(self._get_parser(), self.location),
 
1242
            key=lambda match: (match[2], match[0]),
 
1243
            reverse=True)
 
1244
        for (section, extra_path, length) in matches:
 
1245
            yield section, extra_path
588
1246
            # should we stop looking for parent configs here?
589
1247
            try:
590
1248
                if self._get_parser()[section].as_bool('ignore_parents'):
591
1249
                    break
592
1250
            except KeyError:
593
1251
                pass
594
 
        return sections
 
1252
 
 
1253
    def _get_sections(self, name=None):
 
1254
        """See IniBasedConfig._get_sections()."""
 
1255
        # We ignore the name here as the only sections handled are named with
 
1256
        # the location path and we don't expose embedded sections either.
 
1257
        parser = self._get_parser()
 
1258
        for name, extra_path in self._get_matching_sections():
 
1259
            yield (name, parser[name], self.config_id())
595
1260
 
596
1261
    def _get_option_policy(self, section, option_name):
597
1262
        """Return the policy for the given (section, option_name) pair."""
641
1306
            if policy_key in self._get_parser()[section]:
642
1307
                del self._get_parser()[section][policy_key]
643
1308
 
 
1309
    @needs_write_lock
644
1310
    def set_user_option(self, option, value, store=STORE_LOCATION):
645
1311
        """Save option and its value in the configuration."""
646
1312
        if store not in [STORE_LOCATION,
648
1314
                         STORE_LOCATION_APPENDPATH]:
649
1315
            raise ValueError('bad storage policy %r for %r' %
650
1316
                (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)
 
1317
        self.reload()
655
1318
        location = self.location
656
1319
        if location.endswith('/'):
657
1320
            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():
 
1321
        parser = self._get_parser()
 
1322
        if not location in parser and not location + '/' in parser:
 
1323
            parser[location] = {}
 
1324
        elif location + '/' in parser:
662
1325
            location = location + '/'
663
 
        self._get_parser()[location][option]=value
 
1326
        parser[location][option]=value
664
1327
        # the allowed values of store match the config policies
665
1328
        self._set_option_policy(location, option, store)
666
 
        self._get_parser().write(file(self._get_filename(), 'wb'))
 
1329
        self._write_config_file()
 
1330
        for hook in OldConfigHooks['set']:
 
1331
            hook(self, option, value)
667
1332
 
668
1333
 
669
1334
class BranchConfig(Config):
670
1335
    """A configuration object giving the policy for a branch."""
671
1336
 
 
1337
    def __init__(self, branch):
 
1338
        super(BranchConfig, self).__init__()
 
1339
        self._location_config = None
 
1340
        self._branch_data_config = None
 
1341
        self._global_config = None
 
1342
        self.branch = branch
 
1343
        self.option_sources = (self._get_location_config,
 
1344
                               self._get_branch_data_config,
 
1345
                               self._get_global_config)
 
1346
 
 
1347
    def config_id(self):
 
1348
        return 'branch'
 
1349
 
672
1350
    def _get_branch_data_config(self):
673
1351
        if self._branch_data_config is None:
674
1352
            self._branch_data_config = TreeConfig(self.branch)
 
1353
            self._branch_data_config.config_id = self.config_id
675
1354
        return self._branch_data_config
676
1355
 
677
1356
    def _get_location_config(self):
717
1396
        e.g. "John Hacker <jhacker@example.com>"
718
1397
        This is looked up in the email controlfile for the branch.
719
1398
        """
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
1399
        return self._get_best_value('_get_user_id')
728
1400
 
729
1401
    def _get_change_editor(self):
745
1417
                return value
746
1418
        return None
747
1419
 
 
1420
    def _get_sections(self, name=None):
 
1421
        """See IniBasedConfig.get_sections()."""
 
1422
        for source in self.option_sources:
 
1423
            for section in source()._get_sections(name):
 
1424
                yield section
 
1425
 
 
1426
    def _get_options(self, sections=None):
 
1427
        opts = []
 
1428
        # First the locations options
 
1429
        for option in self._get_location_config()._get_options():
 
1430
            yield option
 
1431
        # Then the branch options
 
1432
        branch_config = self._get_branch_data_config()
 
1433
        if sections is None:
 
1434
            sections = [('DEFAULT', branch_config._get_parser())]
 
1435
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
 
1436
        # Config itself has no notion of sections :( -- vila 20101001
 
1437
        config_id = self.config_id()
 
1438
        for (section_name, section) in sections:
 
1439
            for (name, value) in section.iteritems():
 
1440
                yield (name, value, section_name,
 
1441
                       config_id, branch_config._get_parser())
 
1442
        # Then the global options
 
1443
        for option in self._get_global_config()._get_options():
 
1444
            yield option
 
1445
 
748
1446
    def set_user_option(self, name, value, store=STORE_BRANCH,
749
1447
        warn_masked=False):
750
1448
        if store == STORE_BRANCH:
768
1466
                        trace.warning('Value "%s" is masked by "%s" from'
769
1467
                                      ' branch.conf', value, mask_value)
770
1468
 
 
1469
    def remove_user_option(self, option_name, section_name=None):
 
1470
        self._get_branch_data_config().remove_option(option_name, section_name)
 
1471
 
771
1472
    def _gpg_signing_command(self):
772
1473
        """See Config.gpg_signing_command."""
773
1474
        return self._get_safe_value('_gpg_signing_command')
774
1475
 
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
1476
    def _post_commit(self):
786
1477
        """See Config.post_commit."""
787
1478
        return self._get_safe_value('_post_commit')
790
1481
        value = self._get_explicit_nickname()
791
1482
        if value is not None:
792
1483
            return value
 
1484
        if self.branch.name:
 
1485
            return self.branch.name
793
1486
        return urlutils.unescape(self.branch.base.split('/')[-2])
794
1487
 
795
1488
    def has_explicit_nickname(self):
803
1496
        """See Config.log_format."""
804
1497
        return self._get_best_value('_log_format')
805
1498
 
 
1499
    def _validate_signatures_in_log(self):
 
1500
        """See Config.validate_signatures_in_log."""
 
1501
        return self._get_best_value('_validate_signatures_in_log')
 
1502
 
 
1503
    def _acceptable_keys(self):
 
1504
        """See Config.acceptable_keys."""
 
1505
        return self._get_best_value('_acceptable_keys')
 
1506
 
806
1507
 
807
1508
def ensure_config_dir_exists(path=None):
808
1509
    """Make sure a configuration directory exists.
817
1518
            parent_dir = os.path.dirname(path)
818
1519
            if not os.path.isdir(parent_dir):
819
1520
                trace.mutter('creating config parent directory: %r', parent_dir)
820
 
            os.mkdir(parent_dir)
 
1521
                os.mkdir(parent_dir)
821
1522
        trace.mutter('creating config directory: %r', path)
822
1523
        os.mkdir(path)
823
1524
        osutils.copy_ownership_from_path(path)
824
1525
 
825
1526
 
 
1527
def bazaar_config_dir():
 
1528
    """Return per-user configuration directory as unicode string
 
1529
 
 
1530
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
 
1531
    and Linux.  On Mac OS X and Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
 
1532
    that will be used instead.
 
1533
 
 
1534
    TODO: Global option --config-dir to override this.
 
1535
    """
 
1536
    base = osutils.path_from_environ('BZR_HOME')
 
1537
    if sys.platform == 'win32':
 
1538
        if base is None:
 
1539
            base = win32utils.get_appdata_location()
 
1540
        if base is None:
 
1541
            base = win32utils.get_home_location()
 
1542
        # GZ 2012-02-01: Really the two level subdirs only make sense inside
 
1543
        #                APPDATA, but hard to move. See bug 348640 for more.
 
1544
        return osutils.pathjoin(base, 'bazaar', '2.0')
 
1545
    if base is None:
 
1546
        xdg_dir = osutils.path_from_environ('XDG_CONFIG_HOME')
 
1547
        if xdg_dir is None:
 
1548
            xdg_dir = osutils.pathjoin(osutils._get_home_dir(), ".config")
 
1549
        xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
 
1550
        if osutils.isdir(xdg_dir):
 
1551
            trace.mutter(
 
1552
                "Using configuration in XDG directory %s." % xdg_dir)
 
1553
            return xdg_dir
 
1554
        base = osutils._get_home_dir()
 
1555
    return osutils.pathjoin(base, ".bazaar")
 
1556
 
 
1557
 
826
1558
def config_dir():
827
 
    """Return per-user configuration directory.
 
1559
    """Return per-user configuration directory as unicode string
828
1560
 
829
 
    By default this is ~/.bazaar/
 
1561
    By default this is %APPDATA%/breezy on Windows, $XDG_CONFIG_HOME/breezy on
 
1562
    Mac OS X and Linux. If the breezy config directory doesn't exist but
 
1563
    the bazaar one (see bazaar_config_dir()) does, use that instead.
830
1564
 
831
1565
    TODO: Global option --config-dir to override this.
832
1566
    """
833
 
    base = os.environ.get('BZR_HOME', None)
 
1567
    base = osutils.path_from_environ('BRZ_HOME')
834
1568
    if sys.platform == 'win32':
835
1569
        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")
 
1570
            base = win32utils.get_appdata_location()
 
1571
        if base is None:
 
1572
            base = win32utils.get_home_location()
 
1573
        # GZ 2012-02-01: Really the two level subdirs only make sense inside
 
1574
        #                APPDATA, but hard to move. See bug 348640 for more.
 
1575
    if base is None:
 
1576
        base = osutils.path_from_environ('XDG_CONFIG_HOME')
 
1577
        if base is None:
 
1578
            base = osutils.pathjoin(osutils._get_home_dir(), ".config")
 
1579
    breezy_dir = osutils.pathjoin(base, 'breezy')
 
1580
    if osutils.isdir(breezy_dir):
 
1581
        return breezy_dir
 
1582
    # If the breezy directory doesn't exist, but the bazaar one does, use that:
 
1583
    bazaar_dir = bazaar_config_dir()
 
1584
    if osutils.isdir(bazaar_dir):
 
1585
        trace.mutter(
 
1586
            "Using Bazaar configuration directory (%s)", bazaar_dir)
 
1587
        return bazaar_dir
 
1588
    return breezy_dir
848
1589
 
849
1590
 
850
1591
def config_filename():
852
1593
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
853
1594
 
854
1595
 
855
 
def branches_config_filename():
856
 
    """Return per-user configuration ini file filename."""
857
 
    return osutils.pathjoin(config_dir(), 'branches.conf')
858
 
 
859
 
 
860
1596
def locations_config_filename():
861
1597
    """Return per-user configuration ini file filename."""
862
1598
    return osutils.pathjoin(config_dir(), 'locations.conf')
892
1628
def xdg_cache_dir():
893
1629
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
894
1630
    # Possibly this should be different on Windows?
895
 
    e = os.environ.get('XDG_CACHE_DIR', None)
 
1631
    e = os.environ.get('XDG_CACHE_HOME', None)
896
1632
    if e:
897
1633
        return e
898
1634
    else:
899
1635
        return os.path.expanduser('~/.cache')
900
1636
 
901
1637
 
 
1638
def _get_default_mail_domain(mailname_file='/etc/mailname'):
 
1639
    """If possible, return the assumed default email domain.
 
1640
 
 
1641
    :returns: string mail domain, or None.
 
1642
    """
 
1643
    if sys.platform == 'win32':
 
1644
        # No implementation yet; patches welcome
 
1645
        return None
 
1646
    try:
 
1647
        f = open(mailname_file)
 
1648
    except (IOError, OSError) as e:
 
1649
        return None
 
1650
    try:
 
1651
        domain = f.readline().strip()
 
1652
        return domain
 
1653
    finally:
 
1654
        f.close()
 
1655
 
 
1656
 
 
1657
def default_email():
 
1658
    v = os.environ.get('BRZ_EMAIL')
 
1659
    if v:
 
1660
        return v.decode(osutils.get_user_encoding())
 
1661
    v = os.environ.get('EMAIL')
 
1662
    if v:
 
1663
        return v.decode(osutils.get_user_encoding())
 
1664
    name, email = _auto_user_id()
 
1665
    if name and email:
 
1666
        return u'%s <%s>' % (name, email)
 
1667
    elif email:
 
1668
        return email
 
1669
    raise errors.NoWhoami()
 
1670
 
 
1671
 
902
1672
def _auto_user_id():
903
1673
    """Calculate automatic user identification.
904
1674
 
905
 
    Returns (realname, email).
 
1675
    :returns: (realname, email), either of which may be None if they can't be
 
1676
    determined.
906
1677
 
907
1678
    Only used when none is set in the environment or the id file.
908
1679
 
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.
 
1680
    This only returns an email address if we can be fairly sure the 
 
1681
    address is reasonable, ie if /etc/mailname is set on unix.
 
1682
 
 
1683
    This doesn't use the FQDN as the default domain because that may be 
 
1684
    slow, and it doesn't use the hostname alone because that's not normally 
 
1685
    a reasonable address.
912
1686
    """
913
 
    import socket
914
 
 
915
1687
    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())
 
1688
        # No implementation to reliably determine Windows default mail
 
1689
        # address; please add one.
 
1690
        return None, None
 
1691
 
 
1692
    default_mail_domain = _get_default_mail_domain()
 
1693
    if not default_mail_domain:
 
1694
        return None, None
 
1695
 
 
1696
    import pwd
 
1697
    uid = os.getuid()
 
1698
    try:
 
1699
        w = pwd.getpwuid(uid)
 
1700
    except KeyError:
 
1701
        trace.mutter('no passwd entry for uid %d?' % uid)
 
1702
        return None, None
 
1703
 
 
1704
    # we try utf-8 first, because on many variants (like Linux),
 
1705
    # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
1706
    # false positives.  (many users will have their user encoding set to
 
1707
    # latin-1, which cannot raise UnicodeError.)
 
1708
    try:
 
1709
        gecos = w.pw_gecos.decode('utf-8')
 
1710
        encoding = 'utf-8'
 
1711
    except UnicodeError:
 
1712
        try:
 
1713
            encoding = osutils.get_user_encoding()
 
1714
            gecos = w.pw_gecos.decode(encoding)
 
1715
        except UnicodeError as e:
 
1716
            trace.mutter("cannot decode passwd entry %s" % w)
 
1717
            return None, None
 
1718
    try:
 
1719
        username = w.pw_name.decode(encoding)
 
1720
    except UnicodeError as e:
 
1721
        trace.mutter("cannot decode passwd entry %s" % w)
 
1722
        return None, None
 
1723
 
 
1724
    comma = gecos.find(',')
 
1725
    if comma == -1:
 
1726
        realname = gecos
 
1727
    else:
 
1728
        realname = gecos[:comma]
 
1729
 
 
1730
    return realname, (username + '@' + default_mail_domain)
973
1731
 
974
1732
 
975
1733
def parse_username(username):
1020
1778
 
1021
1779
    def set_option(self, value, name, section=None):
1022
1780
        """Set a per-branch configuration option"""
 
1781
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1782
        # higher levels providing the right lock -- vila 20101004
1023
1783
        self.branch.lock_write()
1024
1784
        try:
1025
1785
            self._config.set_option(value, name, section)
1026
1786
        finally:
1027
1787
            self.branch.unlock()
1028
1788
 
 
1789
    def remove_option(self, option_name, section_name=None):
 
1790
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1791
        # higher levels providing the right lock -- vila 20101004
 
1792
        self.branch.lock_write()
 
1793
        try:
 
1794
            self._config.remove_option(option_name, section_name)
 
1795
        finally:
 
1796
            self.branch.unlock()
 
1797
 
1029
1798
 
1030
1799
class AuthenticationConfig(object):
1031
1800
    """The authentication configuration file based on a ini file.
1055
1824
            # Note: the encoding below declares that the file itself is utf-8
1056
1825
            # encoded, but the values in the ConfigObj are always Unicode.
1057
1826
            self._config = ConfigObj(self._input, encoding='utf-8')
1058
 
        except configobj.ConfigObjError, e:
 
1827
        except configobj.ConfigObjError as e:
1059
1828
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
1829
        except UnicodeError:
 
1830
            raise errors.ConfigContentError(self._filename)
1060
1831
        return self._config
1061
1832
 
1062
1833
    def _save(self):
1063
1834
        """Save the config file, only tests should use it for now."""
1064
1835
        conf_dir = os.path.dirname(self._filename)
1065
1836
        ensure_config_dir_exists(conf_dir)
1066
 
        self._get_config().write(file(self._filename, 'wb'))
 
1837
        f = file(self._filename, 'wb')
 
1838
        try:
 
1839
            self._get_config().write(f)
 
1840
        finally:
 
1841
            f.close()
1067
1842
 
1068
1843
    def _set_option(self, section_name, option_name, value):
1069
1844
        """Set an authentication configuration option"""
1075
1850
        section[option_name] = value
1076
1851
        self._save()
1077
1852
 
1078
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
 
1853
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
1079
1854
                        realm=None):
1080
1855
        """Returns the matching credentials from authentication.conf file.
1081
1856
 
1088
1863
        :param user: login (optional)
1089
1864
 
1090
1865
        :param path: the absolute path on the server (optional)
1091
 
        
 
1866
 
1092
1867
        :param realm: the http authentication realm (optional)
1093
1868
 
1094
1869
        :return: A dict containing the matching credentials or None.
1108
1883
        """
1109
1884
        credentials = None
1110
1885
        for auth_def_name, auth_def in self._get_config().items():
1111
 
            if type(auth_def) is not configobj.Section:
 
1886
            if not isinstance(auth_def, configobj.Section):
1112
1887
                raise ValueError("%s defined outside a section" % auth_def_name)
1113
1888
 
1114
1889
            a_scheme, a_host, a_user, a_path = map(
1249
2024
            if ask:
1250
2025
                if prompt is None:
1251
2026
                    # Create a default prompt suitable for most cases
1252
 
                    prompt = scheme.upper() + ' %(host)s username'
 
2027
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
1253
2028
                # Special handling for optional fields in the prompt
1254
2029
                if port is not None:
1255
2030
                    prompt_host = '%s:%d' % (host, port)
1293
2068
        if password is None:
1294
2069
            if prompt is None:
1295
2070
                # Create a default prompt suitable for most cases
1296
 
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
2071
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
1297
2072
            # Special handling for optional fields in the prompt
1298
2073
            if port is not None:
1299
2074
                prompt_host = '%s:%d' % (host, port)
1318
2093
    A credential store provides access to credentials via the password_encoding
1319
2094
    field in authentication.conf sections.
1320
2095
 
1321
 
    Except for stores provided by bzr itself, most stores are expected to be
 
2096
    Except for stores provided by brz itself, most stores are expected to be
1322
2097
    provided by plugins that will therefore use
1323
2098
    register_lazy(password_encoding, module_name, member_name, help=help,
1324
2099
    fallback=fallback) to install themselves.
1429
2204
credential_store_registry.default_key = 'plain'
1430
2205
 
1431
2206
 
 
2207
class Base64CredentialStore(CredentialStore):
 
2208
    __doc__ = """Base64 credential store for the authentication.conf file"""
 
2209
 
 
2210
    def decode_password(self, credentials):
 
2211
        """See CredentialStore.decode_password."""
 
2212
        # GZ 2012-07-28: Will raise binascii.Error if password is not base64,
 
2213
        #                should probably propogate as something more useful.
 
2214
        return base64.decodestring(credentials['password'])
 
2215
 
 
2216
credential_store_registry.register('base64', Base64CredentialStore,
 
2217
                                   help=Base64CredentialStore.__doc__)
 
2218
 
 
2219
 
1432
2220
class BzrDirConfig(object):
1433
2221
 
1434
2222
    def __init__(self, bzrdir):
1440
2228
 
1441
2229
        It may be set to a location, or None.
1442
2230
 
1443
 
        This policy affects all branches contained by this bzrdir, except for
1444
 
        those under repositories.
 
2231
        This policy affects all branches contained by this control dir, except
 
2232
        for those under repositories.
1445
2233
        """
1446
2234
        if self._config is None:
1447
 
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
 
2235
            raise errors.BzrError("Cannot set configuration in %s"
 
2236
                                  % self._bzrdir)
1448
2237
        if value is None:
1449
2238
            self._config.set_option('', 'default_stack_on')
1450
2239
        else:
1455
2244
 
1456
2245
        This will either be a location, or None.
1457
2246
 
1458
 
        This policy affects all branches contained by this bzrdir, except for
1459
 
        those under repositories.
 
2247
        This policy affects all branches contained by this control dir, except
 
2248
        for those under repositories.
1460
2249
        """
1461
2250
        if self._config is None:
1462
2251
            return None
1470
2259
    """A Config that reads/writes a config file on a Transport.
1471
2260
 
1472
2261
    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.
 
2262
    that may be associated with a section.  Assigning meaning to these values
 
2263
    is done at higher levels like TreeConfig.
1475
2264
    """
1476
2265
 
1477
2266
    def __init__(self, transport, filename):
1494
2283
                section_obj = configobj[section]
1495
2284
            except KeyError:
1496
2285
                return default
1497
 
        return section_obj.get(name, default)
 
2286
        value = section_obj.get(name, default)
 
2287
        for hook in OldConfigHooks['get']:
 
2288
            hook(self, name, value)
 
2289
        return value
1498
2290
 
1499
2291
    def set_option(self, value, name, section=None):
1500
2292
        """Set the value associated with a named option.
1508
2300
            configobj[name] = value
1509
2301
        else:
1510
2302
            configobj.setdefault(section, {})[name] = value
 
2303
        for hook in OldConfigHooks['set']:
 
2304
            hook(self, name, value)
 
2305
        self._set_configobj(configobj)
 
2306
 
 
2307
    def remove_option(self, option_name, section_name=None):
 
2308
        configobj = self._get_configobj()
 
2309
        if section_name is None:
 
2310
            del configobj[option_name]
 
2311
        else:
 
2312
            del configobj[section_name][option_name]
 
2313
        for hook in OldConfigHooks['remove']:
 
2314
            hook(self, option_name)
1511
2315
        self._set_configobj(configobj)
1512
2316
 
1513
2317
    def _get_config_file(self):
1514
2318
        try:
1515
 
            return StringIO(self._transport.get_bytes(self._filename))
 
2319
            f = BytesIO(self._transport.get_bytes(self._filename))
 
2320
            for hook in OldConfigHooks['load']:
 
2321
                hook(self)
 
2322
            return f
1516
2323
        except errors.NoSuchFile:
1517
 
            return StringIO()
 
2324
            return BytesIO()
 
2325
        except errors.PermissionDenied as e:
 
2326
            trace.warning("Permission denied while trying to open "
 
2327
                "configuration file %s.", urlutils.unescape_for_display(
 
2328
                urlutils.join(self._transport.base, self._filename), "utf-8"))
 
2329
            return BytesIO()
 
2330
 
 
2331
    def _external_url(self):
 
2332
        return urlutils.join(self._transport.external_url(), self._filename)
1518
2333
 
1519
2334
    def _get_configobj(self):
1520
 
        return ConfigObj(self._get_config_file(), encoding='utf-8')
 
2335
        f = self._get_config_file()
 
2336
        try:
 
2337
            try:
 
2338
                conf = ConfigObj(f, encoding='utf-8')
 
2339
            except configobj.ConfigObjError as e:
 
2340
                raise errors.ParseConfigError(e.errors, self._external_url())
 
2341
            except UnicodeDecodeError:
 
2342
                raise errors.ConfigContentError(self._external_url())
 
2343
        finally:
 
2344
            f.close()
 
2345
        return conf
1521
2346
 
1522
2347
    def _set_configobj(self, configobj):
1523
 
        out_file = StringIO()
 
2348
        out_file = BytesIO()
1524
2349
        configobj.write(out_file)
1525
2350
        out_file.seek(0)
1526
2351
        self._transport.put_file(self._filename, out_file)
 
2352
        for hook in OldConfigHooks['save']:
 
2353
            hook(self)
 
2354
 
 
2355
 
 
2356
class Option(object):
 
2357
    """An option definition.
 
2358
 
 
2359
    The option *values* are stored in config files and found in sections.
 
2360
 
 
2361
    Here we define various properties about the option itself, its default
 
2362
    value, how to convert it from stores, what to do when invalid values are
 
2363
    encoutered, in which config files it can be stored.
 
2364
    """
 
2365
 
 
2366
    def __init__(self, name, override_from_env=None,
 
2367
                 default=None, default_from_env=None,
 
2368
                 help=None, from_unicode=None, invalid=None, unquote=True):
 
2369
        """Build an option definition.
 
2370
 
 
2371
        :param name: the name used to refer to the option.
 
2372
 
 
2373
        :param override_from_env: A list of environment variables which can
 
2374
           provide override any configuration setting.
 
2375
 
 
2376
        :param default: the default value to use when none exist in the config
 
2377
            stores. This is either a string that ``from_unicode`` will convert
 
2378
            into the proper type, a callable returning a unicode string so that
 
2379
            ``from_unicode`` can be used on the return value, or a python
 
2380
            object that can be stringified (so only the empty list is supported
 
2381
            for example).
 
2382
 
 
2383
        :param default_from_env: A list of environment variables which can
 
2384
           provide a default value. 'default' will be used only if none of the
 
2385
           variables specified here are set in the environment.
 
2386
 
 
2387
        :param help: a doc string to explain the option to the user.
 
2388
 
 
2389
        :param from_unicode: a callable to convert the unicode string
 
2390
            representing the option value in a store or its default value.
 
2391
 
 
2392
        :param invalid: the action to be taken when an invalid value is
 
2393
            encountered in a store. This is called only when from_unicode is
 
2394
            invoked to convert a string and returns None or raise ValueError or
 
2395
            TypeError. Accepted values are: None (ignore invalid values),
 
2396
            'warning' (emit a warning), 'error' (emit an error message and
 
2397
            terminates).
 
2398
 
 
2399
        :param unquote: should the unicode value be unquoted before conversion.
 
2400
           This should be used only when the store providing the values cannot
 
2401
           safely unquote them (see http://pad.lv/906897). It is provided so
 
2402
           daughter classes can handle the quoting themselves.
 
2403
        """
 
2404
        if override_from_env is None:
 
2405
            override_from_env = []
 
2406
        if default_from_env is None:
 
2407
            default_from_env = []
 
2408
        self.name = name
 
2409
        self.override_from_env = override_from_env
 
2410
        # Convert the default value to a unicode string so all values are
 
2411
        # strings internally before conversion (via from_unicode) is attempted.
 
2412
        if default is None:
 
2413
            self.default = None
 
2414
        elif isinstance(default, list):
 
2415
            # Only the empty list is supported
 
2416
            if default:
 
2417
                raise AssertionError(
 
2418
                    'Only empty lists are supported as default values')
 
2419
            self.default = u','
 
2420
        elif isinstance(default, (binary_type, text_type, bool, int, float)):
 
2421
            # Rely on python to convert strings, booleans and integers
 
2422
            self.default = u'%s' % (default,)
 
2423
        elif callable(default):
 
2424
            self.default = default
 
2425
        else:
 
2426
            # other python objects are not expected
 
2427
            raise AssertionError('%r is not supported as a default value'
 
2428
                                 % (default,))
 
2429
        self.default_from_env = default_from_env
 
2430
        self._help = help
 
2431
        self.from_unicode = from_unicode
 
2432
        self.unquote = unquote
 
2433
        if invalid and invalid not in ('warning', 'error'):
 
2434
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
 
2435
        self.invalid = invalid
 
2436
 
 
2437
    @property
 
2438
    def help(self):
 
2439
        return self._help
 
2440
 
 
2441
    def convert_from_unicode(self, store, unicode_value):
 
2442
        if self.unquote and store is not None and unicode_value is not None:
 
2443
            unicode_value = store.unquote(unicode_value)
 
2444
        if self.from_unicode is None or unicode_value is None:
 
2445
            # Don't convert or nothing to convert
 
2446
            return unicode_value
 
2447
        try:
 
2448
            converted = self.from_unicode(unicode_value)
 
2449
        except (ValueError, TypeError):
 
2450
            # Invalid values are ignored
 
2451
            converted = None
 
2452
        if converted is None and self.invalid is not None:
 
2453
            # The conversion failed
 
2454
            if self.invalid == 'warning':
 
2455
                trace.warning('Value "%s" is not valid for "%s"',
 
2456
                              unicode_value, self.name)
 
2457
            elif self.invalid == 'error':
 
2458
                raise errors.ConfigOptionValueError(self.name, unicode_value)
 
2459
        return converted
 
2460
 
 
2461
    def get_override(self):
 
2462
        value = None
 
2463
        for var in self.override_from_env:
 
2464
            try:
 
2465
                # If the env variable is defined, its value takes precedence
 
2466
                value = os.environ[var].decode(osutils.get_user_encoding())
 
2467
                break
 
2468
            except KeyError:
 
2469
                continue
 
2470
        return value
 
2471
 
 
2472
    def get_default(self):
 
2473
        value = None
 
2474
        for var in self.default_from_env:
 
2475
            try:
 
2476
                # If the env variable is defined, its value is the default one
 
2477
                value = os.environ[var].decode(osutils.get_user_encoding())
 
2478
                break
 
2479
            except KeyError:
 
2480
                continue
 
2481
        if value is None:
 
2482
            # Otherwise, fallback to the value defined at registration
 
2483
            if callable(self.default):
 
2484
                value = self.default()
 
2485
                if not isinstance(value, text_type):
 
2486
                    raise AssertionError(
 
2487
                        "Callable default value for '%s' should be unicode"
 
2488
                        % (self.name))
 
2489
            else:
 
2490
                value = self.default
 
2491
        return value
 
2492
 
 
2493
    def get_help_topic(self):
 
2494
        return self.name
 
2495
 
 
2496
    def get_help_text(self, additional_see_also=None, plain=True):
 
2497
        result = self.help
 
2498
        from breezy import help_topics
 
2499
        result += help_topics._format_see_also(additional_see_also)
 
2500
        if plain:
 
2501
            result = help_topics.help_as_plain_text(result)
 
2502
        return result
 
2503
 
 
2504
 
 
2505
# Predefined converters to get proper values from store
 
2506
 
 
2507
def bool_from_store(unicode_str):
 
2508
    return ui.bool_from_string(unicode_str)
 
2509
 
 
2510
 
 
2511
def int_from_store(unicode_str):
 
2512
    return int(unicode_str)
 
2513
 
 
2514
 
 
2515
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
 
2516
 
 
2517
def int_SI_from_store(unicode_str):
 
2518
    """Convert a human readable size in SI units, e.g 10MB into an integer.
 
2519
 
 
2520
    Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
2521
    by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
2522
    pedantic.
 
2523
 
 
2524
    :return Integer, expanded to its base-10 value if a proper SI unit is 
 
2525
        found, None otherwise.
 
2526
    """
 
2527
    regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
 
2528
    p = re.compile(regexp, re.IGNORECASE)
 
2529
    m = p.match(unicode_str)
 
2530
    val = None
 
2531
    if m is not None:
 
2532
        val, _, unit = m.groups()
 
2533
        val = int(val)
 
2534
        if unit:
 
2535
            try:
 
2536
                coeff = _unit_suffixes[unit.upper()]
 
2537
            except KeyError:
 
2538
                raise ValueError(gettext('{0} is not an SI unit.').format(unit))
 
2539
            val *= coeff
 
2540
    return val
 
2541
 
 
2542
 
 
2543
def float_from_store(unicode_str):
 
2544
    return float(unicode_str)
 
2545
 
 
2546
 
 
2547
# Use an empty dict to initialize an empty configobj avoiding all parsing and
 
2548
# encoding checks
 
2549
_list_converter_config = configobj.ConfigObj(
 
2550
    {}, encoding='utf-8', list_values=True, interpolation=False)
 
2551
 
 
2552
 
 
2553
class ListOption(Option):
 
2554
 
 
2555
    def __init__(self, name, default=None, default_from_env=None,
 
2556
                 help=None, invalid=None):
 
2557
        """A list Option definition.
 
2558
 
 
2559
        This overrides the base class so the conversion from a unicode string
 
2560
        can take quoting into account.
 
2561
        """
 
2562
        super(ListOption, self).__init__(
 
2563
            name, default=default, default_from_env=default_from_env,
 
2564
            from_unicode=self.from_unicode, help=help,
 
2565
            invalid=invalid, unquote=False)
 
2566
 
 
2567
    def from_unicode(self, unicode_str):
 
2568
        if not isinstance(unicode_str, string_types):
 
2569
            raise TypeError
 
2570
        # Now inject our string directly as unicode. All callers got their
 
2571
        # value from configobj, so values that need to be quoted are already
 
2572
        # properly quoted.
 
2573
        _list_converter_config.reset()
 
2574
        _list_converter_config._parse([u"list=%s" % (unicode_str,)])
 
2575
        maybe_list = _list_converter_config['list']
 
2576
        if isinstance(maybe_list, string_types):
 
2577
            if maybe_list:
 
2578
                # A single value, most probably the user forgot (or didn't care
 
2579
                # to add) the final ','
 
2580
                l = [maybe_list]
 
2581
            else:
 
2582
                # The empty string, convert to empty list
 
2583
                l = []
 
2584
        else:
 
2585
            # We rely on ConfigObj providing us with a list already
 
2586
            l = maybe_list
 
2587
        return l
 
2588
 
 
2589
 
 
2590
class RegistryOption(Option):
 
2591
    """Option for a choice from a registry."""
 
2592
 
 
2593
    def __init__(self, name, registry, default_from_env=None,
 
2594
                 help=None, invalid=None):
 
2595
        """A registry based Option definition.
 
2596
 
 
2597
        This overrides the base class so the conversion from a unicode string
 
2598
        can take quoting into account.
 
2599
        """
 
2600
        super(RegistryOption, self).__init__(
 
2601
            name, default=lambda: unicode(registry.default_key),
 
2602
            default_from_env=default_from_env,
 
2603
            from_unicode=self.from_unicode, help=help,
 
2604
            invalid=invalid, unquote=False)
 
2605
        self.registry = registry
 
2606
 
 
2607
    def from_unicode(self, unicode_str):
 
2608
        if not isinstance(unicode_str, string_types):
 
2609
            raise TypeError
 
2610
        try:
 
2611
            return self.registry.get(unicode_str)
 
2612
        except KeyError:
 
2613
            raise ValueError(
 
2614
                "Invalid value %s for %s."
 
2615
                "See help for a list of possible values." % (unicode_str,
 
2616
                    self.name))
 
2617
 
 
2618
    @property
 
2619
    def help(self):
 
2620
        ret = [self._help, "\n\nThe following values are supported:\n"]
 
2621
        for key in self.registry.keys():
 
2622
            ret.append(" %s - %s\n" % (key, self.registry.get_help(key)))
 
2623
        return "".join(ret)
 
2624
 
 
2625
 
 
2626
_option_ref_re = lazy_regex.lazy_compile('({[^\d\W](?:\.\w|-\w|\w)*})')
 
2627
"""Describes an expandable option reference.
 
2628
 
 
2629
We want to match the most embedded reference first.
 
2630
 
 
2631
I.e. for '{{foo}}' we will get '{foo}',
 
2632
for '{bar{baz}}' we will get '{baz}'
 
2633
"""
 
2634
 
 
2635
def iter_option_refs(string):
 
2636
    # Split isolate refs so every other chunk is a ref
 
2637
    is_ref = False
 
2638
    for chunk  in _option_ref_re.split(string):
 
2639
        yield is_ref, chunk
 
2640
        is_ref = not is_ref
 
2641
 
 
2642
 
 
2643
class OptionRegistry(registry.Registry):
 
2644
    """Register config options by their name.
 
2645
 
 
2646
    This overrides ``registry.Registry`` to simplify registration by acquiring
 
2647
    some information from the option object itself.
 
2648
    """
 
2649
 
 
2650
    def _check_option_name(self, option_name):
 
2651
        """Ensures an option name is valid.
 
2652
 
 
2653
        :param option_name: The name to validate.
 
2654
        """
 
2655
        if _option_ref_re.match('{%s}' % option_name) is None:
 
2656
            raise errors.IllegalOptionName(option_name)
 
2657
 
 
2658
    def register(self, option):
 
2659
        """Register a new option to its name.
 
2660
 
 
2661
        :param option: The option to register. Its name is used as the key.
 
2662
        """
 
2663
        self._check_option_name(option.name)
 
2664
        super(OptionRegistry, self).register(option.name, option,
 
2665
                                             help=option.help)
 
2666
 
 
2667
    def register_lazy(self, key, module_name, member_name):
 
2668
        """Register a new option to be loaded on request.
 
2669
 
 
2670
        :param key: the key to request the option later. Since the registration
 
2671
            is lazy, it should be provided and match the option name.
 
2672
 
 
2673
        :param module_name: the python path to the module. Such as 'os.path'.
 
2674
 
 
2675
        :param member_name: the member of the module to return.  If empty or 
 
2676
                None, get() will return the module itself.
 
2677
        """
 
2678
        self._check_option_name(key)
 
2679
        super(OptionRegistry, self).register_lazy(key,
 
2680
                                                  module_name, member_name)
 
2681
 
 
2682
    def get_help(self, key=None):
 
2683
        """Get the help text associated with the given key"""
 
2684
        option = self.get(key)
 
2685
        the_help = option.help
 
2686
        if callable(the_help):
 
2687
            return the_help(self, key)
 
2688
        return the_help
 
2689
 
 
2690
 
 
2691
option_registry = OptionRegistry()
 
2692
 
 
2693
 
 
2694
# Registered options in lexicographical order
 
2695
 
 
2696
option_registry.register(
 
2697
    Option('append_revisions_only',
 
2698
           default=None, from_unicode=bool_from_store, invalid='warning',
 
2699
           help='''\
 
2700
Whether to only append revisions to the mainline.
 
2701
 
 
2702
If this is set to true, then it is not possible to change the
 
2703
existing mainline of the branch.
 
2704
'''))
 
2705
option_registry.register(
 
2706
    ListOption('acceptable_keys',
 
2707
           default=None,
 
2708
           help="""\
 
2709
List of GPG key patterns which are acceptable for verification.
 
2710
"""))
 
2711
option_registry.register(
 
2712
    Option('add.maximum_file_size',
 
2713
           default=u'20MB', from_unicode=int_SI_from_store,
 
2714
           help="""\
 
2715
Size above which files should be added manually.
 
2716
 
 
2717
Files below this size are added automatically when using ``bzr add`` without
 
2718
arguments.
 
2719
 
 
2720
A negative value means disable the size check.
 
2721
"""))
 
2722
option_registry.register(
 
2723
    Option('bound',
 
2724
           default=None, from_unicode=bool_from_store,
 
2725
           help="""\
 
2726
Is the branch bound to ``bound_location``.
 
2727
 
 
2728
If set to "True", the branch should act as a checkout, and push each commit to
 
2729
the bound_location.  This option is normally set by ``bind``/``unbind``.
 
2730
 
 
2731
See also: bound_location.
 
2732
"""))
 
2733
option_registry.register(
 
2734
    Option('bound_location',
 
2735
           default=None,
 
2736
           help="""\
 
2737
The location that commits should go to when acting as a checkout.
 
2738
 
 
2739
This option is normally set by ``bind``.
 
2740
 
 
2741
See also: bound.
 
2742
"""))
 
2743
option_registry.register(
 
2744
    Option('branch.fetch_tags', default=False,  from_unicode=bool_from_store,
 
2745
           help="""\
 
2746
Whether revisions associated with tags should be fetched.
 
2747
"""))
 
2748
option_registry.register_lazy(
 
2749
    'bzr.transform.orphan_policy', 'breezy.transform', 'opt_transform_orphan')
 
2750
option_registry.register(
 
2751
    Option('bzr.workingtree.worth_saving_limit', default=10,
 
2752
           from_unicode=int_from_store,  invalid='warning',
 
2753
           help='''\
 
2754
How many changes before saving the dirstate.
 
2755
 
 
2756
-1 means that we will never rewrite the dirstate file for only
 
2757
stat-cache changes. Regardless of this setting, we will always rewrite
 
2758
the dirstate file if a file is added/removed/renamed/etc. This flag only
 
2759
affects the behavior of updating the dirstate file after we notice that
 
2760
a file has been touched.
 
2761
'''))
 
2762
option_registry.register(
 
2763
    Option('bugtracker', default=None,
 
2764
           help='''\
 
2765
Default bug tracker to use.
 
2766
 
 
2767
This bug tracker will be used for example when marking bugs
 
2768
as fixed using ``bzr commit --fixes``, if no explicit
 
2769
bug tracker was specified.
 
2770
'''))
 
2771
option_registry.register(
 
2772
    Option('check_signatures', default=CHECK_IF_POSSIBLE,
 
2773
           from_unicode=signature_policy_from_unicode,
 
2774
           help='''\
 
2775
GPG checking policy.
 
2776
 
 
2777
Possible values: require, ignore, check-available (default)
 
2778
 
 
2779
this option will control whether bzr will require good gpg
 
2780
signatures, ignore them, or check them if they are
 
2781
present.
 
2782
'''))
 
2783
option_registry.register(
 
2784
    Option('child_submit_format',
 
2785
           help='''The preferred format of submissions to this branch.'''))
 
2786
option_registry.register(
 
2787
    Option('child_submit_to',
 
2788
           help='''Where submissions to this branch are mailed to.'''))
 
2789
option_registry.register(
 
2790
    Option('create_signatures', default=SIGN_WHEN_REQUIRED,
 
2791
           from_unicode=signing_policy_from_unicode,
 
2792
           help='''\
 
2793
GPG Signing policy.
 
2794
 
 
2795
Possible values: always, never, when-required (default)
 
2796
 
 
2797
This option controls whether bzr will always create
 
2798
gpg signatures or not on commits.
 
2799
'''))
 
2800
option_registry.register(
 
2801
    Option('dirstate.fdatasync', default=True,
 
2802
           from_unicode=bool_from_store,
 
2803
           help='''\
 
2804
Flush dirstate changes onto physical disk?
 
2805
 
 
2806
If true (default), working tree metadata changes are flushed through the
 
2807
OS buffers to physical disk.  This is somewhat slower, but means data
 
2808
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2809
'''))
 
2810
option_registry.register(
 
2811
    ListOption('debug_flags', default=[],
 
2812
           help='Debug flags to activate.'))
 
2813
option_registry.register(
 
2814
    Option('default_format', default='2a',
 
2815
           help='Format used when creating branches.'))
 
2816
option_registry.register(
 
2817
    Option('dpush_strict', default=None,
 
2818
           from_unicode=bool_from_store,
 
2819
           help='''\
 
2820
The default value for ``dpush --strict``.
 
2821
 
 
2822
If present, defines the ``--strict`` option default value for checking
 
2823
uncommitted changes before pushing into a different VCS without any
 
2824
custom bzr metadata.
 
2825
'''))
 
2826
option_registry.register(
 
2827
    Option('editor',
 
2828
           help='The command called to launch an editor to enter a message.'))
 
2829
option_registry.register(
 
2830
    Option('email', override_from_env=['BRZ_EMAIL'], default=default_email,
 
2831
           help='The users identity'))
 
2832
option_registry.register(
 
2833
    Option('gpg_signing_command',
 
2834
           default='gpg',
 
2835
           help="""\
 
2836
Program to use use for creating signatures.
 
2837
 
 
2838
This should support at least the -u and --clearsign options.
 
2839
"""))
 
2840
option_registry.register(
 
2841
    Option('gpg_signing_key',
 
2842
           default=None,
 
2843
           help="""\
 
2844
GPG key to use for signing.
 
2845
 
 
2846
This defaults to the first key associated with the users email.
 
2847
"""))
 
2848
option_registry.register(
 
2849
    Option('ignore_missing_extensions', default=False,
 
2850
           from_unicode=bool_from_store,
 
2851
           help='''\
 
2852
Control the missing extensions warning display.
 
2853
 
 
2854
The warning will not be emitted if set to True.
 
2855
'''))
 
2856
option_registry.register(
 
2857
    Option('language',
 
2858
           help='Language to translate messages into.'))
 
2859
option_registry.register(
 
2860
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
 
2861
           help='''\
 
2862
Steal locks that appears to be dead.
 
2863
 
 
2864
If set to True, bzr will check if a lock is supposed to be held by an
 
2865
active process from the same user on the same machine. If the user and
 
2866
machine match, but no process with the given PID is active, then bzr
 
2867
will automatically break the stale lock, and create a new lock for
 
2868
this process.
 
2869
Otherwise, bzr will prompt as normal to break the lock.
 
2870
'''))
 
2871
option_registry.register(
 
2872
    Option('log_format', default='long',
 
2873
           help= '''\
 
2874
Log format to use when displaying revisions.
 
2875
 
 
2876
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
 
2877
may be provided by plugins.
 
2878
'''))
 
2879
option_registry.register_lazy('mail_client', 'breezy.mail_client',
 
2880
    'opt_mail_client')
 
2881
option_registry.register(
 
2882
    Option('output_encoding',
 
2883
           help= 'Unicode encoding for output'
 
2884
           ' (terminal encoding if not specified).'))
 
2885
option_registry.register(
 
2886
    Option('parent_location',
 
2887
           default=None,
 
2888
           help="""\
 
2889
The location of the default branch for pull or merge.
 
2890
 
 
2891
This option is normally set when creating a branch, the first ``pull`` or by
 
2892
``pull --remember``.
 
2893
"""))
 
2894
option_registry.register(
 
2895
    Option('post_commit', default=None,
 
2896
           help='''\
 
2897
Post commit functions.
 
2898
 
 
2899
An ordered list of python functions to call, separated by spaces.
 
2900
 
 
2901
Each function takes branch, rev_id as parameters.
 
2902
'''))
 
2903
option_registry.register_lazy('progress_bar', 'breezy.ui.text',
 
2904
                              'opt_progress_bar')
 
2905
option_registry.register(
 
2906
    Option('public_branch',
 
2907
           default=None,
 
2908
           help="""\
 
2909
A publically-accessible version of this branch.
 
2910
 
 
2911
This implies that the branch setting this option is not publically-accessible.
 
2912
Used and set by ``bzr send``.
 
2913
"""))
 
2914
option_registry.register(
 
2915
    Option('push_location',
 
2916
           default=None,
 
2917
           help="""\
 
2918
The location of the default branch for push.
 
2919
 
 
2920
This option is normally set by the first ``push`` or ``push --remember``.
 
2921
"""))
 
2922
option_registry.register(
 
2923
    Option('push_strict', default=None,
 
2924
           from_unicode=bool_from_store,
 
2925
           help='''\
 
2926
The default value for ``push --strict``.
 
2927
 
 
2928
If present, defines the ``--strict`` option default value for checking
 
2929
uncommitted changes before sending a merge directive.
 
2930
'''))
 
2931
option_registry.register(
 
2932
    Option('repository.fdatasync', default=True,
 
2933
           from_unicode=bool_from_store,
 
2934
           help='''\
 
2935
Flush repository changes onto physical disk?
 
2936
 
 
2937
If true (default), repository changes are flushed through the OS buffers
 
2938
to physical disk.  This is somewhat slower, but means data should not be
 
2939
lost if the machine crashes.  See also dirstate.fdatasync.
 
2940
'''))
 
2941
option_registry.register_lazy('smtp_server',
 
2942
    'breezy.smtp_connection', 'smtp_server')
 
2943
option_registry.register_lazy('smtp_password',
 
2944
    'breezy.smtp_connection', 'smtp_password')
 
2945
option_registry.register_lazy('smtp_username',
 
2946
    'breezy.smtp_connection', 'smtp_username')
 
2947
option_registry.register(
 
2948
    Option('selftest.timeout',
 
2949
        default='600',
 
2950
        from_unicode=int_from_store,
 
2951
        help='Abort selftest if one test takes longer than this many seconds',
 
2952
        ))
 
2953
 
 
2954
option_registry.register(
 
2955
    Option('send_strict', default=None,
 
2956
           from_unicode=bool_from_store,
 
2957
           help='''\
 
2958
The default value for ``send --strict``.
 
2959
 
 
2960
If present, defines the ``--strict`` option default value for checking
 
2961
uncommitted changes before sending a bundle.
 
2962
'''))
 
2963
 
 
2964
option_registry.register(
 
2965
    Option('serve.client_timeout',
 
2966
           default=300.0, from_unicode=float_from_store,
 
2967
           help="If we wait for a new request from a client for more than"
 
2968
                " X seconds, consider the client idle, and hangup."))
 
2969
option_registry.register(
 
2970
    Option('stacked_on_location',
 
2971
           default=None,
 
2972
           help="""The location where this branch is stacked on."""))
 
2973
option_registry.register(
 
2974
    Option('submit_branch',
 
2975
           default=None,
 
2976
           help="""\
 
2977
The branch you intend to submit your current work to.
 
2978
 
 
2979
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
 
2980
by the ``submit:`` revision spec.
 
2981
"""))
 
2982
option_registry.register(
 
2983
    Option('submit_to',
 
2984
           help='''Where submissions from this branch are mailed to.'''))
 
2985
option_registry.register(
 
2986
    ListOption('suppress_warnings',
 
2987
           default=[],
 
2988
           help="List of warning classes to suppress."))
 
2989
option_registry.register(
 
2990
    Option('validate_signatures_in_log', default=False,
 
2991
           from_unicode=bool_from_store, invalid='warning',
 
2992
           help='''Whether to validate signatures in brz log.'''))
 
2993
option_registry.register_lazy('ssl.ca_certs',
 
2994
    'breezy.transport.http._urllib2_wrappers', 'opt_ssl_ca_certs')
 
2995
 
 
2996
option_registry.register_lazy('ssl.cert_reqs',
 
2997
    'breezy.transport.http._urllib2_wrappers', 'opt_ssl_cert_reqs')
 
2998
 
 
2999
 
 
3000
class Section(object):
 
3001
    """A section defines a dict of option name => value.
 
3002
 
 
3003
    This is merely a read-only dict which can add some knowledge about the
 
3004
    options. It is *not* a python dict object though and doesn't try to mimic
 
3005
    its API.
 
3006
    """
 
3007
 
 
3008
    def __init__(self, section_id, options):
 
3009
        self.id = section_id
 
3010
        # We re-use the dict-like object received
 
3011
        self.options = options
 
3012
 
 
3013
    def get(self, name, default=None, expand=True):
 
3014
        return self.options.get(name, default)
 
3015
 
 
3016
    def iter_option_names(self):
 
3017
        for k in self.options.iterkeys():
 
3018
            yield k
 
3019
 
 
3020
    def __repr__(self):
 
3021
        # Mostly for debugging use
 
3022
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
 
3023
 
 
3024
 
 
3025
_NewlyCreatedOption = object()
 
3026
"""Was the option created during the MutableSection lifetime"""
 
3027
_DeletedOption = object()
 
3028
"""Was the option deleted during the MutableSection lifetime"""
 
3029
 
 
3030
 
 
3031
class MutableSection(Section):
 
3032
    """A section allowing changes and keeping track of the original values."""
 
3033
 
 
3034
    def __init__(self, section_id, options):
 
3035
        super(MutableSection, self).__init__(section_id, options)
 
3036
        self.reset_changes()
 
3037
 
 
3038
    def set(self, name, value):
 
3039
        if name not in self.options:
 
3040
            # This is a new option
 
3041
            self.orig[name] = _NewlyCreatedOption
 
3042
        elif name not in self.orig:
 
3043
            self.orig[name] = self.get(name, None)
 
3044
        self.options[name] = value
 
3045
 
 
3046
    def remove(self, name):
 
3047
        if name not in self.orig and name in self.options:
 
3048
            self.orig[name] = self.get(name, None)
 
3049
        del self.options[name]
 
3050
 
 
3051
    def reset_changes(self):
 
3052
        self.orig = {}
 
3053
 
 
3054
    def apply_changes(self, dirty, store):
 
3055
        """Apply option value changes.
 
3056
 
 
3057
        ``self`` has been reloaded from the persistent storage. ``dirty``
 
3058
        contains the changes made since the previous loading.
 
3059
 
 
3060
        :param dirty: the mutable section containing the changes.
 
3061
 
 
3062
        :param store: the store containing the section
 
3063
        """
 
3064
        for k, expected in dirty.orig.iteritems():
 
3065
            actual = dirty.get(k, _DeletedOption)
 
3066
            reloaded = self.get(k, _NewlyCreatedOption)
 
3067
            if actual is _DeletedOption:
 
3068
                if k in self.options:
 
3069
                    self.remove(k)
 
3070
            else:
 
3071
                self.set(k, actual)
 
3072
            # Report concurrent updates in an ad-hoc way. This should only
 
3073
            # occurs when different processes try to update the same option
 
3074
            # which is not supported (as in: the config framework is not meant
 
3075
            # to be used as a sharing mechanism).
 
3076
            if expected != reloaded:
 
3077
                if actual is _DeletedOption:
 
3078
                    actual = '<DELETED>'
 
3079
                if reloaded is _NewlyCreatedOption:
 
3080
                    reloaded = '<CREATED>'
 
3081
                if expected is _NewlyCreatedOption:
 
3082
                    expected = '<CREATED>'
 
3083
                # Someone changed the value since we get it from the persistent
 
3084
                # storage.
 
3085
                trace.warning(gettext(
 
3086
                        "Option {0} in section {1} of {2} was changed"
 
3087
                        " from {3} to {4}. The {5} value will be saved.".format(
 
3088
                            k, self.id, store.external_url(), expected,
 
3089
                            reloaded, actual)))
 
3090
        # No need to keep track of these changes
 
3091
        self.reset_changes()
 
3092
 
 
3093
 
 
3094
class Store(object):
 
3095
    """Abstract interface to persistent storage for configuration options."""
 
3096
 
 
3097
    readonly_section_class = Section
 
3098
    mutable_section_class = MutableSection
 
3099
 
 
3100
    def __init__(self):
 
3101
        # Which sections need to be saved (by section id). We use a dict here
 
3102
        # so the dirty sections can be shared by multiple callers.
 
3103
        self.dirty_sections = {}
 
3104
 
 
3105
    def is_loaded(self):
 
3106
        """Returns True if the Store has been loaded.
 
3107
 
 
3108
        This is used to implement lazy loading and ensure the persistent
 
3109
        storage is queried only when needed.
 
3110
        """
 
3111
        raise NotImplementedError(self.is_loaded)
 
3112
 
 
3113
    def load(self):
 
3114
        """Loads the Store from persistent storage."""
 
3115
        raise NotImplementedError(self.load)
 
3116
 
 
3117
    def _load_from_string(self, bytes):
 
3118
        """Create a store from a string in configobj syntax.
 
3119
 
 
3120
        :param bytes: A string representing the file content.
 
3121
        """
 
3122
        raise NotImplementedError(self._load_from_string)
 
3123
 
 
3124
    def unload(self):
 
3125
        """Unloads the Store.
 
3126
 
 
3127
        This should make is_loaded() return False. This is used when the caller
 
3128
        knows that the persistent storage has changed or may have change since
 
3129
        the last load.
 
3130
        """
 
3131
        raise NotImplementedError(self.unload)
 
3132
 
 
3133
    def quote(self, value):
 
3134
        """Quote a configuration option value for storing purposes.
 
3135
 
 
3136
        This allows Stacks to present values as they will be stored.
 
3137
        """
 
3138
        return value
 
3139
 
 
3140
    def unquote(self, value):
 
3141
        """Unquote a configuration option value into unicode.
 
3142
 
 
3143
        The received value is quoted as stored.
 
3144
        """
 
3145
        return value
 
3146
 
 
3147
    def save(self):
 
3148
        """Saves the Store to persistent storage."""
 
3149
        raise NotImplementedError(self.save)
 
3150
 
 
3151
    def _need_saving(self):
 
3152
        for s in self.dirty_sections.values():
 
3153
            if s.orig:
 
3154
                # At least one dirty section contains a modification
 
3155
                return True
 
3156
        return False
 
3157
 
 
3158
    def apply_changes(self, dirty_sections):
 
3159
        """Apply changes from dirty sections while checking for coherency.
 
3160
 
 
3161
        The Store content is discarded and reloaded from persistent storage to
 
3162
        acquire up-to-date values.
 
3163
 
 
3164
        Dirty sections are MutableSection which kept track of the value they
 
3165
        are expected to update.
 
3166
        """
 
3167
        # We need an up-to-date version from the persistent storage, unload the
 
3168
        # store. The reload will occur when needed (triggered by the first
 
3169
        # get_mutable_section() call below.
 
3170
        self.unload()
 
3171
        # Apply the changes from the preserved dirty sections
 
3172
        for section_id, dirty in dirty_sections.iteritems():
 
3173
            clean = self.get_mutable_section(section_id)
 
3174
            clean.apply_changes(dirty, self)
 
3175
        # Everything is clean now
 
3176
        self.dirty_sections = {}
 
3177
 
 
3178
    def save_changes(self):
 
3179
        """Saves the Store to persistent storage if changes occurred.
 
3180
 
 
3181
        Apply the changes recorded in the mutable sections to a store content
 
3182
        refreshed from persistent storage.
 
3183
        """
 
3184
        raise NotImplementedError(self.save_changes)
 
3185
 
 
3186
    def external_url(self):
 
3187
        raise NotImplementedError(self.external_url)
 
3188
 
 
3189
    def get_sections(self):
 
3190
        """Returns an ordered iterable of existing sections.
 
3191
 
 
3192
        :returns: An iterable of (store, section).
 
3193
        """
 
3194
        raise NotImplementedError(self.get_sections)
 
3195
 
 
3196
    def get_mutable_section(self, section_id=None):
 
3197
        """Returns the specified mutable section.
 
3198
 
 
3199
        :param section_id: The section identifier
 
3200
        """
 
3201
        raise NotImplementedError(self.get_mutable_section)
 
3202
 
 
3203
    def __repr__(self):
 
3204
        # Mostly for debugging use
 
3205
        return "<config.%s(%s)>" % (self.__class__.__name__,
 
3206
                                    self.external_url())
 
3207
 
 
3208
 
 
3209
class CommandLineStore(Store):
 
3210
    "A store to carry command line overrides for the config options."""
 
3211
 
 
3212
    def __init__(self, opts=None):
 
3213
        super(CommandLineStore, self).__init__()
 
3214
        if opts is None:
 
3215
            opts = {}
 
3216
        self.options = {}
 
3217
        self.id = 'cmdline'
 
3218
 
 
3219
    def _reset(self):
 
3220
        # The dict should be cleared but not replaced so it can be shared.
 
3221
        self.options.clear()
 
3222
 
 
3223
    def _from_cmdline(self, overrides):
 
3224
        # Reset before accepting new definitions
 
3225
        self._reset()
 
3226
        for over in overrides:
 
3227
            try:
 
3228
                name, value = over.split('=', 1)
 
3229
            except ValueError:
 
3230
                raise errors.BzrCommandError(
 
3231
                    gettext("Invalid '%s', should be of the form 'name=value'")
 
3232
                    % (over,))
 
3233
            self.options[name] = value
 
3234
 
 
3235
    def external_url(self):
 
3236
        # Not an url but it makes debugging easier and is never needed
 
3237
        # otherwise
 
3238
        return 'cmdline'
 
3239
 
 
3240
    def get_sections(self):
 
3241
        yield self,  self.readonly_section_class(None, self.options)
 
3242
 
 
3243
 
 
3244
class IniFileStore(Store):
 
3245
    """A config Store using ConfigObj for storage.
 
3246
 
 
3247
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
 
3248
        serialize/deserialize the config file.
 
3249
    """
 
3250
 
 
3251
    def __init__(self):
 
3252
        """A config Store using ConfigObj for storage.
 
3253
        """
 
3254
        super(IniFileStore, self).__init__()
 
3255
        self._config_obj = None
 
3256
 
 
3257
    def is_loaded(self):
 
3258
        return self._config_obj != None
 
3259
 
 
3260
    def unload(self):
 
3261
        self._config_obj = None
 
3262
        self.dirty_sections = {}
 
3263
 
 
3264
    def _load_content(self):
 
3265
        """Load the config file bytes.
 
3266
 
 
3267
        This should be provided by subclasses
 
3268
 
 
3269
        :return: Byte string
 
3270
        """
 
3271
        raise NotImplementedError(self._load_content)
 
3272
 
 
3273
    def _save_content(self, content):
 
3274
        """Save the config file bytes.
 
3275
 
 
3276
        This should be provided by subclasses
 
3277
 
 
3278
        :param content: Config file bytes to write
 
3279
        """
 
3280
        raise NotImplementedError(self._save_content)
 
3281
 
 
3282
    def load(self):
 
3283
        """Load the store from the associated file."""
 
3284
        if self.is_loaded():
 
3285
            return
 
3286
        content = self._load_content()
 
3287
        self._load_from_string(content)
 
3288
        for hook in ConfigHooks['load']:
 
3289
            hook(self)
 
3290
 
 
3291
    def _load_from_string(self, bytes):
 
3292
        """Create a config store from a string.
 
3293
 
 
3294
        :param bytes: A string representing the file content.
 
3295
        """
 
3296
        if self.is_loaded():
 
3297
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
 
3298
        co_input = BytesIO(bytes)
 
3299
        try:
 
3300
            # The config files are always stored utf8-encoded
 
3301
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
 
3302
                                         list_values=False)
 
3303
        except configobj.ConfigObjError as e:
 
3304
            self._config_obj = None
 
3305
            raise errors.ParseConfigError(e.errors, self.external_url())
 
3306
        except UnicodeDecodeError:
 
3307
            raise errors.ConfigContentError(self.external_url())
 
3308
 
 
3309
    def save_changes(self):
 
3310
        if not self.is_loaded():
 
3311
            # Nothing to save
 
3312
            return
 
3313
        if not self._need_saving():
 
3314
            return
 
3315
        # Preserve the current version
 
3316
        dirty_sections = dict(self.dirty_sections.items())
 
3317
        self.apply_changes(dirty_sections)
 
3318
        # Save to the persistent storage
 
3319
        self.save()
 
3320
 
 
3321
    def save(self):
 
3322
        if not self.is_loaded():
 
3323
            # Nothing to save
 
3324
            return
 
3325
        out = BytesIO()
 
3326
        self._config_obj.write(out)
 
3327
        self._save_content(out.getvalue())
 
3328
        for hook in ConfigHooks['save']:
 
3329
            hook(self)
 
3330
 
 
3331
    def get_sections(self):
 
3332
        """Get the configobj section in the file order.
 
3333
 
 
3334
        :returns: An iterable of (store, section).
 
3335
        """
 
3336
        # We need a loaded store
 
3337
        try:
 
3338
            self.load()
 
3339
        except (errors.NoSuchFile, errors.PermissionDenied):
 
3340
            # If the file can't be read, there is no sections
 
3341
            return
 
3342
        cobj = self._config_obj
 
3343
        if cobj.scalars:
 
3344
            yield self, self.readonly_section_class(None, cobj)
 
3345
        for section_name in cobj.sections:
 
3346
            yield (self,
 
3347
                   self.readonly_section_class(section_name,
 
3348
                                               cobj[section_name]))
 
3349
 
 
3350
    def get_mutable_section(self, section_id=None):
 
3351
        # We need a loaded store
 
3352
        try:
 
3353
            self.load()
 
3354
        except errors.NoSuchFile:
 
3355
            # The file doesn't exist, let's pretend it was empty
 
3356
            self._load_from_string('')
 
3357
        if section_id in self.dirty_sections:
 
3358
            # We already created a mutable section for this id
 
3359
            return self.dirty_sections[section_id]
 
3360
        if section_id is None:
 
3361
            section = self._config_obj
 
3362
        else:
 
3363
            section = self._config_obj.setdefault(section_id, {})
 
3364
        mutable_section = self.mutable_section_class(section_id, section)
 
3365
        # All mutable sections can become dirty
 
3366
        self.dirty_sections[section_id] = mutable_section
 
3367
        return mutable_section
 
3368
 
 
3369
    def quote(self, value):
 
3370
        try:
 
3371
            # configobj conflates automagical list values and quoting
 
3372
            self._config_obj.list_values = True
 
3373
            return self._config_obj._quote(value)
 
3374
        finally:
 
3375
            self._config_obj.list_values = False
 
3376
 
 
3377
    def unquote(self, value):
 
3378
        if value and isinstance(value, string_types):
 
3379
            # _unquote doesn't handle None nor empty strings nor anything that
 
3380
            # is not a string, really.
 
3381
            value = self._config_obj._unquote(value)
 
3382
        return value
 
3383
 
 
3384
    def external_url(self):
 
3385
        # Since an IniFileStore can be used without a file (at least in tests),
 
3386
        # it's better to provide something than raising a NotImplementedError.
 
3387
        # All daughter classes are supposed to provide an implementation
 
3388
        # anyway.
 
3389
        return 'In-Process Store, no URL'
 
3390
 
 
3391
 
 
3392
class TransportIniFileStore(IniFileStore):
 
3393
    """IniFileStore that loads files from a transport.
 
3394
 
 
3395
    :ivar transport: The transport object where the config file is located.
 
3396
 
 
3397
    :ivar file_name: The config file basename in the transport directory.
 
3398
    """
 
3399
 
 
3400
    def __init__(self, transport, file_name):
 
3401
        """A Store using a ini file on a Transport
 
3402
 
 
3403
        :param transport: The transport object where the config file is located.
 
3404
        :param file_name: The config file basename in the transport directory.
 
3405
        """
 
3406
        super(TransportIniFileStore, self).__init__()
 
3407
        self.transport = transport
 
3408
        self.file_name = file_name
 
3409
 
 
3410
    def _load_content(self):
 
3411
        try:
 
3412
            return self.transport.get_bytes(self.file_name)
 
3413
        except errors.PermissionDenied:
 
3414
            trace.warning("Permission denied while trying to load "
 
3415
                          "configuration store %s.", self.external_url())
 
3416
            raise
 
3417
 
 
3418
    def _save_content(self, content):
 
3419
        self.transport.put_bytes(self.file_name, content)
 
3420
 
 
3421
    def external_url(self):
 
3422
        # FIXME: external_url should really accepts an optional relpath
 
3423
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
3424
        # The following will do in the interim but maybe we don't want to
 
3425
        # expose a path here but rather a config ID and its associated
 
3426
        # object </hand wawe>.
 
3427
        return urlutils.join(self.transport.external_url(), self.file_name.encode("ascii"))
 
3428
 
 
3429
 
 
3430
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
 
3431
# unlockable stores for use with objects that can already ensure the locking
 
3432
# (think branches). If different stores (not based on ConfigObj) are created,
 
3433
# they may face the same issue.
 
3434
 
 
3435
 
 
3436
class LockableIniFileStore(TransportIniFileStore):
 
3437
    """A ConfigObjStore using locks on save to ensure store integrity."""
 
3438
 
 
3439
    def __init__(self, transport, file_name, lock_dir_name=None):
 
3440
        """A config Store using ConfigObj for storage.
 
3441
 
 
3442
        :param transport: The transport object where the config file is located.
 
3443
 
 
3444
        :param file_name: The config file basename in the transport directory.
 
3445
        """
 
3446
        if lock_dir_name is None:
 
3447
            lock_dir_name = 'lock'
 
3448
        self.lock_dir_name = lock_dir_name
 
3449
        super(LockableIniFileStore, self).__init__(transport, file_name)
 
3450
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
 
3451
 
 
3452
    def lock_write(self, token=None):
 
3453
        """Takes a write lock in the directory containing the config file.
 
3454
 
 
3455
        If the directory doesn't exist it is created.
 
3456
        """
 
3457
        # FIXME: This doesn't check the ownership of the created directories as
 
3458
        # ensure_config_dir_exists does. It should if the transport is local
 
3459
        # -- vila 2011-04-06
 
3460
        self.transport.create_prefix()
 
3461
        return self._lock.lock_write(token)
 
3462
 
 
3463
    def unlock(self):
 
3464
        self._lock.unlock()
 
3465
 
 
3466
    def break_lock(self):
 
3467
        self._lock.break_lock()
 
3468
 
 
3469
    @needs_write_lock
 
3470
    def save(self):
 
3471
        # We need to be able to override the undecorated implementation
 
3472
        self.save_without_locking()
 
3473
 
 
3474
    def save_without_locking(self):
 
3475
        super(LockableIniFileStore, self).save()
 
3476
 
 
3477
 
 
3478
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
 
3479
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
 
3480
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
 
3481
 
 
3482
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
 
3483
# functions or a registry will make it easier and clearer for tests, focusing
 
3484
# on the relevant parts of the API that needs testing -- vila 20110503 (based
 
3485
# on a poolie's remark)
 
3486
class GlobalStore(LockableIniFileStore):
 
3487
    """A config store for global options.
 
3488
 
 
3489
    There is a single GlobalStore for a given process.
 
3490
    """
 
3491
 
 
3492
    def __init__(self, possible_transports=None):
 
3493
        t = transport.get_transport_from_path(
 
3494
            config_dir(), possible_transports=possible_transports)
 
3495
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
3496
        self.id = 'bazaar'
 
3497
 
 
3498
 
 
3499
class LocationStore(LockableIniFileStore):
 
3500
    """A config store for options specific to a location.
 
3501
 
 
3502
    There is a single LocationStore for a given process.
 
3503
    """
 
3504
 
 
3505
    def __init__(self, possible_transports=None):
 
3506
        t = transport.get_transport_from_path(
 
3507
            config_dir(), possible_transports=possible_transports)
 
3508
        super(LocationStore, self).__init__(t, 'locations.conf')
 
3509
        self.id = 'locations'
 
3510
 
 
3511
 
 
3512
class BranchStore(TransportIniFileStore):
 
3513
    """A config store for branch options.
 
3514
 
 
3515
    There is a single BranchStore for a given branch.
 
3516
    """
 
3517
 
 
3518
    def __init__(self, branch):
 
3519
        super(BranchStore, self).__init__(branch.control_transport,
 
3520
                                          'branch.conf')
 
3521
        self.branch = branch
 
3522
        self.id = 'branch'
 
3523
 
 
3524
 
 
3525
class ControlStore(LockableIniFileStore):
 
3526
 
 
3527
    def __init__(self, bzrdir):
 
3528
        super(ControlStore, self).__init__(bzrdir.transport,
 
3529
                                          'control.conf',
 
3530
                                           lock_dir_name='branch_lock')
 
3531
        self.id = 'control'
 
3532
 
 
3533
 
 
3534
class SectionMatcher(object):
 
3535
    """Select sections into a given Store.
 
3536
 
 
3537
    This is intended to be used to postpone getting an iterable of sections
 
3538
    from a store.
 
3539
    """
 
3540
 
 
3541
    def __init__(self, store):
 
3542
        self.store = store
 
3543
 
 
3544
    def get_sections(self):
 
3545
        # This is where we require loading the store so we can see all defined
 
3546
        # sections.
 
3547
        sections = self.store.get_sections()
 
3548
        # Walk the revisions in the order provided
 
3549
        for store, s in sections:
 
3550
            if self.match(s):
 
3551
                yield store, s
 
3552
 
 
3553
    def match(self, section):
 
3554
        """Does the proposed section match.
 
3555
 
 
3556
        :param section: A Section object.
 
3557
 
 
3558
        :returns: True if the section matches, False otherwise.
 
3559
        """
 
3560
        raise NotImplementedError(self.match)
 
3561
 
 
3562
 
 
3563
class NameMatcher(SectionMatcher):
 
3564
 
 
3565
    def __init__(self, store, section_id):
 
3566
        super(NameMatcher, self).__init__(store)
 
3567
        self.section_id = section_id
 
3568
 
 
3569
    def match(self, section):
 
3570
        return section.id == self.section_id
 
3571
 
 
3572
 
 
3573
class LocationSection(Section):
 
3574
 
 
3575
    def __init__(self, section, extra_path, branch_name=None):
 
3576
        super(LocationSection, self).__init__(section.id, section.options)
 
3577
        self.extra_path = extra_path
 
3578
        if branch_name is None:
 
3579
            branch_name = ''
 
3580
        self.locals = {'relpath': extra_path,
 
3581
                       'basename': urlutils.basename(extra_path),
 
3582
                       'branchname': branch_name}
 
3583
 
 
3584
    def get(self, name, default=None, expand=True):
 
3585
        value = super(LocationSection, self).get(name, default)
 
3586
        if value is not None and expand:
 
3587
            policy_name = self.get(name + ':policy', None)
 
3588
            policy = _policy_value.get(policy_name, POLICY_NONE)
 
3589
            if policy == POLICY_APPENDPATH:
 
3590
                value = urlutils.join(value, self.extra_path)
 
3591
            # expand section local options right now (since POLICY_APPENDPATH
 
3592
            # will never add options references, it's ok to expand after it).
 
3593
            chunks = []
 
3594
            for is_ref, chunk in iter_option_refs(value):
 
3595
                if not is_ref:
 
3596
                    chunks.append(chunk)
 
3597
                else:
 
3598
                    ref = chunk[1:-1]
 
3599
                    if ref in self.locals:
 
3600
                        chunks.append(self.locals[ref])
 
3601
                    else:
 
3602
                        chunks.append(chunk)
 
3603
            value = ''.join(chunks)
 
3604
        return value
 
3605
 
 
3606
 
 
3607
class StartingPathMatcher(SectionMatcher):
 
3608
    """Select sections for a given location respecting the Store order."""
 
3609
 
 
3610
    # FIXME: Both local paths and urls can be used for section names as well as
 
3611
    # ``location`` to stay consistent with ``LocationMatcher`` which itself
 
3612
    # inherited the fuzziness from the previous ``LocationConfig``
 
3613
    # implementation. We probably need to revisit which encoding is allowed for
 
3614
    # both ``location`` and section names and how we normalize
 
3615
    # them. http://pad.lv/85479, http://pad.lv/437009 and http://359320 are
 
3616
    # related too. -- vila 2012-01-04
 
3617
 
 
3618
    def __init__(self, store, location):
 
3619
        super(StartingPathMatcher, self).__init__(store)
 
3620
        if location.startswith('file://'):
 
3621
            location = urlutils.local_path_from_url(location)
 
3622
        self.location = location
 
3623
 
 
3624
    def get_sections(self):
 
3625
        """Get all sections matching ``location`` in the store.
 
3626
 
 
3627
        The most generic sections are described first in the store, then more
 
3628
        specific ones can be provided for reduced scopes.
 
3629
 
 
3630
        The returned section are therefore returned in the reversed order so
 
3631
        the most specific ones can be found first.
 
3632
        """
 
3633
        location_parts = self.location.rstrip('/').split('/')
 
3634
        store = self.store
 
3635
        # Later sections are more specific, they should be returned first
 
3636
        for _, section in reversed(list(store.get_sections())):
 
3637
            if section.id is None:
 
3638
                # The no-name section is always included if present
 
3639
                yield store, LocationSection(section, self.location)
 
3640
                continue
 
3641
            section_path = section.id
 
3642
            if section_path.startswith('file://'):
 
3643
                # the location is already a local path or URL, convert the
 
3644
                # section id to the same format
 
3645
                section_path = urlutils.local_path_from_url(section_path)
 
3646
            if (self.location.startswith(section_path)
 
3647
                or fnmatch.fnmatch(self.location, section_path)):
 
3648
                section_parts = section_path.rstrip('/').split('/')
 
3649
                extra_path = '/'.join(location_parts[len(section_parts):])
 
3650
                yield store, LocationSection(section, extra_path)
 
3651
 
 
3652
 
 
3653
class LocationMatcher(SectionMatcher):
 
3654
 
 
3655
    def __init__(self, store, location):
 
3656
        super(LocationMatcher, self).__init__(store)
 
3657
        url, params = urlutils.split_segment_parameters(location)
 
3658
        if location.startswith('file://'):
 
3659
            location = urlutils.local_path_from_url(location)
 
3660
        self.location = location
 
3661
        branch_name = params.get('branch')
 
3662
        if branch_name is None:
 
3663
            self.branch_name = urlutils.basename(self.location)
 
3664
        else:
 
3665
            self.branch_name = urlutils.unescape(branch_name)
 
3666
 
 
3667
    def _get_matching_sections(self):
 
3668
        """Get all sections matching ``location``."""
 
3669
        # We slightly diverge from LocalConfig here by allowing the no-name
 
3670
        # section as the most generic one and the lower priority.
 
3671
        no_name_section = None
 
3672
        all_sections = []
 
3673
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
3674
        # used (it assumes all sections have a name).
 
3675
        for _, section in self.store.get_sections():
 
3676
            if section.id is None:
 
3677
                no_name_section = section
 
3678
            else:
 
3679
                all_sections.append(section)
 
3680
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
3681
        # we have to resync.
 
3682
        filtered_sections = _iter_for_location_by_parts(
 
3683
            [s.id for s in all_sections], self.location)
 
3684
        iter_all_sections = iter(all_sections)
 
3685
        matching_sections = []
 
3686
        if no_name_section is not None:
 
3687
            matching_sections.append(
 
3688
                (0, LocationSection(no_name_section, self.location)))
 
3689
        for section_id, extra_path, length in filtered_sections:
 
3690
            # a section id is unique for a given store so it's safe to take the
 
3691
            # first matching section while iterating. Also, all filtered
 
3692
            # sections are part of 'all_sections' and will always be found
 
3693
            # there.
 
3694
            while True:
 
3695
                section = iter_all_sections.next()
 
3696
                if section_id == section.id:
 
3697
                    section = LocationSection(section, extra_path,
 
3698
                                              self.branch_name)
 
3699
                    matching_sections.append((length, section))
 
3700
                    break
 
3701
        return matching_sections
 
3702
 
 
3703
    def get_sections(self):
 
3704
        # Override the default implementation as we want to change the order
 
3705
        # We want the longest (aka more specific) locations first
 
3706
        sections = sorted(self._get_matching_sections(),
 
3707
                          key=lambda match: (match[0], match[1].id),
 
3708
                          reverse=True)
 
3709
        # Sections mentioning 'ignore_parents' restrict the selection
 
3710
        for _, section in sections:
 
3711
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
 
3712
            ignore = section.get('ignore_parents', None)
 
3713
            if ignore is not None:
 
3714
                ignore = ui.bool_from_string(ignore)
 
3715
            if ignore:
 
3716
                break
 
3717
            # Finally, we have a valid section
 
3718
            yield self.store, section
 
3719
 
 
3720
 
 
3721
# FIXME: _shared_stores should be an attribute of a library state once a
 
3722
# library_state object is always available.
 
3723
_shared_stores = {}
 
3724
_shared_stores_at_exit_installed = False
 
3725
 
 
3726
class Stack(object):
 
3727
    """A stack of configurations where an option can be defined"""
 
3728
 
 
3729
    def __init__(self, sections_def, store=None, mutable_section_id=None):
 
3730
        """Creates a stack of sections with an optional store for changes.
 
3731
 
 
3732
        :param sections_def: A list of Section or callables that returns an
 
3733
            iterable of Section. This defines the Sections for the Stack and
 
3734
            can be called repeatedly if needed.
 
3735
 
 
3736
        :param store: The optional Store where modifications will be
 
3737
            recorded. If none is specified, no modifications can be done.
 
3738
 
 
3739
        :param mutable_section_id: The id of the MutableSection where changes
 
3740
            are recorded. This requires the ``store`` parameter to be
 
3741
            specified.
 
3742
        """
 
3743
        self.sections_def = sections_def
 
3744
        self.store = store
 
3745
        self.mutable_section_id = mutable_section_id
 
3746
 
 
3747
    def iter_sections(self):
 
3748
        """Iterate all the defined sections."""
 
3749
        # Ensuring lazy loading is achieved by delaying section matching (which
 
3750
        # implies querying the persistent storage) until it can't be avoided
 
3751
        # anymore by using callables to describe (possibly empty) section
 
3752
        # lists.
 
3753
        for sections in self.sections_def:
 
3754
            for store, section in sections():
 
3755
                yield store, section
 
3756
 
 
3757
    def get(self, name, expand=True, convert=True):
 
3758
        """Return the *first* option value found in the sections.
 
3759
 
 
3760
        This is where we guarantee that sections coming from Store are loaded
 
3761
        lazily: the loading is delayed until we need to either check that an
 
3762
        option exists or get its value, which in turn may require to discover
 
3763
        in which sections it can be defined. Both of these (section and option
 
3764
        existence) require loading the store (even partially).
 
3765
 
 
3766
        :param name: The queried option.
 
3767
 
 
3768
        :param expand: Whether options references should be expanded.
 
3769
 
 
3770
        :param convert: Whether the option value should be converted from
 
3771
            unicode (do nothing for non-registered options).
 
3772
 
 
3773
        :returns: The value of the option.
 
3774
        """
 
3775
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
3776
        value = None
 
3777
        found_store = None # Where the option value has been found
 
3778
        # If the option is registered, it may provide additional info about
 
3779
        # value handling
 
3780
        try:
 
3781
            opt = option_registry.get(name)
 
3782
        except KeyError:
 
3783
            # Not registered
 
3784
            opt = None
 
3785
 
 
3786
        def expand_and_convert(val):
 
3787
            # This may need to be called in different contexts if the value is
 
3788
            # None or ends up being None during expansion or conversion.
 
3789
            if val is not None:
 
3790
                if expand:
 
3791
                    if isinstance(val, string_types):
 
3792
                        val = self._expand_options_in_string(val)
 
3793
                    else:
 
3794
                        trace.warning('Cannot expand "%s":'
 
3795
                                      ' %s does not support option expansion'
 
3796
                                      % (name, type(val)))
 
3797
                if opt is None:
 
3798
                    val = found_store.unquote(val)
 
3799
                elif convert:
 
3800
                    val = opt.convert_from_unicode(found_store, val)
 
3801
            return val
 
3802
 
 
3803
        # First of all, check if the environment can override the configuration
 
3804
        # value
 
3805
        if opt is not None and opt.override_from_env:
 
3806
            value = opt.get_override()
 
3807
            value = expand_and_convert(value)
 
3808
        if value is None:
 
3809
            for store, section in self.iter_sections():
 
3810
                value = section.get(name)
 
3811
                if value is not None:
 
3812
                    found_store = store
 
3813
                    break
 
3814
            value = expand_and_convert(value)
 
3815
            if opt is not None and value is None:
 
3816
                # If the option is registered, it may provide a default value
 
3817
                value = opt.get_default()
 
3818
                value = expand_and_convert(value)
 
3819
        for hook in ConfigHooks['get']:
 
3820
            hook(self, name, value)
 
3821
        return value
 
3822
 
 
3823
    def expand_options(self, string, env=None):
 
3824
        """Expand option references in the string in the configuration context.
 
3825
 
 
3826
        :param string: The string containing option(s) to expand.
 
3827
 
 
3828
        :param env: An option dict defining additional configuration options or
 
3829
            overriding existing ones.
 
3830
 
 
3831
        :returns: The expanded string.
 
3832
        """
 
3833
        return self._expand_options_in_string(string, env)
 
3834
 
 
3835
    def _expand_options_in_string(self, string, env=None, _refs=None):
 
3836
        """Expand options in the string in the configuration context.
 
3837
 
 
3838
        :param string: The string to be expanded.
 
3839
 
 
3840
        :param env: An option dict defining additional configuration options or
 
3841
            overriding existing ones.
 
3842
 
 
3843
        :param _refs: Private list (FIFO) containing the options being expanded
 
3844
            to detect loops.
 
3845
 
 
3846
        :returns: The expanded string.
 
3847
        """
 
3848
        if string is None:
 
3849
            # Not much to expand there
 
3850
            return None
 
3851
        if _refs is None:
 
3852
            # What references are currently resolved (to detect loops)
 
3853
            _refs = []
 
3854
        result = string
 
3855
        # We need to iterate until no more refs appear ({{foo}} will need two
 
3856
        # iterations for example).
 
3857
        expanded = True
 
3858
        while expanded:
 
3859
            expanded = False
 
3860
            chunks = []
 
3861
            for is_ref, chunk in iter_option_refs(result):
 
3862
                if not is_ref:
 
3863
                    chunks.append(chunk)
 
3864
                else:
 
3865
                    expanded = True
 
3866
                    name = chunk[1:-1]
 
3867
                    if name in _refs:
 
3868
                        raise errors.OptionExpansionLoop(string, _refs)
 
3869
                    _refs.append(name)
 
3870
                    value = self._expand_option(name, env, _refs)
 
3871
                    if value is None:
 
3872
                        raise errors.ExpandingUnknownOption(name, string)
 
3873
                    chunks.append(value)
 
3874
                    _refs.pop()
 
3875
            result = ''.join(chunks)
 
3876
        return result
 
3877
 
 
3878
    def _expand_option(self, name, env, _refs):
 
3879
        if env is not None and name in env:
 
3880
            # Special case, values provided in env takes precedence over
 
3881
            # anything else
 
3882
            value = env[name]
 
3883
        else:
 
3884
            value = self.get(name, expand=False, convert=False)
 
3885
            value = self._expand_options_in_string(value, env, _refs)
 
3886
        return value
 
3887
 
 
3888
    def _get_mutable_section(self):
 
3889
        """Get the MutableSection for the Stack.
 
3890
 
 
3891
        This is where we guarantee that the mutable section is lazily loaded:
 
3892
        this means we won't load the corresponding store before setting a value
 
3893
        or deleting an option. In practice the store will often be loaded but
 
3894
        this helps catching some programming errors.
 
3895
        """
 
3896
        store = self.store
 
3897
        section = store.get_mutable_section(self.mutable_section_id)
 
3898
        return store, section
 
3899
 
 
3900
    def set(self, name, value):
 
3901
        """Set a new value for the option."""
 
3902
        store, section = self._get_mutable_section()
 
3903
        section.set(name, store.quote(value))
 
3904
        for hook in ConfigHooks['set']:
 
3905
            hook(self, name, value)
 
3906
 
 
3907
    def remove(self, name):
 
3908
        """Remove an existing option."""
 
3909
        _, section = self._get_mutable_section()
 
3910
        section.remove(name)
 
3911
        for hook in ConfigHooks['remove']:
 
3912
            hook(self, name)
 
3913
 
 
3914
    def __repr__(self):
 
3915
        # Mostly for debugging use
 
3916
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
 
3917
 
 
3918
    def _get_overrides(self):
 
3919
        # FIXME: Hack around library_state.initialize never called
 
3920
        if breezy.global_state is not None:
 
3921
            return breezy.global_state.cmdline_overrides.get_sections()
 
3922
        return []
 
3923
 
 
3924
    def get_shared_store(self, store, state=None):
 
3925
        """Get a known shared store.
 
3926
 
 
3927
        Store urls uniquely identify them and are used to ensure a single copy
 
3928
        is shared across all users.
 
3929
 
 
3930
        :param store: The store known to the caller.
 
3931
 
 
3932
        :param state: The library state where the known stores are kept.
 
3933
 
 
3934
        :returns: The store received if it's not a known one, an already known
 
3935
            otherwise.
 
3936
        """
 
3937
        if state is None:
 
3938
            state = breezy.global_state
 
3939
        if state is None:
 
3940
            global _shared_stores_at_exit_installed
 
3941
            stores = _shared_stores
 
3942
            def save_config_changes():
 
3943
                for k, store in stores.items():
 
3944
                    store.save_changes()
 
3945
            if not _shared_stores_at_exit_installed:
 
3946
                # FIXME: Ugly hack waiting for library_state to always be
 
3947
                # available. -- vila 20120731
 
3948
                import atexit
 
3949
                atexit.register(save_config_changes)
 
3950
                _shared_stores_at_exit_installed = True
 
3951
        else:
 
3952
            stores = state.config_stores
 
3953
        url = store.external_url()
 
3954
        try:
 
3955
            return stores[url]
 
3956
        except KeyError:
 
3957
            stores[url] = store
 
3958
            return store
 
3959
 
 
3960
 
 
3961
class MemoryStack(Stack):
 
3962
    """A configuration stack defined from a string.
 
3963
 
 
3964
    This is mainly intended for tests and requires no disk resources.
 
3965
    """
 
3966
 
 
3967
    def __init__(self, content=None):
 
3968
        """Create an in-memory stack from a given content.
 
3969
 
 
3970
        It uses a single store based on configobj and support reading and
 
3971
        writing options.
 
3972
 
 
3973
        :param content: The initial content of the store. If None, the store is
 
3974
            not loaded and ``_load_from_string`` can and should be used if
 
3975
            needed.
 
3976
        """
 
3977
        store = IniFileStore()
 
3978
        if content is not None:
 
3979
            store._load_from_string(content)
 
3980
        super(MemoryStack, self).__init__(
 
3981
            [store.get_sections], store)
 
3982
 
 
3983
 
 
3984
class _CompatibleStack(Stack):
 
3985
    """Place holder for compatibility with previous design.
 
3986
 
 
3987
    This is intended to ease the transition from the Config-based design to the
 
3988
    Stack-based design and should not be used nor relied upon by plugins.
 
3989
 
 
3990
    One assumption made here is that the daughter classes will all use Stores
 
3991
    derived from LockableIniFileStore).
 
3992
 
 
3993
    It implements set() and remove () by re-loading the store before applying
 
3994
    the modification and saving it.
 
3995
 
 
3996
    The long term plan being to implement a single write by store to save
 
3997
    all modifications, this class should not be used in the interim.
 
3998
    """
 
3999
 
 
4000
    def set(self, name, value):
 
4001
        # Force a reload
 
4002
        self.store.unload()
 
4003
        super(_CompatibleStack, self).set(name, value)
 
4004
        # Force a write to persistent storage
 
4005
        self.store.save()
 
4006
 
 
4007
    def remove(self, name):
 
4008
        # Force a reload
 
4009
        self.store.unload()
 
4010
        super(_CompatibleStack, self).remove(name)
 
4011
        # Force a write to persistent storage
 
4012
        self.store.save()
 
4013
 
 
4014
 
 
4015
class GlobalStack(Stack):
 
4016
    """Global options only stack.
 
4017
 
 
4018
    The following sections are queried:
 
4019
 
 
4020
    * command-line overrides,
 
4021
 
 
4022
    * the 'DEFAULT' section in bazaar.conf
 
4023
 
 
4024
    This stack will use the ``DEFAULT`` section in bazaar.conf as its
 
4025
    MutableSection.
 
4026
    """
 
4027
 
 
4028
    def __init__(self):
 
4029
        gstore = self.get_shared_store(GlobalStore())
 
4030
        super(GlobalStack, self).__init__(
 
4031
            [self._get_overrides,
 
4032
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
4033
            gstore, mutable_section_id='DEFAULT')
 
4034
 
 
4035
 
 
4036
class LocationStack(Stack):
 
4037
    """Per-location options falling back to global options stack.
 
4038
 
 
4039
 
 
4040
    The following sections are queried:
 
4041
 
 
4042
    * command-line overrides,
 
4043
 
 
4044
    * the sections matching ``location`` in ``locations.conf``, the order being
 
4045
      defined by the number of path components in the section glob, higher
 
4046
      numbers first (from most specific section to most generic).
 
4047
 
 
4048
    * the 'DEFAULT' section in bazaar.conf
 
4049
 
 
4050
    This stack will use the ``location`` section in locations.conf as its
 
4051
    MutableSection.
 
4052
    """
 
4053
 
 
4054
    def __init__(self, location):
 
4055
        """Make a new stack for a location and global configuration.
 
4056
 
 
4057
        :param location: A URL prefix to """
 
4058
        lstore = self.get_shared_store(LocationStore())
 
4059
        if location.startswith('file://'):
 
4060
            location = urlutils.local_path_from_url(location)
 
4061
        gstore = self.get_shared_store(GlobalStore())
 
4062
        super(LocationStack, self).__init__(
 
4063
            [self._get_overrides,
 
4064
             LocationMatcher(lstore, location).get_sections,
 
4065
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
4066
            lstore, mutable_section_id=location)
 
4067
 
 
4068
 
 
4069
class BranchStack(Stack):
 
4070
    """Per-location options falling back to branch then global options stack.
 
4071
 
 
4072
    The following sections are queried:
 
4073
 
 
4074
    * command-line overrides,
 
4075
 
 
4076
    * the sections matching ``location`` in ``locations.conf``, the order being
 
4077
      defined by the number of path components in the section glob, higher
 
4078
      numbers first (from most specific section to most generic),
 
4079
 
 
4080
    * the no-name section in branch.conf,
 
4081
 
 
4082
    * the ``DEFAULT`` section in ``bazaar.conf``.
 
4083
 
 
4084
    This stack will use the no-name section in ``branch.conf`` as its
 
4085
    MutableSection.
 
4086
    """
 
4087
 
 
4088
    def __init__(self, branch):
 
4089
        lstore = self.get_shared_store(LocationStore())
 
4090
        bstore = branch._get_config_store()
 
4091
        gstore = self.get_shared_store(GlobalStore())
 
4092
        super(BranchStack, self).__init__(
 
4093
            [self._get_overrides,
 
4094
             LocationMatcher(lstore, branch.base).get_sections,
 
4095
             NameMatcher(bstore, None).get_sections,
 
4096
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
4097
            bstore)
 
4098
        self.branch = branch
 
4099
 
 
4100
    def lock_write(self, token=None):
 
4101
        return self.branch.lock_write(token)
 
4102
 
 
4103
    def unlock(self):
 
4104
        return self.branch.unlock()
 
4105
 
 
4106
    @needs_write_lock
 
4107
    def set(self, name, value):
 
4108
        super(BranchStack, self).set(name, value)
 
4109
        # Unlocking the branch will trigger a store.save_changes() so the last
 
4110
        # unlock saves all the changes.
 
4111
 
 
4112
    @needs_write_lock
 
4113
    def remove(self, name):
 
4114
        super(BranchStack, self).remove(name)
 
4115
        # Unlocking the branch will trigger a store.save_changes() so the last
 
4116
        # unlock saves all the changes.
 
4117
 
 
4118
 
 
4119
class RemoteControlStack(Stack):
 
4120
    """Remote control-only options stack."""
 
4121
 
 
4122
    # FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
 
4123
    # with the stack used for remote bzr dirs. RemoteControlStack only uses
 
4124
    # control.conf and is used only for stack options.
 
4125
 
 
4126
    def __init__(self, bzrdir):
 
4127
        cstore = bzrdir._get_config_store()
 
4128
        super(RemoteControlStack, self).__init__(
 
4129
            [NameMatcher(cstore, None).get_sections],
 
4130
            cstore)
 
4131
        self.bzrdir = bzrdir
 
4132
 
 
4133
 
 
4134
class BranchOnlyStack(Stack):
 
4135
    """Branch-only options stack."""
 
4136
 
 
4137
    # FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
 
4138
    # stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
 
4139
    # -- vila 2011-12-16
 
4140
 
 
4141
    def __init__(self, branch):
 
4142
        bstore = branch._get_config_store()
 
4143
        super(BranchOnlyStack, self).__init__(
 
4144
            [NameMatcher(bstore, None).get_sections],
 
4145
            bstore)
 
4146
        self.branch = branch
 
4147
 
 
4148
    def lock_write(self, token=None):
 
4149
        return self.branch.lock_write(token)
 
4150
 
 
4151
    def unlock(self):
 
4152
        return self.branch.unlock()
 
4153
 
 
4154
    @needs_write_lock
 
4155
    def set(self, name, value):
 
4156
        super(BranchOnlyStack, self).set(name, value)
 
4157
        # Force a write to persistent storage
 
4158
        self.store.save_changes()
 
4159
 
 
4160
    @needs_write_lock
 
4161
    def remove(self, name):
 
4162
        super(BranchOnlyStack, self).remove(name)
 
4163
        # Force a write to persistent storage
 
4164
        self.store.save_changes()
 
4165
 
 
4166
 
 
4167
class cmd_config(commands.Command):
 
4168
    __doc__ = """Display, set or remove a configuration option.
 
4169
 
 
4170
    Display the active value for option NAME.
 
4171
 
 
4172
    If --all is specified, NAME is interpreted as a regular expression and all
 
4173
    matching options are displayed mentioning their scope and without resolving
 
4174
    option references in the value). The active value that bzr will take into
 
4175
    account is the first one displayed for each option.
 
4176
 
 
4177
    If NAME is not given, --all .* is implied (all options are displayed for the
 
4178
    current scope).
 
4179
 
 
4180
    Setting a value is achieved by using NAME=value without spaces. The value
 
4181
    is set in the most relevant scope and can be checked by displaying the
 
4182
    option again.
 
4183
 
 
4184
    Removing a value is achieved by using --remove NAME.
 
4185
    """
 
4186
 
 
4187
    takes_args = ['name?']
 
4188
 
 
4189
    takes_options = [
 
4190
        'directory',
 
4191
        # FIXME: This should be a registry option so that plugins can register
 
4192
        # their own config files (or not) and will also address
 
4193
        # http://pad.lv/788991 -- vila 20101115
 
4194
        commands.Option('scope', help='Reduce the scope to the specified'
 
4195
                        ' configuration file.',
 
4196
                        type=text_type),
 
4197
        commands.Option('all',
 
4198
            help='Display all the defined values for the matching options.',
 
4199
            ),
 
4200
        commands.Option('remove', help='Remove the option from'
 
4201
                        ' the configuration file.'),
 
4202
        ]
 
4203
 
 
4204
    _see_also = ['configuration']
 
4205
 
 
4206
    @commands.display_command
 
4207
    def run(self, name=None, all=False, directory=None, scope=None,
 
4208
            remove=False):
 
4209
        if directory is None:
 
4210
            directory = '.'
 
4211
        directory = directory_service.directories.dereference(directory)
 
4212
        directory = urlutils.normalize_url(directory)
 
4213
        if remove and all:
 
4214
            raise errors.BzrError(
 
4215
                '--all and --remove are mutually exclusive.')
 
4216
        elif remove:
 
4217
            # Delete the option in the given scope
 
4218
            self._remove_config_option(name, directory, scope)
 
4219
        elif name is None:
 
4220
            # Defaults to all options
 
4221
            self._show_matching_options('.*', directory, scope)
 
4222
        else:
 
4223
            try:
 
4224
                name, value = name.split('=', 1)
 
4225
            except ValueError:
 
4226
                # Display the option(s) value(s)
 
4227
                if all:
 
4228
                    self._show_matching_options(name, directory, scope)
 
4229
                else:
 
4230
                    self._show_value(name, directory, scope)
 
4231
            else:
 
4232
                if all:
 
4233
                    raise errors.BzrError(
 
4234
                        'Only one option can be set.')
 
4235
                # Set the option value
 
4236
                self._set_config_option(name, value, directory, scope)
 
4237
 
 
4238
    def _get_stack(self, directory, scope=None, write_access=False):
 
4239
        """Get the configuration stack specified by ``directory`` and ``scope``.
 
4240
 
 
4241
        :param directory: Where the configurations are derived from.
 
4242
 
 
4243
        :param scope: A specific config to start from.
 
4244
 
 
4245
        :param write_access: Whether a write access to the stack will be
 
4246
            attempted.
 
4247
        """
 
4248
        # FIXME: scope should allow access to plugin-specific stacks (even
 
4249
        # reduced to the plugin-specific store), related to
 
4250
        # http://pad.lv/788991 -- vila 2011-11-15
 
4251
        if scope is not None:
 
4252
            if scope == 'bazaar':
 
4253
                return GlobalStack()
 
4254
            elif scope == 'locations':
 
4255
                return LocationStack(directory)
 
4256
            elif scope == 'branch':
 
4257
                (_, br, _) = (
 
4258
                    controldir.ControlDir.open_containing_tree_or_branch(
 
4259
                        directory))
 
4260
                if write_access:
 
4261
                    self.add_cleanup(br.lock_write().unlock)
 
4262
                return br.get_config_stack()
 
4263
            raise errors.NoSuchConfig(scope)
 
4264
        else:
 
4265
            try:
 
4266
                (_, br, _) = (
 
4267
                    controldir.ControlDir.open_containing_tree_or_branch(
 
4268
                        directory))
 
4269
                if write_access:
 
4270
                    self.add_cleanup(br.lock_write().unlock)
 
4271
                return br.get_config_stack()
 
4272
            except errors.NotBranchError:
 
4273
                return LocationStack(directory)
 
4274
 
 
4275
    def _quote_multiline(self, value):
 
4276
        if '\n' in value:
 
4277
            value = '"""' + value + '"""'
 
4278
        return value
 
4279
 
 
4280
    def _show_value(self, name, directory, scope):
 
4281
        conf = self._get_stack(directory, scope)
 
4282
        value = conf.get(name, expand=True, convert=False)
 
4283
        if value is not None:
 
4284
            # Quote the value appropriately
 
4285
            value = self._quote_multiline(value)
 
4286
            self.outf.write('%s\n' % (value,))
 
4287
        else:
 
4288
            raise errors.NoSuchConfigOption(name)
 
4289
 
 
4290
    def _show_matching_options(self, name, directory, scope):
 
4291
        name = lazy_regex.lazy_compile(name)
 
4292
        # We want any error in the regexp to be raised *now* so we need to
 
4293
        # avoid the delay introduced by the lazy regexp.  But, we still do
 
4294
        # want the nicer errors raised by lazy_regex.
 
4295
        name._compile_and_collapse()
 
4296
        cur_store_id = None
 
4297
        cur_section = None
 
4298
        conf = self._get_stack(directory, scope)
 
4299
        for store, section in conf.iter_sections():
 
4300
            for oname in section.iter_option_names():
 
4301
                if name.search(oname):
 
4302
                    if cur_store_id != store.id:
 
4303
                        # Explain where the options are defined
 
4304
                        self.outf.write('%s:\n' % (store.id,))
 
4305
                        cur_store_id = store.id
 
4306
                        cur_section = None
 
4307
                    if (section.id is not None and cur_section != section.id):
 
4308
                        # Display the section id as it appears in the store
 
4309
                        # (None doesn't appear by definition)
 
4310
                        self.outf.write('  [%s]\n' % (section.id,))
 
4311
                        cur_section = section.id
 
4312
                    value = section.get(oname, expand=False)
 
4313
                    # Quote the value appropriately
 
4314
                    value = self._quote_multiline(value)
 
4315
                    self.outf.write('  %s = %s\n' % (oname, value))
 
4316
 
 
4317
    def _set_config_option(self, name, value, directory, scope):
 
4318
        conf = self._get_stack(directory, scope, write_access=True)
 
4319
        conf.set(name, value)
 
4320
        # Explicitly save the changes
 
4321
        conf.store.save_changes()
 
4322
 
 
4323
    def _remove_config_option(self, name, directory, scope):
 
4324
        if name is None:
 
4325
            raise errors.BzrCommandError(
 
4326
                '--remove expects an option to remove.')
 
4327
        conf = self._get_stack(directory, scope, write_access=True)
 
4328
        try:
 
4329
            conf.remove(name)
 
4330
            # Explicitly save the changes
 
4331
            conf.store.save_changes()
 
4332
        except KeyError:
 
4333
            raise errors.NoSuchConfigOption(name)
 
4334
 
 
4335
 
 
4336
# Test registries
 
4337
#
 
4338
# We need adapters that can build a Store or a Stack in a test context. Test
 
4339
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
4340
# themselves. The builder will receive a test instance and should return a
 
4341
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
4342
# register themselves here to be tested against the tests defined in
 
4343
# breezy.tests.test_config. Note that the builder can be called multiple times
 
4344
# for the same test.
 
4345
 
 
4346
# The registered object should be a callable receiving a test instance
 
4347
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
4348
# object.
 
4349
test_store_builder_registry = registry.Registry()
 
4350
 
 
4351
# The registered object should be a callable receiving a test instance
 
4352
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
4353
# object.
 
4354
test_stack_builder_registry = registry.Registry()