/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: Jelmer Vernooij
  • Date: 2017-09-01 07:15:43 UTC
  • mfrom: (6770.3.2 py3_test_cleanup)
  • Revision ID: jelmer@jelmer.uk-20170901071543-1t83321xkog9qrxh
Merge lp:~gz/brz/py3_test_cleanup

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