/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5598.2.1 by John Arbash Meinel
Decode windows env vars using mbcs rather than assuming the 8-bit string is ok.
1
# Copyright (C) 2005-2011 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
1442.1.20 by Robert Collins
add some documentation on options
19
"""Configuration that affects the behaviour of Bazaar.
20
21
Currently this configuration resides in ~/.bazaar/bazaar.conf
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
22
and ~/.bazaar/locations.conf, which is written to by bzr.
1442.1.20 by Robert Collins
add some documentation on options
23
1461 by Robert Collins
Typo in config.py (Thanks Fabbione)
24
In bazaar.conf the following options may be set:
1442.1.20 by Robert Collins
add some documentation on options
25
[DEFAULT]
26
editor=name-of-program
27
email=Your Name <your@email.address>
28
check_signatures=require|ignore|check-available(default)
29
create_signatures=always|never|when-required(default)
1442.1.56 by Robert Collins
gpg_signing_command configuration item
30
gpg_signing_command=name-of-program
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
31
log_format=name-of-format
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
32
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
33
acceptable_keys=pattern1,pattern2
1442.1.20 by Robert Collins
add some documentation on options
34
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
35
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
36
Wildcards may be used - * and ? as normal in shell completion. Options
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
37
set in both bazaar.conf and locations.conf are overridden by the locations.conf
1442.1.20 by Robert Collins
add some documentation on options
38
setting.
39
[/home/robertc/source]
40
recurse=False|True(default)
41
email= as above
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
42
check_signatures= as above
1442.1.20 by Robert Collins
add some documentation on options
43
create_signatures= as above.
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
44
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
45
acceptable_keys=as above
1442.1.20 by Robert Collins
add some documentation on options
46
47
explanation of options
48
----------------------
49
editor - this option sets the pop up editor to use during commits.
50
email - this option sets the user id bzr will use when committing.
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
51
check_signatures - this option will control whether bzr will require good gpg
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
52
                   signatures, ignore them, or check them if they are
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
53
                   present.  Currently it is unused except that check_signatures
54
                   turns on create_signatures.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
55
create_signatures - this option controls whether bzr 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
56
                    gpg signatures or not on commits.  There is an unused
57
                    option which in future is expected to work if               
58
                    branch settings require signatures.
1887.2.1 by Adeodato Simó
Fix some typos and grammar issues.
59
log_format - this option sets the default log format.  Possible values are
60
             long, short, line, or a plugin can register new formats.
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
61
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
62
acceptable_keys - comma separated list of key patterns acceptable for
63
                  verify-signatures command
1553.6.2 by Erik Bågfors
documentation and NEWS
64
65
In bazaar.conf you can also define aliases in the ALIASES sections, example
66
67
[ALIASES]
68
lastlog=log --line -r-10..-1
69
ll=log --line -r-10..-1
70
h=help
71
up=pull
1442.1.20 by Robert Collins
add some documentation on options
72
"""
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
73
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
74
import os
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
75
import string
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
76
import sys
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
77
78
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
79
from bzrlib.decorators import needs_write_lock
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
80
from bzrlib.lazy_import import lazy_import
81
lazy_import(globals(), """
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
82
import fnmatch
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
83
import re
2900.2.22 by Vincent Ladeuil
Polishing.
84
from cStringIO import StringIO
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
85
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
86
from bzrlib import (
4797.59.2 by Vincent Ladeuil
Use AtomicFile and avoid all unicode/encoding issues around transport (thanks jam).
87
    atomicfile,
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
88
    bzrdir,
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
89
    debug,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
90
    errors,
5967.9.3 by Martin Pool
Explicitly use lazy_regexp where we count on its error reporting behaviour
91
    lazy_regex,
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
92
    lockdir,
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
93
    mail_client,
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
94
    mergetools,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
95
    osutils,
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
96
    symbol_versioning,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
97
    trace,
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
98
    transport,
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
99
    ui,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
100
    urlutils,
2245.4.3 by Alexander Belchenko
config.py: changing _auto_user_id() and config_dir() to use functions from win32utils
101
    win32utils,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
102
    )
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
103
from bzrlib.util.configobj import configobj
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
104
""")
5904.1.2 by Martin Pool
Various pyflakes import fixes.
105
from bzrlib import (
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
106
    commands,
107
    hooks,
5904.1.2 by Martin Pool
Various pyflakes import fixes.
108
    registry,
109
    )
5743.13.1 by Vincent Ladeuil
Deprecate _get_editor to identify its usages.
110
from bzrlib.symbol_versioning import (
111
    deprecated_in,
112
    deprecated_method,
113
    )
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
114
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
115
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
116
CHECK_IF_POSSIBLE=0
117
CHECK_ALWAYS=1
118
CHECK_NEVER=2
119
120
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
121
SIGN_WHEN_REQUIRED=0
122
SIGN_ALWAYS=1
123
SIGN_NEVER=2
124
125
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
126
POLICY_NONE = 0
127
POLICY_NORECURSE = 1
128
POLICY_APPENDPATH = 2
129
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
130
_policy_name = {
131
    POLICY_NONE: None,
132
    POLICY_NORECURSE: 'norecurse',
133
    POLICY_APPENDPATH: 'appendpath',
134
    }
135
_policy_value = {
136
    None: POLICY_NONE,
137
    'none': POLICY_NONE,
138
    'norecurse': POLICY_NORECURSE,
139
    'appendpath': POLICY_APPENDPATH,
140
    }
2120.6.4 by James Henstridge
add support for specifying policy when storing options
141
142
143
STORE_LOCATION = POLICY_NONE
144
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
145
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
146
STORE_BRANCH = 3
147
STORE_GLOBAL = 4
148
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
149
150
class ConfigObj(configobj.ConfigObj):
151
152
    def __init__(self, infile=None, **kwargs):
153
        # We define our own interpolation mechanism calling it option expansion
154
        super(ConfigObj, self).__init__(infile=infile,
155
                                        interpolation=False,
156
                                        **kwargs)
157
158
    def get_bool(self, section, key):
159
        return self[section].as_bool(key)
160
161
    def get_value(self, section, name):
162
        # Try [] for the old DEFAULT section.
163
        if section == "DEFAULT":
164
            try:
165
                return self[name]
166
            except KeyError:
167
                pass
168
        return self[section][name]
169
170
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
171
# FIXME: Until we can guarantee that each config file is loaded once and
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
172
# only once for a given bzrlib session, we don't want to re-read the file every
173
# time we query for an option so we cache the value (bad ! watch out for tests
174
# needing to restore the proper value).This shouldn't be part of 2.4.0 final,
175
# yell at mgz^W vila and the RM if this is still present at that time
176
# -- vila 20110219
177
_expand_default_value = None
178
def _get_expand_default_value():
179
    global _expand_default_value
180
    if _expand_default_value is not None:
181
        return _expand_default_value
182
    conf = GlobalConfig()
183
    # Note that we must not use None for the expand value below or we'll run
184
    # into infinite recursion. Using False really would be quite silly ;)
185
    expand = conf.get_user_option_as_bool('bzr.config.expand', expand=True)
186
    if expand is None:
187
        # This is an opt-in feature, you *really* need to clearly say you want
188
        # to activate it !
189
        expand = False
190
    _expand_default_value = expand
191
    return expand
5549.1.31 by Vincent Ladeuil
Implement a default value for config option expansion (what ? No tests ?).
192
5549.1.19 by Vincent Ladeuil
Push down interpolation at the config level (make tests slightly less
193
194
class Config(object):
195
    """A configuration policy - what username, editor, gpg needs etc."""
196
197
    def __init__(self):
198
        super(Config, self).__init__()
199
200
    def config_id(self):
201
        """Returns a unique ID for the config."""
202
        raise NotImplementedError(self.config_id)
203
5743.13.1 by Vincent Ladeuil
Deprecate _get_editor to identify its usages.
204
    @deprecated_method(deprecated_in((2, 4, 0)))
5549.1.19 by Vincent Ladeuil
Push down interpolation at the config level (make tests slightly less
205
    def get_editor(self):
206
        """Get the users pop up editor."""
207
        raise NotImplementedError
208
209
    def get_change_editor(self, old_tree, new_tree):
210
        from bzrlib import diff
211
        cmd = self._get_change_editor()
212
        if cmd is None:
213
            return None
214
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
215
                                             sys.stdout)
216
217
    def get_mail_client(self):
218
        """Get a mail client to use"""
219
        selected_client = self.get_user_option('mail_client')
220
        _registry = mail_client.mail_client_registry
221
        try:
222
            mail_client_class = _registry.get(selected_client)
223
        except KeyError:
224
            raise errors.UnknownMailClient(selected_client)
225
        return mail_client_class(self)
226
227
    def _get_signature_checking(self):
228
        """Template method to override signature checking policy."""
229
230
    def _get_signing_policy(self):
231
        """Template method to override signature creation policy."""
232
6012.2.3 by Jonathan Riddell
add config option for signing key
233
    def _get_signing_key(self):
234
        """Template method to override default gpg key."""
235
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
236
    option_ref_re = None
237
238
    def expand_options(self, string, env=None):
239
        """Expand option references in the string in the configuration context.
240
241
        :param string: The string containing option to expand.
242
243
        :param env: An option dict defining additional configuration options or
244
            overriding existing ones.
245
246
        :returns: The expanded string.
247
        """
248
        return self._expand_options_in_string(string, env)
249
250
    def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
251
        """Expand options in  a list of strings in the configuration context.
252
253
        :param slist: A list of strings.
254
255
        :param env: An option dict defining additional configuration options or
256
            overriding existing ones.
257
258
        :param _ref_stack: Private list containing the options being
259
            expanded to detect loops.
260
261
        :returns: The flatten list of expanded strings.
262
        """
263
        # expand options in each value separately flattening lists
264
        result = []
265
        for s in slist:
266
            value = self._expand_options_in_string(s, env, _ref_stack)
267
            if isinstance(value, list):
268
                result.extend(value)
269
            else:
270
                result.append(value)
271
        return result
272
273
    def _expand_options_in_string(self, string, env=None, _ref_stack=None):
274
        """Expand options in the string in the configuration context.
275
276
        :param string: The string to be expanded.
277
278
        :param env: An option dict defining additional configuration options or
279
            overriding existing ones.
280
281
        :param _ref_stack: Private list containing the options being
282
            expanded to detect loops.
283
284
        :returns: The expanded string.
285
        """
286
        if string is None:
287
            # Not much to expand there
288
            return None
289
        if _ref_stack is None:
290
            # What references are currently resolved (to detect loops)
291
            _ref_stack = []
292
        if self.option_ref_re is None:
293
            # We want to match the most embedded reference first (i.e. for
294
            # '{{foo}}' we will get '{foo}',
295
            # for '{bar{baz}}' we will get '{baz}'
296
            self.option_ref_re = re.compile('({[^{}]+})')
297
        result = string
298
        # We need to iterate until no more refs appear ({{foo}} will need two
299
        # iterations for example).
300
        while True:
5745.1.1 by Vincent Ladeuil
Remove debug code
301
            raw_chunks = self.option_ref_re.split(result)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
302
            if len(raw_chunks) == 1:
303
                # Shorcut the trivial case: no refs
304
                return result
305
            chunks = []
306
            list_value = False
307
            # Split will isolate refs so that every other chunk is a ref
308
            chunk_is_ref = False
309
            for chunk in raw_chunks:
310
                if not chunk_is_ref:
311
                    if chunk:
312
                        # Keep only non-empty strings (or we get bogus empty
313
                        # slots when a list value is involved).
314
                        chunks.append(chunk)
315
                    chunk_is_ref = True
316
                else:
317
                    name = chunk[1:-1]
318
                    if name in _ref_stack:
319
                        raise errors.OptionExpansionLoop(string, _ref_stack)
320
                    _ref_stack.append(name)
321
                    value = self._expand_option(name, env, _ref_stack)
322
                    if value is None:
323
                        raise errors.ExpandingUnknownOption(name, string)
324
                    if isinstance(value, list):
325
                        list_value = True
326
                        chunks.extend(value)
327
                    else:
328
                        chunks.append(value)
329
                    _ref_stack.pop()
330
                    chunk_is_ref = False
331
            if list_value:
332
                # Once a list appears as the result of an expansion, all
333
                # callers will get a list result. This allows a consistent
334
                # behavior even when some options in the expansion chain
335
                # defined as strings (no comma in their value) but their
336
                # expanded value is a list.
337
                return self._expand_options_in_list(chunks, env, _ref_stack)
338
            else:
339
                result = ''.join(chunks)
340
        return result
341
342
    def _expand_option(self, name, env, _ref_stack):
343
        if env is not None and name in env:
344
            # Special case, values provided in env takes precedence over
345
            # anything else
346
            value = env[name]
347
        else:
348
            # FIXME: This is a limited implementation, what we really need is a
349
            # way to query the bzr config for the value of an option,
350
            # respecting the scope rules (That is, once we implement fallback
351
            # configs, getting the option value should restart from the top
352
            # config, not the current one) -- vila 20101222
353
            value = self.get_user_option(name, expand=False)
354
            if isinstance(value, list):
355
                value = self._expand_options_in_list(value, env, _ref_stack)
356
            else:
357
                value = self._expand_options_in_string(value, env, _ref_stack)
358
        return value
359
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
360
    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.
361
        """Template method to provide a user option."""
362
        return None
363
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
364
    def get_user_option(self, option_name, expand=None):
365
        """Get a generic option - no special process, no default.
366
367
        :param option_name: The queried option.
368
369
        :param expand: Whether options references should be expanded.
370
371
        :returns: The value of the option.
372
        """
373
        if expand is None:
374
            expand = _get_expand_default_value()
375
        value = self._get_user_option(option_name)
376
        if expand:
377
            if isinstance(value, list):
378
                value = self._expand_options_in_list(value)
379
            elif isinstance(value, dict):
380
                trace.warning('Cannot expand "%s":'
381
                              ' Dicts do not support option expansion'
382
                              % (option_name,))
383
            else:
384
                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.
385
        for hook in OldConfigHooks['get']:
5743.8.25 by Vincent Ladeuil
Fix spurious spaces.
386
            hook(self, option_name, value)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
387
        return value
388
5425.4.14 by Martin Pool
Allow get_user_option_as_bool to take a default
389
    def get_user_option_as_bool(self, option_name, expand=None, default=None):
390
        """Get a generic option as a boolean.
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
391
5425.4.14 by Martin Pool
Allow get_user_option_as_bool to take a default
392
        :param expand: Allow expanding references to other config values.
393
        :param default: Default value if nothing is configured
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
394
        :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.
395
            interpreted as a boolean. Returns True or False otherwise.
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
396
        """
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
397
        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.
398
        if s is None:
399
            # The option doesn't exist
5425.4.14 by Martin Pool
Allow get_user_option_as_bool to take a default
400
            return default
4989.2.15 by Vincent Ladeuil
Fixed as per Andrew's review.
401
        val = ui.bool_from_string(s)
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
402
        if val is None:
403
            # The value can't be interpreted as a boolean
404
            trace.warning('Value "%s" is not a boolean for "%s"',
405
                          s, option_name)
406
        return val
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
407
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
408
    def get_user_option_as_list(self, option_name, expand=None):
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
409
        """Get a generic option as a list - no special process, no default.
410
411
        :return None if the option doesn't exist. Returns the value as a list
412
            otherwise.
413
        """
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
414
        l = self.get_user_option(option_name, expand=expand)
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
415
        if isinstance(l, (str, unicode)):
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
416
            # A single value, most probably the user forgot (or didn't care to
417
            # add) the final ','
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
418
            l = [l]
419
        return l
420
1442.1.56 by Robert Collins
gpg_signing_command configuration item
421
    def gpg_signing_command(self):
422
        """What program should be used to sign signatures?"""
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
423
        result = self._gpg_signing_command()
424
        if result is None:
425
            result = "gpg"
426
        return result
427
428
    def _gpg_signing_command(self):
429
        """See gpg_signing_command()."""
430
        return None
1442.1.56 by Robert Collins
gpg_signing_command configuration item
431
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
432
    def log_format(self):
433
        """What log format should be used"""
434
        result = self._log_format()
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
435
        if result is None:
436
            result = "long"
437
        return result
438
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
439
    def _log_format(self):
440
        """See log_format()."""
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
441
        return None
442
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
443
    def validate_signatures_in_log(self):
444
        """Show GPG signature validity in log"""
445
        result = self._validate_signatures_in_log()
446
        if result == "true":
447
            result = True
448
        else:
449
            result = False
450
        return result
451
452
    def _validate_signatures_in_log(self):
453
        """See validate_signatures_in_log()."""
454
        return None
455
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
456
    def acceptable_keys(self):
457
        """Comma separated list of key patterns acceptable to 
458
        verify-signatures command"""
459
        result = self._acceptable_keys()
460
        return result
461
462
    def _acceptable_keys(self):
463
        """See acceptable_keys()."""
464
        return None
465
1472 by Robert Collins
post commit hook, first pass implementation
466
    def post_commit(self):
467
        """An ordered list of python functions to call.
468
469
        Each function takes branch, rev_id as parameters.
470
        """
471
        return self._post_commit()
472
473
    def _post_commit(self):
474
        """See Config.post_commit."""
475
        return None
476
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
477
    def user_email(self):
478
        """Return just the email component of a username."""
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
479
        return extract_email_address(self.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
480
481
    def username(self):
482
        """Return email-style username.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
483
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
484
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
485
5187.2.1 by Parth Malwankar
removed comment about deprecated BZREMAIL.
486
        $BZR_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
487
        the concrete policy type is checked, and finally
1185.37.2 by Jamie Wilkinson
Fix a typo and grammar in Config.username() docstring.
488
        $EMAIL is examined.
5187.2.12 by Parth Malwankar
trivial clarification in docstring.
489
        If no username can be found, errors.NoWhoami exception is raised.
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
490
        """
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
491
        v = os.environ.get('BZR_EMAIL')
492
        if v:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
493
            return v.decode(osutils.get_user_encoding())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
494
        v = self._get_user_id()
495
        if v:
496
            return v
497
        v = os.environ.get('EMAIL')
498
        if v:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
499
            return v.decode(osutils.get_user_encoding())
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
500
        name, email = _auto_user_id()
501
        if name and email:
502
            return '%s <%s>' % (name, email)
503
        elif email:
504
            return email
5187.2.6 by Parth Malwankar
lockdir no long mandates whoami but uses unicode version of getuser
505
        raise errors.NoWhoami()
5187.2.3 by Parth Malwankar
init and init-repo now fail before creating dir if username is not set.
506
507
    def ensure_username(self):
5187.2.11 by Parth Malwankar
documentation updates
508
        """Raise errors.NoWhoami if username is not set.
5187.2.3 by Parth Malwankar
init and init-repo now fail before creating dir if username is not set.
509
510
        This method relies on the username() function raising the error.
511
        """
512
        self.username()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
513
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
514
    def signature_checking(self):
515
        """What is the current policy for signature checking?."""
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
516
        policy = self._get_signature_checking()
517
        if policy is not None:
518
            return policy
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
519
        return CHECK_IF_POSSIBLE
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
520
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
521
    def signing_policy(self):
522
        """What is the current policy for signature checking?."""
523
        policy = self._get_signing_policy()
524
        if policy is not None:
525
            return policy
526
        return SIGN_WHEN_REQUIRED
527
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
528
    def signature_needed(self):
529
        """Is a signature needed when committing ?."""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
530
        policy = self._get_signing_policy()
531
        if policy is None:
532
            policy = self._get_signature_checking()
533
            if policy is not None:
5967.3.2 by Jonathan Riddell
do not treat 'check_signatures = require' as if it were 'create_signatures = always', this is confusing and wrong
534
                #this warning should go away once check_signatures is
535
                #implemented (if not before)
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
536
                trace.warning("Please use create_signatures,"
537
                              " not check_signatures to set signing policy.")
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
538
        elif policy == SIGN_ALWAYS:
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
539
            return True
540
        return False
541
6012.2.3 by Jonathan Riddell
add config option for signing key
542
    def signing_key(self):
543
        """GPG user-id to sign commits"""
544
        key = self._get_signing_key()
545
        if key == "default":
546
            return None
547
        else:
548
            return key
549
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
550
    def get_alias(self, value):
551
        return self._get_alias(value)
552
553
    def _get_alias(self, value):
554
        pass
555
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
556
    def get_nickname(self):
557
        return self._get_nickname()
558
559
    def _get_nickname(self):
560
        return None
561
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
562
    def get_bzr_remote_path(self):
563
        try:
564
            return os.environ['BZR_REMOTE_PATH']
565
        except KeyError:
566
            path = self.get_user_option("bzr_remote_path")
567
            if path is None:
568
                path = 'bzr'
569
            return path
570
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
571
    def suppress_warning(self, warning):
572
        """Should the warning be suppressed or emitted.
573
574
        :param warning: The name of the warning being tested.
575
576
        :returns: True if the warning should be suppressed, False otherwise.
577
        """
578
        warnings = self.get_user_option_as_list('suppress_warnings')
579
        if warnings is None or warning not in warnings:
580
            return False
581
        else:
582
            return True
583
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
584
    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.
585
        tools = {}
5321.1.99 by Gordon Tyler
Fixes for changes to Config._get_options().
586
        for (oname, value, section, conf_id, parser) in self._get_options():
5321.2.3 by Vincent Ladeuil
Prefix mergetools option names with 'bzr.'.
587
            if oname.startswith('bzr.mergetool.'):
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.
588
                tool_name = oname[len('bzr.mergetool.'):]
5321.1.116 by Gordon Tyler
Simplified mergetools module down to functions which deal with command lines -- no MergeTool class.
589
                tools[tool_name] = value
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
590
        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.
591
        return tools
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
592
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.
593
    def find_merge_tool(self, name):
5967.3.6 by Jonathan Riddell
use example.com for e-mails, make bzrlib/config.py pep8 happy
594
        # 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.
595
        # be found in the known_merge_tools if it's not found in the config.
596
        # This should be done through the proposed config defaults mechanism
597
        # when it becomes available in the future.
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
598
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
599
                                             expand=False)
600
                        or 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.
601
        return command_line
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
602
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
603
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.
604
class _ConfigHooks(hooks.Hooks):
605
    """A dict mapping hook names and a list of callables for configs.
606
    """
607
608
    def __init__(self):
609
        """Create the default hooks.
610
611
        These are all empty initially, because by default nothing should get
612
        notified.
613
        """
614
        super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
615
        self.add_hook('load',
616
                      'Invoked when a config store is loaded.'
617
                      ' The signature is (store).',
618
                      (2, 4))
619
        self.add_hook('save',
620
                      'Invoked when a config store is saved.'
621
                      ' The signature is (store).',
622
                      (2, 4))
623
        # The hooks for config options
624
        self.add_hook('get',
625
                      'Invoked when a config option is read.'
626
                      ' The signature is (stack, name, value).',
627
                      (2, 4))
628
        self.add_hook('set',
629
                      'Invoked when a config option is set.'
630
                      ' The signature is (stack, name, value).',
631
                      (2, 4))
632
        self.add_hook('remove',
633
                      'Invoked when a config option is removed.'
634
                      ' The signature is (stack, name).',
635
                      (2, 4))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
636
ConfigHooks = _ConfigHooks()
637
638
639
class _OldConfigHooks(hooks.Hooks):
640
    """A dict mapping hook names and a list of callables for configs.
641
    """
642
643
    def __init__(self):
644
        """Create the default hooks.
645
646
        These are all empty initially, because by default nothing should get
647
        notified.
648
        """
649
        super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
650
        self.add_hook('load',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
651
                      'Invoked when a config store is loaded.'
652
                      ' The signature is (config).',
653
                      (2, 4))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
654
        self.add_hook('save',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
655
                      'Invoked when a config store is saved.'
656
                      ' The signature is (config).',
657
                      (2, 4))
658
        # The hooks for config options
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
659
        self.add_hook('get',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
660
                      'Invoked when a config option is read.'
661
                      ' The signature is (config, name, value).',
662
                      (2, 4))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
663
        self.add_hook('set',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
664
                      'Invoked when a config option is set.'
665
                      ' The signature is (config, name, value).',
666
                      (2, 4))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
667
        self.add_hook('remove',
5743.8.14 by Vincent Ladeuil
Separate the hooks for old and new config implementations instead of cheating like crazy.
668
                      'Invoked when a config option is removed.'
669
                      ' The signature is (config, name).',
670
                      (2, 4))
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
671
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.
672
673
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
674
class IniBasedConfig(Config):
675
    """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
676
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
677
    def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
678
                 file_name=None):
5345.2.5 by Vincent Ladeuil
Add docstring.
679
        """Base class for configuration files using an ini-like syntax.
680
681
        :param file_name: The configuration file path.
682
        """
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
683
        super(IniBasedConfig, self).__init__()
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
684
        self.file_name = file_name
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
685
        if symbol_versioning.deprecated_passed(get_filename):
686
            symbol_versioning.warn(
687
                'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
688
                ' Use file_name instead.',
689
                DeprecationWarning,
690
                stacklevel=2)
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
691
            if get_filename is not None:
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
692
                self.file_name = get_filename()
693
        else:
694
            self.file_name = file_name
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
695
        self._content = None
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
696
        self._parser = None
697
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
698
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
699
    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
700
        """Create a config object from a string.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
701
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
702
        :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.
703
            be utf-8 encoded.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
704
705
        :param file_name: The configuration file path.
706
707
        :param _save: Whether the file should be saved upon creation.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
708
        """
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
709
        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
710
        conf._create_from_string(str_or_unicode, save)
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
711
        return conf
712
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
713
    def _create_from_string(self, str_or_unicode, save):
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
714
        self._content = StringIO(str_or_unicode.encode('utf-8'))
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
715
        # Some tests use in-memory configs, some other always need the config
716
        # file to exist on disk.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
717
        if save:
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
718
            self._write_config_file()
5345.5.12 by Vincent Ladeuil
Fix fallouts from replacing '_content' by 'from_bytes' for config files.
719
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
720
    def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
721
        if self._parser is not None:
722
            return self._parser
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
723
        if symbol_versioning.deprecated_passed(file):
724
            symbol_versioning.warn(
725
                'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
5345.1.5 by Vincent Ladeuil
Fix fallouts by slightly editing the tests. More refactoring avoided to keep the review light.
726
                ' Use IniBasedConfig(_content=xxx) instead.',
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
727
                DeprecationWarning,
728
                stacklevel=2)
729
        if self._content is not None:
730
            co_input = self._content
731
        elif self.file_name is None:
732
            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
733
        else:
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
734
            co_input = self.file_name
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
735
        try:
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
736
            self._parser = ConfigObj(co_input, encoding='utf-8')
1474 by Robert Collins
Merge from Aaron Bentley.
737
        except configobj.ConfigObjError, e:
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
738
            raise errors.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
739
        except UnicodeDecodeError:
740
            raise errors.ConfigContentError(self.file_name)
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
741
        # 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.
742
        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.
743
        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.
744
            hook(self)
1185.12.49 by Aaron Bentley
Switched to ConfigObj
745
        return self._parser
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
746
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
747
    def reload(self):
748
        """Reload the config file from disk."""
749
        if self.file_name is None:
750
            raise AssertionError('We need a file name to reload the config')
751
        if self._parser is not None:
752
            self._parser.reload()
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
753
        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.
754
            hook(self)
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
755
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
756
    def _get_matching_sections(self):
757
        """Return an ordered list of (section_name, extra_path) pairs.
758
759
        If the section contains inherited configuration, extra_path is
760
        a string containing the additional path components.
761
        """
762
        section = self._get_section()
763
        if section is not None:
764
            return [(section, '')]
765
        else:
766
            return []
767
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
768
    def _get_section(self):
769
        """Override this to define the section used by the config."""
770
        return "DEFAULT"
771
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.
772
    def _get_sections(self, name=None):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
773
        """Returns an iterator of the sections specified by ``name``.
774
775
        :param name: The section name. If None is supplied, the default
776
            configurations are yielded.
777
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
778
        :return: A tuple (name, section, config_id) for all sections that will
779
            be walked by user_get_option() in the 'right' order. The first one
780
            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.
781
        """
782
        parser = self._get_parser()
783
        if name is not None:
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
784
            yield (name, parser[name], self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
785
        else:
786
            # No section name has been given so we fallback to the configobj
787
            # 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.
788
            yield (None, parser, self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
789
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.
790
    def _get_options(self, sections=None):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
791
        """Return an ordered list of (name, value, section, config_id) tuples.
792
793
        All options are returned with their associated value and the section
794
        they appeared in. ``config_id`` is a unique identifier for the
795
        configuration file the option is defined in.
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
796
797
        :param sections: Default to ``_get_matching_sections`` if not
798
            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.
799
            which sections should be searched. This is a list of (name,
800
            configobj) tuples.
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
801
        """
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
802
        opts = []
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
803
        if sections is None:
804
            parser = self._get_parser()
805
            sections = []
806
            for (section_name, _) in self._get_matching_sections():
807
                try:
808
                    section = parser[section_name]
809
                except KeyError:
810
                    # This could happen for an empty file for which we define a
811
                    # DEFAULT section. FIXME: Force callers to provide sections
812
                    # instead ? -- vila 20100930
813
                    continue
814
                sections.append((section_name, section))
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
815
        config_id = self.config_id()
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
816
        for (section_name, section) in sections:
817
            for (name, value) in section.iteritems():
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
818
                yield (name, parser._quote(value), section_name,
819
                       config_id, parser)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
820
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
821
    def _get_option_policy(self, section, option_name):
822
        """Return the policy for the given (section, option_name) pair."""
823
        return POLICY_NONE
824
4603.1.10 by Aaron Bentley
Provide change editor via config.
825
    def _get_change_editor(self):
826
        return self.get_user_option('change_editor')
827
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
828
    def _get_signature_checking(self):
829
        """See Config._get_signature_checking."""
1474 by Robert Collins
Merge from Aaron Bentley.
830
        policy = self._get_user_option('check_signatures')
831
        if policy:
832
            return self._string_to_signature_policy(policy)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
833
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
834
    def _get_signing_policy(self):
1773.4.3 by Martin Pool
[merge] bzr.dev
835
        """See Config._get_signing_policy"""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
836
        policy = self._get_user_option('create_signatures')
837
        if policy:
838
            return self._string_to_signing_policy(policy)
839
6012.2.3 by Jonathan Riddell
add config option for signing key
840
    def _get_signing_key(self):
841
        """See Config._get_signing_key"""
842
        return self._get_user_option('signing_key')
843
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
844
    def _get_user_id(self):
845
        """Get the user id from the 'email' key in the current section."""
1474 by Robert Collins
Merge from Aaron Bentley.
846
        return self._get_user_option('email')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
847
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
848
    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.
849
        """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
850
        for (section, extra_path) in self._get_matching_sections():
851
            try:
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
852
                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
853
            except KeyError:
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
854
                continue
855
            policy = self._get_option_policy(section, option_name)
856
            if policy == POLICY_NONE:
857
                return value
858
            elif policy == POLICY_NORECURSE:
859
                # norecurse items only apply to the exact path
860
                if extra_path:
861
                    continue
862
                else:
863
                    return value
864
            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
865
                if extra_path:
866
                    value = urlutils.join(value, extra_path)
867
                return value
2120.6.6 by James Henstridge
fix test_set_push_location test
868
            else:
869
                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
870
        else:
1993.3.1 by James Henstridge
first go at making location config lookup recursive
871
            return None
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
872
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
873
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
874
        """See Config.gpg_signing_command."""
1472 by Robert Collins
post commit hook, first pass implementation
875
        return self._get_user_option('gpg_signing_command')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
876
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
877
    def _log_format(self):
878
        """See Config.log_format."""
879
        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
880
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
881
    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
882
        """See Config.validate_signatures_in_log."""
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
883
        return self._get_user_option('validate_signatures_in_log')
884
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
885
    def _acceptable_keys(self):
886
        """See Config.acceptable_keys."""
887
        return self._get_user_option('acceptable_keys')
888
1472 by Robert Collins
post commit hook, first pass implementation
889
    def _post_commit(self):
890
        """See Config.post_commit."""
891
        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
892
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
893
    def _string_to_signature_policy(self, signature_string):
894
        """Convert a string to a signing policy."""
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
895
        if signature_string.lower() == 'check-available':
896
            return CHECK_IF_POSSIBLE
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
897
        if signature_string.lower() == 'ignore':
898
            return CHECK_NEVER
1442.1.17 by Robert Collins
allow global overriding of signature policy to force checking, or (pointless but allowed) to set auto checking
899
        if signature_string.lower() == 'require':
900
            return CHECK_ALWAYS
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
901
        raise errors.BzrError("Invalid signatures policy '%s'"
902
                              % signature_string)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
903
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
904
    def _string_to_signing_policy(self, signature_string):
905
        """Convert a string to a signing policy."""
906
        if signature_string.lower() == 'when-required':
907
            return SIGN_WHEN_REQUIRED
908
        if signature_string.lower() == 'never':
909
            return SIGN_NEVER
910
        if signature_string.lower() == 'always':
911
            return SIGN_ALWAYS
912
        raise errors.BzrError("Invalid signing policy '%s'"
913
                              % signature_string)
914
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
915
    def _get_alias(self, value):
916
        try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
917
            return self._get_parser().get_value("ALIASES",
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
918
                                                value)
919
        except KeyError:
920
            pass
921
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
922
    def _get_nickname(self):
923
        return self.get_user_option('nickname')
924
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
925
    def remove_user_option(self, option_name, section_name=None):
926
        """Remove a user option and save the configuration file.
927
928
        :param option_name: The option to be removed.
929
930
        :param section_name: The section the option is defined in, default to
931
            the default section.
932
        """
933
        self.reload()
934
        parser = self._get_parser()
935
        if section_name is None:
936
            section = parser
937
        else:
938
            section = parser[section_name]
939
        try:
940
            del section[option_name]
941
        except KeyError:
942
            raise errors.NoSuchConfigOption(option_name)
943
        self._write_config_file()
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
944
        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.
945
            hook(self, option_name)
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
946
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
947
    def _write_config_file(self):
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
948
        if self.file_name is None:
949
            raise AssertionError('We cannot save, self.file_name is None')
5345.1.9 by Vincent Ladeuil
Refactor config dir check.
950
        conf_dir = os.path.dirname(self.file_name)
951
        ensure_config_dir_exists(conf_dir)
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
952
        atomic_file = atomicfile.AtomicFile(self.file_name)
5050.6.1 by Vincent Ladeuil
Merge 2.1 into 2.2 including fixes for bug #525571 and bug #494221
953
        self._get_parser().write(atomic_file)
954
        atomic_file.commit()
955
        atomic_file.close()
5345.3.3 by Vincent Ladeuil
Merge bzr.dev into deprecate-get-filename resolving conflicts
956
        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.
957
        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.
958
            hook(self)
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
959
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
960
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
961
class LockableConfig(IniBasedConfig):
962
    """A configuration needing explicit locking for access.
963
964
    If several processes try to write the config file, the accesses need to be
965
    serialized.
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
966
967
    Daughter classes should decorate all methods that update a config with the
968
    ``@needs_write_lock`` decorator (they call, directly or indirectly, the
969
    ``_write_config_file()`` method. These methods (typically ``set_option()``
970
    and variants must reload the config file from disk before calling
971
    ``_write_config_file()``), this can be achieved by calling the
972
    ``self.reload()`` method. Note that the lock scope should cover both the
973
    reading and the writing of the config file which is why the decorator can't
974
    be applied to ``_write_config_file()`` only.
975
976
    This should be enough to implement the following logic:
977
    - lock for exclusive write access,
978
    - reload the config file from disk,
979
    - set the new value
980
    - unlock
981
982
    This logic guarantees that a writer can update a value without erasing an
983
    update made by another writer.
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
984
    """
985
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
986
    lock_name = 'lock'
987
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
988
    def __init__(self, file_name):
989
        super(LockableConfig, self).__init__(file_name=file_name)
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
990
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
991
        # FIXME: It doesn't matter that we don't provide possible_transports
992
        # below since this is currently used only for local config files ;
993
        # local transports are not shared. But if/when we start using
994
        # LockableConfig for other kind of transports, we will need to reuse
995
        # whatever connection is already established -- vila 20100929
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
996
        self.transport = transport.get_transport(self.dir)
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
997
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
998
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
999
    def _create_from_string(self, unicode_bytes, save):
1000
        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.
1001
        if save:
5345.1.24 by Vincent Ladeuil
Implement _save for LockableConfig too.
1002
            # We need to handle the saving here (as opposed to IniBasedConfig)
1003
            # to be able to lock
1004
            self.lock_write()
1005
            self._write_config_file()
1006
            self.unlock()
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
1007
1008
    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.
1009
        """Takes a write lock in the directory containing the config file.
1010
1011
        If the directory doesn't exist it is created.
1012
        """
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
1013
        ensure_config_dir_exists(self.dir)
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
1014
        return self._lock.lock_write(token)
1015
1016
    def unlock(self):
1017
        self._lock.unlock()
1018
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
1019
    def break_lock(self):
1020
        self._lock.break_lock()
1021
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1022
    @needs_write_lock
1023
    def remove_user_option(self, option_name, section_name=None):
1024
        super(LockableConfig, self).remove_user_option(option_name,
1025
                                                       section_name)
1026
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
1027
    def _write_config_file(self):
1028
        if self._lock is None or not self._lock.is_held:
1029
            # NB: if the following exception is raised it probably means a
1030
            # missing @needs_write_lock decorator on one of the callers.
1031
            raise errors.ObjectNotLocked(self)
1032
        super(LockableConfig, self)._write_config_file()
1033
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
1034
1035
class GlobalConfig(LockableConfig):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1036
    """The configuration that should be used for a specific location."""
1037
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1038
    def __init__(self):
1039
        super(GlobalConfig, self).__init__(file_name=config_filename())
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
1040
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1041
    def config_id(self):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1042
        return 'bazaar'
1043
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1044
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1045
    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
1046
        """Create a config object from a string.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1047
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
1048
        :param str_or_unicode: A string representing the file content. This
1049
            will be utf-8 encoded.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
1050
1051
        :param save: Whether the file should be saved upon creation.
1052
        """
1053
        conf = cls()
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1054
        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.
1055
        return conf
5345.5.12 by Vincent Ladeuil
Fix fallouts from replacing '_content' by 'from_bytes' for config files.
1056
5743.13.1 by Vincent Ladeuil
Deprecate _get_editor to identify its usages.
1057
    @deprecated_method(deprecated_in((2, 4, 0)))
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1058
    def get_editor(self):
1474 by Robert Collins
Merge from Aaron Bentley.
1059
        return self._get_user_option('editor')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1060
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
1061
    @needs_write_lock
1816.2.1 by Robey Pointer
add set_user_option to GlobalConfig, and make /etc/passwd username lookup try harder with encodings
1062
    def set_user_option(self, option, value):
1063
        """Save option and its value in the configuration."""
2900.3.2 by Tim Penhey
A working alias command.
1064
        self._set_option(option, value, 'DEFAULT')
1065
1066
    def get_aliases(self):
1067
        """Return the aliases section."""
1068
        if 'ALIASES' in self._get_parser():
1069
            return self._get_parser()['ALIASES']
1070
        else:
1071
            return {}
1072
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
1073
    @needs_write_lock
2900.3.2 by Tim Penhey
A working alias command.
1074
    def set_alias(self, alias_name, alias_command):
1075
        """Save the alias in the configuration."""
1076
        self._set_option(alias_name, alias_command, 'ALIASES')
1077
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
1078
    @needs_write_lock
2900.3.2 by Tim Penhey
A working alias command.
1079
    def unset_alias(self, alias_name):
1080
        """Unset an existing alias."""
5345.5.10 by Vincent Ladeuil
Add a missing config.reload().
1081
        self.reload()
2900.3.2 by Tim Penhey
A working alias command.
1082
        aliases = self._get_parser().get('ALIASES')
2900.3.7 by Tim Penhey
Updates from Aaron's review.
1083
        if not aliases or alias_name not in aliases:
1084
            raise errors.NoSuchAlias(alias_name)
2900.3.2 by Tim Penhey
A working alias command.
1085
        del aliases[alias_name]
2900.3.12 by Tim Penhey
Final review comments.
1086
        self._write_config_file()
2900.3.2 by Tim Penhey
A working alias command.
1087
1088
    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.
1089
        self.reload()
2900.3.7 by Tim Penhey
Updates from Aaron's review.
1090
        self._get_parser().setdefault(section, {})[option] = value
2900.3.12 by Tim Penhey
Final review comments.
1091
        self._write_config_file()
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
1092
        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.
1093
            hook(self, option, value)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1094
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.
1095
    def _get_sections(self, name=None):
1096
        """See IniBasedConfig._get_sections()."""
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1097
        parser = self._get_parser()
1098
        # We don't give access to options defined outside of any section, we
1099
        # used the DEFAULT section by... default.
1100
        if name in (None, 'DEFAULT'):
1101
            # This could happen for an empty file where the DEFAULT section
1102
            # doesn't exist yet. So we force DEFAULT when yielding
1103
            name = 'DEFAULT'
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1104
            if 'DEFAULT' not in parser:
1105
               parser['DEFAULT']= {}
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1106
        yield (name, parser[name], self.config_id())
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1107
1108
    @needs_write_lock
1109
    def remove_user_option(self, option_name, section_name=None):
1110
        if section_name is None:
1111
            # We need to force the default section.
1112
            section_name = 'DEFAULT'
1113
        # We need to avoid the LockableConfig implementation or we'll lock
1114
        # twice
1115
        super(LockableConfig, self).remove_user_option(option_name,
1116
                                                       section_name)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1117
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1118
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.
1119
    """Keep only the sessions matching the specified location.
1120
1121
    :param sections: An iterable of section names.
1122
1123
    :param location: An url or a local path to match against.
1124
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1125
    :returns: An iterator of (section, extra_path, nb_parts) where nb is the
1126
        number of path components in the section name, section is the section
1127
        name and extra_path is the difference between location and the section
1128
        name.
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
1129
1130
    ``location`` will always be a local path and never a 'file://' url but the
1131
    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.
1132
    """
5764.1.2 by Vincent Ladeuil
This put a common processing into the loop to avoid bad inputs. The
1133
    location_parts = location.rstrip('/').split('/')
1134
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.
1135
    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).
1136
        # location is a local path if possible, so we need to convert 'file://'
1137
        # 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.
1138
1139
        # This also avoids having file:///path be a more exact
1140
        # match than '/path'.
1141
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
1142
        # FIXME: This still raises an issue if a user defines both file:///path
1143
        # *and* /path. Should we raise an error in this case -- vila 20110505
1144
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
        if section.startswith('file://'):
1146
            section_path = urlutils.local_path_from_url(section)
1147
        else:
1148
            section_path = section
1149
        section_parts = section_path.rstrip('/').split('/')
1150
1151
        matched = True
1152
        if len(section_parts) > len(location_parts):
1153
            # More path components in the section, they can't match
1154
            matched = False
1155
        else:
1156
            # Rely on zip truncating in length to the length of the shortest
1157
            # argument sequence.
1158
            names = zip(location_parts, section_parts)
1159
            for name in names:
1160
                if not fnmatch.fnmatch(name[0], name[1]):
1161
                    matched = False
1162
                    break
1163
        if not matched:
1164
            continue
5764.1.1 by Vincent Ladeuil
Extract _match_section_by_parts from LocationConfig._get_matching_sections and more comments to explain the behavior.
1165
        # 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.
1166
        extra_path = '/'.join(location_parts[len(section_parts):])
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1167
        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.
1168
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1169
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
1170
class LocationConfig(LockableConfig):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1171
    """A configuration object that gives the policy for a location."""
1172
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1173
    def __init__(self, location):
5345.1.2 by Vincent Ladeuil
Get rid of 'branches.conf' references.
1174
        super(LocationConfig, self).__init__(
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1175
            file_name=locations_config_filename())
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1176
        # local file locations are looked up by local path, rather than
1177
        # by file url. This is because the config file is a user
1178
        # file, and we would rather not expose the user to file urls.
1179
        if location.startswith('file://'):
1180
            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
1181
        self.location = location
1182
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1183
    def config_id(self):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1184
        return 'locations'
1185
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1186
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1187
    def from_string(cls, str_or_unicode, location, save=False):
1188
        """Create a config object from a string.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1189
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
1190
        :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.
1191
            be utf-8 encoded.
1192
1193
        :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.
1194
1195
        :param save: Whether the file should be saved upon creation.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1196
        """
1197
        conf = cls(location)
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
1198
        conf._create_from_string(str_or_unicode, save)
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
1199
        return conf
1200
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1201
    def _get_matching_sections(self):
1202
        """Return an ordered list of section names matching this location."""
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1203
        matches = list(_iter_for_location_by_parts(self._get_parser(),
1204
                                                   self.location))
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1205
        # put the longest (aka more specific) locations first
5764.1.4 by Vincent Ladeuil
Using iterators is even clearer.
1206
        matches.sort(
1207
            key=lambda (section, extra_path, length): (length, section),
1208
            reverse=True)
1209
        for (section, extra_path, length) in matches:
1210
            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
1211
            # should we stop looking for parent configs here?
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1212
            try:
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1213
                if self._get_parser()[section].as_bool('ignore_parents'):
1214
                    break
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1215
            except KeyError:
1216
                pass
1442.1.9 by Robert Collins
exact section test passes
1217
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.
1218
    def _get_sections(self, name=None):
1219
        """See IniBasedConfig._get_sections()."""
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1220
        # We ignore the name here as the only sections handled are named with
1221
        # the location path and we don't expose embedded sections either.
1222
        parser = self._get_parser()
1223
        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.
1224
            yield (name, parser[name], self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1225
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1226
    def _get_option_policy(self, section, option_name):
1227
        """Return the policy for the given (section, option_name) pair."""
1228
        # check for the old 'recurse=False' flag
1229
        try:
1230
            recurse = self._get_parser()[section].as_bool('recurse')
1231
        except KeyError:
1232
            recurse = True
1233
        if not recurse:
1234
            return POLICY_NORECURSE
1235
2120.6.10 by James Henstridge
Catch another deprecation warning, and more cleanup
1236
        policy_key = option_name + ':policy'
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1237
        try:
1238
            policy_name = self._get_parser()[section][policy_key]
1239
        except KeyError:
1240
            policy_name = None
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1241
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1242
        return _policy_value[policy_name]
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1243
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1244
    def _set_option_policy(self, section, option_name, option_policy):
1245
        """Set the policy for the given option name in the given section."""
1246
        # The old recurse=False option affects all options in the
1247
        # section.  To handle multiple policies in the section, we
1248
        # need to convert it to a policy_norecurse key.
1249
        try:
1250
            recurse = self._get_parser()[section].as_bool('recurse')
1251
        except KeyError:
1252
            pass
1253
        else:
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1254
            symbol_versioning.warn(
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
1255
                'The recurse option is deprecated as of 0.14.  '
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1256
                'The section "%s" has been converted to use policies.'
1257
                % section,
1258
                DeprecationWarning)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1259
            del self._get_parser()[section]['recurse']
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1260
            if not recurse:
1261
                for key in self._get_parser()[section].keys():
1262
                    if not key.endswith(':policy'):
1263
                        self._get_parser()[section][key +
1264
                                                    ':policy'] = 'norecurse'
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1265
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1266
        policy_key = option_name + ':policy'
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1267
        policy_name = _policy_name[option_policy]
1268
        if policy_name is not None:
1269
            self._get_parser()[section][policy_key] = policy_name
1270
        else:
1271
            if policy_key in self._get_parser()[section]:
1272
                del self._get_parser()[section][policy_key]
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1273
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
1274
    @needs_write_lock
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1275
    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.
1276
        """Save option and its value in the configuration."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1277
        if store not in [STORE_LOCATION,
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1278
                         STORE_LOCATION_NORECURSE,
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1279
                         STORE_LOCATION_APPENDPATH]:
1280
            raise ValueError('bad storage policy %r for %r' %
1281
                (store, option))
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
1282
        self.reload()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1283
        location = self.location
1284
        if location.endswith('/'):
1285
            location = location[:-1]
5345.1.24 by Vincent Ladeuil
Implement _save for LockableConfig too.
1286
        parser = self._get_parser()
5345.1.21 by Vincent Ladeuil
Slight rewrite to make the method more readable.
1287
        if not location in parser and not location + '/' in parser:
1288
            parser[location] = {}
1289
        elif location + '/' in parser:
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1290
            location = location + '/'
5345.1.21 by Vincent Ladeuil
Slight rewrite to make the method more readable.
1291
        parser[location][option]=value
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1292
        # the allowed values of store match the config policies
1293
        self._set_option_policy(location, option, store)
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
1294
        self._write_config_file()
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
1295
        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.
1296
            hook(self, option, value)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1297
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1298
1299
class BranchConfig(Config):
1300
    """A configuration object giving the policy for a branch."""
1301
5345.1.3 by Vincent Ladeuil
Make __init__ the first method in the BranchConfig class.
1302
    def __init__(self, branch):
1303
        super(BranchConfig, self).__init__()
1304
        self._location_config = None
1305
        self._branch_data_config = None
1306
        self._global_config = None
1307
        self.branch = branch
1308
        self.option_sources = (self._get_location_config,
1309
                               self._get_branch_data_config,
1310
                               self._get_global_config)
1311
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1312
    def config_id(self):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1313
        return 'branch'
1314
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1315
    def _get_branch_data_config(self):
1316
        if self._branch_data_config is None:
1317
            self._branch_data_config = TreeConfig(self.branch)
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1318
            self._branch_data_config.config_id = self.config_id
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1319
        return self._branch_data_config
1320
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1321
    def _get_location_config(self):
1322
        if self._location_config is None:
1323
            self._location_config = LocationConfig(self.branch.base)
1324
        return self._location_config
1325
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1326
    def _get_global_config(self):
1327
        if self._global_config is None:
1328
            self._global_config = GlobalConfig()
1329
        return self._global_config
1330
1331
    def _get_best_value(self, option_name):
1332
        """This returns a user option from local, tree or global config.
1333
1334
        They are tried in that order.  Use get_safe_value if trusted values
1335
        are necessary.
1336
        """
1337
        for source in self.option_sources:
1338
            value = getattr(source(), option_name)()
1339
            if value is not None:
1340
                return value
1341
        return None
1342
1343
    def _get_safe_value(self, option_name):
1344
        """This variant of get_best_value never returns untrusted values.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1345
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1346
        It does not return values from the branch data, because the branch may
1347
        not be controlled by the user.
1348
1349
        We may wish to allow locations.conf to control whether branches are
1350
        trusted in the future.
1351
        """
1352
        for source in (self._get_location_config, self._get_global_config):
1353
            value = getattr(source(), option_name)()
1354
            if value is not None:
1355
                return value
1356
        return None
1357
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1358
    def _get_user_id(self):
1359
        """Return the full user id for the branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1360
3407.2.14 by Martin Pool
Remove more cases of getting transport via control_files
1361
        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
1362
        This is looked up in the email controlfile for the branch.
1363
        """
1364
        try:
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1365
            return (self.branch._transport.get_bytes("email")
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
1366
                    .decode(osutils.get_user_encoding())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1367
                    .rstrip("\r\n"))
1368
        except errors.NoSuchFile, e:
1369
            pass
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1370
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1371
        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
1372
4603.1.10 by Aaron Bentley
Provide change editor via config.
1373
    def _get_change_editor(self):
1374
        return self._get_best_value('_get_change_editor')
1375
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1376
    def _get_signature_checking(self):
1377
        """See Config._get_signature_checking."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1378
        return self._get_best_value('_get_signature_checking')
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1379
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1380
    def _get_signing_policy(self):
1381
        """See Config._get_signing_policy."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1382
        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
1383
6012.2.3 by Jonathan Riddell
add config option for signing key
1384
    def _get_signing_key(self):
1385
        """See Config._get_signing_key."""
1386
        return self._get_best_value('_get_signing_key')
1387
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
1388
    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.
1389
        """See Config._get_user_option."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1390
        for source in self.option_sources:
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
1391
            value = source()._get_user_option(option_name)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1392
            if value is not None:
1393
                return value
1394
        return None
1395
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.
1396
    def _get_sections(self, name=None):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1397
        """See IniBasedConfig.get_sections()."""
1398
        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.
1399
            for section in source()._get_sections(name):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1400
                yield section
1401
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.
1402
    def _get_options(self, sections=None):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1403
        opts = []
1404
        # 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.
1405
        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.
1406
            yield option
1407
        # Then the branch options
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1408
        branch_config = self._get_branch_data_config()
1409
        if sections is None:
1410
            sections = [('DEFAULT', branch_config._get_parser())]
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1411
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
1412
        # 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.
1413
        config_id = self.config_id()
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1414
        for (section_name, section) in sections:
1415
            for (name, value) in section.iteritems():
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1416
                yield (name, value, section_name,
1417
                       config_id, branch_config._get_parser())
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1418
        # 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.
1419
        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.
1420
            yield option
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1421
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1422
    def set_user_option(self, name, value, store=STORE_BRANCH,
1423
        warn_masked=False):
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1424
        if store == STORE_BRANCH:
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1425
            self._get_branch_data_config().set_option(value, name)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1426
        elif store == STORE_GLOBAL:
2120.6.7 by James Henstridge
Fix GlobalConfig.set_user_option() call
1427
            self._get_global_config().set_user_option(name, value)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1428
        else:
1429
            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)
1430
        if not warn_masked:
1431
            return
1432
        if store in (STORE_GLOBAL, STORE_BRANCH):
1433
            mask_value = self._get_location_config().get_user_option(name)
1434
            if mask_value is not None:
1435
                trace.warning('Value "%s" is masked by "%s" from'
1436
                              ' locations.conf', value, mask_value)
1437
            else:
1438
                if store == STORE_GLOBAL:
1439
                    branch_config = self._get_branch_data_config()
1440
                    mask_value = branch_config.get_user_option(name)
1441
                    if mask_value is not None:
1442
                        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
1443
                                      ' branch.conf', value, mask_value)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1444
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1445
    def remove_user_option(self, option_name, section_name=None):
1446
        self._get_branch_data_config().remove_option(option_name, section_name)
1447
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
1448
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1449
        """See Config.gpg_signing_command."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1450
        return self._get_safe_value('_gpg_signing_command')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1451
1472 by Robert Collins
post commit hook, first pass implementation
1452
    def _post_commit(self):
1453
        """See Config.post_commit."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1454
        return self._get_safe_value('_post_commit')
1472 by Robert Collins
post commit hook, first pass implementation
1455
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1456
    def _get_nickname(self):
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
1457
        value = self._get_explicit_nickname()
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1458
        if value is not None:
1459
            return value
2120.5.2 by Alexander Belchenko
(jam) Fix for bug #66857
1460
        return urlutils.unescape(self.branch.base.split('/')[-2])
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1461
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
1462
    def has_explicit_nickname(self):
1463
        """Return true if a nickname has been explicitly assigned."""
1464
        return self._get_explicit_nickname() is not None
1465
1466
    def _get_explicit_nickname(self):
1467
        return self._get_best_value('_get_nickname')
1468
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
1469
    def _log_format(self):
1470
        """See Config.log_format."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1471
        return self._get_best_value('_log_format')
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1472
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
1473
    def _validate_signatures_in_log(self):
1474
        """See Config.validate_signatures_in_log."""
1475
        return self._get_best_value('_validate_signatures_in_log')
1476
5971.1.56 by Jonathan Riddell
add an option for acceptable_keys in config, also make config docs match reality for signature options
1477
    def _acceptable_keys(self):
1478
        """See Config.acceptable_keys."""
1479
        return self._get_best_value('_acceptable_keys')
1480
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
1481
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
1482
def ensure_config_dir_exists(path=None):
5519.4.4 by Neil Martinsen-Burrell
restore ensure_config_dir since XDG_CONFIG_HOME is optional
1483
    """Make sure a configuration directory exists.
1484
    This makes sure that the directory exists.
1485
    On windows, since configuration directories are 2 levels deep,
1486
    it makes sure both the directory and the parent directory exists.
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
1487
    """
1488
    if path is None:
1489
        path = config_dir()
1490
    if not os.path.isdir(path):
5519.4.4 by Neil Martinsen-Burrell
restore ensure_config_dir since XDG_CONFIG_HOME is optional
1491
        if sys.platform == 'win32':
1492
            parent_dir = os.path.dirname(path)
1493
            if not os.path.isdir(parent_dir):
1494
                trace.mutter('creating config parent directory: %r', parent_dir)
1495
                os.mkdir(parent_dir)
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1496
        trace.mutter('creating config directory: %r', path)
5116.2.4 by Parth Malwankar
removed mkdir_with_ownership as its probably cleaner to just use copy_ownership
1497
        os.mkdir(path)
5116.2.6 by Parth Malwankar
renamed copy_ownership to copy_ownership_from_path.
1498
        osutils.copy_ownership_from_path(path)
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
1499
1532 by Robert Collins
Merge in John Meinels integration branch.
1500
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1501
def config_dir():
1502
    """Return per-user configuration directory.
1503
5519.4.1 by Neil Martinsen-Burrell
spec and first implementation, next tests
1504
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
5519.4.3 by Neil Martinsen-Burrell
be permissive about using $XDG_CONFIG_HOME/bazaar, but dont complain
1505
    and Linux.  On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
1506
    that will be used instead.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1507
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1508
    TODO: Global option --config-dir to override this.
1509
    """
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1510
    base = os.environ.get('BZR_HOME', None)
1511
    if sys.platform == 'win32':
5598.2.2 by John Arbash Meinel
Change the comment slightly
1512
        # environ variables on Windows are in user encoding/mbcs. So decode
1513
        # before using one
5598.2.1 by John Arbash Meinel
Decode windows env vars using mbcs rather than assuming the 8-bit string is ok.
1514
        if base is not None:
1515
            base = base.decode('mbcs')
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1516
        if base is None:
2245.4.3 by Alexander Belchenko
config.py: changing _auto_user_id() and config_dir() to use functions from win32utils
1517
            base = win32utils.get_appdata_location_unicode()
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1518
        if base is None:
1519
            base = os.environ.get('HOME', None)
5598.2.1 by John Arbash Meinel
Decode windows env vars using mbcs rather than assuming the 8-bit string is ok.
1520
            if base is not None:
1521
                base = base.decode('mbcs')
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1522
        if base is None:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1523
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1524
                                  ' or HOME set')
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
1525
        return osutils.pathjoin(base, 'bazaar', '2.0')
5519.4.1 by Neil Martinsen-Burrell
spec and first implementation, next tests
1526
    elif sys.platform == 'darwin':
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1527
        if base is None:
5519.4.1 by Neil Martinsen-Burrell
spec and first implementation, next tests
1528
            # this takes into account $HOME
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1529
            base = os.path.expanduser("~")
5519.4.1 by Neil Martinsen-Burrell
spec and first implementation, next tests
1530
        return osutils.pathjoin(base, '.bazaar')
1531
    else:
1532
        if base is None:
5519.4.3 by Neil Martinsen-Burrell
be permissive about using $XDG_CONFIG_HOME/bazaar, but dont complain
1533
1534
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
1535
            if xdg_dir is None:
1536
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
1537
            xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
1538
            if osutils.isdir(xdg_dir):
1539
                trace.mutter(
1540
                    "Using configuration in XDG directory %s." % xdg_dir)
1541
                return xdg_dir
1542
1543
            base = os.path.expanduser("~")
5519.4.4 by Neil Martinsen-Burrell
restore ensure_config_dir since XDG_CONFIG_HOME is optional
1544
        return osutils.pathjoin(base, ".bazaar")
1185.31.32 by John Arbash Meinel
Updated the bzr sourcecode to use bzrlib.osutils.pathjoin rather than os.path.join to enforce internal use of / instead of \
1545
1546
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1547
def config_filename():
1548
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
1549
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1550
1551
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1552
def locations_config_filename():
1553
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
1554
    return osutils.pathjoin(config_dir(), 'locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1555
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1556
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1557
def authentication_config_filename():
1558
    """Return per-user authentication ini file filename."""
1559
    return osutils.pathjoin(config_dir(), 'authentication.conf')
1560
1561
1836.1.6 by John Arbash Meinel
Creating a helper function for getting the user ignore filename
1562
def user_ignore_config_filename():
1563
    """Return the user default ignore filename"""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
1564
    return osutils.pathjoin(config_dir(), 'ignore')
1836.1.6 by John Arbash Meinel
Creating a helper function for getting the user ignore filename
1565
1566
4584.3.4 by Martin Pool
Add crash_dir and xdg_cache_dir functions
1567
def crash_dir():
1568
    """Return the directory name to store crash files.
1569
1570
    This doesn't implicitly create it.
1571
4634.128.2 by Martin Pool
Write crash files into /var/crash where apport can see them.
1572
    On Windows it's in the config directory; elsewhere it's /var/crash
4634.128.18 by Martin Pool
Update apport crash tests
1573
    which may be monitored by apport.  It can be overridden by
1574
    $APPORT_CRASH_DIR.
4584.3.4 by Martin Pool
Add crash_dir and xdg_cache_dir functions
1575
    """
1576
    if sys.platform == 'win32':
1577
        return osutils.pathjoin(config_dir(), 'Crash')
1578
    else:
4634.128.2 by Martin Pool
Write crash files into /var/crash where apport can see them.
1579
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
1580
        # 2010-01-31
4634.128.18 by Martin Pool
Update apport crash tests
1581
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
4584.3.4 by Martin Pool
Add crash_dir and xdg_cache_dir functions
1582
1583
1584
def xdg_cache_dir():
4584.3.23 by Martin Pool
Correction to xdg_cache_dir and add a simple test
1585
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
1586
    # Possibly this should be different on Windows?
1587
    e = os.environ.get('XDG_CACHE_DIR', None)
1588
    if e:
1589
        return e
1590
    else:
1591
        return os.path.expanduser('~/.cache')
4584.3.4 by Martin Pool
Add crash_dir and xdg_cache_dir functions
1592
1593
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
1594
def _get_default_mail_domain():
1595
    """If possible, return the assumed default email domain.
1596
1597
    :returns: string mail domain, or None.
1598
    """
1599
    if sys.platform == 'win32':
1600
        # No implementation yet; patches welcome
1601
        return None
1602
    try:
1603
        f = open('/etc/mailname')
1604
    except (IOError, OSError), e:
1605
        return None
1606
    try:
1607
        domain = f.read().strip()
1608
        return domain
1609
    finally:
1610
        f.close()
1611
1612
1613
def _auto_user_id():
1614
    """Calculate automatic user identification.
1615
1616
    :returns: (realname, email), either of which may be None if they can't be
1617
    determined.
1618
1619
    Only used when none is set in the environment or the id file.
1620
1621
    This only returns an email address if we can be fairly sure the 
1622
    address is reasonable, ie if /etc/mailname is set on unix.
1623
1624
    This doesn't use the FQDN as the default domain because that may be 
1625
    slow, and it doesn't use the hostname alone because that's not normally 
1626
    a reasonable address.
1627
    """
1628
    if sys.platform == 'win32':
1629
        # No implementation to reliably determine Windows default mail
1630
        # address; please add one.
1631
        return None, None
1632
1633
    default_mail_domain = _get_default_mail_domain()
1634
    if not default_mail_domain:
1635
        return None, None
1636
1637
    import pwd
1638
    uid = os.getuid()
1639
    try:
1640
        w = pwd.getpwuid(uid)
1641
    except KeyError:
5904.1.2 by Martin Pool
Various pyflakes import fixes.
1642
        trace.mutter('no passwd entry for uid %d?' % uid)
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
1643
        return None, None
1644
1645
    # we try utf-8 first, because on many variants (like Linux),
1646
    # /etc/passwd "should" be in utf-8, and because it's unlikely to give
1647
    # false positives.  (many users will have their user encoding set to
1648
    # latin-1, which cannot raise UnicodeError.)
1649
    try:
1650
        gecos = w.pw_gecos.decode('utf-8')
1651
        encoding = 'utf-8'
1652
    except UnicodeError:
1653
        try:
1654
            encoding = osutils.get_user_encoding()
1655
            gecos = w.pw_gecos.decode(encoding)
1656
        except UnicodeError, e:
5904.1.2 by Martin Pool
Various pyflakes import fixes.
1657
            trace.mutter("cannot decode passwd entry %s" % w)
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
1658
            return None, None
1659
    try:
1660
        username = w.pw_name.decode(encoding)
1661
    except UnicodeError, e:
5904.1.2 by Martin Pool
Various pyflakes import fixes.
1662
        trace.mutter("cannot decode passwd entry %s" % w)
5050.72.1 by Martin Pool
Set email address from /etc/mailname if possible
1663
        return None, None
1664
1665
    comma = gecos.find(',')
1666
    if comma == -1:
1667
        realname = gecos
1668
    else:
1669
        realname = gecos[:comma]
1670
1671
    return realname, (username + '@' + default_mail_domain)
1672
1673
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1674
def parse_username(username):
1675
    """Parse e-mail username and return a (name, address) tuple."""
1676
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1677
    if match is None:
1678
        return (username, '')
1679
    else:
1680
        return (match.group(1), match.group(2))
1681
1682
1185.16.52 by Martin Pool
- add extract_email_address
1683
def extract_email_address(e):
1684
    """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.
1685
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1686
    That is just the user@domain part, nothing else.
1185.16.52 by Martin Pool
- add extract_email_address
1687
    This part is required to contain only ascii characters.
1688
    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.
1689
1185.16.52 by Martin Pool
- add extract_email_address
1690
    >>> extract_email_address('Jane Tester <jane@test.com>')
1691
    "jane@test.com"
1692
    """
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1693
    name, email = parse_username(e)
1694
    if not email:
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
1695
        raise errors.NoEmailInUsername(e)
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1696
    return email
1185.35.11 by Aaron Bentley
Added support for branch nicks
1697
1185.85.30 by John Arbash Meinel
Fixing 'bzr push' exposed that IniBasedConfig didn't handle unicode.
1698
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1699
class TreeConfig(IniBasedConfig):
1185.35.11 by Aaron Bentley
Added support for branch nicks
1700
    """Branch configuration data associated with its contents, not location"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1701
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
1702
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
1703
1185.35.11 by Aaron Bentley
Added support for branch nicks
1704
    def __init__(self, branch):
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
1705
        self._config = branch._get_config()
1185.35.11 by Aaron Bentley
Added support for branch nicks
1706
        self.branch = branch
1707
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1708
    def _get_parser(self, file=None):
1709
        if file is not None:
1710
            return IniBasedConfig._get_parser(file)
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1711
        return self._config._get_configobj()
1185.35.11 by Aaron Bentley
Added support for branch nicks
1712
1713
    def get_option(self, name, section=None, default=None):
1714
        self.branch.lock_read()
1715
        try:
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1716
            return self._config.get_option(name, section, default)
1185.35.11 by Aaron Bentley
Added support for branch nicks
1717
        finally:
1718
            self.branch.unlock()
1719
1720
    def set_option(self, value, name, section=None):
1721
        """Set a per-branch configuration option"""
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1722
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
1723
        # higher levels providing the right lock -- vila 20101004
1185.35.11 by Aaron Bentley
Added support for branch nicks
1724
        self.branch.lock_write()
1725
        try:
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1726
            self._config.set_option(value, name, section)
1185.35.11 by Aaron Bentley
Added support for branch nicks
1727
        finally:
1728
            self.branch.unlock()
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1729
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1730
    def remove_option(self, option_name, section_name=None):
1731
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
1732
        # higher levels providing the right lock -- vila 20101004
1733
        self.branch.lock_write()
1734
        try:
1735
            self._config.remove_option(option_name, section_name)
1736
        finally:
1737
            self.branch.unlock()
1738
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1739
1740
class AuthenticationConfig(object):
1741
    """The authentication configuration file based on a ini file.
1742
1743
    Implements the authentication.conf file described in
1744
    doc/developers/authentication-ring.txt.
1745
    """
1746
1747
    def __init__(self, _file=None):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1748
        self._config = None # The ConfigObj
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1749
        if _file is None:
2900.2.24 by Vincent Ladeuil
Review feedback.
1750
            self._filename = authentication_config_filename()
1751
            self._input = self._filename = authentication_config_filename()
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1752
        else:
2900.2.24 by Vincent Ladeuil
Review feedback.
1753
            # Tests can provide a string as _file
1754
            self._filename = None
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1755
            self._input = _file
1756
1757
    def _get_config(self):
1758
        if self._config is not None:
1759
            return self._config
1760
        try:
2900.2.22 by Vincent Ladeuil
Polishing.
1761
            # FIXME: Should we validate something here ? Includes: empty
1762
            # sections are useless, at least one of
1763
            # user/password/password_encoding should be defined, etc.
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1764
1765
            # Note: the encoding below declares that the file itself is utf-8
1766
            # encoded, but the values in the ConfigObj are always Unicode.
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1767
            self._config = ConfigObj(self._input, encoding='utf-8')
1768
        except configobj.ConfigObjError, e:
1769
            raise errors.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
1770
        except UnicodeError:
5987.1.3 by Vincent Ladeuil
Proper message when authentication.conf has non-utf8 content
1771
            raise errors.ConfigContentError(self._filename)
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1772
        return self._config
1773
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1774
    def _save(self):
1775
        """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.
1776
        conf_dir = os.path.dirname(self._filename)
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1777
        ensure_config_dir_exists(conf_dir)
4708.2.2 by Martin
Workingtree changes sitting around since November, more explict closing of files in bzrlib
1778
        f = file(self._filename, 'wb')
1779
        try:
1780
            self._get_config().write(f)
1781
        finally:
1782
            f.close()
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1783
1784
    def _set_option(self, section_name, option_name, value):
1785
        """Set an authentication configuration option"""
1786
        conf = self._get_config()
1787
        section = conf.get(section_name)
1788
        if section is None:
1789
            conf[section] = {}
1790
            section = conf[section]
1791
        section[option_name] = value
1792
        self._save()
1793
5743.8.25 by Vincent Ladeuil
Fix spurious spaces.
1794
    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
1795
                        realm=None):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1796
        """Returns the matching credentials from authentication.conf file.
1797
1798
        :param scheme: protocol
1799
1800
        :param host: the server address
1801
1802
        :param port: the associated port (optional)
1803
1804
        :param user: login (optional)
1805
1806
        :param path: the absolute path on the server (optional)
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1807
        
1808
        :param realm: the http authentication realm (optional)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1809
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1810
        :return: A dict containing the matching credentials or None.
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1811
           This includes:
1812
           - name: the section name of the credentials in the
1813
             authentication.conf file,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1814
           - 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.
1815
           - scheme: the server protocol,
1816
           - host: the server address,
1817
           - port: the server port (can be None),
1818
           - path: the absolute server path (can be None),
1819
           - realm: the http specific authentication realm (can be None),
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1820
           - password: the decoded password, could be None if the credential
1821
             defines only the user
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1822
           - verify_certificates: https specific, True if the server
1823
             certificate should be verified, False otherwise.
1824
        """
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1825
        credentials = None
1826
        for auth_def_name, auth_def in self._get_config().items():
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1827
            if type(auth_def) is not configobj.Section:
1828
                raise ValueError("%s defined outside a section" % auth_def_name)
1829
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1830
            a_scheme, a_host, a_user, a_path = map(
1831
                auth_def.get, ['scheme', 'host', 'user', 'path'])
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1832
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1833
            try:
1834
                a_port = auth_def.as_int('port')
1835
            except KeyError:
1836
                a_port = None
2900.2.22 by Vincent Ladeuil
Polishing.
1837
            except ValueError:
1838
                raise ValueError("'port' not numeric in %s" % auth_def_name)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1839
            try:
1840
                a_verify_certificates = auth_def.as_bool('verify_certificates')
1841
            except KeyError:
1842
                a_verify_certificates = True
2900.2.22 by Vincent Ladeuil
Polishing.
1843
            except ValueError:
1844
                raise ValueError(
1845
                    "'verify_certificates' not boolean in %s" % auth_def_name)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1846
1847
            # Attempt matching
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1848
            if a_scheme is not None and scheme != a_scheme:
1849
                continue
1850
            if a_host is not None:
1851
                if not (host == a_host
1852
                        or (a_host.startswith('.') and host.endswith(a_host))):
1853
                    continue
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1854
            if a_port is not None and port != a_port:
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1855
                continue
1856
            if (a_path is not None and path is not None
1857
                and not path.startswith(a_path)):
1858
                continue
1859
            if (a_user is not None and user is not None
1860
                and a_user != user):
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1861
                # Never contradict the caller about the user to be used
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1862
                continue
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1863
            if a_user is None:
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1864
                # Can't find a user
1865
                continue
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1866
            # Prepare a credentials dictionary with additional keys
1867
            # for the credential providers
2900.2.24 by Vincent Ladeuil
Review feedback.
1868
            credentials = dict(name=auth_def_name,
3418.4.2 by Vincent Ladeuil
Fix bug #199440 by taking into account that a section may not
1869
                               user=a_user,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1870
                               scheme=a_scheme,
1871
                               host=host,
1872
                               port=port,
1873
                               path=path,
1874
                               realm=realm,
3418.4.2 by Vincent Ladeuil
Fix bug #199440 by taking into account that a section may not
1875
                               password=auth_def.get('password', None),
2900.2.24 by Vincent Ladeuil
Review feedback.
1876
                               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
1877
            # Decode the password in the credentials (or get one)
2900.2.22 by Vincent Ladeuil
Polishing.
1878
            self.decode_password(credentials,
1879
                                 auth_def.get('password_encoding', None))
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1880
            if 'auth' in debug.debug_flags:
1881
                trace.mutter("Using authentication section: %r", auth_def_name)
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1882
            break
1883
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1884
        if credentials is None:
1885
            # No credentials were found in authentication.conf, try the fallback
1886
            # credentials stores.
1887
            credentials = credential_store_registry.get_fallback_credentials(
1888
                scheme, host, port, user, path, realm)
1889
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1890
        return credentials
1891
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1892
    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
1893
                        port=None, path=None, verify_certificates=None,
1894
                        realm=None):
3777.3.1 by Aaron Bentley
Update docs
1895
        """Set authentication credentials for a host.
1896
1897
        Any existing credentials with matching scheme, host, port and path
1898
        will be deleted, regardless of name.
1899
1900
        :param name: An arbitrary name to describe this set of credentials.
1901
        :param host: Name of the host that accepts these credentials.
1902
        :param user: The username portion of these credentials.
1903
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1904
            to.
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1905
        :param password: Password portion of these credentials.
3777.3.1 by Aaron Bentley
Update docs
1906
        :param port: The IP port on the host that these credentials apply to.
1907
        :param path: A filesystem path on the host that these credentials
1908
            apply to.
1909
        :param verify_certificates: On https, verify server certificates if
1910
            True.
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1911
        :param realm: The http authentication realm (optional).
3777.3.1 by Aaron Bentley
Update docs
1912
        """
3777.1.8 by Aaron Bentley
Commit work-in-progress
1913
        values = {'host': host, 'user': user}
1914
        if password is not None:
1915
            values['password'] = password
1916
        if scheme is not None:
1917
            values['scheme'] = scheme
1918
        if port is not None:
1919
            values['port'] = '%d' % port
1920
        if path is not None:
1921
            values['path'] = path
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1922
        if verify_certificates is not None:
1923
            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
1924
        if realm is not None:
1925
            values['realm'] = realm
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1926
        config = self._get_config()
1927
        for_deletion = []
1928
        for section, existing_values in config.items():
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1929
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1930
                if existing_values.get(key) != values.get(key):
1931
                    break
1932
            else:
1933
                del config[section]
1934
        config.update({name: values})
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1935
        self._save()
3777.1.8 by Aaron Bentley
Commit work-in-progress
1936
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1937
    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.
1938
                 prompt=None, ask=False, default=None):
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1939
        """Get a user from authentication file.
1940
1941
        :param scheme: protocol
1942
1943
        :param host: the server address
1944
1945
        :param port: the associated port (optional)
1946
1947
        :param realm: the realm sent by the server (optional)
1948
1949
        :param path: the absolute path on the server (optional)
1950
4222.3.4 by Jelmer Vernooij
Default to getpass.getuser() in AuthenticationConfig.get_user(), but allow
1951
        :param ask: Ask the user if there is no explicitly configured username 
1952
                    (optional)
1953
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1954
        :param default: The username returned if none is defined (optional).
1955
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1956
        :return: The found user.
1957
        """
2900.2.16 by Vincent Ladeuil
Make hhtp proxy aware of AuthenticationConfig (for password).
1958
        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
1959
                                           path=path, realm=realm)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1960
        if credentials is not None:
1961
            user = credentials['user']
1962
        else:
1963
            user = None
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1964
        if user is None:
4222.3.4 by Jelmer Vernooij
Default to getpass.getuser() in AuthenticationConfig.get_user(), but allow
1965
            if ask:
1966
                if prompt is None:
1967
                    # Create a default prompt suitable for most cases
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
1968
                    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
1969
                # Special handling for optional fields in the prompt
1970
                if port is not None:
1971
                    prompt_host = '%s:%d' % (host, port)
1972
                else:
1973
                    prompt_host = host
1974
                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.
1975
            else:
4222.3.10 by Jelmer Vernooij
Avoid using the default username in the case of SMTP.
1976
                user = default
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1977
        return user
1978
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1979
    def get_password(self, scheme, host, user, port=None,
1980
                     realm=None, path=None, prompt=None):
1981
        """Get a password from authentication file or prompt the user for one.
1982
1983
        :param scheme: protocol
1984
1985
        :param host: the server address
1986
1987
        :param port: the associated port (optional)
1988
1989
        :param user: login
1990
1991
        :param realm: the realm sent by the server (optional)
1992
1993
        :param path: the absolute path on the server (optional)
1994
1995
        :return: The found password or the one entered by the user.
1996
        """
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1997
        credentials = self.get_credentials(scheme, host, port, user, path,
1998
                                           realm)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1999
        if credentials is not None:
2000
            password = credentials['password']
3420.1.3 by Vincent Ladeuil
John's review feedback.
2001
            if password is not None and scheme is 'ssh':
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2002
                trace.warning('password ignored in section [%s],'
2003
                              ' use an ssh agent instead'
2004
                              % credentials['name'])
2005
                password = None
2900.2.16 by Vincent Ladeuil
Make hhtp proxy aware of AuthenticationConfig (for password).
2006
        else:
2007
            password = None
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
2008
        # 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).
2009
        if password is None:
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
2010
            if prompt is None:
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
2011
                # Create a default prompt suitable for most cases
5923.1.3 by Vincent Ladeuil
Even more unicode prompts fixes revealed by pqm.
2012
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
2013
            # Special handling for optional fields in the prompt
2014
            if port is not None:
2015
                prompt_host = '%s:%d' % (host, port)
2016
            else:
2017
                prompt_host = host
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
2018
            password = ui.ui_factory.get_password(prompt,
2019
                                                  host=prompt_host, user=user)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
2020
        return password
2021
2900.2.22 by Vincent Ladeuil
Polishing.
2022
    def decode_password(self, credentials, encoding):
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2023
        try:
2024
            cs = credential_store_registry.get_credential_store(encoding)
2025
        except KeyError:
2026
            raise ValueError('%r is not a known password_encoding' % encoding)
2027
        credentials['password'] = cs.decode_password(credentials)
2900.2.22 by Vincent Ladeuil
Polishing.
2028
        return credentials
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2029
3242.3.17 by Aaron Bentley
Whitespace cleanup
2030
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2031
class CredentialStoreRegistry(registry.Registry):
2032
    """A class that registers credential stores.
2033
2034
    A credential store provides access to credentials via the password_encoding
2035
    field in authentication.conf sections.
2036
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2037
    Except for stores provided by bzr itself, most stores are expected to be
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2038
    provided by plugins that will therefore use
2039
    register_lazy(password_encoding, module_name, member_name, help=help,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2040
    fallback=fallback) to install themselves.
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2041
2042
    A fallback credential store is one that is queried if no credentials can be
2043
    found via authentication.conf.
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2044
    """
2045
2046
    def get_credential_store(self, encoding=None):
2047
        cs = self.get(encoding)
2048
        if callable(cs):
2049
            cs = cs()
2050
        return cs
2051
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2052
    def is_fallback(self, name):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2053
        """Check if the named credentials store should be used as fallback."""
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2054
        return self.get_info(name)
2055
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2056
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2057
                                 path=None, realm=None):
2058
        """Request credentials from all fallback credentials stores.
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2059
2060
        The first credentials store that can provide credentials wins.
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2061
        """
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2062
        credentials = None
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2063
        for name in self.keys():
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
2064
            if not self.is_fallback(name):
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2065
                continue
2066
            cs = self.get_credential_store(name)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2067
            credentials = cs.get_credentials(scheme, host, port, user,
2068
                                             path, realm)
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2069
            if credentials is not None:
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2070
                # We found some credentials
2071
                break
2072
        return credentials
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2073
2074
    def register(self, key, obj, help=None, override_existing=False,
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2075
                 fallback=False):
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2076
        """Register a new object to a name.
2077
2078
        :param key: This is the key to use to request the object later.
2079
        :param obj: The object to register.
2080
        :param help: Help text for this entry. This may be a string or
2081
                a callable. If it is a callable, it should take two
2082
                parameters (registry, key): this registry and the key that
2083
                the help was registered under.
2084
        :param override_existing: Raise KeyErorr if False and something has
2085
                already been registered for that key. If True, ignore if there
2086
                is an existing key (always register the new value).
2087
        :param fallback: Whether this credential store should be 
2088
                used as fallback.
2089
        """
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2090
        return super(CredentialStoreRegistry,
2091
                     self).register(key, obj, help, info=fallback,
2092
                                    override_existing=override_existing)
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2093
2094
    def register_lazy(self, key, module_name, member_name,
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2095
                      help=None, override_existing=False,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2096
                      fallback=False):
2097
        """Register a new credential store to be loaded on request.
2098
2099
        :param module_name: The python path to the module. Such as 'os.path'.
2100
        :param member_name: The member of the module to return.  If empty or
2101
                None, get() will return the module itself.
2102
        :param help: Help text for this entry. This may be a string or
2103
                a callable.
2104
        :param override_existing: If True, replace the existing object
2105
                with the new one. If False, if there is already something
2106
                registered with the same key, raise a KeyError
2107
        :param fallback: Whether this credential store should be 
2108
                used as fallback.
2109
        """
2110
        return super(CredentialStoreRegistry, self).register_lazy(
2111
            key, module_name, member_name, help,
2112
            info=fallback, override_existing=override_existing)
2113
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2114
2115
credential_store_registry = CredentialStoreRegistry()
2116
2117
2118
class CredentialStore(object):
2119
    """An abstract class to implement storage for credentials"""
2120
2121
    def decode_password(self, credentials):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2122
        """Returns a clear text password for the provided credentials."""
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2123
        raise NotImplementedError(self.decode_password)
2124
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
2125
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
2126
                        realm=None):
2127
        """Return the matching credentials from this credential store.
2128
2129
        This method is only called on fallback credential stores.
2130
        """
2131
        raise NotImplementedError(self.get_credentials)
2132
2133
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2134
2135
class PlainTextCredentialStore(CredentialStore):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2136
    __doc__ = """Plain text credential store for the authentication.conf file"""
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
2137
2138
    def decode_password(self, credentials):
2139
        """See CredentialStore.decode_password."""
2140
        return credentials['password']
2141
2142
2143
credential_store_registry.register('plain', PlainTextCredentialStore,
2144
                                   help=PlainTextCredentialStore.__doc__)
2145
credential_store_registry.default_key = 'plain'
2146
2147
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
2148
class BzrDirConfig(object):
2149
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2150
    def __init__(self, bzrdir):
2151
        self._bzrdir = bzrdir
2152
        self._config = bzrdir._get_config()
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2153
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
2154
    def set_default_stack_on(self, value):
2155
        """Set the default stacking location.
2156
2157
        It may be set to a location, or None.
2158
2159
        This policy affects all branches contained by this bzrdir, except for
2160
        those under repositories.
2161
        """
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2162
        if self._config is None:
2163
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
2164
        if value is None:
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
2165
            self._config.set_option('', 'default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
2166
        else:
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
2167
            self._config.set_option(value, 'default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
2168
2169
    def get_default_stack_on(self):
2170
        """Return the default stacking location.
2171
2172
        This will either be a location, or None.
2173
2174
        This policy affects all branches contained by this bzrdir, except for
2175
        those under repositories.
2176
        """
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
2177
        if self._config is None:
2178
            return None
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
2179
        value = self._config.get_option('default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
2180
        if value == '':
2181
            value = None
2182
        return value
2183
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
2184
2185
class TransportConfig(object):
3242.1.5 by Aaron Bentley
Update per review comments
2186
    """A Config that reads/writes a config file on a Transport.
3242.1.4 by Aaron Bentley
Clean-up
2187
2188
    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.
2189
    that may be associated with a section.  Assigning meaning to these values
2190
    is done at higher levels like TreeConfig.
3242.1.4 by Aaron Bentley
Clean-up
2191
    """
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
2192
2193
    def __init__(self, transport, filename):
2194
        self._transport = transport
2195
        self._filename = filename
2196
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2197
    def get_option(self, name, section=None, default=None):
2198
        """Return the value associated with a named option.
2199
2200
        :param name: The name of the value
2201
        :param section: The section the option is in (if any)
2202
        :param default: The value to return if the value is not set
2203
        :return: The value or default value
2204
        """
2205
        configobj = self._get_configobj()
2206
        if section is None:
2207
            section_obj = configobj
2208
        else:
2209
            try:
2210
                section_obj = configobj[section]
2211
            except KeyError:
2212
                return default
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
2213
        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.
2214
        for hook in OldConfigHooks['get']:
5743.8.25 by Vincent Ladeuil
Fix spurious spaces.
2215
            hook(self, name, value)
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
2216
        return value
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2217
2218
    def set_option(self, value, name, section=None):
2219
        """Set the value associated with a named option.
2220
2221
        :param value: The value to set
2222
        :param name: The name of the value to set
2223
        :param section: The section the option is in (if any)
2224
        """
2225
        configobj = self._get_configobj()
2226
        if section is None:
2227
            configobj[name] = value
2228
        else:
2229
            configobj.setdefault(section, {})[name] = value
5743.8.24 by Vincent Ladeuil
Clearly seaparate both sets of hooks for the old and new config implementations.
2230
        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.
2231
            hook(self, name, value)
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2232
        self._set_configobj(configobj)
2233
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
2234
    def remove_option(self, option_name, section_name=None):
2235
        configobj = self._get_configobj()
2236
        if section_name is None:
2237
            del configobj[option_name]
2238
        else:
2239
            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.
2240
        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.
2241
            hook(self, option_name)
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
2242
        self._set_configobj(configobj)
2243
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
2244
    def _get_config_file(self):
2245
        try:
5743.8.13 by Vincent Ladeuil
Fix config calls for the actual implementation, including typos in parameters and TransportConfig support.
2246
            f = StringIO(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.
2247
            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.
2248
                hook(self)
2249
            return f
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
2250
        except errors.NoSuchFile:
2251
            return StringIO()
2252
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
2253
    def _external_url(self):
2254
        return urlutils.join(self._transport.external_url(), self._filename)
2255
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2256
    def _get_configobj(self):
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
2257
        f = self._get_config_file()
2258
        try:
5987.1.4 by Vincent Ladeuil
Proper error messages for config files with content in non-utf encoding or that cannot be parsed
2259
            try:
2260
                conf = ConfigObj(f, encoding='utf-8')
2261
            except configobj.ConfigObjError, e:
2262
                raise errors.ParseConfigError(e.errors, self._external_url())
2263
            except UnicodeDecodeError:
2264
                raise errors.ConfigContentError(self._external_url())
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
2265
        finally:
2266
            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
2267
        return conf
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
2268
2269
    def _set_configobj(self, configobj):
2270
        out_file = StringIO()
2271
        configobj.write(out_file)
2272
        out_file.seek(0)
2273
        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.
2274
        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.
2275
            hook(self)
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2276
2277
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2278
class Option(object):
5743.12.10 by Vincent Ladeuil
Add documentation.
2279
    """An option definition.
2280
2281
    The option *values* are stored in config files and found in sections.
2282
2283
    Here we define various properties about the option itself, its default
2284
    value, in which config files it can be stored, etc (TBC).
2285
    """
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2286
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
2287
    def __init__(self, name, default=None):
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2288
        self.name = name
5743.12.4 by Vincent Ladeuil
An option can provide a default value.
2289
        self.default = default
2290
2291
    def get_default(self):
2292
        return self.default
2293
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2294
2295
# Options registry
2296
2297
option_registry = registry.Registry()
2298
5743.12.3 by Vincent Ladeuil
More basic tests for options. Start tests for all registered options.
2299
5743.13.6 by Vincent Ladeuil
Register the 'editor' option.
2300
option_registry.register(
2301
    'editor', Option('editor'),
2302
    help='The command called to launch an editor to enter a message.')
5743.12.3 by Vincent Ladeuil
More basic tests for options. Start tests for all registered options.
2303
2304
5743.3.11 by Vincent Ladeuil
Config sections only implement read access.
2305
class Section(object):
5743.12.2 by Vincent Ladeuil
Basic registry for options.
2306
    """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.
2307
2308
    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.
2309
    options. It is *not* a python dict object though and doesn't try to mimic
2310
    its API.
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2311
    """
2312
2313
    def __init__(self, section_id, options):
2314
        self.id = section_id
2315
        # We re-use the dict-like object received
2316
        self.options = options
2317
2318
    def get(self, name, default=None):
2319
        return self.options.get(name, default)
2320
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
2321
    def __repr__(self):
2322
        # Mostly for debugging use
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2323
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
5743.3.12 by Vincent Ladeuil
Add an ad-hoc __repr__.
2324
5743.2.3 by Vincent Ladeuil
The option is either new or has an existing value.
2325
5743.3.6 by Vincent Ladeuil
Use a name less likely to be reused.
2326
_NewlyCreatedOption = object()
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2327
"""Was the option created during the MutableSection lifetime"""
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2328
5743.2.3 by Vincent Ladeuil
The option is either new or has an existing value.
2329
5743.3.11 by Vincent Ladeuil
Config sections only implement read access.
2330
class MutableSection(Section):
5743.3.1 by Vincent Ladeuil
Add a docstring and dates to FIXMEs.
2331
    """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.
2332
2333
    def __init__(self, section_id, options):
2334
        super(MutableSection, self).__init__(section_id, options)
2335
        self.orig = {}
2336
2337
    def set(self, name, value):
5743.2.2 by Vincent Ladeuil
Add tests for remove.
2338
        if name not in self.options:
5743.2.3 by Vincent Ladeuil
The option is either new or has an existing value.
2339
            # This is a new option
5743.3.6 by Vincent Ladeuil
Use a name less likely to be reused.
2340
            self.orig[name] = _NewlyCreatedOption
5743.2.3 by Vincent Ladeuil
The option is either new or has an existing value.
2341
        elif name not in self.orig:
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2342
            self.orig[name] = self.get(name, None)
2343
        self.options[name] = value
2344
2345
    def remove(self, name):
2346
        if name not in self.orig:
2347
            self.orig[name] = self.get(name, None)
2348
        del self.options[name]
2349
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2350
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2351
class Store(object):
2352
    """Abstract interface to persistent storage for configuration options."""
2353
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2354
    readonly_section_class = Section
5743.4.22 by Vincent Ladeuil
Allow daughter classes to use different Section classes if/when needed.
2355
    mutable_section_class = MutableSection
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2356
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2357
    def is_loaded(self):
2358
        """Returns True if the Store has been loaded.
2359
2360
        This is used to implement lazy loading and ensure the persistent
2361
        storage is queried only when needed.
2362
        """
2363
        raise NotImplementedError(self.is_loaded)
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2364
2365
    def load(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2366
        """Loads the Store from persistent storage."""
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2367
        raise NotImplementedError(self.load)
2368
5987.1.5 by Vincent Ladeuil
Those are just bytes.
2369
    def _load_from_string(self, bytes):
5743.4.21 by Vincent Ladeuil
All stores should provide _load_from_string to reuse the existing tests.
2370
        """Create a store from a string in configobj syntax.
2371
5987.1.5 by Vincent Ladeuil
Those are just bytes.
2372
        :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.
2373
        """
2374
        raise NotImplementedError(self._load_from_string)
2375
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2376
    def unload(self):
2377
        """Unloads the Store.
2378
2379
        This should make is_loaded() return False. This is used when the caller
2380
        knows that the persistent storage has changed or may have change since
2381
        the last load.
2382
        """
2383
        raise NotImplementedError(self.unload)
2384
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2385
    def save(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2386
        """Saves the Store to persistent storage."""
5743.4.10 by Vincent Ladeuil
Fix copy/paste, bad.
2387
        raise NotImplementedError(self.save)
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2388
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2389
    def external_url(self):
2390
        raise NotImplementedError(self.external_url)
2391
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2392
    def get_sections(self):
2393
        """Returns an ordered iterable of existing sections.
2394
2395
        :returns: An iterable of (name, dict).
2396
        """
2397
        raise NotImplementedError(self.get_sections)
2398
5743.4.2 by Vincent Ladeuil
Stores don't implement set_option, they just provide a mutable section.
2399
    def get_mutable_section(self, section_name=None):
2400
        """Returns the specified mutable section.
2401
2402
        :param section_name: The section identifier
2403
        """
2404
        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).
2405
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2406
    def __repr__(self):
2407
        # Mostly for debugging use
5743.5.17 by Vincent Ladeuil
Use external_url to identify stores.
2408
        return "<config.%s(%s)>" % (self.__class__.__name__,
5743.5.18 by Vincent Ladeuil
Fix typo.
2409
                                    self.external_url())
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2410
2411
2412
class IniFileStore(Store):
2413
    """A config Store using ConfigObj for storage.
2414
2415
    :ivar transport: The transport object where the config file is located.
2416
2417
    :ivar file_name: The config file basename in the transport directory.
2418
2419
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
2420
        serialize/deserialize the config file.
2421
    """
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2422
2423
    def __init__(self, transport, file_name):
2424
        """A config Store using ConfigObj for storage.
2425
2426
        :param transport: The transport object where the config file is located.
2427
2428
        :param file_name: The config file basename in the transport directory.
2429
        """
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2430
        super(IniFileStore, self).__init__()
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2431
        self.transport = transport
2432
        self.file_name = file_name
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2433
        self._config_obj = None
2434
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2435
    def is_loaded(self):
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2436
        return self._config_obj != None
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2437
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2438
    def unload(self):
2439
        self._config_obj = None
2440
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2441
    def load(self):
2442
        """Load the store from the associated file."""
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2443
        if self.is_loaded():
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2444
            return
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2445
        content = self.transport.get_bytes(self.file_name)
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2446
        self._load_from_string(content)
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.
2447
        for hook in ConfigHooks['load']:
5743.8.8 by Vincent Ladeuil
Puth the load hook in the right place.
2448
            hook(self)
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2449
5987.1.5 by Vincent Ladeuil
Those are just bytes.
2450
    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.
2451
        """Create a config store from a string.
2452
5987.1.5 by Vincent Ladeuil
Those are just bytes.
2453
        :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.
2454
        """
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2455
        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.
2456
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
5987.1.5 by Vincent Ladeuil
Those are just bytes.
2457
        co_input = StringIO(bytes)
5743.4.3 by Vincent Ladeuil
Implement get_mutable_section.
2458
        try:
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2459
            # The config files are always stored utf8-encoded
2460
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
2461
        except configobj.ConfigObjError, e:
5743.4.18 by Vincent Ladeuil
Replace class.from_string with self._load_from_string to all stores can use it.
2462
            self._config_obj = None
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2463
            raise errors.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
2464
        except UnicodeDecodeError:
2465
            raise errors.ConfigContentError(self.external_url())
5743.2.7 by Vincent Ladeuil
Implement loading a config store from a string or a file.
2466
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.
2467
    def save(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2468
        if not self.is_loaded():
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2469
            # Nothing to save
2470
            return
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.
2471
        out = StringIO()
2472
        self._config_obj.write(out)
2473
        self.transport.put_bytes(self.file_name, 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.
2474
        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).
2475
            hook(self)
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.
2476
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2477
    def external_url(self):
2478
        # FIXME: external_url should really accepts an optional relpath
2479
        # parameter (bug #750169) :-/ -- vila 2011-04-04
2480
        # The following will do in the interim but maybe we don't want to
2481
        # expose a path here but rather a config ID and its associated
2482
        # object </hand wawe>.
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
2483
        return urlutils.join(self.transport.external_url(), self.file_name)
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2484
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2485
    def get_sections(self):
2486
        """Get the configobj section in the file order.
2487
2488
        :returns: An iterable of (name, dict).
2489
        """
2490
        # We need a loaded store
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2491
        try:
2492
            self.load()
2493
        except errors.NoSuchFile:
2494
            # If the file doesn't exist, there is no sections
2495
            return
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2496
        cobj = self._config_obj
2497
        if cobj.scalars:
5743.4.22 by Vincent Ladeuil
Allow daughter classes to use different Section classes if/when needed.
2498
            yield self.readonly_section_class(None, cobj)
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2499
        for section_name in cobj.sections:
5743.4.22 by Vincent Ladeuil
Allow daughter classes to use different Section classes if/when needed.
2500
            yield self.readonly_section_class(section_name, cobj[section_name])
5743.2.10 by Vincent Ladeuil
Implement store.get_sections() as an iterator and provides the configobj implementation.
2501
5743.4.2 by Vincent Ladeuil
Stores don't implement set_option, they just provide a mutable section.
2502
    def get_mutable_section(self, section_name=None):
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
2503
        # We need a loaded store
5743.4.19 by Vincent Ladeuil
Clarify that only Store.get_mutable_section() can accept an empty file.
2504
        try:
2505
            self.load()
2506
        except errors.NoSuchFile:
2507
            # The file doesn't exist, let's pretend it was empty
2508
            self._load_from_string('')
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
2509
        if section_name is None:
2510
            section = self._config_obj
2511
        else:
2512
            section = self._config_obj.setdefault(section_name, {})
5743.4.22 by Vincent Ladeuil
Allow daughter classes to use different Section classes if/when needed.
2513
        return self.mutable_section_class(section_name, section)
5743.2.11 by Vincent Ladeuil
Basic store.set implementation.
2514
5743.2.1 by Vincent Ladeuil
Basic tests and implementations for read-only and mutable sections.
2515
5743.4.16 by Vincent Ladeuil
Some doc for the stores.
2516
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2517
# unlockable stores for use with objects that can already ensure the locking
2518
# (think branches). If different stores (not based on ConfigObj) are created,
2519
# they may face the same issue.
2520
2521
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2522
class LockableIniFileStore(IniFileStore):
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2523
    """A ConfigObjStore using locks on save to ensure store integrity."""
2524
2525
    def __init__(self, transport, file_name, lock_dir_name=None):
2526
        """A config Store using ConfigObj for storage.
2527
2528
        :param transport: The transport object where the config file is located.
2529
2530
        :param file_name: The config file basename in the transport directory.
2531
        """
2532
        if lock_dir_name is None:
2533
            lock_dir_name = 'lock'
2534
        self.lock_dir_name = lock_dir_name
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2535
        super(LockableIniFileStore, self).__init__(transport, file_name)
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2536
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2537
2538
    def lock_write(self, token=None):
2539
        """Takes a write lock in the directory containing the config file.
2540
2541
        If the directory doesn't exist it is created.
2542
        """
2543
        # FIXME: This doesn't check the ownership of the created directories as
2544
        # ensure_config_dir_exists does. It should if the transport is local
2545
        # -- vila 2011-04-06
2546
        self.transport.create_prefix()
2547
        return self._lock.lock_write(token)
2548
2549
    def unlock(self):
2550
        self._lock.unlock()
2551
2552
    def break_lock(self):
2553
        self._lock.break_lock()
2554
2555
    @needs_write_lock
2556
    def save(self):
5743.6.25 by Vincent Ladeuil
Last test rewritten.
2557
        # We need to be able to override the undecorated implementation
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2558
        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.
2559
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2560
    def save_without_locking(self):
5743.4.25 by Vincent Ladeuil
Address review comments by jelmer and poolie.
2561
        super(LockableIniFileStore, self).save()
5743.4.9 by Vincent Ladeuil
Implement a LockableConfigObjStore to be able to mimick the actual behaviour.
2562
2563
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2564
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2565
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2566
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
5743.5.15 by Vincent Ladeuil
Mention poolie's point about focusing tests.
2567
2568
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2569
# functions or a registry will make it easier and clearer for tests, focusing
2570
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2571
# on a poolie's remark)
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
2572
class GlobalStore(LockableIniFileStore):
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2573
2574
    def __init__(self, possible_transports=None):
2575
        t = transport.get_transport(config_dir(),
2576
                                    possible_transports=possible_transports)
2577
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
2578
2579
5743.5.13 by Vincent Ladeuil
Merge config-abstract-store into config-concrete-stores resolving conflicts
2580
class LocationStore(LockableIniFileStore):
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2581
2582
    def __init__(self, possible_transports=None):
2583
        t = transport.get_transport(config_dir(),
2584
                                    possible_transports=possible_transports)
5743.5.10 by Vincent Ladeuil
Parametrize the generic tests against the concrete stores.
2585
        super(LocationStore, self).__init__(t, 'locations.conf')
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2586
2587
5743.9.1 by Vincent Ladeuil
Properly implement locking for BranchStore by delegating all the lock operations to the branch itself.
2588
class BranchStore(IniFileStore):
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2589
2590
    def __init__(self, branch):
2591
        super(BranchStore, self).__init__(branch.control_transport,
2592
                                          'branch.conf')
5743.6.34 by Vincent Ladeuil
Forget weakref for branch <-> config.
2593
        self.branch = branch
5743.10.5 by Vincent Ladeuil
Give up.
2594
5743.9.1 by Vincent Ladeuil
Properly implement locking for BranchStore by delegating all the lock operations to the branch itself.
2595
    def lock_write(self, token=None):
5743.6.34 by Vincent Ladeuil
Forget weakref for branch <-> config.
2596
        return self.branch.lock_write(token)
5743.9.1 by Vincent Ladeuil
Properly implement locking for BranchStore by delegating all the lock operations to the branch itself.
2597
2598
    def unlock(self):
5743.6.34 by Vincent Ladeuil
Forget weakref for branch <-> config.
2599
        return self.branch.unlock()
5743.9.1 by Vincent Ladeuil
Properly implement locking for BranchStore by delegating all the lock operations to the branch itself.
2600
2601
    @needs_write_lock
2602
    def save(self):
2603
        # We need to be able to override the undecorated implementation
5743.9.5 by Vincent Ladeuil
Fix test failure, forgot a call site when renaming _save to save_without_locking.
2604
        self.save_without_locking()
5743.9.1 by Vincent Ladeuil
Properly implement locking for BranchStore by delegating all the lock operations to the branch itself.
2605
5743.9.5 by Vincent Ladeuil
Fix test failure, forgot a call site when renaming _save to save_without_locking.
2606
    def save_without_locking(self):
5743.9.1 by Vincent Ladeuil
Properly implement locking for BranchStore by delegating all the lock operations to the branch itself.
2607
        super(BranchStore, self).save()
2608
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2609
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2610
class SectionMatcher(object):
2611
    """Select sections into a given Store.
2612
2613
    This intended to be used to postpone getting an iterable of sections from a
2614
    store.
2615
    """
2616
2617
    def __init__(self, store):
2618
        self.store = store
2619
2620
    def get_sections(self):
5743.2.29 by Vincent Ladeuil
Add doc for the section matchers.
2621
        # 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.
2622
        # sections.
2623
        sections = self.store.get_sections()
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2624
        # Walk the revisions in the order provided
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2625
        for s in sections:
2626
            if self.match(s):
2627
                yield s
2628
2629
    def match(self, secion):
2630
        raise NotImplementedError(self.match)
2631
2632
5743.2.37 by Vincent Ladeuil
Merge config-concrete-stores into config-section-matchers resolving conflicts
2633
class LocationSection(Section):
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2634
2635
    def __init__(self, section, length, extra_path):
2636
        super(LocationSection, self).__init__(section.id, section.options)
2637
        self.length = length
2638
        self.extra_path = extra_path
2639
2640
    def get(self, name, default=None):
2641
        value = super(LocationSection, self).get(name, default)
2642
        if value is not None:
2643
            policy_name = self.get(name + ':policy', None)
2644
            policy = _policy_value.get(policy_name, POLICY_NONE)
2645
            if policy == POLICY_APPENDPATH:
2646
                value = urlutils.join(value, self.extra_path)
2647
        return value
2648
2649
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2650
class LocationMatcher(SectionMatcher):
2651
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2652
    def __init__(self, store, location):
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2653
        super(LocationMatcher, self).__init__(store)
5743.6.19 by Vincent Ladeuil
Clarify comments about section names for Location-related objects (also fix LocationMatcher and add tests).
2654
        if location.startswith('file://'):
2655
            location = urlutils.local_path_from_url(location)
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2656
        self.location = location
2657
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
2658
    def _get_matching_sections(self):
2659
        """Get all sections matching ``location``."""
2660
        # We slightly diverge from LocalConfig here by allowing the no-name
2661
        # section as the most generic one and the lower priority.
2662
        no_name_section = None
2663
        sections = []
2664
        # Filter out the no_name_section so _iter_for_location_by_parts can be
2665
        # used (it assumes all sections have a name).
2666
        for section in self.store.get_sections():
2667
            if section.id is None:
2668
                no_name_section = section
2669
            else:
2670
                sections.append(section)
2671
        # Unfortunately _iter_for_location_by_parts deals with section names so
2672
        # we have to resync.
5743.2.31 by Vincent Ladeuil
Both the length and the section id should be used to sort.
2673
        filtered_sections = _iter_for_location_by_parts(
5743.2.27 by Vincent Ladeuil
Merge the use of _filter_for_location_by_parts, uglier, but better for
2674
            [s.id for s in sections], self.location)
2675
        iter_sections = iter(sections)
2676
        matching_sections = []
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
2677
        if no_name_section is not None:
2678
            matching_sections.append(
2679
                LocationSection(no_name_section, 0, self.location))
5743.2.31 by Vincent Ladeuil
Both the length and the section id should be used to sort.
2680
        for section_id, extra_path, length in filtered_sections:
5743.2.27 by Vincent Ladeuil
Merge the use of _filter_for_location_by_parts, uglier, but better for
2681
            # a section id is unique for a given store so it's safe to iterate
2682
            # again
2683
            section = iter_sections.next()
2684
            if section_id == section.id:
2685
                matching_sections.append(
2686
                    LocationSection(section, length, extra_path))
5743.6.15 by Vincent Ladeuil
Don't pollute _iter_for_location_by_parts.
2687
        return matching_sections
2688
2689
    def get_sections(self):
2690
        # Override the default implementation as we want to change the order
2691
        matching_sections = self._get_matching_sections()
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2692
        # We want the longest (aka more specific) locations first
5743.2.31 by Vincent Ladeuil
Both the length and the section id should be used to sort.
2693
        sections = sorted(matching_sections,
2694
                          key=lambda section: (section.length, section.id),
5743.2.24 by Vincent Ladeuil
Complete location config helpers with basic tests.
2695
                          reverse=True)
2696
        # Sections mentioning 'ignore_parents' restrict the selection
2697
        for section in sections:
2698
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
2699
            ignore = section.get('ignore_parents', None)
2700
            if ignore is not None:
2701
                ignore = ui.bool_from_string(ignore)
2702
            if ignore:
2703
                break
2704
            # Finally, we have a valid section
2705
            yield section
5743.2.22 by Vincent Ladeuil
Some minimal SectionMatcher implementation to setup the test infrastucture.
2706
5743.2.13 by Vincent Ladeuil
Trivial implementations for stores with smoke tests.
2707
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2708
class Stack(object):
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2709
    """A stack of configurations where an option can be defined"""
2710
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.
2711
    def __init__(self, sections_def, store=None, mutable_section_name=None):
5743.1.11 by Vincent Ladeuil
Properly use MutableSection for write operations.
2712
        """Creates a stack of sections with an optional store for changes.
2713
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.
2714
        :param sections_def: A list of Section or callables that returns an
2715
            iterable of Section. This defines the Sections for the Stack and
2716
            can be called repeatedly if needed.
5743.1.11 by Vincent Ladeuil
Properly use MutableSection for write operations.
2717
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.
2718
        :param store: The optional Store where modifications will be
2719
            recorded. If none is specified, no modifications can be done.
2720
2721
        :param mutable_section_name: The name of the MutableSection where
2722
            changes are recorded. This requires the ``store`` parameter to be
2723
            specified.
5743.1.11 by Vincent Ladeuil
Properly use MutableSection for write operations.
2724
        """
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.
2725
        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.
2726
        self.store = store
2727
        self.mutable_section_name = mutable_section_name
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2728
2729
    def get(self, name):
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
2730
        """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.
2731
5743.1.16 by Vincent Ladeuil
Allows empty sections and empty section callables.
2732
        This is where we guarantee that sections coming from Store are loaded
2733
        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.
2734
        option exists or get its value, which in turn may require to discover
2735
        in which sections it can be defined. Both of these (section and option
2736
        existence) require loading the store (even partially).
2737
        """
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.
2738
        # FIXME: No caching of options nor sections yet -- vila 20110503
5743.12.6 by Vincent Ladeuil
Stack.get() provides the registered option default value.
2739
        value = None
5743.6.17 by Vincent Ladeuil
Clarify comment.
2740
        # Ensuring lazy loading is achieved by delaying section matching (which
2741
        # implies querying the persistent storage) until it can't be avoided
2742
        # anymore by using callables to describe (possibly empty) section
2743
        # lists.
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.
2744
        for section_or_callable in self.sections_def:
5743.1.12 by Vincent Ladeuil
Clarify ConfigStack.get() about lazy evaluation of sections.
2745
            # Each section can expand to multiple ones when a callable is used
2746
            if callable(section_or_callable):
2747
                sections = section_or_callable()
5743.1.9 by Vincent Ladeuil
Fix the issue by allowing delayed section acquisition.
2748
            else:
5743.1.12 by Vincent Ladeuil
Clarify ConfigStack.get() about lazy evaluation of sections.
2749
                sections = [section_or_callable]
2750
            for section in sections:
2751
                value = section.get(name)
2752
                if value is not None:
5743.12.6 by Vincent Ladeuil
Stack.get() provides the registered option default value.
2753
                    break
2754
            if value is not None:
2755
                break
2756
        if value is None:
2757
            # If the option is registered, it may provide a default value
5743.12.7 by Vincent Ladeuil
Test that providing a default value doesn't break for non-registered options.
2758
            try:
2759
                opt = option_registry.get(name)
2760
            except KeyError:
2761
                # Not registered
2762
                opt = None
2763
            if opt is not None:
2764
                value = opt.get_default()
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.
2765
        for hook in ConfigHooks['get']:
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
2766
            hook(self, name, value)
5743.12.6 by Vincent Ladeuil
Stack.get() provides the registered option default value.
2767
        return value
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2768
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.
2769
    def _get_mutable_section(self):
2770
        """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.
2771
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2772
        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.
2773
        this means we won't load the corresponding store before setting a value
2774
        or deleting an option. In practice the store will often be loaded but
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2775
        this allows helps catching some programming errors.
5743.1.13 by Vincent Ladeuil
Better explain lazy loading and make sure the mutable section respect the design.
2776
        """
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.
2777
        section = self.store.get_mutable_section(self.mutable_section_name)
2778
        return section
2779
2780
    def set(self, name, value):
2781
        """Set a new value for the option."""
2782
        section = self._get_mutable_section()
5743.1.13 by Vincent Ladeuil
Better explain lazy loading and make sure the mutable section respect the design.
2783
        section.set(name, 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.
2784
        for hook in ConfigHooks['set']:
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
2785
            hook(self, name, value)
5743.1.7 by Vincent Ladeuil
Simple set implementation.
2786
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2787
    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.
2788
        """Remove an existing option."""
2789
        section = self._get_mutable_section()
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2790
        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.
2791
        for hook in ConfigHooks['remove']:
5743.8.6 by Vincent Ladeuil
Add hooks for config stacks.
2792
            hook(self, name)
5743.1.15 by Vincent Ladeuil
Test and implement ConfigStack.remove.
2793
5743.1.34 by Vincent Ladeuil
Merge config-section-matchers into config-stack resolving conflicts
2794
    def __repr__(self):
2795
        # Mostly for debugging use
2796
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2797
5743.1.1 by Vincent Ladeuil
Start implementing a config stack.
2798
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2799
class _CompatibleStack(Stack):
5743.6.26 by Vincent Ladeuil
Clarify _CompatibleStack aims.
2800
    """Place holder for compatibility with previous design.
2801
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2802
    This is intended to ease the transition from the Config-based design to the
5743.6.26 by Vincent Ladeuil
Clarify _CompatibleStack aims.
2803
    Stack-based design and should not be used nor relied upon by plugins.
2804
2805
    One assumption made here is that the daughter classes will all use Stores
2806
    derived from LockableIniFileStore).
5743.6.32 by Vincent Ladeuil
Address poolie's review comments.
2807
2808
    It implements set() by re-loading the store before applying the
2809
    modification and saving it.
2810
2811
    The long term plan being to implement a single write by store to save
2812
    all modifications, this class should not be used in the interim.
5743.6.26 by Vincent Ladeuil
Clarify _CompatibleStack aims.
2813
    """
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2814
2815
    def set(self, name, value):
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2816
        # Force a reload
2817
        self.store.unload()
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2818
        super(_CompatibleStack, self).set(name, value)
2819
        # Force a write to persistent storage
2820
        self.store.save()
2821
2822
2823
class GlobalStack(_CompatibleStack):
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
2824
2825
    def __init__(self):
2826
        # Get a GlobalStore
2827
        gstore = GlobalStore()
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2828
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
2829
2830
5743.6.23 by Vincent Ladeuil
More config concurrent updates tests.
2831
class LocationStack(_CompatibleStack):
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
2832
2833
    def __init__(self, location):
2834
        lstore = LocationStore()
2835
        matcher = LocationMatcher(lstore, location)
2836
        gstore = GlobalStore()
2837
        super(LocationStack, self).__init__(
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2838
            [matcher.get_sections, gstore.get_sections], lstore)
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
2839
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
2840
class BranchStack(_CompatibleStack):
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
2841
2842
    def __init__(self, branch):
2843
        bstore = BranchStore(branch)
2844
        lstore = LocationStore()
2845
        matcher = LocationMatcher(lstore, branch.base)
2846
        gstore = GlobalStore()
2847
        super(BranchStack, self).__init__(
2848
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
5743.6.14 by Vincent Ladeuil
Parametrize the Stack tests.
2849
            bstore)
5743.10.2 by Vincent Ladeuil
Make sure RemoteBranch are supported as well, relying on the vfs API.
2850
        self.branch = branch
5743.6.1 by Vincent Ladeuil
Outline concrete stacks and basic smoke tests.
2851
2852
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2853
class cmd_config(commands.Command):
5447.4.19 by Vincent Ladeuil
Add some more documentation.
2854
    __doc__ = """Display, set or remove a configuration option.
2855
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2856
    Display the active value for a given option.
2857
2858
    If --all is specified, NAME is interpreted as a regular expression and all
2859
    matching options are displayed mentioning their scope. The active value
2860
    that bzr will take into account is the first one displayed for each option.
2861
2862
    If no NAME is given, --all .* is implied.
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2863
5447.4.19 by Vincent Ladeuil
Add some more documentation.
2864
    Setting a value is achieved by using name=value without spaces. The value
2865
    is set in the most relevant scope and can be checked by displaying the
2866
    option again.
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2867
    """
2868
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2869
    takes_args = ['name?']
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2870
2871
    takes_options = [
2872
        'directory',
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2873
        # FIXME: This should be a registry option so that plugins can register
2874
        # their own config files (or not) -- vila 20101002
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2875
        commands.Option('scope', help='Reduce the scope to the specified'
2876
                        ' configuration file',
2877
                        type=unicode),
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2878
        commands.Option('all',
2879
            help='Display all the defined values for the matching options.',
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2880
            ),
5447.4.8 by Vincent Ladeuil
Make the test properly fail and provide a fake implementation for ``bzr config --remove opt_name``.
2881
        commands.Option('remove', help='Remove the option from'
2882
                        ' the configuration file'),
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2883
        ]
2884
5425.4.24 by Martin Pool
Mention 'configuration' help topic from 'bzr help config'
2885
    _see_also = ['configuration']
2886
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2887
    @commands.display_command
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2888
    def run(self, name=None, all=False, directory=None, scope=None,
2889
            remove=False):
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2890
        if directory is None:
2891
            directory = '.'
2892
        directory = urlutils.normalize_url(directory)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2893
        if remove and all:
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2894
            raise errors.BzrError(
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2895
                '--all and --remove are mutually exclusive.')
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2896
        elif remove:
2897
            # Delete the option in the given scope
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2898
            self._remove_config_option(name, directory, scope)
2899
        elif name is None:
2900
            # Defaults to all options
2901
            self._show_matching_options('.*', directory, scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2902
        else:
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2903
            try:
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2904
                name, value = name.split('=', 1)
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2905
            except ValueError:
2906
                # Display the option(s) value(s)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2907
                if all:
2908
                    self._show_matching_options(name, directory, scope)
2909
                else:
2910
                    self._show_value(name, directory, scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2911
            else:
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2912
                if all:
2913
                    raise errors.BzrError(
2914
                        'Only one option can be set.')
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2915
                # Set the option value
2916
                self._set_config_option(name, value, directory, scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2917
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2918
    def _get_configs(self, directory, scope=None):
2919
        """Iterate the configurations specified by ``directory`` and ``scope``.
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2920
2921
        :param directory: Where the configurations are derived from.
2922
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2923
        :param scope: A specific config to start from.
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2924
        """
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2925
        if scope is not None:
2926
            if scope == 'bazaar':
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2927
                yield GlobalConfig()
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2928
            elif scope == 'locations':
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2929
                yield LocationConfig(directory)
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2930
            elif scope == 'branch':
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2931
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2932
                    directory)
2933
                yield br.get_config()
2934
        else:
2935
            try:
2936
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2937
                    directory)
2938
                yield br.get_config()
2939
            except errors.NotBranchError:
2940
                yield LocationConfig(directory)
2941
                yield GlobalConfig()
2942
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2943
    def _show_value(self, name, directory, scope):
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2944
        displayed = False
2945
        for c in self._get_configs(directory, scope):
2946
            if displayed:
2947
                break
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2948
            for (oname, value, section, conf_id, parser) in c._get_options():
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2949
                if name == oname:
5533.1.3 by Vincent Ladeuil
Tweak comment as per poolie's suggestion.
2950
                    # Display only the first value and exit
5533.2.3 by Vincent Ladeuil
Merge 671050-config-policy into 672382-list-values 672382-list-values resolving conflicts
2951
5533.1.3 by Vincent Ladeuil
Tweak comment as per poolie's suggestion.
2952
                    # FIXME: We need to use get_user_option to take policies
2953
                    # into account and we need to make sure the option exists
5533.2.3 by Vincent Ladeuil
Merge 671050-config-policy into 672382-list-values 672382-list-values resolving conflicts
2954
                    # too (hence the two for loops), this needs a better API
2955
                    # -- vila 20101117
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2956
                    value = c.get_user_option(name)
2957
                    # Quote the value appropriately
2958
                    value = parser._quote(value)
2959
                    self.outf.write('%s\n' % (value,))
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2960
                    displayed = True
2961
                    break
2962
        if not displayed:
2963
            raise errors.NoSuchConfigOption(name)
2964
2965
    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
2966
        name = lazy_regex.lazy_compile(name)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2967
        # 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
2968
        # avoid the delay introduced by the lazy regexp.  But, we still do
2969
        # want the nicer errors raised by lazy_regex.
2970
        name._compile_and_collapse()
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2971
        cur_conf_id = None
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
2972
        cur_section = None
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2973
        for c in self._get_configs(directory, scope):
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2974
            for (oname, value, section, conf_id, parser) in c._get_options():
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2975
                if name.search(oname):
2976
                    if cur_conf_id != conf_id:
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2977
                        # Explain where the options are defined
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
2978
                        self.outf.write('%s:\n' % (conf_id,))
2979
                        cur_conf_id = conf_id
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
2980
                        cur_section = None
2981
                    if (section not in (None, 'DEFAULT')
2982
                        and cur_section != section):
2983
                        # Display the section if it's not the default (or only)
2984
                        # one.
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2985
                        self.outf.write('  [%s]\n' % (section,))
5533.1.1 by Vincent Ladeuil
Fix ``bzr config`` to respect policies when displaying values and also display sections when appropriate.
2986
                        cur_section = section
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2987
                    self.outf.write('  %s = %s\n' % (oname, value))
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2988
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2989
    def _set_config_option(self, name, value, directory, scope):
2990
        for conf in self._get_configs(directory, scope):
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2991
            conf.set_user_option(name, value)
2992
            break
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2993
        else:
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2994
            raise errors.NoSuchConfig(scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2995
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2996
    def _remove_config_option(self, name, directory, scope):
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2997
        if name is None:
2998
            raise errors.BzrCommandError(
2999
                '--remove expects an option to remove.')
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
3000
        removed = False
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
3001
        for conf in self._get_configs(directory, scope):
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.
3002
            for (section_name, section, conf_id) in conf._get_sections():
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
3003
                if scope is not None and conf_id != scope:
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
3004
                    # Not the right configuration file
3005
                    continue
3006
                if name in section:
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
3007
                    if conf_id != conf.config_id():
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
3008
                        conf = self._get_configs(directory, conf_id).next()
3009
                    # We use the first section in the first config where the
3010
                    # option is defined to remove it
3011
                    conf.remove_user_option(name, section_name)
3012
                    removed = True
3013
                    break
3014
            break
3015
        else:
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
3016
            raise errors.NoSuchConfig(scope)
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
3017
        if not removed:
3018
            raise errors.NoSuchConfigOption(name)
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
3019
3020
# Test registries
5743.6.29 by Vincent Ladeuil
For jam.
3021
#
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
3022
# We need adapters that can build a Store or a Stack in a test context. Test
3023
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3024
# themselves. The builder will receive a test instance and should return a
5743.6.29 by Vincent Ladeuil
For jam.
3025
# 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
3026
# register themselves here to be tested against the tests defined in
5743.11.1 by Vincent Ladeuil
Add a note about config store builders being called several times by some tests.
3027
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3028
# for the same tests.
5743.6.27 by Vincent Ladeuil
Move the test registries to bzrlib.config so plugins will be able to use
3029
3030
# The registered object should be a callable receiving a test instance
3031
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3032
# object.
3033
test_store_builder_registry = registry.Registry()
3034
5743.10.1 by Vincent Ladeuil
Derefence the ref to use it.
3035
# 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
3036
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3037
# object.
3038
test_stack_builder_registry = registry.Registry()