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