/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6587.2.4 by Vincent Ladeuil
Allow hyphens in option names to unbreak compatibility.
1
# Copyright (C) 2005-2014, 2016 Canonical Ltd
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
2
#   Authors: Robert Collins <robert.collins@canonical.com>
2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
3
#            and others
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
4
#
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
18
6741 by Jelmer Vernooij
Merge lp:~jelmer/brz/breezy-conf
19
"""Configuration that affects the behaviour of Breezy.
1442.1.20 by Robert Collins
add some documentation on options
20
6740.1.1 by Jelmer Vernooij
Rename bazaar.conf to breezy.conf.
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:
1442.1.20 by Robert Collins
add some documentation on options
28
[DEFAULT]
29
editor=name-of-program
30
email=Your Name <your@email.address>
31
check_signatures=require|ignore|check-available(default)
32
create_signatures=always|never|when-required(default)
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
33
log_format=name-of-format
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
34
validate_signatures_in_log=true|false(default)
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
35
acceptable_keys=pattern1,pattern2
6012.2.11 by Jonathan Riddell
rename config option signing_key to gpg_signing_key
36
gpg_signing_key=amy@example.com
1442.1.20 by Robert Collins
add some documentation on options
37
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
38
in locations.conf, you specify the url of a branch and options for it.
1442.1.20 by Robert Collins
add some documentation on options
39
Wildcards may be used - * and ? as normal in shell completion. Options
6740.1.1 by Jelmer Vernooij
Rename bazaar.conf to breezy.conf.
40
set in both breezy.conf and locations.conf are overridden by the locations.conf
1442.1.20 by Robert Collins
add some documentation on options
41
setting.
42
[/home/robertc/source]
43
recurse=False|True(default)
44
email= as above
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
45
check_signatures= as above
1442.1.20 by Robert Collins
add some documentation on options
46
create_signatures= as above.
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
47
validate_signatures_in_log=as above
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
48
acceptable_keys=as above
1442.1.20 by Robert Collins
add some documentation on options
49
50
explanation of options
51
----------------------
52
editor - this option sets the pop up editor to use during commits.
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
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
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
55
                   signatures, ignore them, or check them if they are
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
56
                   present.  Currently it is unused except that
57
                   check_signatures turns on create_signatures.
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
58
create_signatures - this option controls whether brz will always create
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
59
                    gpg signatures or not on commits.  There is an unused
6449.6.7 by Jelmer Vernooij
Fix tests.
60
                    option which in future is expected to work if
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
61
                    branch settings require signatures.
1887.2.1 by Adeodato Simó
Fix some typos and grammar issues.
62
log_format - this option sets the default log format.  Possible values are
63
             long, short, line, or a plugin can register new formats.
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
64
validate_signatures_in_log - show GPG signature validity in log output
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
65
acceptable_keys - comma separated list of key patterns acceptable for
66
                  verify-signatures command
1553.6.2 by Erik Bågfors
documentation and NEWS
67
6740.1.1 by Jelmer Vernooij
Rename bazaar.conf to breezy.conf.
68
In breezy.conf you can also define aliases in the ALIASES sections, example
1553.6.2 by Erik Bågfors
documentation and NEWS
69
70
[ALIASES]
71
lastlog=log --line -r-10..-1
72
ll=log --line -r-10..-1
73
h=help
74
up=pull
1442.1.20 by Robert Collins
add some documentation on options
75
"""
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
76
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
77
from __future__ import absolute_import
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
78
import os
79
import sys
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
80
6621.5.1 by Martin
Remove internal copy of configobj and add workarounds for bugs in latest version
81
import configobj
82
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
83
import breezy
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
84
from .lazy_import import lazy_import
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
85
lazy_import(globals(), """
5912.5.7 by Martin
Minor cleanups and note about error case
86
import base64
6690.1.3 by Jelmer Vernooij
Review comments.
87
import errno
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
88
import fnmatch
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
89
import re
6690.1.3 by Jelmer Vernooij
Review comments.
90
import stat
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
91
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
92
from breezy import (
4797.59.2 by Vincent Ladeuil
Use AtomicFile and avoid all unicode/encoding issues around transport (thanks jam).
93
    atomicfile,
7358.6.1 by Jelmer Vernooij
Use standard syntax for the ``change_editor`` configuration option.
94
    cmdline,
6207.3.3 by jelmer at samba
Fix tests and the like.
95
    controldir,
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
96
    debug,
6437.66.1 by Wouter van Heyst
Dereference directory services in cmd_config.
97
    directory_service,
6754.8.4 by Jelmer Vernooij
Use new context stuff.
98
    lock,
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
99
    lockdir,
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
100
    mergetools,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
101
    osutils,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
102
    trace,
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
103
    transport,
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
104
    ui,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
105
    urlutils,
2245.4.3 by Alexander Belchenko
config.py: changing _auto_user_id() and config_dir() to use functions from win32utils
106
    win32utils,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
107
    )
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
108
from breezy.i18n import gettext
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
109
""")
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
110
from . import (
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
111
    commands,
7336.2.1 by Martin
Split non-ini config methods to bedding
112
    bedding,
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
113
    errors,
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
114
    hooks,
6082.5.10 by Vincent Ladeuil
Tweaks suggested by jam during review.
115
    lazy_regex,
5904.1.2 by Martin Pool
Various pyflakes import fixes.
116
    registry,
117
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
118
from .sixish import (
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
119
    binary_type,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
120
    BytesIO,
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
121
    PY3,
6973.6.2 by Jelmer Vernooij
Fix more tests.
122
    string_types,
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
123
    text_type,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
124
    )
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
125
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
126
7143.15.2 by Jelmer Vernooij
Run autopep8.
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
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
135
136
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
137
POLICY_NONE = 0
138
POLICY_NORECURSE = 1
139
POLICY_APPENDPATH = 2
140
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
141
_policy_name = {
142
    POLICY_NONE: None,
143
    POLICY_NORECURSE: 'norecurse',
144
    POLICY_APPENDPATH: 'appendpath',
145
    }
146
_policy_value = {
147
    None: POLICY_NONE,
148
    'none': POLICY_NONE,
149
    'norecurse': POLICY_NORECURSE,
150
    'appendpath': POLICY_APPENDPATH,
151
    }
2120.6.4 by James Henstridge
add support for specifying policy when storing options
152
153
154
STORE_LOCATION = POLICY_NONE
155
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
156
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
157
STORE_BRANCH = 3
158
STORE_GLOBAL = 4
159
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
160
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
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
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
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
6621.5.1 by Martin
Remove internal copy of configobj and add workarounds for bugs in latest version
261
def _has_decode_bug():
262
    """True if configobj will fail to decode to unicode on Python 2."""
7336.2.1 by Martin
Split non-ini config methods to bedding
263
    if PY3:
6621.5.1 by Martin
Remove internal copy of configobj and add workarounds for bugs in latest version
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
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
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
6621.5.1 by Martin
Remove internal copy of configobj and add workarounds for bugs in latest version
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
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
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]
315
316
5549.1.19 by Vincent Ladeuil
Push down interpolation at the config level (make tests slightly less
317
class Config(object):
318
    """A configuration policy - what username, editor, gpg needs etc."""
319
320
    def __init__(self):
321
        super(Config, self).__init__()
322
323
    def config_id(self):
324
        """Returns a unique ID for the config."""
325
        raise NotImplementedError(self.config_id)
326
327
    def get_change_editor(self, old_tree, new_tree):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
328
        from breezy import diff
5549.1.19 by Vincent Ladeuil
Push down interpolation at the config level (make tests slightly less
329
        cmd = self._get_change_editor()
330
        if cmd is None:
331
            return None
7358.6.1 by Jelmer Vernooij
Use standard syntax for the ``change_editor`` configuration option.
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}'])
5549.1.19 by Vincent Ladeuil
Push down interpolation at the config level (make tests slightly less
337
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
338
                                             sys.stdout)
339
340
    def _get_signature_checking(self):
341
        """Template method to override signature checking policy."""
342
343
    def _get_signing_policy(self):
344
        """Template method to override signature creation policy."""
345
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
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:
5745.1.1 by Vincent Ladeuil
Remove debug code
411
            raw_chunks = self.option_ref_re.split(result)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
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:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
429
                        raise OptionExpansionLoop(string, _ref_stack)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
430
                    _ref_stack.append(name)
431
                    value = self._expand_option(name, env, _ref_stack)
432
                    if value is None:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
433
                        raise ExpandingUnknownOption(name, string)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
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
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
459
            # way to query the brz config for the value of an option,
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
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
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
470
    def _get_user_option(self, option_name):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
471
        """Template method to provide a user option."""
472
        return None
473
6468.5.1 by Vincent Ladeuil
Change default for ``bzr.config.expand`` to True
474
    def get_user_option(self, option_name, expand=True):
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
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)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
493
        for hook in OldConfigHooks['get']:
5743.8.25 by Vincent Ladeuil
Fix spurious spaces.
494
            hook(self, option_name, value)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
495
        return value
496
5425.4.14 by Martin Pool
Allow get_user_option_as_bool to take a default
497
    def get_user_option_as_bool(self, option_name, expand=None, default=None):
498
        """Get a generic option as a boolean.
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
499
5425.4.14 by Martin Pool
Allow get_user_option_as_bool to take a default
500
        :param expand: Allow expanding references to other config values.
501
        :param default: Default value if nothing is configured
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
502
        :return None if the option doesn't exist or its value can't be
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
503
            interpreted as a boolean. Returns True or False otherwise.
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
504
        """
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
505
        s = self.get_user_option(option_name, expand=expand)
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
506
        if s is None:
507
            # The option doesn't exist
5425.4.14 by Martin Pool
Allow get_user_option_as_bool to take a default
508
            return default
4989.2.15 by Vincent Ladeuil
Fixed as per Andrew's review.
509
        val = ui.bool_from_string(s)
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
510
        if val is None:
511
            # The value can't be interpreted as a boolean
512
            trace.warning('Value "%s" is not a boolean for "%s"',
513
                          s, option_name)
514
        return val
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
515
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
516
    def get_user_option_as_list(self, option_name, expand=None):
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
517
        """Get a generic option as a list - no special process, no default.
518
519
        :return None if the option doesn't exist. Returns the value as a list
520
            otherwise.
521
        """
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
522
        l = self.get_user_option(option_name, expand=expand)
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
523
        if isinstance(l, string_types):
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
524
            # A single value, most probably the user forgot (or didn't care to
525
            # add) the final ','
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
526
            l = [l]
527
        return l
6371.1.1 by Jelmer Vernooij
Fix some whitespace in bzrlib.config.
528
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
529
    def _log_format(self):
530
        """See log_format()."""
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
531
        return None
532
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
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
541
542
    def _validate_signatures_in_log(self):
543
        """See validate_signatures_in_log()."""
544
        return None
545
1472 by Robert Collins
post commit hook, first pass implementation
546
    def _post_commit(self):
547
        """See Config.post_commit."""
548
        return None
549
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
550
    def user_email(self):
551
        """Return just the email component of a username."""
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
552
        return extract_email_address(self.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
553
554
    def username(self):
555
        """Return email-style username.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
556
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
557
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
558
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
559
        $BRZ_EMAIL can be set to override this, then
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
560
        the concrete policy type is checked, and finally
1185.37.2 by Jamie Wilkinson
Fix a typo and grammar in Config.username() docstring.
561
        $EMAIL is examined.
6737 by Jelmer Vernooij
Merge lp:~jelmer/brz/move-errors-config.
562
        If no username can be found, NoWhoami exception is raised.
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
563
        """
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
564
        v = os.environ.get('BRZ_EMAIL')
6684.1.3 by Martin
Changes across many modules working towards Python 3 support
565
        if v:
566
            if not PY3:
567
                v = v.decode(osutils.get_user_encoding())
568
            return v
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
569
        v = self._get_user_id()
6684.1.3 by Martin
Changes across many modules working towards Python 3 support
570
        if v:
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
571
            return v
7336.2.1 by Martin
Split non-ini config methods to bedding
572
        return bedding.default_email()
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
573
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
574
    def get_alias(self, value):
575
        return self._get_alias(value)
576
577
    def _get_alias(self, value):
578
        pass
579
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
580
    def get_nickname(self):
581
        return self._get_nickname()
582
583
    def _get_nickname(self):
584
        return None
585
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
586
    def get_bzr_remote_path(self):
587
        try:
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
588
            return os.environ['BZR_REMOTE_PATH']
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
589
        except KeyError:
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
590
            path = self.get_user_option("bzr_remote_path")
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
591
            if path is None:
592
                path = 'bzr'
593
            return path
594
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
595
    def suppress_warning(self, warning):
596
        """Should the warning be suppressed or emitted.
597
598
        :param warning: The name of the warning being tested.
599
600
        :returns: True if the warning should be suppressed, False otherwise.
601
        """
602
        warnings = self.get_user_option_as_list('suppress_warnings')
603
        if warnings is None or warning not in warnings:
604
            return False
605
        else:
606
            return True
607
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
608
    def get_merge_tools(self):
5321.1.108 by Gordon Tyler
Changed known merge tools into a default set of merge tools that are always defined but can be overridden by user-defined merge tools.
609
        tools = {}
5321.1.99 by Gordon Tyler
Fixes for changes to Config._get_options().
610
        for (oname, value, section, conf_id, parser) in self._get_options():
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
611
            if oname.startswith('bzr.mergetool.'):
612
                tool_name = oname[len('bzr.mergetool.'):]
6468.5.1 by Vincent Ladeuil
Change default for ``bzr.config.expand`` to True
613
                tools[tool_name] = self.get_user_option(oname, False)
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
614
        trace.mutter('loaded merge tools: %r' % tools)
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
615
        return tools
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
616
5321.1.103 by Gordon Tyler
Renamed _find_merge_tool back to find_merge_tool since it must be public for UI code to lookup merge tools by name, and added tests for it.
617
    def find_merge_tool(self, name):
5967.3.6 by Jonathan Riddell
use example.com for e-mails, make bzrlib/config.py pep8 happy
618
        # We fake a defaults mechanism here by checking if the given name can
5321.1.111 by Gordon Tyler
Remove predefined merge tools from list returned by get_merge_tools.
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.
6622.1.33 by Jelmer Vernooij
Fix more tests (all?)
622
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
7143.15.2 by Jelmer Vernooij
Run autopep8.
623
                                             expand=False) or
624
                        mergetools.known_merge_tools.get(name, None))
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
625
        return command_line
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
626
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
627
5743.8.10 by Vincent Ladeuil
We don't need (nor want) to tie the config hooks to a particular class. Especially when we want to use the same hooks on both implementations.
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
        """
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
638
        super(_ConfigHooks, self).__init__('breezy.config', 'ConfigHooks')
5743.8.10 by Vincent Ladeuil
We don't need (nor want) to tie the config hooks to a particular class. Especially when we want to use the same hooks on both implementations.
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))
7143.15.2 by Jelmer Vernooij
Run autopep8.
660
661
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
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
        """
7143.15.2 by Jelmer Vernooij
Run autopep8.
675
        super(_OldConfigHooks, self).__init__(
676
            'breezy.config', 'OldConfigHooks')
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
677
        self.add_hook('load',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
678
                      'Invoked when a config store is loaded.'
679
                      ' The signature is (config).',
680
                      (2, 4))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
681
        self.add_hook('save',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
682
                      'Invoked when a config store is saved.'
683
                      ' The signature is (config).',
684
                      (2, 4))
685
        # The hooks for config options
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
686
        self.add_hook('get',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
687
                      'Invoked when a config option is read.'
688
                      ' The signature is (config, name, value).',
689
                      (2, 4))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
690
        self.add_hook('set',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
691
                      'Invoked when a config option is set.'
692
                      ' The signature is (config, name, value).',
693
                      (2, 4))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
694
        self.add_hook('remove',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
695
                      'Invoked when a config option is removed.'
696
                      ' The signature is (config, name).',
697
                      (2, 4))
7143.15.2 by Jelmer Vernooij
Run autopep8.
698
699
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
700
OldConfigHooks = _OldConfigHooks()
5743.8.10 by Vincent Ladeuil
We don't need (nor want) to tie the config hooks to a particular class. Especially when we want to use the same hooks on both implementations.
701
702
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
703
class IniBasedConfig(Config):
704
    """A configuration policy that draws from ini files."""
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
705
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
706
    def __init__(self, file_name=None):
5345.2.5 by Vincent Ladeuil
Add docstring.
707
        """Base class for configuration files using an ini-like syntax.
708
709
        :param file_name: The configuration file path.
710
        """
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
711
        super(IniBasedConfig, self).__init__()
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
712
        self.file_name = file_name
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
713
        self.file_name = file_name
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
714
        self._content = None
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
715
        self._parser = None
716
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
717
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
718
    def from_string(cls, str_or_unicode, file_name=None, save=False):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
719
        """Create a config object from a string.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
720
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
721
        :param str_or_unicode: A string representing the file content. This
722
            will be utf-8 encoded.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
723
724
        :param file_name: The configuration file path.
725
726
        :param _save: Whether the file should be saved upon creation.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
727
        """
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
728
        conf = cls(file_name=file_name)
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
729
        conf._create_from_string(str_or_unicode, save)
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
730
        return conf
731
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
732
    def _create_from_string(self, str_or_unicode, save):
6973.10.4 by Jelmer Vernooij
Update python3.passing.
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)
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
736
        # Some tests use in-memory configs, some other always need the config
737
        # file to exist on disk.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
738
        if save:
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
739
            self._write_config_file()
5345.5.12 by Vincent Ladeuil
Fix fallouts from replacing '_content' by 'from_bytes' for config files.
740
6630.1.1 by Jelmer Vernooij
Remove deprecated functionality.
741
    def _get_parser(self):
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
742
        if self._parser is not None:
743
            return self._parser
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
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')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
748
        else:
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
749
            co_input = self.file_name
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
750
        try:
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
751
            self._parser = ConfigObj(co_input, encoding='utf-8')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
752
        except configobj.ConfigObjError as e:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
753
            raise ParseConfigError(e.errors, e.config.filename)
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
754
        except UnicodeDecodeError:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
755
            raise ConfigContentError(self.file_name)
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
756
        # Make sure self.reload() will use the right file name
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
757
        self._parser.filename = self.file_name
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
758
        for hook in OldConfigHooks['load']:
5743.8.12 by Vincent Ladeuil
Fire config hooks for the actual implementation even if these calls should be deleted in the end. This will help the transition by providing *some* measurements.
759
            hook(self)
1185.12.49 by Aaron Bentley
Switched to ConfigObj
760
        return self._parser
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
761
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
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()
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
768
        for hook in ConfigHooks['load']:
5743.8.12 by Vincent Ladeuil
Fire config hooks for the actual implementation even if these calls should be deleted in the end. This will help the transition by providing *some* measurements.
769
            hook(self)
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
770
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
771
    def _get_matching_sections(self):
772
        """Return an ordered list of (section_name, extra_path) pairs.
773
774
        If the section contains inherited configuration, extra_path is
775
        a string containing the additional path components.
776
        """
777
        section = self._get_section()
778
        if section is not None:
779
            return [(section, '')]
780
        else:
781
            return []
782
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
783
    def _get_section(self):
784
        """Override this to define the section used by the config."""
785
        return "DEFAULT"
786
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
787
    def _get_sections(self, name=None):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
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
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
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.
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
796
        """
797
        parser = self._get_parser()
798
        if name is not None:
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
799
            yield (name, parser[name], self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
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.
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
803
            yield (None, parser, self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
804
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
805
    def _get_options(self, sections=None):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
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.
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
811
812
        :param sections: Default to ``_get_matching_sections`` if not
813
            specified. This gives a better control to daughter classes about
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
814
            which sections should be searched. This is a list of (name,
815
            configobj) tuples.
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
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))
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
829
        config_id = self.config_id()
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
830
        for (section_name, section) in sections:
831
            for (name, value) in section.iteritems():
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
832
                yield (name, parser._quote(value), section_name,
833
                       config_id, parser)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
834
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
835
    def _get_option_policy(self, section, option_name):
836
        """Return the policy for the given (section, option_name) pair."""
837
        return POLICY_NONE
838
4603.1.10 by Aaron Bentley
Provide change editor via config.
839
    def _get_change_editor(self):
7358.6.1 by Jelmer Vernooij
Use standard syntax for the ``change_editor`` configuration option.
840
        return self.get_user_option('change_editor', expand=False)
4603.1.10 by Aaron Bentley
Provide change editor via config.
841
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
842
    def _get_signature_checking(self):
843
        """See Config._get_signature_checking."""
1474 by Robert Collins
Merge from Aaron Bentley.
844
        policy = self._get_user_option('check_signatures')
845
        if policy:
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
846
            return signature_policy_from_unicode(policy)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
847
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
848
    def _get_signing_policy(self):
1773.4.3 by Martin Pool
[merge] bzr.dev
849
        """See Config._get_signing_policy"""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
850
        policy = self._get_user_option('create_signatures')
851
        if policy:
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
852
            return signing_policy_from_unicode(policy)
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
853
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
854
    def _get_user_id(self):
855
        """Get the user id from the 'email' key in the current section."""
1474 by Robert Collins
Merge from Aaron Bentley.
856
        return self._get_user_option('email')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
857
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
858
    def _get_user_option(self, option_name):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
859
        """See Config._get_user_option."""
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
860
        for (section, extra_path) in self._get_matching_sections():
861
            try:
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
862
                value = self._get_parser().get_value(section, option_name)
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
863
            except KeyError:
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
864
                continue
865
            policy = self._get_option_policy(section, option_name)
866
            if policy == POLICY_NONE:
867
                return value
868
            elif policy == POLICY_NORECURSE:
869
                # norecurse items only apply to the exact path
870
                if extra_path:
871
                    continue
872
                else:
873
                    return value
874
            elif policy == POLICY_APPENDPATH:
2120.6.3 by James Henstridge
add some more tests for getting policy options, and behaviour of get_user_option in the presence of config policies
875
                if extra_path:
876
                    value = urlutils.join(value, extra_path)
877
                return value
2120.6.6 by James Henstridge
fix test_set_push_location test
878
            else:
879
                raise AssertionError('Unexpected config policy %r' % policy)
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
880
        else:
1993.3.1 by James Henstridge
first go at making location config lookup recursive
881
            return None
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
882
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
883
    def _log_format(self):
884
        """See Config.log_format."""
885
        return self._get_user_option('log_format')
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
886
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
887
    def _validate_signatures_in_log(self):
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
888
        """See Config.validate_signatures_in_log."""
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
889
        return self._get_user_option('validate_signatures_in_log')
890
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
891
    def _acceptable_keys(self):
892
        """See Config.acceptable_keys."""
893
        return self._get_user_option('acceptable_keys')
894
1472 by Robert Collins
post commit hook, first pass implementation
895
    def _post_commit(self):
896
        """See Config.post_commit."""
897
        return self._get_user_option('post_commit')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
898
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
899
    def _get_alias(self, value):
900
        try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
901
            return self._get_parser().get_value("ALIASES",
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
902
                                                value)
903
        except KeyError:
904
            pass
905
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
906
    def _get_nickname(self):
907
        return self.get_user_option('nickname')
908
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
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:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
926
            raise NoSuchConfigOption(option_name)
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
927
        self._write_config_file()
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
928
        for hook in OldConfigHooks['remove']:
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
929
            hook(self, option_name)
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
930
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
931
    def _write_config_file(self):
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
932
        if self.file_name is None:
933
            raise AssertionError('We cannot save, self.file_name is None')
5345.1.9 by Vincent Ladeuil
Refactor config dir check.
934
        conf_dir = os.path.dirname(self.file_name)
7336.2.1 by Martin
Split non-ini config methods to bedding
935
        bedding.ensure_config_dir_exists(conf_dir)
7067.12.1 by Jelmer Vernooij
Fix an ignore test. Make AtomicFile a contextmanager.
936
        with atomicfile.AtomicFile(self.file_name) as atomic_file:
937
            self._get_parser().write(atomic_file)
5345.3.3 by Vincent Ladeuil
Merge bzr.dev into deprecate-get-filename resolving conflicts
938
        osutils.copy_ownership_from_path(self.file_name)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
939
        for hook in OldConfigHooks['save']:
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
940
            hook(self)
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
941
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
942
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
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.
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
948
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
949
    Daughter classes should use the self.lock_write() decorator method when
950
    they upate a config (they call, directly or indirectly, the
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
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.
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
966
    """
967
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
968
    lock_name = 'lock'
969
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
970
    def __init__(self, file_name):
971
        super(LockableConfig, self).__init__(file_name=file_name)
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
972
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
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
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
978
        self.transport = transport.get_transport_from_path(self.dir)
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
979
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
980
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
981
    def _create_from_string(self, unicode_bytes, save):
982
        super(LockableConfig, self)._create_from_string(unicode_bytes, False)
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
983
        if save:
5345.1.24 by Vincent Ladeuil
Implement _save for LockableConfig too.
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()
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
989
990
    def lock_write(self, token=None):
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
991
        """Takes a write lock in the directory containing the config file.
992
993
        If the directory doesn't exist it is created.
994
        """
7336.2.1 by Martin
Split non-ini config methods to bedding
995
        bedding.ensure_config_dir_exists(self.dir)
6754.8.4 by Jelmer Vernooij
Use new context stuff.
996
        token = self._lock.lock_write(token)
997
        return lock.LogicalLockResult(self.unlock, token)
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
998
999
    def unlock(self):
1000
        self._lock.unlock()
1001
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
1002
    def break_lock(self):
1003
        self._lock.break_lock()
1004
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1005
    def remove_user_option(self, option_name, section_name=None):
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
1006
        with self.lock_write():
1007
            super(LockableConfig, self).remove_user_option(
7143.15.2 by Jelmer Vernooij
Run autopep8.
1008
                option_name, section_name)
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1009
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
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
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
1013
            # missing call to lock_write() by one of the callers.
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
1014
            raise errors.ObjectNotLocked(self)
1015
        super(LockableConfig, self)._write_config_file()
1016
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
1017
1018
class GlobalConfig(LockableConfig):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1019
    """The configuration that should be used for a specific location."""
1020
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1021
    def __init__(self):
7336.2.1 by Martin
Split non-ini config methods to bedding
1022
        super(GlobalConfig, self).__init__(file_name=bedding.config_path())
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
1023
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1024
    def config_id(self):
6741 by Jelmer Vernooij
Merge lp:~jelmer/brz/breezy-conf
1025
        return 'breezy'
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1026
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1027
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1028
    def from_string(cls, str_or_unicode, save=False):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
1029
        """Create a config object from a string.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1030
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
1031
        :param str_or_unicode: A string representing the file content. This
1032
            will be utf-8 encoded.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1033
1034
        :param save: Whether the file should be saved upon creation.
1035
        """
1036
        conf = cls()
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1037
        conf._create_from_string(str_or_unicode, save)
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1038
        return conf
5345.5.12 by Vincent Ladeuil
Fix fallouts from replacing '_content' by 'from_bytes' for config files.
1039
1816.2.1 by Robey Pointer
add set_user_option to GlobalConfig, and make /etc/passwd username lookup try harder with encodings
1040
    def set_user_option(self, option, value):
1041
        """Save option and its value in the configuration."""
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
1042
        with self.lock_write():
1043
            self._set_option(option, value, 'DEFAULT')
2900.3.2 by Tim Penhey
A working alias command.
1044
1045
    def get_aliases(self):
1046
        """Return the aliases section."""
1047
        if 'ALIASES' in self._get_parser():
1048
            return self._get_parser()['ALIASES']
1049
        else:
1050
            return {}
1051
1052
    def set_alias(self, alias_name, alias_command):
1053
        """Save the alias in the configuration."""
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
1054
        with self.lock_write():
1055
            self._set_option(alias_name, alias_command, 'ALIASES')
2900.3.2 by Tim Penhey
A working alias command.
1056
1057
    def unset_alias(self, alias_name):
1058
        """Unset an existing alias."""
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
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()
2900.3.2 by Tim Penhey
A working alias command.
1066
1067
    def _set_option(self, option, value, section):
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
1068
        self.reload()
2900.3.7 by Tim Penhey
Updates from Aaron's review.
1069
        self._get_parser().setdefault(section, {})[option] = value
2900.3.12 by Tim Penhey
Final review comments.
1070
        self._write_config_file()
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
1071
        for hook in OldConfigHooks['set']:
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
1072
            hook(self, option, value)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1073
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1074
    def _get_sections(self, name=None):
1075
        """See IniBasedConfig._get_sections()."""
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
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'
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1083
            if 'DEFAULT' not in parser:
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
1084
                parser['DEFAULT'] = {}
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1085
        yield (name, parser[name], self.config_id())
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
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'
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
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(
7143.15.2 by Jelmer Vernooij
Run autopep8.
1095
                option_name, section_name)
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
1096
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1097
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1098
def _iter_for_location_by_parts(sections, location):
5764.1.3 by Vincent Ladeuil
Add a doctrsing and address the location being split for all iterations by making letting the function iterate over all sections.
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
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
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.
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
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.
5764.1.3 by Vincent Ladeuil
Add a doctrsing and address the location being split for all iterations by making letting the function iterate over all sections.
1112
    """
5764.1.2 by Vincent Ladeuil
This put a common processing into the loop to avoid bad inputs. The
1113
    location_parts = location.rstrip('/').split('/')
1114
5764.1.3 by Vincent Ladeuil
Add a doctrsing and address the location being split for all iterations by making letting the function iterate over all sections.
1115
    for section in sections:
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
1116
        # location is a local path if possible, so we need to convert 'file://'
1117
        # urls in section names to local paths if necessary.
5764.1.3 by Vincent Ladeuil
Add a doctrsing and address the location being split for all iterations by making letting the function iterate over all sections.
1118
1119
        # This also avoids having file:///path be a more exact
1120
        # match than '/path'.
1121
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
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
5764.1.3 by Vincent Ladeuil
Add a doctrsing and address the location being split for all iterations by making letting the function iterate over all sections.
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.
6631.2.1 by Martin
Run 2to3 zip fixer and refactor
1138
            for name in zip(location_parts, section_parts):
5764.1.3 by Vincent Ladeuil
Add a doctrsing and address the location being split for all iterations by making letting the function iterate over all sections.
1139
                if not fnmatch.fnmatch(name[0], name[1]):
1140
                    matched = False
1141
                    break
1142
        if not matched:
1143
            continue
5764.1.1 by Vincent Ladeuil
Extract _match_section_by_parts from LocationConfig._get_matching_sections and more comments to explain the behavior.
1144
        # build the path difference between the section and the location
5764.1.3 by Vincent Ladeuil
Add a doctrsing and address the location being split for all iterations by making letting the function iterate over all sections.
1145
        extra_path = '/'.join(location_parts[len(section_parts):])
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1146
        yield section, extra_path, len(section_parts)
5764.1.1 by Vincent Ladeuil
Extract _match_section_by_parts from LocationConfig._get_matching_sections and more comments to explain the behavior.
1147
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1148
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
1149
class LocationConfig(LockableConfig):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1150
    """A configuration object that gives the policy for a location."""
1151
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1152
    def __init__(self, location):
5345.1.2 by Vincent Ladeuil
Get rid of 'branches.conf' references.
1153
        super(LocationConfig, self).__init__(
7336.2.1 by Martin
Split non-ini config methods to bedding
1154
            file_name=bedding.locations_config_path())
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1155
        # local file locations are looked up by local path, rather than
1156
        # by file url. This is because the config file is a user
1157
        # file, and we would rather not expose the user to file urls.
1158
        if location.startswith('file://'):
1159
            location = urlutils.local_path_from_url(location)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1160
        self.location = location
1161
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1162
    def config_id(self):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1163
        return 'locations'
1164
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1165
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1166
    def from_string(cls, str_or_unicode, location, save=False):
1167
        """Create a config object from a string.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1168
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1169
        :param str_or_unicode: A string representing the file content. This will
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1170
            be utf-8 encoded.
1171
1172
        :param location: The location url to filter the configuration.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1173
1174
        :param save: Whether the file should be saved upon creation.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1175
        """
1176
        conf = cls(location)
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1177
        conf._create_from_string(str_or_unicode, save)
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1178
        return conf
1179
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1180
    def _get_matching_sections(self):
1181
        """Return an ordered list of section names matching this location."""
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1182
        # put the longest (aka more specific) locations first
6621.20.1 by Martin
Run 2to3 tuple_params fixer and tidy up.
1183
        matches = sorted(
1184
            _iter_for_location_by_parts(self._get_parser(), self.location),
1185
            key=lambda match: (match[2], match[0]),
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1186
            reverse=True)
1187
        for (section, extra_path, length) in matches:
1188
            yield section, extra_path
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1189
            # should we stop looking for parent configs here?
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1190
            try:
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1191
                if self._get_parser()[section].as_bool('ignore_parents'):
1192
                    break
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1193
            except KeyError:
1194
                pass
1442.1.9 by Robert Collins
exact section test passes
1195
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1196
    def _get_sections(self, name=None):
1197
        """See IniBasedConfig._get_sections()."""
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
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():
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1202
            yield (name, parser[name], self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1203
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1204
    def _get_option_policy(self, section, option_name):
1205
        """Return the policy for the given (section, option_name) pair."""
1206
        # check for the old 'recurse=False' flag
1207
        try:
1208
            recurse = self._get_parser()[section].as_bool('recurse')
1209
        except KeyError:
1210
            recurse = True
1211
        if not recurse:
1212
            return POLICY_NORECURSE
1213
2120.6.10 by James Henstridge
Catch another deprecation warning, and more cleanup
1214
        policy_key = option_name + ':policy'
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1215
        try:
1216
            policy_name = self._get_parser()[section][policy_key]
1217
        except KeyError:
1218
            policy_name = None
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1219
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1220
        return _policy_value[policy_name]
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1221
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1222
    def _set_option_policy(self, section, option_name, option_policy):
1223
        """Set the policy for the given option name in the given section."""
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1224
        policy_key = option_name + ':policy'
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1225
        policy_name = _policy_name[option_policy]
1226
        if policy_name is not None:
1227
            self._get_parser()[section][policy_key] = policy_name
1228
        else:
1229
            if policy_key in self._get_parser()[section]:
1230
                del self._get_parser()[section][policy_key]
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1231
1232
    def set_user_option(self, option, value, store=STORE_LOCATION):
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1233
        """Save option and its value in the configuration."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1234
        if store not in [STORE_LOCATION,
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1235
                         STORE_LOCATION_NORECURSE,
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1236
                         STORE_LOCATION_APPENDPATH]:
1237
            raise ValueError('bad storage policy %r for %r' %
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
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)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1255
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1256
1257
class BranchConfig(Config):
1258
    """A configuration object giving the policy for a branch."""
1259
5345.1.3 by Vincent Ladeuil
Make __init__ the first method in the BranchConfig class.
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
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1270
    def config_id(self):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1271
        return 'branch'
1272
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1273
    def _get_branch_data_config(self):
1274
        if self._branch_data_config is None:
1275
            self._branch_data_config = TreeConfig(self.branch)
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1276
            self._branch_data_config.config_id = self.config_id
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1277
        return self._branch_data_config
1278
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1279
    def _get_location_config(self):
1280
        if self._location_config is None:
1281
            self._location_config = LocationConfig(self.branch.base)
1282
        return self._location_config
1283
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1284
    def _get_global_config(self):
1285
        if self._global_config is None:
1286
            self._global_config = GlobalConfig()
1287
        return self._global_config
1288
1289
    def _get_best_value(self, option_name):
1290
        """This returns a user option from local, tree or global config.
1291
1292
        They are tried in that order.  Use get_safe_value if trusted values
1293
        are necessary.
1294
        """
1295
        for source in self.option_sources:
1296
            value = getattr(source(), option_name)()
1297
            if value is not None:
1298
                return value
1299
        return None
1300
1301
    def _get_safe_value(self, option_name):
1302
        """This variant of get_best_value never returns untrusted values.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1303
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1304
        It does not return values from the branch data, because the branch may
1305
        not be controlled by the user.
1306
1307
        We may wish to allow locations.conf to control whether branches are
1308
        trusted in the future.
1309
        """
1310
        for source in (self._get_location_config, self._get_global_config):
1311
            value = getattr(source(), option_name)()
1312
            if value is not None:
1313
                return value
1314
        return None
1315
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1316
    def _get_user_id(self):
1317
        """Return the full user id for the branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1318
3407.2.14 by Martin Pool
Remove more cases of getting transport via control_files
1319
        e.g. "John Hacker <jhacker@example.com>"
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1320
        This is looked up in the email controlfile for the branch.
1321
        """
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1322
        return self._get_best_value('_get_user_id')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1323
4603.1.10 by Aaron Bentley
Provide change editor via config.
1324
    def _get_change_editor(self):
1325
        return self._get_best_value('_get_change_editor')
1326
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1327
    def _get_signature_checking(self):
1328
        """See Config._get_signature_checking."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1329
        return self._get_best_value('_get_signature_checking')
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1330
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1331
    def _get_signing_policy(self):
1332
        """See Config._get_signing_policy."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1333
        return self._get_best_value('_get_signing_policy')
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1334
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
1335
    def _get_user_option(self, option_name):
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
1336
        """See Config._get_user_option."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1337
        for source in self.option_sources:
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
1338
            value = source()._get_user_option(option_name)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1339
            if value is not None:
1340
                return value
1341
        return None
1342
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1343
    def _get_sections(self, name=None):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1344
        """See IniBasedConfig.get_sections()."""
1345
        for source in self.option_sources:
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1346
            for section in source()._get_sections(name):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1347
                yield section
1348
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1349
    def _get_options(self, sections=None):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1350
        # First the locations options
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1351
        for option in self._get_location_config()._get_options():
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1352
            yield option
1353
        # Then the branch options
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1354
        branch_config = self._get_branch_data_config()
1355
        if sections is None:
1356
            sections = [('DEFAULT', branch_config._get_parser())]
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1357
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
1358
        # Config itself has no notion of sections :( -- vila 20101001
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1359
        config_id = self.config_id()
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1360
        for (section_name, section) in sections:
1361
            for (name, value) in section.iteritems():
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1362
                yield (name, value, section_name,
1363
                       config_id, branch_config._get_parser())
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1364
        # Then the global options
5447.4.12 by Vincent Ladeuil
Turn get_options() and get_sections() into private methods because section handling is too messy and needs to be discussed and settled.
1365
        for option in self._get_global_config()._get_options():
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1366
            yield option
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1367
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1368
    def set_user_option(self, name, value, store=STORE_BRANCH,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1369
                        warn_masked=False):
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1370
        if store == STORE_BRANCH:
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1371
            self._get_branch_data_config().set_option(value, name)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1372
        elif store == STORE_GLOBAL:
2120.6.7 by James Henstridge
Fix GlobalConfig.set_user_option() call
1373
            self._get_global_config().set_user_option(name, value)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1374
        else:
1375
            self._get_location_config().set_user_option(name, value, store)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1376
        if not warn_masked:
1377
            return
1378
        if store in (STORE_GLOBAL, STORE_BRANCH):
1379
            mask_value = self._get_location_config().get_user_option(name)
1380
            if mask_value is not None:
1381
                trace.warning('Value "%s" is masked by "%s" from'
1382
                              ' locations.conf', value, mask_value)
1383
            else:
1384
                if store == STORE_GLOBAL:
1385
                    branch_config = self._get_branch_data_config()
1386
                    mask_value = branch_config.get_user_option(name)
1387
                    if mask_value is not None:
1388
                        trace.warning('Value "%s" is masked by "%s" from'
1551.15.37 by Aaron Bentley
Don't treat a format string as a normal string
1389
                                      ' branch.conf', value, mask_value)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1390
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1391
    def remove_user_option(self, option_name, section_name=None):
1392
        self._get_branch_data_config().remove_option(option_name, section_name)
1393
1472 by Robert Collins
post commit hook, first pass implementation
1394
    def _post_commit(self):
1395
        """See Config.post_commit."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1396
        return self._get_safe_value('_post_commit')
1472 by Robert Collins
post commit hook, first pass implementation
1397
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1398
    def _get_nickname(self):
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
1399
        value = self._get_explicit_nickname()
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1400
        if value is not None:
1401
            return value
6437.32.1 by Aaron Bentley
Use colocated branch names as nicknames.
1402
        if self.branch.name:
1403
            return self.branch.name
2120.5.2 by Alexander Belchenko
(jam) Fix for bug #66857
1404
        return urlutils.unescape(self.branch.base.split('/')[-2])
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1405
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
1406
    def has_explicit_nickname(self):
1407
        """Return true if a nickname has been explicitly assigned."""
1408
        return self._get_explicit_nickname() is not None
1409
1410
    def _get_explicit_nickname(self):
1411
        return self._get_best_value('_get_nickname')
1412
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
1413
    def _log_format(self):
1414
        """See Config.log_format."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1415
        return self._get_best_value('_log_format')
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1416
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
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
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
1421
    def _acceptable_keys(self):
1422
        """See Config.acceptable_keys."""
1423
        return self._get_best_value('_acceptable_keys')
1424
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
1425
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1426
def parse_username(username):
1427
    """Parse e-mail username and return a (name, address) tuple."""
1428
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1429
    if match is None:
1430
        return (username, '')
7336.2.1 by Martin
Split non-ini config methods to bedding
1431
    return (match.group(1), match.group(2))
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1432
1433
1185.16.52 by Martin Pool
- add extract_email_address
1434
def extract_email_address(e):
1435
    """Return just the address part of an email string.
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1436
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1437
    That is just the user@domain part, nothing else.
1185.16.52 by Martin Pool
- add extract_email_address
1438
    This part is required to contain only ascii characters.
1439
    If it can't be extracted, raises an error.
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1440
1185.16.52 by Martin Pool
- add extract_email_address
1441
    >>> extract_email_address('Jane Tester <jane@test.com>')
1442
    "jane@test.com"
1443
    """
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1444
    name, email = parse_username(e)
1445
    if not email:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
1446
        raise NoEmailInUsername(e)
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1447
    return email
1185.35.11 by Aaron Bentley
Added support for branch nicks
1448
1185.85.30 by John Arbash Meinel
Fixing 'bzr push' exposed that IniBasedConfig didn't handle unicode.
1449
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1450
class TreeConfig(IniBasedConfig):
1185.35.11 by Aaron Bentley
Added support for branch nicks
1451
    """Branch configuration data associated with its contents, not location"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1452
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1453
    # XXX: Really needs a better name, as this is not part of the tree!
1454
    # -- mbp 20080507
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
1455
1185.35.11 by Aaron Bentley
Added support for branch nicks
1456
    def __init__(self, branch):
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
1457
        self._config = branch._get_config()
1185.35.11 by Aaron Bentley
Added support for branch nicks
1458
        self.branch = branch
1459
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1460
    def _get_parser(self, file=None):
1461
        if file is not None:
1462
            return IniBasedConfig._get_parser(file)
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1463
        return self._config._get_configobj()
1185.35.11 by Aaron Bentley
Added support for branch nicks
1464
1465
    def get_option(self, name, section=None, default=None):
6754.8.4 by Jelmer Vernooij
Use new context stuff.
1466
        with self.branch.lock_read():
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1467
            return self._config.get_option(name, section, default)
1185.35.11 by Aaron Bentley
Added support for branch nicks
1468
1469
    def set_option(self, value, name, section=None):
1470
        """Set a per-branch configuration option"""
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1471
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
1472
        # higher levels providing the right lock -- vila 20101004
6754.8.4 by Jelmer Vernooij
Use new context stuff.
1473
        with self.branch.lock_write():
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1474
            self._config.set_option(value, name, section)
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1475
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
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
6754.8.4 by Jelmer Vernooij
Use new context stuff.
1479
        with self.branch.lock_write():
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1480
            self._config.remove_option(option_name, section_name)
1481
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1482
6695.4.1 by Jelmer Vernooij
Only print warning about authentication.conf permissions once.
1483
_authentication_config_permission_errors = set()
1484
1485
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1486
class AuthenticationConfig(object):
1487
    """The authentication configuration file based on a ini file.
1488
1489
    Implements the authentication.conf file described in
1490
    doc/developers/authentication-ring.txt.
1491
    """
1492
1493
    def __init__(self, _file=None):
7143.15.2 by Jelmer Vernooij
Run autopep8.
1494
        self._config = None  # The ConfigObj
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1495
        if _file is None:
7336.2.1 by Martin
Split non-ini config methods to bedding
1496
            self._input = self._filename = bedding.authentication_config_path()
4788.3.2 by Joke de Buhr
Emit warning message if an authentication.conf file hase insecure file permissions.
1497
            self._check_permissions()
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1498
        else:
2900.2.24 by Vincent Ladeuil
Review feedback.
1499
            # Tests can provide a string as _file
1500
            self._filename = None
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1501
            self._input = _file
1502
1503
    def _get_config(self):
1504
        if self._config is not None:
1505
            return self._config
1506
        try:
2900.2.22 by Vincent Ladeuil
Polishing.
1507
            # FIXME: Should we validate something here ? Includes: empty
1508
            # sections are useless, at least one of
1509
            # user/password/password_encoding should be defined, etc.
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1510
1511
            # Note: the encoding below declares that the file itself is utf-8
1512
            # encoded, but the values in the ConfigObj are always Unicode.
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1513
            self._config = ConfigObj(self._input, encoding='utf-8')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
1514
        except configobj.ConfigObjError as e:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
1515
            raise ParseConfigError(e.errors, e.config.filename)
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
1516
        except UnicodeError:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
1517
            raise ConfigContentError(self._filename)
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1518
        return self._config
1519
4788.3.2 by Joke de Buhr
Emit warning message if an authentication.conf file hase insecure file permissions.
1520
    def _check_permissions(self):
4788.3.3 by Joke de Buhr
Don't emit warning message if the option 'no_insecure_permissions_warning'
1521
        """Check permission of auth file are user read/write able only."""
6690.1.1 by Jelmer Vernooij
Create authentication.conf in a way that it is only readable to the user.
1522
        try:
1523
            st = os.stat(self._filename)
6690.1.3 by Jelmer Vernooij
Review comments.
1524
        except OSError as e:
1525
            if e.errno != errno.ENOENT:
1526
                trace.mutter('Unable to stat %r: %r', self._filename, e)
6690.1.1 by Jelmer Vernooij
Create authentication.conf in a way that it is only readable to the user.
1527
            return
1528
        mode = stat.S_IMODE(st.st_mode)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1529
        if ((stat.S_IXOTH | stat.S_IWOTH | stat.S_IROTH | stat.S_IXGRP
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1530
             | stat.S_IWGRP | stat.S_IRGRP) & mode):
6695.4.1 by Jelmer Vernooij
Only print warning about authentication.conf permissions once.
1531
            # Only warn once
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1532
            if (self._filename not in _authentication_config_permission_errors and
7143.15.2 by Jelmer Vernooij
Run autopep8.
1533
                not GlobalConfig().suppress_warning(
6695.4.1 by Jelmer Vernooij
Only print warning about authentication.conf permissions once.
1534
                    'insecure_permissions')):
6690.1.1 by Jelmer Vernooij
Create authentication.conf in a way that it is only readable to the user.
1535
                trace.warning("The file '%s' has insecure "
7143.15.2 by Jelmer Vernooij
Run autopep8.
1536
                              "file permissions. Saved passwords may be accessible "
1537
                              "by other users.", self._filename)
6695.4.1 by Jelmer Vernooij
Only print warning about authentication.conf permissions once.
1538
                _authentication_config_permission_errors.add(self._filename)
4788.3.2 by Joke de Buhr
Emit warning message if an authentication.conf file hase insecure file permissions.
1539
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1540
    def _save(self):
1541
        """Save the config file, only tests should use it for now."""
2900.2.26 by Vincent Ladeuil
Fix forgotten reference to _get_filename and duplicated code.
1542
        conf_dir = os.path.dirname(self._filename)
7336.2.1 by Martin
Split non-ini config methods to bedding
1543
        bedding.ensure_config_dir_exists(conf_dir)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1544
        fd = os.open(self._filename, os.O_RDWR | os.O_CREAT, 0o600)
4708.2.2 by Martin
Workingtree changes sitting around since November, more explict closing of files in bzrlib
1545
        try:
6690.1.2 by Jelmer Vernooij
Use os.fdopen.
1546
            f = os.fdopen(fd, 'wb')
1547
            self._get_config().write(f)
4708.2.2 by Martin
Workingtree changes sitting around since November, more explict closing of files in bzrlib
1548
        finally:
6690.1.2 by Jelmer Vernooij
Use os.fdopen.
1549
            f.close()
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1550
1551
    def _set_option(self, section_name, option_name, value):
1552
        """Set an authentication configuration option"""
1553
        conf = self._get_config()
1554
        section = conf.get(section_name)
1555
        if section is None:
1556
            conf[section] = {}
1557
            section = conf[section]
1558
        section[option_name] = value
1559
        self._save()
1560
5743.8.25 by Vincent Ladeuil
Fix spurious spaces.
1561
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1562
                        realm=None):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1563
        """Returns the matching credentials from authentication.conf file.
1564
1565
        :param scheme: protocol
1566
1567
        :param host: the server address
1568
1569
        :param port: the associated port (optional)
1570
1571
        :param user: login (optional)
1572
1573
        :param path: the absolute path on the server (optional)
6371.1.1 by Jelmer Vernooij
Fix some whitespace in bzrlib.config.
1574
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1575
        :param realm: the http authentication realm (optional)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1576
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1577
        :return: A dict containing the matching credentials or None.
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1578
           This includes:
1579
           - name: the section name of the credentials in the
1580
             authentication.conf file,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1581
           - user: can't be different from the provided user if any,
4107.1.7 by Jean-Francois Roy
No longer deleting the extra credentials keys in get_credentials.
1582
           - scheme: the server protocol,
1583
           - host: the server address,
1584
           - port: the server port (can be None),
1585
           - path: the absolute server path (can be None),
1586
           - realm: the http specific authentication realm (can be None),
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1587
           - password: the decoded password, could be None if the credential
1588
             defines only the user
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1589
           - verify_certificates: https specific, True if the server
1590
             certificate should be verified, False otherwise.
1591
        """
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1592
        credentials = None
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
1593
        for auth_def_name, auth_def in self._get_config().iteritems():
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
1594
            if not isinstance(auth_def, configobj.Section):
7143.15.2 by Jelmer Vernooij
Run autopep8.
1595
                raise ValueError("%s defined outside a section" %
1596
                                 auth_def_name)
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1597
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1598
            a_scheme, a_host, a_user, a_path = map(
1599
                auth_def.get, ['scheme', 'host', 'user', 'path'])
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1600
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1601
            try:
1602
                a_port = auth_def.as_int('port')
1603
            except KeyError:
1604
                a_port = None
2900.2.22 by Vincent Ladeuil
Polishing.
1605
            except ValueError:
1606
                raise ValueError("'port' not numeric in %s" % auth_def_name)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1607
            try:
1608
                a_verify_certificates = auth_def.as_bool('verify_certificates')
1609
            except KeyError:
1610
                a_verify_certificates = True
2900.2.22 by Vincent Ladeuil
Polishing.
1611
            except ValueError:
1612
                raise ValueError(
1613
                    "'verify_certificates' not boolean in %s" % auth_def_name)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1614
1615
            # Attempt matching
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1616
            if a_scheme is not None and scheme != a_scheme:
1617
                continue
1618
            if a_host is not None:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1619
                if not (host == a_host or
1620
                        (a_host.startswith('.') and host.endswith(a_host))):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1621
                    continue
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1622
            if a_port is not None and port != a_port:
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1623
                continue
7143.15.2 by Jelmer Vernooij
Run autopep8.
1624
            if (a_path is not None and path is not None and
1625
                    not path.startswith(a_path)):
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1626
                continue
7143.15.2 by Jelmer Vernooij
Run autopep8.
1627
            if (a_user is not None and user is not None and
1628
                    a_user != user):
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1629
                # Never contradict the caller about the user to be used
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1630
                continue
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1631
            if a_user is None:
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1632
                # Can't find a user
1633
                continue
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1634
            # Prepare a credentials dictionary with additional keys
1635
            # for the credential providers
2900.2.24 by Vincent Ladeuil
Review feedback.
1636
            credentials = dict(name=auth_def_name,
3418.4.2 by Vincent Ladeuil
Fix bug #199440 by taking into account that a section may not
1637
                               user=a_user,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1638
                               scheme=a_scheme,
1639
                               host=host,
1640
                               port=port,
1641
                               path=path,
1642
                               realm=realm,
3418.4.2 by Vincent Ladeuil
Fix bug #199440 by taking into account that a section may not
1643
                               password=auth_def.get('password', None),
2900.2.24 by Vincent Ladeuil
Review feedback.
1644
                               verify_certificates=a_verify_certificates)
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1645
            # Decode the password in the credentials (or get one)
2900.2.22 by Vincent Ladeuil
Polishing.
1646
            self.decode_password(credentials,
1647
                                 auth_def.get('password_encoding', None))
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1648
            if 'auth' in debug.debug_flags:
1649
                trace.mutter("Using authentication section: %r", auth_def_name)
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1650
            break
1651
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1652
        if credentials is None:
1653
            # No credentials were found in authentication.conf, try the fallback
1654
            # credentials stores.
1655
            credentials = credential_store_registry.get_fallback_credentials(
1656
                scheme, host, port, user, path, realm)
1657
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1658
        return credentials
1659
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1660
    def set_credentials(self, name, host, user, scheme=None, password=None,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1661
                        port=None, path=None, verify_certificates=None,
1662
                        realm=None):
3777.3.1 by Aaron Bentley
Update docs
1663
        """Set authentication credentials for a host.
1664
1665
        Any existing credentials with matching scheme, host, port and path
1666
        will be deleted, regardless of name.
1667
1668
        :param name: An arbitrary name to describe this set of credentials.
1669
        :param host: Name of the host that accepts these credentials.
1670
        :param user: The username portion of these credentials.
1671
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1672
            to.
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1673
        :param password: Password portion of these credentials.
3777.3.1 by Aaron Bentley
Update docs
1674
        :param port: The IP port on the host that these credentials apply to.
1675
        :param path: A filesystem path on the host that these credentials
1676
            apply to.
1677
        :param verify_certificates: On https, verify server certificates if
1678
            True.
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1679
        :param realm: The http authentication realm (optional).
3777.3.1 by Aaron Bentley
Update docs
1680
        """
3777.1.8 by Aaron Bentley
Commit work-in-progress
1681
        values = {'host': host, 'user': user}
1682
        if password is not None:
1683
            values['password'] = password
1684
        if scheme is not None:
1685
            values['scheme'] = scheme
1686
        if port is not None:
1687
            values['port'] = '%d' % port
1688
        if path is not None:
1689
            values['path'] = path
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1690
        if verify_certificates is not None:
1691
            values['verify_certificates'] = str(verify_certificates)
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1692
        if realm is not None:
1693
            values['realm'] = realm
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1694
        config = self._get_config()
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
1695
        for section, existing_values in config.iteritems():
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1696
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1697
                if existing_values.get(key) != values.get(key):
1698
                    break
1699
            else:
1700
                del config[section]
1701
        config.update({name: values})
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1702
        self._save()
3777.1.8 by Aaron Bentley
Commit work-in-progress
1703
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1704
    def get_user(self, scheme, host, port=None, realm=None, path=None,
4222.3.10 by Jelmer Vernooij
Avoid using the default username in the case of SMTP.
1705
                 prompt=None, ask=False, default=None):
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1706
        """Get a user from authentication file.
1707
1708
        :param scheme: protocol
1709
1710
        :param host: the server address
1711
1712
        :param port: the associated port (optional)
1713
1714
        :param realm: the realm sent by the server (optional)
1715
1716
        :param path: the absolute path on the server (optional)
1717
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1718
        :param ask: Ask the user if there is no explicitly configured username
4222.3.4 by Jelmer Vernooij
Default to getpass.getuser() in AuthenticationConfig.get_user(), but allow
1719
                    (optional)
1720
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1721
        :param default: The username returned if none is defined (optional).
1722
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1723
        :return: The found user.
1724
        """
2900.2.16 by Vincent Ladeuil
Make hhtp proxy aware of AuthenticationConfig (for password).
1725
        credentials = self.get_credentials(scheme, host, port, user=None,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1726
                                           path=path, realm=realm)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1727
        if credentials is not None:
1728
            user = credentials['user']
1729
        else:
1730
            user = None
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1731
        if user is None:
4222.3.4 by Jelmer Vernooij
Default to getpass.getuser() in AuthenticationConfig.get_user(), but allow
1732
            if ask:
1733
                if prompt is None:
1734
                    # Create a default prompt suitable for most cases
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
1735
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
4222.3.4 by Jelmer Vernooij
Default to getpass.getuser() in AuthenticationConfig.get_user(), but allow
1736
                # Special handling for optional fields in the prompt
1737
                if port is not None:
1738
                    prompt_host = '%s:%d' % (host, port)
1739
                else:
1740
                    prompt_host = host
1741
                user = ui.ui_factory.get_username(prompt, host=prompt_host)
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1742
            else:
4222.3.10 by Jelmer Vernooij
Avoid using the default username in the case of SMTP.
1743
                user = default
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1744
        return user
1745
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1746
    def get_password(self, scheme, host, user, port=None,
1747
                     realm=None, path=None, prompt=None):
1748
        """Get a password from authentication file or prompt the user for one.
1749
1750
        :param scheme: protocol
1751
1752
        :param host: the server address
1753
1754
        :param port: the associated port (optional)
1755
1756
        :param user: login
1757
1758
        :param realm: the realm sent by the server (optional)
1759
1760
        :param path: the absolute path on the server (optional)
1761
1762
        :return: The found password or the one entered by the user.
1763
        """
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1764
        credentials = self.get_credentials(scheme, host, port, user, path,
1765
                                           realm)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1766
        if credentials is not None:
1767
            password = credentials['password']
7260.1.2 by Jelmer Vernooij
Fix flake8 issues.
1768
            if password is not None and scheme == 'ssh':
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1769
                trace.warning('password ignored in section [%s],'
1770
                              ' use an ssh agent instead'
1771
                              % credentials['name'])
1772
                password = None
2900.2.16 by Vincent Ladeuil
Make hhtp proxy aware of AuthenticationConfig (for password).
1773
        else:
1774
            password = None
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1775
        # Prompt user only if we could't find a password
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1776
        if password is None:
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1777
            if prompt is None:
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1778
                # Create a default prompt suitable for most cases
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
1779
                prompt = (u'%s' %
1780
                          scheme.upper() + u' %(user)s@%(host)s password')
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1781
            # Special handling for optional fields in the prompt
1782
            if port is not None:
1783
                prompt_host = '%s:%d' % (host, port)
1784
            else:
1785
                prompt_host = host
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1786
            password = ui.ui_factory.get_password(prompt,
1787
                                                  host=prompt_host, user=user)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1788
        return password
1789
2900.2.22 by Vincent Ladeuil
Polishing.
1790
    def decode_password(self, credentials, encoding):
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1791
        try:
1792
            cs = credential_store_registry.get_credential_store(encoding)
1793
        except KeyError:
1794
            raise ValueError('%r is not a known password_encoding' % encoding)
1795
        credentials['password'] = cs.decode_password(credentials)
2900.2.22 by Vincent Ladeuil
Polishing.
1796
        return credentials
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1797
3242.3.17 by Aaron Bentley
Whitespace cleanup
1798
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1799
class CredentialStoreRegistry(registry.Registry):
1800
    """A class that registers credential stores.
1801
1802
    A credential store provides access to credentials via the password_encoding
1803
    field in authentication.conf sections.
1804
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
1805
    Except for stores provided by brz itself, most stores are expected to be
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1806
    provided by plugins that will therefore use
1807
    register_lazy(password_encoding, module_name, member_name, help=help,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1808
    fallback=fallback) to install themselves.
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1809
1810
    A fallback credential store is one that is queried if no credentials can be
1811
    found via authentication.conf.
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1812
    """
1813
1814
    def get_credential_store(self, encoding=None):
1815
        cs = self.get(encoding)
1816
        if callable(cs):
1817
            cs = cs()
1818
        return cs
1819
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1820
    def is_fallback(self, name):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1821
        """Check if the named credentials store should be used as fallback."""
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1822
        return self.get_info(name)
1823
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1824
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1825
                                 path=None, realm=None):
1826
        """Request credentials from all fallback credentials stores.
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1827
1828
        The first credentials store that can provide credentials wins.
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1829
        """
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1830
        credentials = None
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1831
        for name in self.keys():
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1832
            if not self.is_fallback(name):
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1833
                continue
1834
            cs = self.get_credential_store(name)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1835
            credentials = cs.get_credentials(scheme, host, port, user,
1836
                                             path, realm)
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1837
            if credentials is not None:
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1838
                # We found some credentials
1839
                break
1840
        return credentials
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1841
1842
    def register(self, key, obj, help=None, override_existing=False,
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1843
                 fallback=False):
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1844
        """Register a new object to a name.
1845
1846
        :param key: This is the key to use to request the object later.
1847
        :param obj: The object to register.
1848
        :param help: Help text for this entry. This may be a string or
1849
                a callable. If it is a callable, it should take two
1850
                parameters (registry, key): this registry and the key that
1851
                the help was registered under.
1852
        :param override_existing: Raise KeyErorr if False and something has
1853
                already been registered for that key. If True, ignore if there
1854
                is an existing key (always register the new value).
7195.5.1 by Martin
Fix remaining whitespace lint in codebase
1855
        :param fallback: Whether this credential store should be
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1856
                used as fallback.
1857
        """
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1858
        return super(CredentialStoreRegistry,
1859
                     self).register(key, obj, help, info=fallback,
1860
                                    override_existing=override_existing)
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1861
1862
    def register_lazy(self, key, module_name, member_name,
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1863
                      help=None, override_existing=False,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1864
                      fallback=False):
1865
        """Register a new credential store to be loaded on request.
1866
1867
        :param module_name: The python path to the module. Such as 'os.path'.
1868
        :param member_name: The member of the module to return.  If empty or
1869
                None, get() will return the module itself.
1870
        :param help: Help text for this entry. This may be a string or
1871
                a callable.
1872
        :param override_existing: If True, replace the existing object
1873
                with the new one. If False, if there is already something
1874
                registered with the same key, raise a KeyError
7195.5.1 by Martin
Fix remaining whitespace lint in codebase
1875
        :param fallback: Whether this credential store should be
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1876
                used as fallback.
1877
        """
1878
        return super(CredentialStoreRegistry, self).register_lazy(
1879
            key, module_name, member_name, help,
1880
            info=fallback, override_existing=override_existing)
1881
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1882
1883
credential_store_registry = CredentialStoreRegistry()
1884
1885
1886
class CredentialStore(object):
1887
    """An abstract class to implement storage for credentials"""
1888
1889
    def decode_password(self, credentials):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1890
        """Returns a clear text password for the provided credentials."""
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1891
        raise NotImplementedError(self.decode_password)
1892
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1893
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1894
                        realm=None):
1895
        """Return the matching credentials from this credential store.
1896
1897
        This method is only called on fallback credential stores.
1898
        """
1899
        raise NotImplementedError(self.get_credentials)
1900
1901
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1902
class PlainTextCredentialStore(CredentialStore):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1903
    __doc__ = """Plain text credential store for the authentication.conf file"""
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1904
1905
    def decode_password(self, credentials):
1906
        """See CredentialStore.decode_password."""
1907
        return credentials['password']
1908
1909
1910
credential_store_registry.register('plain', PlainTextCredentialStore,
1911
                                   help=PlainTextCredentialStore.__doc__)
1912
credential_store_registry.default_key = 'plain'
1913
5912.5.5 by Florian Dorn
re-added blanks
1914
5912.5.6 by Martin
Revert to implementation in config rather than a plugin
1915
class Base64CredentialStore(CredentialStore):
1916
    __doc__ = """Base64 credential store for the authentication.conf file"""
6561.2.1 by Vincent Ladeuil
Add a ``progress_bar`` config option.
1917
5912.5.6 by Martin
Revert to implementation in config rather than a plugin
1918
    def decode_password(self, credentials):
1919
        """See CredentialStore.decode_password."""
5912.5.7 by Martin
Minor cleanups and note about error case
1920
        # GZ 2012-07-28: Will raise binascii.Error if password is not base64,
1921
        #                should probably propogate as something more useful.
6973.10.4 by Jelmer Vernooij
Update python3.passing.
1922
        return base64.standard_b64decode(credentials['password'])
5912.5.6 by Martin
Revert to implementation in config rather than a plugin
1923
7143.15.2 by Jelmer Vernooij
Run autopep8.
1924
5912.5.6 by Martin
Revert to implementation in config rather than a plugin
1925
credential_store_registry.register('base64', Base64CredentialStore,
1926
                                   help=Base64CredentialStore.__doc__)
1927
1928
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1929
class BzrDirConfig(object):
1930
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1931
    def __init__(self, bzrdir):
1932
        self._bzrdir = bzrdir
1933
        self._config = bzrdir._get_config()
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1934
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1935
    def set_default_stack_on(self, value):
1936
        """Set the default stacking location.
1937
1938
        It may be set to a location, or None.
1939
6472.2.3 by Jelmer Vernooij
More control dir.
1940
        This policy affects all branches contained by this control dir, except
1941
        for those under repositories.
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1942
        """
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1943
        if self._config is None:
6561.2.1 by Vincent Ladeuil
Add a ``progress_bar`` config option.
1944
            raise errors.BzrError("Cannot set configuration in %s"
1945
                                  % self._bzrdir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1946
        if value is None:
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1947
            self._config.set_option('', 'default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1948
        else:
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1949
            self._config.set_option(value, 'default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1950
1951
    def get_default_stack_on(self):
1952
        """Return the default stacking location.
1953
1954
        This will either be a location, or None.
1955
6472.2.3 by Jelmer Vernooij
More control dir.
1956
        This policy affects all branches contained by this control dir, except
1957
        for those under repositories.
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1958
        """
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1959
        if self._config is None:
1960
            return None
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1961
        value = self._config.get_option('default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1962
        if value == '':
1963
            value = None
1964
        return value
1965
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1966
1967
class TransportConfig(object):
3242.1.5 by Aaron Bentley
Update per review comments
1968
    """A Config that reads/writes a config file on a Transport.
3242.1.4 by Aaron Bentley
Clean-up
1969
1970
    It is a low-level object that considers config data to be name/value pairs
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1971
    that may be associated with a section.  Assigning meaning to these values
1972
    is done at higher levels like TreeConfig.
3242.1.4 by Aaron Bentley
Clean-up
1973
    """
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1974
1975
    def __init__(self, transport, filename):
1976
        self._transport = transport
1977
        self._filename = filename
1978
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1979
    def get_option(self, name, section=None, default=None):
1980
        """Return the value associated with a named option.
1981
1982
        :param name: The name of the value
1983
        :param section: The section the option is in (if any)
1984
        :param default: The value to return if the value is not set
1985
        :return: The value or default value
1986
        """
1987
        configobj = self._get_configobj()
1988
        if section is None:
1989
            section_obj = configobj
1990
        else:
1991
            try:
1992
                section_obj = configobj[section]
1993
            except KeyError:
1994
                return default
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
1995
        value = section_obj.get(name, default)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
1996
        for hook in OldConfigHooks['get']:
5743.8.25 by Vincent Ladeuil
Fix spurious spaces.
1997
            hook(self, name, value)
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
1998
        return value
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1999
2000
    def set_option(self, value, name, section=None):
2001
        """Set the value associated with a named option.
2002
2003
        :param value: The value to set
2004
        :param name: The name of the value to set
2005
        :param section: The section the option is in (if any)
2006
        """
2007
        configobj = self._get_configobj()
2008
        if section is None:
2009
            configobj[name] = value
2010
        else:
2011
            configobj.setdefault(section, {})[name] = value
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2012
        for hook in OldConfigHooks['set']:
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
2013
            hook(self, name, value)
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2014
        self._set_configobj(configobj)
2015
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
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]
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2022
        for hook in OldConfigHooks['remove']:
5743.8.15 by Vincent Ladeuil
Add tests for old config hooks covering bazaar.conf, locations.conf and branch.conf.
2023
            hook(self, option_name)
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
2024
        self._set_configobj(configobj)
2025
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
2026
    def _get_config_file(self):
2027
        try:
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2028
            f = BytesIO(self._transport.get_bytes(self._filename))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2029
            for hook in OldConfigHooks['load']:
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
2030
                hook(self)
2031
            return f
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
2032
        except errors.NoSuchFile:
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2033
            return BytesIO()
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
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"))
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2041
            return BytesIO()
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
2042
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
2043
    def _external_url(self):
2044
        return urlutils.join(self._transport.external_url(), self._filename)
2045
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2046
    def _get_configobj(self):
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
2047
        f = self._get_config_file()
2048
        try:
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
2049
            try:
2050
                conf = ConfigObj(f, encoding='utf-8')
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
2051
            except configobj.ConfigObjError as e:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
2052
                raise ParseConfigError(e.errors, self._external_url())
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
2053
            except UnicodeDecodeError:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
2054
                raise ConfigContentError(self._external_url())
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
2055
        finally:
2056
            f.close()
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
2057
        return conf
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2058
2059
    def _set_configobj(self, configobj):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
2060
        out_file = BytesIO()
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2061
        configobj.write(out_file)
2062
        out_file.seek(0)
2063
        self._transport.put_file(self._filename, out_file)
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2064
        for hook in OldConfigHooks['save']:
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
2065
            hook(self)
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2066
2067
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2068
class Option(object):
5743.12.10 by Vincent Ladeuil
Add documentation.
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
6059.1.4 by Vincent Ladeuil
Add a doc string for the Option constructor.
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.
5743.12.10 by Vincent Ladeuil
Add documentation.
2076
    """
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2077
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
2078
    def __init__(self, name, override_from_env=None,
2079
                 default=None, default_from_env=None,
6393.3.2 by Vincent Ladeuil
Merge trunk resolving conflicts
2080
                 help=None, from_unicode=None, invalid=None, unquote=True):
6059.1.4 by Vincent Ladeuil
Add a doc string for the Option constructor.
2081
        """Build an option definition.
2082
2083
        :param name: the name used to refer to the option.
2084
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
2085
        :param override_from_env: A list of environment variables which can
2086
           provide override any configuration setting.
2087
6059.1.4 by Vincent Ladeuil
Add a doc string for the Option constructor.
2088
        :param default: the default value to use when none exist in the config
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
2089
            stores. This is either a string that ``from_unicode`` will convert
6349.3.1 by Vincent Ladeuil
Allow config option default value to be a python callable
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).
6059.1.4 by Vincent Ladeuil
Add a doc string for the Option constructor.
2094
6082.2.1 by Vincent Ladeuil
Implement default values from environment for config options
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
6059.1.4 by Vincent Ladeuil
Add a doc string for the Option constructor.
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
6586.1.1 by Vincent Ladeuil
Fix various typos in docstrings. Rename 'buffer' to 'buf' since it's now a python builtin function.
2102
            representing the option value in a store or its default value.
6059.1.5 by Vincent Ladeuil
Handle invalid config option values.
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
6059.1.7 by Vincent Ladeuil
Catch TypeError when a list value is encountered while attempting to
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).
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
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.
6059.1.4 by Vincent Ladeuil
Add a doc string for the Option constructor.
2115
        """
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
2116
        if override_from_env is None:
2117
            override_from_env = []
6082.2.1 by Vincent Ladeuil
Implement default values from environment for config options
2118
        if default_from_env is None:
2119
            default_from_env = []
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2120
        self.name = name
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
2121
        self.override_from_env = override_from_env
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
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','
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
2132
        elif isinstance(default, (binary_type, text_type, bool, int, float)):
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
2133
            # Rely on python to convert strings, booleans and integers
2134
            self.default = u'%s' % (default,)
6351.3.3 by Jelmer Vernooij
Convert more stuff to use config stacks.
2135
        elif callable(default):
2136
            self.default = default
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
2137
        else:
2138
            # other python objects are not expected
2139
            raise AssertionError('%r is not supported as a default value'
2140
                                 % (default,))
6082.2.1 by Vincent Ladeuil
Implement default values from environment for config options
2141
        self.default_from_env = default_from_env
6449.2.2 by Jelmer Vernooij
Moar tests.
2142
        self._help = help
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
2143
        self.from_unicode = from_unicode
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
2144
        self.unquote = unquote
6059.1.5 by Vincent Ladeuil
Handle invalid config option values.
2145
        if invalid and invalid not in ('warning', 'error'):
2146
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2147
        self.invalid = invalid
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
2148
6449.2.2 by Jelmer Vernooij
Moar tests.
2149
    @property
2150
    def help(self):
2151
        return self._help
2152
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
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)
6091.3.1 by Vincent Ladeuil
Add convert_from_unicode to Option and rewrite the tests to need only an
2156
        if self.from_unicode is None or unicode_value is None:
6091.3.3 by Vincent Ladeuil
Update registered option default values and also convert the default value if the first conversion fails.
2157
            # Don't convert or nothing to convert
6091.3.1 by Vincent Ladeuil
Add convert_from_unicode to Option and rewrite the tests to need only an
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':
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
2170
                raise ConfigOptionValueError(self.name, unicode_value)
6091.3.1 by Vincent Ladeuil
Add convert_from_unicode to Option and rewrite the tests to need only an
2171
        return converted
2172
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
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
6973.13.3 by Jelmer Vernooij
Review feedback.
2178
                value = os.environ[var]
2179
                if not PY3:
2180
                    value = value.decode(osutils.get_user_encoding())
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
2181
                break
2182
            except KeyError:
2183
                continue
2184
        return value
2185
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
2186
    def get_default(self):
6091.3.4 by Vincent Ladeuil
Clarify get_default.
2187
        value = None
6082.2.1 by Vincent Ladeuil
Implement default values from environment for config options
2188
        for var in self.default_from_env:
2189
            try:
6091.3.4 by Vincent Ladeuil
Clarify get_default.
2190
                # If the env variable is defined, its value is the default one
6695.1.1 by Martin
Make ui package pass tests on Python 3
2191
                value = os.environ[var]
2192
                if not PY3:
2193
                    value = value.decode(osutils.get_user_encoding())
6091.3.4 by Vincent Ladeuil
Clarify get_default.
2194
                break
6082.2.1 by Vincent Ladeuil
Implement default values from environment for config options
2195
            except KeyError:
2196
                continue
6091.3.4 by Vincent Ladeuil
Clarify get_default.
2197
        if value is None:
2198
            # Otherwise, fallback to the value defined at registration
6351.3.3 by Jelmer Vernooij
Convert more stuff to use config stacks.
2199
            if callable(self.default):
2200
                value = self.default()
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
2201
                if not isinstance(value, text_type):
6349.3.1 by Vincent Ladeuil
Allow config option default value to be a python callable
2202
                    raise AssertionError(
6523.1.1 by Vincent Ladeuil
Fix some test issues raised by mgz.
2203
                        "Callable default value for '%s' should be unicode"
2204
                        % (self.name))
6351.3.3 by Jelmer Vernooij
Convert more stuff to use config stacks.
2205
            else:
2206
                value = self.default
6091.3.4 by Vincent Ladeuil
Clarify get_default.
2207
        return value
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
2208
6437.42.1 by Jelmer Vernooij
Make sure help options can provide their own help topic.
2209
    def get_help_topic(self):
2210
        return self.name
2211
6059.3.1 by Vincent Ladeuil
Provide per-config option help
2212
    def get_help_text(self, additional_see_also=None, plain=True):
2213
        result = self.help
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2214
        from breezy import help_topics
6059.3.1 by Vincent Ladeuil
Provide per-config option help
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
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2220
6059.1.2 by Vincent Ladeuil
Define a proper converter to avoid lazy import issues.
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
6015.25.1 by Vincent Ladeuil
Minimal backport to fix fdatasync options handling
2226
6059.1.6 by Vincent Ladeuil
Implement integer config options.
2227
def int_from_store(unicode_str):
2228
    return int(unicode_str)
2229
2230
6385.1.7 by Vincent Ladeuil
Feedback from review and minor tweaks.
2231
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
6378.1.1 by Vincent Ladeuil
Add int_SI_from_store as a config option helper
2232
7143.15.2 by Jelmer Vernooij
Run autopep8.
2233
6378.1.1 by Vincent Ladeuil
Add int_SI_from_store as a config option helper
2234
def int_SI_from_store(unicode_str):
6378.1.2 by Vincent Ladeuil
Migrate add.maximum_file_size to the new config scheme
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
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2241
    :return Integer, expanded to its base-10 value if a proper SI unit is
6378.1.2 by Vincent Ladeuil
Migrate add.maximum_file_size to the new config scheme
2242
        found, None otherwise.
2243
    """
6797 by Jelmer Vernooij
Merge lp:~jelmer/brz/fix-imports.
2244
    regexp = "^(\\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
6378.1.1 by Vincent Ladeuil
Add int_SI_from_store as a config option helper
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:
6385.1.7 by Vincent Ladeuil
Feedback from review and minor tweaks.
2253
                coeff = _unit_suffixes[unit.upper()]
6378.1.1 by Vincent Ladeuil
Add int_SI_from_store as a config option helper
2254
            except KeyError:
7143.15.2 by Jelmer Vernooij
Run autopep8.
2255
                raise ValueError(
2256
                    gettext('{0} is not an SI unit.').format(unit))
6378.1.1 by Vincent Ladeuil
Add int_SI_from_store as a config option helper
2257
            val *= coeff
2258
    return val
2259
2260
6133.4.35 by John Arbash Meinel
Change int_from_store into float_from_store, which allows us to set the time under 1.0s.
2261
def float_from_store(unicode_str):
2262
    return float(unicode_str)
2263
2264
6561.2.1 by Vincent Ladeuil
Add a ``progress_bar`` config option.
2265
# Use an empty dict to initialize an empty configobj avoiding all parsing and
2266
# encoding checks
6082.5.15 by Vincent Ladeuil
Use explicit kwargs for the list converter.
2267
_list_converter_config = configobj.ConfigObj(
2268
    {}, encoding='utf-8', list_values=True, interpolation=False)
2269
6082.5.14 by Vincent Ladeuil
Create a single configobj for list conversions and just reset() it when needed.
2270
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
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
6385.1.7 by Vincent Ladeuil
Feedback from review and minor tweaks.
2285
    def from_unicode(self, unicode_str):
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
2286
        if not isinstance(unicode_str, string_types):
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
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()
6385.1.7 by Vincent Ladeuil
Feedback from review and minor tweaks.
2292
        _list_converter_config._parse([u"list=%s" % (unicode_str,)])
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
2293
        maybe_list = _list_converter_config['list']
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
2294
        if isinstance(maybe_list, string_types):
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
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 = []
6059.2.1 by Vincent Ladeuil
Implement list config options.
2302
        else:
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
2303
            # We rely on ConfigObj providing us with a list already
2304
            l = maybe_list
2305
        return l
6059.2.1 by Vincent Ladeuil
Implement list config options.
2306
2307
6449.2.1 by Jelmer Vernooij
Add bzrlib.config.RegistryOption.
2308
class RegistryOption(Option):
2309
    """Option for a choice from a registry."""
2310
6449.3.1 by Jelmer Vernooij
convert bzr.transform.orphan_policy over to using config stacks.
2311
    def __init__(self, name, registry, default_from_env=None,
6449.2.1 by Jelmer Vernooij
Add bzrlib.config.RegistryOption.
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__(
6973.11.8 by Jelmer Vernooij
Merge python3-i.
2319
            name, default=lambda: registry.default_key,
6449.3.1 by Jelmer Vernooij
convert bzr.transform.orphan_policy over to using config stacks.
2320
            default_from_env=default_from_env,
6449.2.2 by Jelmer Vernooij
Moar tests.
2321
            from_unicode=self.from_unicode, help=help,
6449.2.1 by Jelmer Vernooij
Add bzrlib.config.RegistryOption.
2322
            invalid=invalid, unquote=False)
2323
        self.registry = registry
2324
2325
    def from_unicode(self, unicode_str):
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
2326
        if not isinstance(unicode_str, string_types):
6449.2.1 by Jelmer Vernooij
Add bzrlib.config.RegistryOption.
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,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2334
                                                             self.name))
6449.2.1 by Jelmer Vernooij
Add bzrlib.config.RegistryOption.
2335
6449.2.2 by Jelmer Vernooij
Moar tests.
2336
    @property
2337
    def help(self):
2338
        ret = [self._help, "\n\nThe following values are supported:\n"]
6449.2.1 by Jelmer Vernooij
Add bzrlib.config.RegistryOption.
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
6797 by Jelmer Vernooij
Merge lp:~jelmer/brz/fix-imports.
2344
_option_ref_re = lazy_regex.lazy_compile('({[^\\d\\W](?:\\.\\w|-\\w|\\w)*})')
6587.2.2 by Vincent Ladeuil
Stricter checks on configuration option names
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
7143.15.2 by Jelmer Vernooij
Run autopep8.
2353
6587.2.2 by Vincent Ladeuil
Stricter checks on configuration option names
2354
def iter_option_refs(string):
2355
    # Split isolate refs so every other chunk is a ref
2356
    is_ref = False
7143.15.2 by Jelmer Vernooij
Run autopep8.
2357
    for chunk in _option_ref_re.split(string):
6587.2.2 by Vincent Ladeuil
Stricter checks on configuration option names
2358
        yield is_ref, chunk
2359
        is_ref = not is_ref
2360
2361
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2362
class OptionRegistry(registry.Registry):
2363
    """Register config options by their name.
2364
2365
    This overrides ``registry.Registry`` to simplify registration by acquiring
6056.2.5 by Vincent Ladeuil
Fix typos caught by jelmer.
2366
    some information from the option object itself.
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2367
    """
2368
6587.2.2 by Vincent Ladeuil
Stricter checks on configuration option names
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:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
2375
            raise IllegalOptionName(option_name)
6587.2.2 by Vincent Ladeuil
Stricter checks on configuration option names
2376
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
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
        """
6587.2.2 by Vincent Ladeuil
Stricter checks on configuration option names
2382
        self._check_option_name(option.name)
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
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
6059.3.1 by Vincent Ladeuil
Provide per-config option help
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
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2394
        :param member_name: the member of the module to return.  If empty or
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2395
                None, get() will return the module itself.
2396
        """
6587.2.2 by Vincent Ladeuil
Stricter checks on configuration option names
2397
        self._check_option_name(key)
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
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()
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2411
5743.12.3 by Vincent Ladeuil
More basic tests for options. Start tests for all registered options.
2412
6056.2.1 by Vincent Ladeuil
Migrate output_encoding.
2413
# Registered options in lexicographical order
2414
2415
option_registry.register(
6372.4.1 by Jelmer Vernooij
Convert 'append_revisions_only' over to config stacks.
2416
    Option('append_revisions_only',
6372.4.2 by Jelmer Vernooij
Fix remaining tests.
2417
           default=None, from_unicode=bool_from_store, invalid='warning',
6372.4.1 by Jelmer Vernooij
Convert 'append_revisions_only' over to config stacks.
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(
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
2425
    ListOption('acceptable_keys',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2426
               default=None,
2427
               help="""\
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
2428
List of GPG key patterns which are acceptable for verification.
2429
"""))
2430
option_registry.register(
6378.1.2 by Vincent Ladeuil
Migrate add.maximum_file_size to the new config scheme
2431
    Option('add.maximum_file_size',
2432
           default=u'20MB', from_unicode=int_SI_from_store,
6378.1.3 by Vincent Ladeuil
log_format has been migrated but the old config method needs to be deprecated.
2433
           help="""\
2434
Size above which files should be added manually.
6378.1.2 by Vincent Ladeuil
Migrate add.maximum_file_size to the new config scheme
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(
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
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(
7143.15.2 by Jelmer Vernooij
Run autopep8.
2463
    Option('branch.fetch_tags', default=False, from_unicode=bool_from_store,
6404.1.1 by Vincent Ladeuil
Migrate branch.fetch_tags
2464
           help="""\
2465
Whether revisions associated with tags should be fetched.
2466
"""))
6449.6.7 by Jelmer Vernooij
Fix tests.
2467
option_registry.register_lazy(
6883.13.1 by Jelmer Vernooij
Rename bzr.transform.orphan_policy -> transform.orphan_policy.
2468
    'transform.orphan_policy', 'breezy.transform', 'opt_transform_orphan')
6404.1.1 by Vincent Ladeuil
Migrate branch.fetch_tags
2469
option_registry.register(
6082.5.9 by Vincent Ladeuil
Cleanup criss-cross merge confusion
2470
    Option('bzr.workingtree.worth_saving_limit', default=10,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2471
           from_unicode=int_from_store, invalid='warning',
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
2472
           help='''\
2473
How many changes before saving the dirstate.
2474
6059.4.6 by Vincent Ladeuil
Fix the help strings as proposed by jam.
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.
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
2480
'''))
2481
option_registry.register(
6463.1.1 by Jelmer Vernooij
Migrate 'bugtracker' setting to config stacks.
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(
7339.1.3 by Jelmer Vernooij
Support calculate_revnos option.
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(
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
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(
6421.3.1 by Vincent Ladeuil
Migrate more branch options to config stacks.
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(
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
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(
6082.5.9 by Vincent Ladeuil
Cleanup criss-cross merge confusion
2530
    Option('dirstate.fdatasync', default=True,
6059.4.4 by Vincent Ladeuil
Migrate bzr.workingtree.worth_saving_limit to stack-based config.
2531
           from_unicode=bool_from_store,
6059.3.1 by Vincent Ladeuil
Provide per-config option help
2532
           help='''\
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
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(
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
2540
    ListOption('debug_flags', default=[],
7143.15.2 by Jelmer Vernooij
Run autopep8.
2541
               help='Debug flags to activate.'))
6059.4.5 by Vincent Ladeuil
Migrate debug_flags to stack-based config.
2542
option_registry.register(
6082.5.9 by Vincent Ladeuil
Cleanup criss-cross merge confusion
2543
    Option('default_format', default='2a',
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
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.'))
6351.3.3 by Jelmer Vernooij
Convert more stuff to use config stacks.
2548
option_registry.register(
7336.2.1 by Martin
Split non-ini config methods to bedding
2549
    Option('email', override_from_env=['BRZ_EMAIL'],
2550
           default=bedding.default_email, help='The users identity'))
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2551
option_registry.register(
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
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
"""))
6351.3.1 by Jelmer Vernooij
Add gpg_signing_command option to registry.
2559
option_registry.register(
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2560
    Option('language',
2561
           help='Language to translate messages into.'))
2562
option_registry.register(
7358.7.1 by Jelmer Vernooij
Enable locks.steal_dead by default.
2563
    Option('locks.steal_dead', default=True, from_unicode=bool_from_store,
6059.4.1 by Vincent Ladeuil
Migrate locks.steal_dead to stack-based config.
2564
           help='''\
2565
Steal locks that appears to be dead.
2566
6059.4.6 by Vincent Ladeuil
Fix the help strings as proposed by jam.
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.
6059.4.1 by Vincent Ladeuil
Migrate locks.steal_dead to stack-based config.
2573
'''))
2574
option_registry.register(
6175.2.1 by Vincent Ladeuil
Migrate log_format to the config stacks.
2575
    Option('log_format', default='long',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2576
           help='''\
6175.2.1 by Vincent Ladeuil
Migrate log_format to the config stacks.
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
'''))
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2582
option_registry.register_lazy('mail_client', 'breezy.mail_client',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2583
                              'opt_mail_client')
6175.2.1 by Vincent Ladeuil
Migrate log_format to the config stacks.
2584
option_registry.register(
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2585
    Option('output_encoding',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2586
           help='Unicode encoding for output'
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
2587
           ' (terminal encoding if not specified).'))
2588
option_registry.register(
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
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(
6351.3.5 by Jelmer Vernooij
Add post_commit.
2598
    Option('post_commit', default=None,
2599
           help='''\
2600
Post commit functions.
2601
6351.3.14 by Jelmer Vernooij
merge lp:~jelmer/bzr/commit-uses-config-stacks
2602
An ordered list of python functions to call, separated by spaces.
6351.3.5 by Jelmer Vernooij
Add post_commit.
2603
2604
Each function takes branch, rev_id as parameters.
2605
'''))
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2606
option_registry.register_lazy('progress_bar', 'breezy.ui.text',
6561.2.1 by Vincent Ladeuil
Add a ``progress_bar`` config option.
2607
                              'opt_progress_bar')
6351.3.5 by Jelmer Vernooij
Add post_commit.
2608
option_registry.register(
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
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(
6155.2.1 by Vincent Ladeuil
Migrate dpush_strict, push_strict and send_strict options to the stack based config design, introducing get_config_stack for branches.
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(
6091.3.6 by Vincent Ladeuil
Replace ugly default value declarations with ad-hoc and limited conversion to unicode strings.
2635
    Option('repository.fdatasync', default=True,
6091.3.5 by Vincent Ladeuil
Use unicode strings to make it clear default values must comply to Store API.
2636
           from_unicode=bool_from_store,
6056.2.4 by Vincent Ladeuil
Option help is now part of the object itself.
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
'''))
6379.8.1 by Jelmer Vernooij
Register smtp options in bzrlib.config, and use config stacks in bzrlib.smtp_conection.
2644
option_registry.register_lazy('smtp_server',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2645
                              'breezy.smtp_connection', 'smtp_server')
6379.8.1 by Jelmer Vernooij
Register smtp options in bzrlib.config, and use config stacks in bzrlib.smtp_conection.
2646
option_registry.register_lazy('smtp_password',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2647
                              'breezy.smtp_connection', 'smtp_password')
6379.8.1 by Jelmer Vernooij
Register smtp options in bzrlib.config, and use config stacks in bzrlib.smtp_conection.
2648
option_registry.register_lazy('smtp_username',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2649
                              'breezy.smtp_connection', 'smtp_username')
6319.1.1 by Martin Pool
Add selftest.timeout option, defaulting to 600
2650
option_registry.register(
2651
    Option('selftest.timeout',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2652
           default='600',
2653
           from_unicode=int_from_store,
2654
           help='Abort selftest if one test takes longer than this many seconds',
2655
           ))
6319.1.1 by Martin Pool
Add selftest.timeout option, defaulting to 600
2656
6155.2.1 by Vincent Ladeuil
Migrate dpush_strict, push_strict and send_strict options to the stack based config design, introducing get_config_stack for branches.
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
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
2664
uncommitted changes before sending a bundle.
6155.2.1 by Vincent Ladeuil
Migrate dpush_strict, push_strict and send_strict options to the stack based config design, introducing get_config_stack for branches.
2665
'''))
6006.4.9 by Martin Pool
Add repository.fdatasync option
2666
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
2667
option_registry.register(
2668
    Option('serve.client_timeout',
6133.4.35 by John Arbash Meinel
Change int_from_store into float_from_store, which allows us to set the time under 1.0s.
2669
           default=300.0, from_unicode=float_from_store,
6133.4.15 by John Arbash Meinel
Start working on exposing timeout as a configuration item.
2670
           help="If we wait for a new request from a client for more than"
2671
                " X seconds, consider the client idle, and hangup."))
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
2672
option_registry.register(
7358.9.1 by Jelmer Vernooij
Allow setting the ssh vendor in configuration.
2673
    Option('ssh',
2674
           default=None, override_from_env=['BRZ_SSH'],
2675
           help='SSH vendor to use.'))
2676
option_registry.register(
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
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
"""))
6421.3.1 by Vincent Ladeuil
Migrate more branch options to config stacks.
2689
option_registry.register(
2690
    Option('submit_to',
2691
           help='''Where submissions from this branch are mailed to.'''))
6449.1.1 by Jelmer Vernooij
Convert 'suppress_warnings' option to config stacks.
2692
option_registry.register(
2693
    ListOption('suppress_warnings',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2694
               default=[],
2695
               help="List of warning classes to suppress."))
6455.1.1 by Jelmer Vernooij
Convert validate_signatures_in_log to config stacks.
2696
option_registry.register(
2697
    Option('validate_signatures_in_log', default=False,
2698
           from_unicode=bool_from_store, invalid='warning',
6622.1.30 by Jelmer Vernooij
Some more test fixes.
2699
           help='''Whether to validate signatures in brz log.'''))
6238.2.8 by Jelmer Vernooij
Move options to bzrlib/transport/http/_urllib2_wrappers.py
2700
option_registry.register_lazy('ssl.ca_certs',
7296.2.1 by Jelmer Vernooij
Integrate _urllib2_wrappers.
2701
                              'breezy.transport.http', 'opt_ssl_ca_certs')
6238.2.8 by Jelmer Vernooij
Move options to bzrlib/transport/http/_urllib2_wrappers.py
2702
2703
option_registry.register_lazy('ssl.cert_reqs',
7296.2.1 by Jelmer Vernooij
Integrate _urllib2_wrappers.
2704
                              'breezy.transport.http', 'opt_ssl_cert_reqs')
6238.2.7 by Jelmer Vernooij
Add ssl.cert_reqs.
2705
2706
5743.3.11 by Vincent Ladeuil
Config sections only implement read access.
2707
class Section(object):
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2708
    """A section defines a dict of option name => value.
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2709
2710
    This is merely a read-only dict which can add some knowledge about the
5743.3.10 by Vincent Ladeuil
Fix typos mentioned in reviews.
2711
    options. It is *not* a python dict object though and doesn't try to mimic
2712
    its API.
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
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
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
2720
    def get(self, name, default=None, expand=True):
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2721
        return self.options.get(name, default)
2722
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
2723
    def iter_option_names(self):
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
2724
        for k in self.options.keys():
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
2725
            yield k
2726
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
2727
    def __repr__(self):
2728
        # Mostly for debugging use
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2729
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
2730
5743.2.3 by Vincent Ladeuil
The option is either new or has an existing value.
2731
5743.3.6 by Vincent Ladeuil
Use a name less likely to be reused.
2732
_NewlyCreatedOption = object()
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2733
"""Was the option created during the MutableSection lifetime"""
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
2734
_DeletedOption = object()
2735
"""Was the option deleted during the MutableSection lifetime"""
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2736
5743.2.3 by Vincent Ladeuil
The option is either new or has an existing value.
2737
5743.3.11 by Vincent Ladeuil
Config sections only implement read access.
2738
class MutableSection(Section):
5743.3.1 by Vincent Ladeuil
Add a docstring and dates to FIXMEs.
2739
    """A section allowing changes and keeping track of the original values."""
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2740
2741
    def __init__(self, section_id, options):
2742
        super(MutableSection, self).__init__(section_id, options)
6404.5.4 by Vincent Ladeuil
Saving changes is incremental and brings back updates from concurrent users
2743
        self.reset_changes()
2744
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2745
    def set(self, name, value):
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2746
        if name not in self.options:
5743.2.3 by Vincent Ladeuil
The option is either new or has an existing value.
2747
            # This is a new option
5743.3.6 by Vincent Ladeuil
Use a name less likely to be reused.
2748
            self.orig[name] = _NewlyCreatedOption
5743.2.3 by Vincent Ladeuil
The option is either new or has an existing value.
2749
        elif name not in self.orig:
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2750
            self.orig[name] = self.get(name, None)
2751
        self.options[name] = value
2752
2753
    def remove(self, name):
6554.1.1 by Vincent Ladeuil
Don't record an option deletion if there is no deletion to record.
2754
        if name not in self.orig and name in self.options:
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2755
            self.orig[name] = self.get(name, None)
2756
        del self.options[name]
2757
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
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
        """
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
2771
        for k, expected in dirty.orig.items():
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
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)
6404.5.6 by Vincent Ladeuil
Add some doc.
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
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
2782
            # to be used as a sharing mechanism).
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
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.
6404.5.9 by Vincent Ladeuil
Don't forget to use gettext.
2792
                trace.warning(gettext(
7143.15.2 by Jelmer Vernooij
Run autopep8.
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)))
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
2797
        # No need to keep track of these changes
2798
        self.reset_changes()
2799
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2800
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2801
class Store(object):
2802
    """Abstract interface to persistent storage for configuration options."""
2803
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2804
    readonly_section_class = Section
5743.4.22 by Vincent Ladeuil
Allow daughter classes to use different Section classes if/when needed.
2805
    mutable_section_class = MutableSection
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2806
6404.5.2 by Vincent Ladeuil
All Stores should handle dirty sections even if the actual tests are only exercising IniFileStore inplementations so far
2807
    def __init__(self):
6499.2.3 by Vincent Ladeuil
Clarify the dict usage to share dirty sections.
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.
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
2810
        self.dirty_sections = {}
6404.5.2 by Vincent Ladeuil
All Stores should handle dirty sections even if the actual tests are only exercising IniFileStore inplementations so far
2811
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
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)
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2819
2820
    def load(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2821
        """Loads the Store from persistent storage."""
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2822
        raise NotImplementedError(self.load)
2823
5987.1.5 by Vincent Ladeuil
Those are just bytes.
2824
    def _load_from_string(self, bytes):
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2825
        """Create a store from a string in configobj syntax.
2826
5987.1.5 by Vincent Ladeuil
Those are just bytes.
2827
        :param bytes: A string representing the file content.
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2828
        """
2829
        raise NotImplementedError(self._load_from_string)
2830
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
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
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
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
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2854
    def save(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2855
        """Saves the Store to persistent storage."""
5743.4.10 by Vincent Ladeuil
Fix copy/paste, bad.
2856
        raise NotImplementedError(self.save)
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2857
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
2858
    def _need_saving(self):
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
2859
        for s in self.dirty_sections.values():
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
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
        """
6404.5.7 by Vincent Ladeuil
Store load is lazy and will happen when needed
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.
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
2877
        self.unload()
2878
        # Apply the changes from the preserved dirty sections
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
2879
        for section_id, dirty in dirty_sections.items():
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
2880
            clean = self.get_mutable_section(section_id)
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
2881
            clean.apply_changes(dirty, self)
2882
        # Everything is clean now
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
2883
        self.dirty_sections = {}
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
2884
6404.5.4 by Vincent Ladeuil
Saving changes is incremental and brings back updates from concurrent users
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
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2893
    def external_url(self):
2894
        raise NotImplementedError(self.external_url)
2895
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2896
    def get_sections(self):
2897
        """Returns an ordered iterable of existing sections.
2898
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
2899
        :returns: An iterable of (store, section).
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2900
        """
2901
        raise NotImplementedError(self.get_sections)
2902
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
2903
    def get_mutable_section(self, section_id=None):
5743.4.2 by Vincent Ladeuil
Stores don't implement set_option, they just provide a mutable section.
2904
        """Returns the specified mutable section.
2905
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
2906
        :param section_id: The section identifier
5743.4.2 by Vincent Ladeuil
Stores don't implement set_option, they just provide a mutable section.
2907
        """
2908
        raise NotImplementedError(self.get_mutable_section)
5743.2.12 by Vincent Ladeuil
Rename store.set to store.set_option as it's clearer in this context and will act as a safe-guard against unintended uses (set() will be used for stacks).
2909
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2910
    def __repr__(self):
2911
        # Mostly for debugging use
5743.5.17 by Vincent Ladeuil
Use external_url to identify stores.
2912
        return "<config.%s(%s)>" % (self.__class__.__name__,
5743.5.18 by Vincent Ladeuil
Fix typo.
2913
                                    self.external_url())
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2914
2915
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
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 = {}
6404.4.1 by Vincent Ladeuil
Properly support config.CommandLineStore in ``bzr config``
2924
        self.id = 'cmdline'
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
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):
6325.1.1 by Vincent Ladeuil
Fix various typos
2943
        # Not an url but it makes debugging easier and is never needed
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
2944
        # otherwise
2945
        return 'cmdline'
2946
2947
    def get_sections(self):
7143.15.2 by Jelmer Vernooij
Run autopep8.
2948
        yield self, self.readonly_section_class(None, self.options)
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
2949
2950
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
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
    """
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2957
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
2958
    def __init__(self):
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2959
        """A config Store using ConfigObj for storage.
2960
        """
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2961
        super(IniFileStore, self).__init__()
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2962
        self._config_obj = None
2963
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2964
    def is_loaded(self):
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
2965
        return self._config_obj is not None
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2966
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2967
    def unload(self):
2968
        self._config_obj = None
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
2969
        self.dirty_sections = {}
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2970
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
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
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2989
    def load(self):
2990
        """Load the store from the associated file."""
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2991
        if self.is_loaded():
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2992
            return
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
2993
        content = self._load_content()
6110.5.5 by Vincent Ladeuil
Warn when loading, fail if saving will occur later
2994
        self._load_from_string(content)
2995
        for hook in ConfigHooks['load']:
2996
            hook(self)
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2997
5987.1.5 by Vincent Ladeuil
Those are just bytes.
2998
    def _load_from_string(self, bytes):
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2999
        """Create a config store from a string.
3000
5987.1.5 by Vincent Ladeuil
Those are just bytes.
3001
        :param bytes: A string representing the file content.
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
3002
        """
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
3003
        if self.is_loaded():
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
3004
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
3005
        co_input = BytesIO(bytes)
5743.4.3 by Vincent Ladeuil
Implement get_mutable_section.
3006
        try:
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
3007
            # The config files are always stored utf8-encoded
6082.5.11 by Vincent Ladeuil
Disable list_values for config.Store, using a dedicated configobj object to trigger the string -> list conversion on-demand (via the option registration) only.
3008
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
3009
                                         list_values=False)
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
3010
        except configobj.ConfigObjError as e:
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
3011
            self._config_obj = None
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
3012
            raise ParseConfigError(e.errors, self.external_url())
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
3013
        except UnicodeDecodeError:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
3014
            raise ConfigContentError(self.external_url())
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
3015
6404.5.4 by Vincent Ladeuil
Saving changes is incremental and brings back updates from concurrent users
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
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
3023
        dirty_sections = self.dirty_sections.copy()
6404.5.5 by Vincent Ladeuil
Refine implementations and add more precise tests. More tests can be added for more scenarios if it doesn't seem worth it until we encounter them in real life (which is unlikely so far)
3024
        self.apply_changes(dirty_sections)
6404.5.4 by Vincent Ladeuil
Saving changes is incremental and brings back updates from concurrent users
3025
        # Save to the persistent storage
3026
        self.save()
3027
5743.2.9 by Vincent Ladeuil
Implement and test store.save() and remove the 'save' parameter from store.from_string() as this won't scale well when adding class specific parameters.
3028
    def save(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
3029
        if not self.is_loaded():
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
3030
            # Nothing to save
3031
            return
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
3032
        out = BytesIO()
5743.2.9 by Vincent Ladeuil
Implement and test store.save() and remove the 'save' parameter from store.from_string() as this won't scale well when adding class specific parameters.
3033
        self._config_obj.write(out)
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
3034
        self._save_content(out.getvalue())
5743.8.10 by Vincent Ladeuil
We don't need (nor want) to tie the config hooks to a particular class. Especially when we want to use the same hooks on both implementations.
3035
        for hook in ConfigHooks['save']:
5743.8.7 by Vincent Ladeuil
Add hooks for config stores (but the load one is not in the right place).
3036
            hook(self)
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
3037
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
3038
    def get_sections(self):
3039
        """Get the configobj section in the file order.
3040
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3041
        :returns: An iterable of (store, section).
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
3042
        """
3043
        # We need a loaded store
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3044
        try:
3045
            self.load()
6110.5.5 by Vincent Ladeuil
Warn when loading, fail if saving will occur later
3046
        except (errors.NoSuchFile, errors.PermissionDenied):
3047
            # If the file can't be read, there is no sections
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3048
            return
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
3049
        cobj = self._config_obj
3050
        if cobj.scalars:
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3051
            yield self, self.readonly_section_class(None, cobj)
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
3052
        for section_name in cobj.sections:
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3053
            yield (self,
3054
                   self.readonly_section_class(section_name,
3055
                                               cobj[section_name]))
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
3056
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3057
    def get_mutable_section(self, section_id=None):
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
3058
        # We need a loaded store
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
3059
        try:
3060
            self.load()
3061
        except errors.NoSuchFile:
3062
            # The file doesn't exist, let's pretend it was empty
6695.1.1 by Martin
Make ui package pass tests on Python 3
3063
            self._load_from_string(b'')
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
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]
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3067
        if section_id is None:
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
3068
            section = self._config_obj
3069
        else:
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3070
            section = self._config_obj.setdefault(section_id, {})
6404.5.1 by Vincent Ladeuil
Setting or removing an option records the section as dirty
3071
        mutable_section = self.mutable_section_class(section_id, section)
3072
        # All mutable sections can become dirty
6499.2.1 by Vincent Ladeuil
Save branch config options only during the final unlock
3073
        self.dirty_sections[section_id] = mutable_section
6404.5.1 by Vincent Ladeuil
Setting or removing an option records the section as dirty
3074
        return mutable_section
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
3075
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
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):
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
3085
        if value and isinstance(value, string_types):
6404.3.1 by Vincent Ladeuil
Robustly unquote configuration values (workaround configobj presenting a section as a dict in weird edge cases)
3086
            # _unquote doesn't handle None nor empty strings nor anything that
3087
            # is not a string, really.
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
3088
            value = self._config_obj._unquote(value)
3089
        return value
3090
6402.2.3 by Vincent Ladeuil
More tests, a real implementation and some tweaks.
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'
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
3097
6499.3.3 by Vincent Ladeuil
Stop using _CompatibleStack now that local config files can be
3098
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
3099
class TransportIniFileStore(IniFileStore):
3100
    """IniFileStore that loads files from a transport.
6402.2.3 by Vincent Ladeuil
More tests, a real implementation and some tweaks.
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.
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
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
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
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>.
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
3134
        return urlutils.join(
3135
            self.transport.external_url(), urlutils.escape(self.file_name))
6270.1.6 by Jelmer Vernooij
Provide RemoteControlStore and RemoteBranchStore.
3136
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
3137
5743.4.16 by Vincent Ladeuil
Some doc for the stores.
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
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
3144
class LockableIniFileStore(TransportIniFileStore):
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
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
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
3157
        super(LockableIniFileStore, self).__init__(transport, file_name)
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
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()
6754.8.4 by Jelmer Vernooij
Use new context stuff.
3169
        token = self._lock.lock_write(token)
3170
        return lock.LogicalLockResult(self.unlock, token)
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
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):
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
3179
        with self.lock_write():
3180
            # We need to be able to override the undecorated implementation
3181
            self.save_without_locking()
5743.6.24 by Vincent Ladeuil
One more test with a ugly hack to allow the test to stop in the right place.
3182
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
3183
    def save_without_locking(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
3184
        super(LockableIniFileStore, self).save()
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
3185
3186
6741 by Jelmer Vernooij
Merge lp:~jelmer/brz/breezy-conf
3187
# FIXME: global, breezy, shouldn't that be 'user' instead or even
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
3188
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
3189
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
5743.5.15 by Vincent Ladeuil
Mention poolie's point about focusing tests.
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)
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
3195
class GlobalStore(LockableIniFileStore):
6499.3.13 by Vincent Ladeuil
Fix typo.
3196
    """A config store for global options.
6499.3.12 by Vincent Ladeuil
Add a reminder in the docstring that local config stores are unique by process.
3197
3198
    There is a single GlobalStore for a given process.
3199
    """
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
3200
3201
    def __init__(self, possible_transports=None):
7336.2.1 by Martin
Split non-ini config methods to bedding
3202
        path, kind = bedding._config_dir()
6055.1.2 by Vincent Ladeuil
Use _fs_enc instead of utf8.
3203
        t = transport.get_transport_from_path(
6741 by Jelmer Vernooij
Merge lp:~jelmer/brz/breezy-conf
3204
            path, possible_transports=possible_transports)
7336.2.1 by Martin
Split non-ini config methods to bedding
3205
        super(GlobalStore, self).__init__(t, kind + '.conf')
6741 by Jelmer Vernooij
Merge lp:~jelmer/brz/breezy-conf
3206
        self.id = 'breezy'
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
3207
3208
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
3209
class LocationStore(LockableIniFileStore):
6586.1.1 by Vincent Ladeuil
Fix various typos in docstrings. Rename 'buffer' to 'buf' since it's now a python builtin function.
3210
    """A config store for options specific to a location.
6499.3.12 by Vincent Ladeuil
Add a reminder in the docstring that local config stores are unique by process.
3211
6586.1.1 by Vincent Ladeuil
Fix various typos in docstrings. Rename 'buffer' to 'buf' since it's now a python builtin function.
3212
    There is a single LocationStore for a given process.
6499.3.12 by Vincent Ladeuil
Add a reminder in the docstring that local config stores are unique by process.
3213
    """
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
3214
3215
    def __init__(self, possible_transports=None):
6055.1.2 by Vincent Ladeuil
Use _fs_enc instead of utf8.
3216
        t = transport.get_transport_from_path(
7336.2.1 by Martin
Split non-ini config methods to bedding
3217
            bedding.config_dir(), possible_transports=possible_transports)
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
3218
        super(LocationStore, self).__init__(t, 'locations.conf')
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3219
        self.id = 'locations'
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
3220
3221
6270.1.5 by Jelmer Vernooij
Add TransportIniFileStore.
3222
class BranchStore(TransportIniFileStore):
6499.3.13 by Vincent Ladeuil
Fix typo.
3223
    """A config store for branch options.
6499.3.12 by Vincent Ladeuil
Add a reminder in the docstring that local config stores are unique by process.
3224
3225
    There is a single BranchStore for a given branch.
3226
    """
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
3227
3228
    def __init__(self, branch):
3229
        super(BranchStore, self).__init__(branch.control_transport,
3230
                                          'branch.conf')
5743.6.34 by Vincent Ladeuil
Forget weakref for branch <-> config.
3231
        self.branch = branch
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3232
        self.id = 'branch'
5743.10.5 by Vincent Ladeuil
Give up.
3233
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
3234
6076.1.1 by Vincent Ladeuil
Add the missing config stacks and store
3235
class ControlStore(LockableIniFileStore):
3236
3237
    def __init__(self, bzrdir):
3238
        super(ControlStore, self).__init__(bzrdir.transport,
7143.15.2 by Jelmer Vernooij
Run autopep8.
3239
                                           'control.conf',
6076.1.1 by Vincent Ladeuil
Add the missing config stacks and store
3240
                                           lock_dir_name='branch_lock')
6404.4.1 by Vincent Ladeuil
Properly support config.CommandLineStore in ``bzr config``
3241
        self.id = 'control'
6076.1.1 by Vincent Ladeuil
Add the missing config stacks and store
3242
3243
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3244
class SectionMatcher(object):
3245
    """Select sections into a given Store.
3246
6123.7.1 by Vincent Ladeuil
Provide config.IdMatcher for config files defining secion names as unique ids
3247
    This is intended to be used to postpone getting an iterable of sections
3248
    from a store.
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3249
    """
3250
3251
    def __init__(self, store):
3252
        self.store = store
3253
3254
    def get_sections(self):
5743.2.29 by Vincent Ladeuil
Add doc for the section matchers.
3255
        # This is where we require loading the store so we can see all defined
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3256
        # sections.
3257
        sections = self.store.get_sections()
6260.3.2 by Vincent Ladeuil
Only the DEFAULT section is searched for the normal uses of bazaar.conf
3258
        # Walk the revisions in the order provided
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3259
        for store, s in sections:
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3260
            if self.match(s):
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3261
                yield store, s
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3262
6123.7.1 by Vincent Ladeuil
Provide config.IdMatcher for config files defining secion names as unique ids
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
        """
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3270
        raise NotImplementedError(self.match)
3271
3272
6123.7.2 by Vincent Ladeuil
Rename IdMatcher to NameMatcher.
3273
class NameMatcher(SectionMatcher):
6123.7.1 by Vincent Ladeuil
Provide config.IdMatcher for config files defining secion names as unique ids
3274
3275
    def __init__(self, store, section_id):
6123.7.2 by Vincent Ladeuil
Rename IdMatcher to NameMatcher.
3276
        super(NameMatcher, self).__init__(store)
6123.7.1 by Vincent Ladeuil
Provide config.IdMatcher for config files defining secion names as unique ids
3277
        self.section_id = section_id
3278
3279
    def match(self, section):
3280
        return section.id == self.section_id
3281
3282
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
3283
class LocationSection(Section):
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3284
6524.2.1 by Aaron Bentley
Implement branchname support in config files.
3285
    def __init__(self, section, extra_path, branch_name=None):
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3286
        super(LocationSection, self).__init__(section.id, section.options)
3287
        self.extra_path = extra_path
6524.2.2 by Aaron Bentley
Test branchname config var.
3288
        if branch_name is None:
3289
            branch_name = ''
6082.5.25 by Vincent Ladeuil
Add ``basename`` as a section local option
3290
        self.locals = {'relpath': extra_path,
6524.2.1 by Aaron Bentley
Implement branchname support in config files.
3291
                       'basename': urlutils.basename(extra_path),
3292
                       'branchname': branch_name}
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3293
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3294
    def get(self, name, default=None, expand=True):
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3295
        value = super(LocationSection, self).get(name, default)
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3296
        if value is not None and expand:
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
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)
6082.5.21 by Vincent Ladeuil
Implement 'relpath' as a section locally expanded option.
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)
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3314
        return value
3315
3316
6402.2.6 by Vincent Ladeuil
Fix {relpath} support, realizing that when a section ends with a glob, it's not obivous to decide what should be done.
3317
class StartingPathMatcher(SectionMatcher):
6402.2.2 by Vincent Ladeuil
Bogus implementation passing smoke test
3318
    """Select sections for a given location respecting the Store order."""
3319
6402.2.8 by Vincent Ladeuil
Feedback from review.
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
6402.2.2 by Vincent Ladeuil
Bogus implementation passing smoke test
3328
    def __init__(self, store, location):
6402.2.6 by Vincent Ladeuil
Fix {relpath} support, realizing that when a section ends with a glob, it's not obivous to decide what should be done.
3329
        super(StartingPathMatcher, self).__init__(store)
6402.2.2 by Vincent Ladeuil
Bogus implementation passing smoke test
3330
        if location.startswith('file://'):
3331
            location = urlutils.local_path_from_url(location)
3332
        self.location = location
3333
3334
    def get_sections(self):
6402.2.5 by Vincent Ladeuil
Always return the no-name section if present.
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
        """
6402.2.6 by Vincent Ladeuil
Fix {relpath} support, realizing that when a section ends with a glob, it's not obivous to decide what should be done.
3343
        location_parts = self.location.rstrip('/').split('/')
6402.2.2 by Vincent Ladeuil
Bogus implementation passing smoke test
3344
        store = self.store
6402.2.3 by Vincent Ladeuil
More tests, a real implementation and some tweaks.
3345
        # Later sections are more specific, they should be returned first
3346
        for _, section in reversed(list(store.get_sections())):
6402.2.5 by Vincent Ladeuil
Always return the no-name section if present.
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
6402.2.3 by Vincent Ladeuil
More tests, a real implementation and some tweaks.
3351
            section_path = section.id
3352
            if section_path.startswith('file://'):
6402.2.6 by Vincent Ladeuil
Fix {relpath} support, realizing that when a section ends with a glob, it's not obivous to decide what should be done.
3353
                # the location is already a local path or URL, convert the
6402.2.7 by Vincent Ladeuil
Cleanup a bit and make sure we use at least one file:// url in the tests.
3354
                # section id to the same format
3355
                section_path = urlutils.local_path_from_url(section_path)
7143.15.2 by Jelmer Vernooij
Run autopep8.
3356
            if (self.location.startswith(section_path) or
3357
                    fnmatch.fnmatch(self.location, section_path)):
6402.2.6 by Vincent Ladeuil
Fix {relpath} support, realizing that when a section ends with a glob, it's not obivous to decide what should be done.
3358
                section_parts = section_path.rstrip('/').split('/')
3359
                extra_path = '/'.join(location_parts[len(section_parts):])
3360
                yield store, LocationSection(section, extra_path)
6402.2.2 by Vincent Ladeuil
Bogus implementation passing smoke test
3361
3362
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3363
class LocationMatcher(SectionMatcher):
3364
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3365
    def __init__(self, store, location):
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3366
        super(LocationMatcher, self).__init__(store)
6524.2.1 by Aaron Bentley
Implement branchname support in config files.
3367
        url, params = urlutils.split_segment_parameters(location)
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
3368
        if location.startswith('file://'):
3369
            location = urlutils.local_path_from_url(location)
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3370
        self.location = location
6524.2.4 by Aaron Bentley
branchname falls back to basename.
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)
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3376
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
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
6015.22.1 by Vincent Ladeuil
config.LocationMatcher properly excludes unrelated sections
3382
        all_sections = []
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
3383
        # Filter out the no_name_section so _iter_for_location_by_parts can be
3384
        # used (it assumes all sections have a name).
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3385
        for _, section in self.store.get_sections():
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
3386
            if section.id is None:
3387
                no_name_section = section
3388
            else:
6015.22.1 by Vincent Ladeuil
config.LocationMatcher properly excludes unrelated sections
3389
                all_sections.append(section)
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
3390
        # Unfortunately _iter_for_location_by_parts deals with section names so
3391
        # we have to resync.
5743.2.31 by Vincent Ladeuil
Both the length and the section id should be used to sort.
3392
        filtered_sections = _iter_for_location_by_parts(
6015.22.1 by Vincent Ladeuil
config.LocationMatcher properly excludes unrelated sections
3393
            [s.id for s in all_sections], self.location)
3394
        iter_all_sections = iter(all_sections)
5743.2.27 by Vincent Ladeuil
Merge the use of _filter_for_location_by_parts, uglier, but better for
3395
        matching_sections = []
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
3396
        if no_name_section is not None:
3397
            matching_sections.append(
6402.2.1 by Vincent Ladeuil
Get rid of LocationSection.length as its not needed in the general case.
3398
                (0, LocationSection(no_name_section, self.location)))
5743.2.31 by Vincent Ladeuil
Both the length and the section id should be used to sort.
3399
        for section_id, extra_path, length in filtered_sections:
6015.22.1 by Vincent Ladeuil
config.LocationMatcher properly excludes unrelated 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:
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
3405
                section = next(iter_all_sections)
6015.22.1 by Vincent Ladeuil
config.LocationMatcher properly excludes unrelated sections
3406
                if section_id == section.id:
6524.2.1 by Aaron Bentley
Implement branchname support in config files.
3407
                    section = LocationSection(section, extra_path,
3408
                                              self.branch_name)
3409
                    matching_sections.append((length, section))
6015.22.1 by Vincent Ladeuil
config.LocationMatcher properly excludes unrelated sections
3410
                    break
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
3411
        return matching_sections
3412
3413
    def get_sections(self):
3414
        # Override the default implementation as we want to change the order
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3415
        # We want the longest (aka more specific) locations first
6621.20.1 by Martin
Run 2to3 tuple_params fixer and tidy up.
3416
        sections = sorted(self._get_matching_sections(),
3417
                          key=lambda match: (match[0], match[1].id),
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
3418
                          reverse=True)
3419
        # Sections mentioning 'ignore_parents' restrict the selection
6402.2.1 by Vincent Ladeuil
Get rid of LocationSection.length as its not needed in the general case.
3420
        for _, section in sections:
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
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
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3428
            yield self.store, section
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
3429
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
3430
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
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
6082.5.20 by Vincent Ladeuil
Refactor iter_option_refs out of Stack so it can be reused.
3435
7143.15.2 by Jelmer Vernooij
Run autopep8.
3436
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
3437
class Stack(object):
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3438
    """A stack of configurations where an option can be defined"""
3439
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3440
    def __init__(self, sections_def, store=None, mutable_section_id=None):
5743.1.11 by Vincent Ladeuil
Properly use MutableSection for write operations.
3441
        """Creates a stack of sections with an optional store for changes.
3442
5743.1.36 by Vincent Ladeuil
Clarify that constructor parameters are here to *define* the stack and as such can be re-used. Also make the sections_def parameter mandatory.
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.
5743.1.11 by Vincent Ladeuil
Properly use MutableSection for write operations.
3446
5743.1.37 by Vincent Ladeuil
Change the way Stacks are built: requires a Store and a mutable section name instead of a callable returning the mutable section.
3447
        :param store: The optional Store where modifications will be
3448
            recorded. If none is specified, no modifications can be done.
3449
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3450
        :param mutable_section_id: The id of the MutableSection where changes
3451
            are recorded. This requires the ``store`` parameter to be
5743.1.37 by Vincent Ladeuil
Change the way Stacks are built: requires a Store and a mutable section name instead of a callable returning the mutable section.
3452
            specified.
5743.1.11 by Vincent Ladeuil
Properly use MutableSection for write operations.
3453
        """
5743.1.36 by Vincent Ladeuil
Clarify that constructor parameters are here to *define* the stack and as such can be re-used. Also make the sections_def parameter mandatory.
3454
        self.sections_def = sections_def
5743.1.37 by Vincent Ladeuil
Change the way Stacks are built: requires a Store and a mutable section name instead of a callable returning the mutable section.
3455
        self.store = store
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3456
        self.mutable_section_id = mutable_section_id
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3457
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
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
6468.5.2 by Vincent Ladeuil
Merge bzr.dev resolving conflicts
3468
    def get(self, name, expand=True, convert=True):
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
3469
        """Return the *first* option value found in the sections.
5743.1.13 by Vincent Ladeuil
Better explain lazy loading and make sure the mutable section respect the design.
3470
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
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
5743.1.13 by Vincent Ladeuil
Better explain lazy loading and make sure the mutable section respect the design.
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).
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
3476
3477
        :param name: The queried option.
3478
3479
        :param expand: Whether options references should be expanded.
3480
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
3481
        :param convert: Whether the option value should be converted from
3482
            unicode (do nothing for non-registered options).
3483
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
3484
        :returns: The value of the option.
5743.1.13 by Vincent Ladeuil
Better explain lazy loading and make sure the mutable section respect the design.
3485
        """
5743.1.36 by Vincent Ladeuil
Clarify that constructor parameters are here to *define* the stack and as such can be re-used. Also make the sections_def parameter mandatory.
3486
        # FIXME: No caching of options nor sections yet -- vila 20110503
5743.12.6 by Vincent Ladeuil
Stack.get() provides the registered option default value.
3487
        value = None
7143.15.2 by Jelmer Vernooij
Run autopep8.
3488
        found_store = None  # Where the option value has been found
6059.1.1 by Vincent Ladeuil
Implement from_unicode to convert config option values from store.
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
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
3496
6082.5.12 by Vincent Ladeuil
Remove duplication in stack.get() and useless code now that list conversion is explicit and delayed.
3497
        def expand_and_convert(val):
6393.3.2 by Vincent Ladeuil
Merge trunk resolving conflicts
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.
6082.5.12 by Vincent Ladeuil
Remove duplication in stack.get() and useless code now that list conversion is explicit and delayed.
3500
            if val is not None:
3501
                if expand:
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
3502
                    if isinstance(val, string_types):
6082.5.12 by Vincent Ladeuil
Remove duplication in stack.get() and useless code now that list conversion is explicit and delayed.
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)))
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
3508
                if opt is None:
3509
                    val = found_store.unquote(val)
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
3510
                elif convert:
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
3511
                    val = opt.convert_from_unicode(found_store, val)
6082.5.12 by Vincent Ladeuil
Remove duplication in stack.get() and useless code now that list conversion is explicit and delayed.
3512
            return val
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
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:
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
3520
            for store, section in self.iter_sections():
3521
                value = section.get(name)
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
3522
                if value is not None:
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
3523
                    found_store = store
6393.3.1 by Vincent Ladeuil
Configuration option value can be overridden by os environ variables
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)
6082.5.3 by Vincent Ladeuil
Fix the hook call.
3530
        for hook in ConfigHooks['get']:
3531
            hook(self, name, value)
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
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).
6082.5.20 by Vincent Ladeuil
Refactor iter_option_refs out of Stack so it can be reused.
3568
        expanded = True
3569
        while expanded:
3570
            expanded = False
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
3571
            chunks = []
6082.5.20 by Vincent Ladeuil
Refactor iter_option_refs out of Stack so it can be reused.
3572
            for is_ref, chunk in iter_option_refs(result):
3573
                if not is_ref:
6082.5.12 by Vincent Ladeuil
Remove duplication in stack.get() and useless code now that list conversion is explicit and delayed.
3574
                    chunks.append(chunk)
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
3575
                else:
6082.5.20 by Vincent Ladeuil
Refactor iter_option_refs out of Stack so it can be reused.
3576
                    expanded = True
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
3577
                    name = chunk[1:-1]
3578
                    if name in _refs:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
3579
                        raise OptionExpansionLoop(string, _refs)
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
3580
                    _refs.append(name)
3581
                    value = self._expand_option(name, env, _refs)
3582
                    if value is None:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
3583
                        raise ExpandingUnknownOption(name, string)
6082.5.12 by Vincent Ladeuil
Remove duplication in stack.get() and useless code now that list conversion is explicit and delayed.
3584
                    chunks.append(value)
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
3585
                    _refs.pop()
6082.5.12 by Vincent Ladeuil
Remove duplication in stack.get() and useless code now that list conversion is explicit and delayed.
3586
            result = ''.join(chunks)
6082.5.2 by Vincent Ladeuil
Cargo-cult the config option expansion implementation with tweaks from the old to the new config design.
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:
6466.1.3 by Vincent Ladeuil
Values should never be converted during expansion.
3595
            value = self.get(name, expand=False, convert=False)
6082.5.12 by Vincent Ladeuil
Remove duplication in stack.get() and useless code now that list conversion is explicit and delayed.
3596
            value = self._expand_options_in_string(value, env, _refs)
5743.12.6 by Vincent Ladeuil
Stack.get() provides the registered option default value.
3597
        return value
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3598
5743.1.37 by Vincent Ladeuil
Change the way Stacks are built: requires a Store and a mutable section name instead of a callable returning the mutable section.
3599
    def _get_mutable_section(self):
3600
        """Get the MutableSection for the Stack.
5743.1.13 by Vincent Ladeuil
Better explain lazy loading and make sure the mutable section respect the design.
3601
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
3602
        This is where we guarantee that the mutable section is lazily loaded:
5743.1.37 by Vincent Ladeuil
Change the way Stacks are built: requires a Store and a mutable section name instead of a callable returning the mutable section.
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
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3605
        this helps catching some programming errors.
5743.1.13 by Vincent Ladeuil
Better explain lazy loading and make sure the mutable section respect the design.
3606
        """
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
3607
        store = self.store
3608
        section = store.get_mutable_section(self.mutable_section_id)
3609
        return store, section
5743.1.37 by Vincent Ladeuil
Change the way Stacks are built: requires a Store and a mutable section name instead of a callable returning the mutable section.
3610
3611
    def set(self, name, value):
3612
        """Set a new value for the option."""
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
3613
        store, section = self._get_mutable_section()
3614
        section.set(name, store.quote(value))
5743.8.10 by Vincent Ladeuil
We don't need (nor want) to tie the config hooks to a particular class. Especially when we want to use the same hooks on both implementations.
3615
        for hook in ConfigHooks['set']:
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3616
            hook(self, name, value)
5743.1.7 by Vincent Ladeuil
Simple set implementation.
3617
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
3618
    def remove(self, name):
5743.1.37 by Vincent Ladeuil
Change the way Stacks are built: requires a Store and a mutable section name instead of a callable returning the mutable section.
3619
        """Remove an existing option."""
6385.1.1 by Vincent Ladeuil
Stores allow Stacks to control when values are quoted/unquoted
3620
        _, section = self._get_mutable_section()
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
3621
        section.remove(name)
5743.8.10 by Vincent Ladeuil
We don't need (nor want) to tie the config hooks to a particular class. Especially when we want to use the same hooks on both implementations.
3622
        for hook in ConfigHooks['remove']:
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
3623
            hook(self, name)
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
3624
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
3625
    def __repr__(self):
3626
        # Mostly for debugging use
3627
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
3628
6161.1.7 by Vincent Ladeuil
Emit a warning when bzrlib.intialize) has not been called
3629
    def _get_overrides(self):
6759.4.2 by Jelmer Vernooij
Use get_global_state>
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()
6161.1.7 by Vincent Ladeuil
Emit a warning when bzrlib.intialize) has not been called
3633
        return []
3634
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
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:
6759.4.2 by Jelmer Vernooij
Use get_global_state>
3649
            # TODO(jelmer): Urgh, this is circular so we can't call breezy.get_global_state()
3650
            state = breezy._global_state
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
3651
        if state is None:
3652
            global _shared_stores_at_exit_installed
3653
            stores = _shared_stores
7143.15.2 by Jelmer Vernooij
Run autopep8.
3654
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
3655
            def save_config_changes():
6677.1.1 by Martin
Go back to native str for urls and many other py3 changes
3656
                for k, store in stores.items():
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
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
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
3673
6393.1.1 by Vincent Ladeuil
Provides MemoryStack to simplify configuration setup in tests
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
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
3697
class _CompatibleStack(Stack):
5743.6.26 by Vincent Ladeuil
Clarify _CompatibleStack aims.
3698
    """Place holder for compatibility with previous design.
3699
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
3700
    This is intended to ease the transition from the Config-based design to the
5743.6.26 by Vincent Ladeuil
Clarify _CompatibleStack aims.
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).
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
3705
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3706
    It implements set() and remove () by re-loading the store before applying
3707
    the modification and saving it.
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
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.
5743.6.26 by Vincent Ladeuil
Clarify _CompatibleStack aims.
3711
    """
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
3712
3713
    def set(self, name, value):
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
3714
        # Force a reload
3715
        self.store.unload()
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
3716
        super(_CompatibleStack, self).set(name, value)
3717
        # Force a write to persistent storage
3718
        self.store.save()
3719
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
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
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
3727
6499.3.3 by Vincent Ladeuil
Stop using _CompatibleStack now that local config files can be
3728
class GlobalStack(Stack):
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
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
    """
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3740
3741
    def __init__(self):
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
3742
        gstore = self.get_shared_store(GlobalStore())
6161.1.1 by Vincent Ladeuil
Allow config options to be overridden from the command line
3743
        super(GlobalStack, self).__init__(
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
3744
            [self._get_overrides,
3745
             NameMatcher(gstore, 'DEFAULT').get_sections],
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3746
            gstore, mutable_section_id='DEFAULT')
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3747
3748
6499.3.3 by Vincent Ladeuil
Stop using _CompatibleStack now that local config files can be
3749
class LocationStack(Stack):
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
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
    """
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3766
3767
    def __init__(self, location):
6006.4.7 by Martin Pool
fdatasync on dirstate can be disabled
3768
        """Make a new stack for a location and global configuration.
6371.1.1 by Jelmer Vernooij
Fix some whitespace in bzrlib.config.
3769
6006.4.7 by Martin Pool
fdatasync on dirstate can be disabled
3770
        :param location: A URL prefix to """
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
3771
        lstore = self.get_shared_store(LocationStore())
6288.1.1 by Vincent Ladeuil
Fix windows test regressions about locations.conf handling
3772
        if location.startswith('file://'):
3773
            location = urlutils.local_path_from_url(location)
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
3774
        gstore = self.get_shared_store(GlobalStore())
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3775
        super(LocationStack, self).__init__(
6161.1.7 by Vincent Ladeuil
Emit a warning when bzrlib.intialize) has not been called
3776
            [self._get_overrides,
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
3777
             LocationMatcher(lstore, location).get_sections,
3778
             NameMatcher(gstore, 'DEFAULT').get_sections],
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3779
            lstore, mutable_section_id=location)
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3780
6076.1.1 by Vincent Ladeuil
Add the missing config stacks and store
3781
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
3782
class BranchStack(Stack):
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
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
6362.3.2 by Vincent Ladeuil
Fix as per jelmer's review.
3798
    MutableSection.
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
3799
    """
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3800
3801
    def __init__(self, branch):
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
3802
        lstore = self.get_shared_store(LocationStore())
6270.1.19 by Jelmer Vernooij
Some changes discussed with vila on IRC.
3803
        bstore = branch._get_config_store()
6499.3.10 by Vincent Ladeuil
Add news entry and cleanup
3804
        gstore = self.get_shared_store(GlobalStore())
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3805
        super(BranchStack, self).__init__(
6161.1.7 by Vincent Ladeuil
Emit a warning when bzrlib.intialize) has not been called
3806
            [self._get_overrides,
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
3807
             LocationMatcher(lstore, branch.base).get_sections,
3808
             NameMatcher(bstore, None).get_sections,
6260.3.2 by Vincent Ladeuil
Only the DEFAULT section is searched for the normal uses of bazaar.conf
3809
             NameMatcher(gstore, 'DEFAULT').get_sections],
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
3810
            bstore)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
3811
        self.branch = branch
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3812
6404.6.7 by Vincent Ladeuil
Change set/remove to require a lock for the branch config files.
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):
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
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.
6404.6.7 by Vincent Ladeuil
Change set/remove to require a lock for the branch config files.
3824
3825
    def remove(self, name):
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
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.
6404.6.7 by Vincent Ladeuil
Change set/remove to require a lock for the branch config files.
3830
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
3831
6499.3.3 by Vincent Ladeuil
Stop using _CompatibleStack now that local config files can be
3832
class RemoteControlStack(Stack):
6270.1.20 by Jelmer Vernooij
Revert RemoteBranchStack / RemoteControlStack changes.
3833
    """Remote control-only options stack."""
3834
6270.1.23 by Jelmer Vernooij
Add notes about Remote{Control,Branch}Store.
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
6270.1.20 by Jelmer Vernooij
Revert RemoteBranchStack / RemoteControlStack changes.
3839
    def __init__(self, bzrdir):
6270.1.21 by Jelmer Vernooij
Use _get_config_store in Remote*Stack
3840
        cstore = bzrdir._get_config_store()
6270.1.20 by Jelmer Vernooij
Revert RemoteBranchStack / RemoteControlStack changes.
3841
        super(RemoteControlStack, self).__init__(
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
3842
            [NameMatcher(cstore, None).get_sections],
6270.1.20 by Jelmer Vernooij
Revert RemoteBranchStack / RemoteControlStack changes.
3843
            cstore)
6653.6.1 by Jelmer Vernooij
Rename a number of attributes from bzrdir to controldir.
3844
        self.controldir = bzrdir
6270.1.20 by Jelmer Vernooij
Revert RemoteBranchStack / RemoteControlStack changes.
3845
3846
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
3847
class BranchOnlyStack(Stack):
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
3848
    """Branch-only options stack."""
6270.1.20 by Jelmer Vernooij
Revert RemoteBranchStack / RemoteControlStack changes.
3849
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
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
6270.1.23 by Jelmer Vernooij
Add notes about Remote{Control,Branch}Store.
3853
6270.1.20 by Jelmer Vernooij
Revert RemoteBranchStack / RemoteControlStack changes.
3854
    def __init__(self, branch):
6270.1.21 by Jelmer Vernooij
Use _get_config_store in Remote*Stack
3855
        bstore = branch._get_config_store()
6379.11.2 by Vincent Ladeuil
No matter how weird BranchOnlyStack is, it's public, the FIXMEs should be enough for devs to notice.
3856
        super(BranchOnlyStack, self).__init__(
6362.3.1 by Vincent Ladeuil
Config doc refresh, clarifying the sections used in the implemented stacks.
3857
            [NameMatcher(bstore, None).get_sections],
6270.1.20 by Jelmer Vernooij
Revert RemoteBranchStack / RemoteControlStack changes.
3858
            bstore)
3859
        self.branch = branch
3860
6404.6.7 by Vincent Ladeuil
Change set/remove to require a lock for the branch config files.
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):
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
3868
        with self.lock_write():
3869
            super(BranchOnlyStack, self).set(name, value)
3870
            # Force a write to persistent storage
3871
            self.store.save_changes()
6404.6.7 by Vincent Ladeuil
Change set/remove to require a lock for the branch config files.
3872
3873
    def remove(self, name):
6754.8.20 by Jelmer Vernooij
Update NEWS.
3874
        with self.lock_write():
6754.8.17 by Jelmer Vernooij
Remove uses of needs_write_lock.
3875
            super(BranchOnlyStack, self).remove(name)
3876
            # Force a write to persistent storage
3877
            self.store.save_changes()
6404.6.7 by Vincent Ladeuil
Change set/remove to require a lock for the branch config files.
3878
6379.11.1 by Vincent Ladeuil
Migrate location options to config stacks.
3879
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
3880
class cmd_config(commands.Command):
5447.4.19 by Vincent Ladeuil
Add some more documentation.
3881
    __doc__ = """Display, set or remove a configuration option.
3882
6561.1.1 by Vincent Ladeuil
Clarify option references expansion for `bzr config`.
3883
    Display the active value for option NAME.
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3884
3885
    If --all is specified, NAME is interpreted as a regular expression and all
6561.1.1 by Vincent Ladeuil
Clarify option references expansion for `bzr config`.
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
5447.4.19 by Vincent Ladeuil
Add some more documentation.
3894
    is set in the most relevant scope and can be checked by displaying the
3895
    option again.
6561.1.1 by Vincent Ladeuil
Clarify option references expansion for `bzr config`.
3896
3897
    Removing a value is achieved by using --remove NAME.
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
3898
    """
3899
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3900
    takes_args = ['name?']
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
3901
3902
    takes_options = [
3903
        'directory',
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
3904
        # FIXME: This should be a registry option so that plugins can register
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3905
        # their own config files (or not) and will also address
3906
        # http://pad.lv/788991 -- vila 20101115
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
3907
        commands.Option('scope', help='Reduce the scope to the specified'
6259.2.5 by Martin Packman
Add full stops to various option help text so test_option_grammar passes
3908
                        ' configuration file.',
6621.2.26 by Martin
Misc set of changes to get started with selftest on Python 3
3909
                        type=text_type),
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3910
        commands.Option('all',
7143.15.2 by Jelmer Vernooij
Run autopep8.
3911
                        help='Display all the defined values for the matching options.',
3912
                        ),
5447.4.8 by Vincent Ladeuil
Make the test properly fail and provide a fake implementation for ``bzr config --remove opt_name``.
3913
        commands.Option('remove', help='Remove the option from'
6259.2.5 by Martin Packman
Add full stops to various option help text so test_option_grammar passes
3914
                        ' the configuration file.'),
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
3915
        ]
3916
5425.4.24 by Martin Pool
Mention 'configuration' help topic from 'bzr help config'
3917
    _see_also = ['configuration']
3918
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
3919
    @commands.display_command
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3920
    def run(self, name=None, all=False, directory=None, scope=None,
3921
            remove=False):
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
3922
        if directory is None:
3923
            directory = '.'
6437.66.1 by Wouter van Heyst
Dereference directory services in cmd_config.
3924
        directory = directory_service.directories.dereference(directory)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
3925
        directory = urlutils.normalize_url(directory)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3926
        if remove and all:
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
3927
            raise errors.BzrError(
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3928
                '--all and --remove are mutually exclusive.')
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
3929
        elif remove:
3930
            # Delete the option in the given scope
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
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)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
3935
        else:
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
3936
            try:
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3937
                name, value = name.split('=', 1)
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
3938
            except ValueError:
3939
                # Display the option(s) value(s)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3940
                if all:
3941
                    self._show_matching_options(name, directory, scope)
3942
                else:
3943
                    self._show_value(name, directory, scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
3944
            else:
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3945
                if all:
3946
                    raise errors.BzrError(
3947
                        'Only one option can be set.')
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
3948
                # Set the option value
3949
                self._set_config_option(name, value, directory, scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
3950
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
3951
    def _get_stack(self, directory, scope=None, write_access=False):
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3952
        """Get the configuration stack specified by ``directory`` and ``scope``.
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
3953
3954
        :param directory: Where the configurations are derived from.
3955
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
3956
        :param scope: A specific config to start from.
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
3957
3958
        :param write_access: Whether a write access to the stack will be
3959
            attempted.
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
3960
        """
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
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
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
3964
        if scope is not None:
6741 by Jelmer Vernooij
Merge lp:~jelmer/brz/breezy-conf
3965
            if scope == 'breezy':
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3966
                return GlobalStack()
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
3967
            elif scope == 'locations':
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3968
                return LocationStack(directory)
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
3969
            elif scope == 'branch':
6207.3.3 by jelmer at samba
Fix tests and the like.
3970
                (_, br, _) = (
3971
                    controldir.ControlDir.open_containing_tree_or_branch(
3972
                        directory))
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
3973
                if write_access:
3974
                    self.add_cleanup(br.lock_write().unlock)
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3975
                return br.get_config_stack()
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
3976
            raise NoSuchConfig(scope)
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
3977
        else:
3978
            try:
6207.3.3 by jelmer at samba
Fix tests and the like.
3979
                (_, br, _) = (
3980
                    controldir.ControlDir.open_containing_tree_or_branch(
3981
                        directory))
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
3982
                if write_access:
3983
                    self.add_cleanup(br.lock_write().unlock)
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3984
                return br.get_config_stack()
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
3985
            except errors.NotBranchError:
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3986
                return LocationStack(directory)
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
3987
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
3988
    def _quote_multiline(self, value):
3989
        if '\n' in value:
3990
            value = '"""' + value + '"""'
3991
        return value
3992
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
3993
    def _show_value(self, name, directory, scope):
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3994
        conf = self._get_stack(directory, scope)
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
3995
        value = conf.get(name, expand=True, convert=False)
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3996
        if value is not None:
3997
            # Quote the value appropriately
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
3998
            value = self._quote_multiline(value)
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
3999
            self.outf.write('%s\n' % (value,))
4000
        else:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
4001
            raise NoSuchConfigOption(name)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
4002
4003
    def _show_matching_options(self, name, directory, scope):
5967.9.3 by Martin Pool
Explicitly use lazy_regexp where we count on its error reporting behaviour
4004
        name = lazy_regex.lazy_compile(name)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
4005
        # We want any error in the regexp to be raised *now* so we need to
5967.9.3 by Martin Pool
Explicitly use lazy_regexp where we count on its error reporting behaviour
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()
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
4009
        cur_store_id = None
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
4010
        cur_section = None
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
4011
        conf = self._get_stack(directory, scope)
6466.1.1 by Vincent Ladeuil
Fix RegistryOption display in bzr config output
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))
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
4029
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
4030
    def _set_config_option(self, name, value, directory, scope):
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
4031
        conf = self._get_stack(directory, scope, write_access=True)
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
4032
        conf.set(name, value)
6597.1.1 by Vincent Ladeuil
Bzr config should save the changes explicitly when needed
4033
        # Explicitly save the changes
4034
        conf.store.save_changes()
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
4035
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
4036
    def _remove_config_option(self, name, directory, scope):
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
4037
        if name is None:
4038
            raise errors.BzrCommandError(
4039
                '--remove expects an option to remove.')
6404.6.1 by Vincent Ladeuil
Tests passing for a first rough version of a cached branch config store. The changes here are too invasive and several parallel proposals have been made.
4040
        conf = self._get_stack(directory, scope, write_access=True)
6060.9.1 by Jelmer Vernooij
Add bzrlib.config.cache_dir.
4041
        try:
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
4042
            conf.remove(name)
6597.1.1 by Vincent Ladeuil
Bzr config should save the changes explicitly when needed
4043
            # Explicitly save the changes
4044
            conf.store.save_changes()
6260.3.1 by Vincent Ladeuil
Switch ``bzr config`` to the new config implementation
4045
        except KeyError:
6733.1.1 by Jelmer Vernooij
Move config errors from breezy.errors to breezy.config.
4046
            raise NoSuchConfigOption(name)
6060.9.1 by Jelmer Vernooij
Add bzrlib.config.cache_dir.
4047
4048
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
4049
# Test registries
5743.6.29 by Vincent Ladeuil
For jam.
4050
#
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
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
5743.6.29 by Vincent Ladeuil
For jam.
4054
# ready-to-use store or stack.  Plugins that define new store/stacks can also
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
4055
# register themselves here to be tested against the tests defined in
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
4056
# breezy.tests.test_config. Note that the builder can be called multiple times
6325.1.1 by Vincent Ladeuil
Fix various typos
4057
# for the same test.
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
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
5743.10.1 by Vincent Ladeuil
Derefence the ref to use it.
4064
# The registered object should be a callable receiving a test instance
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
4065
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
4066
# object.
4067
test_stack_builder_registry = registry.Registry()