/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Robert Collins
  • Date: 2010-05-05 00:05:29 UTC
  • mto: This revision was merged to the branch mainline in revision 5206.
  • Revision ID: robertc@robertcollins.net-20100505000529-ltmllyms5watqj5u
Make 'pydoc bzrlib.tests.build_tree_shape' useful.

Show diffs side-by-side

added added

removed removed

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