/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
1442.1.20 by Robert Collins
add some documentation on options
32
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
33
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
34
Wildcards may be used - * and ? as normal in shell completion. Options
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
35
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
36
setting.
37
[/home/robertc/source]
38
recurse=False|True(default)
39
email= as above
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
40
check_signatures= as above
1442.1.20 by Robert Collins
add some documentation on options
41
create_signatures= as above.
42
43
explanation of options
44
----------------------
45
editor - this option sets the pop up editor to use during commits.
46
email - this option sets the user id bzr will use when committing.
47
check_signatures - this option controls whether bzr will require good gpg
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
48
                   signatures, ignore them, or check them if they are
1442.1.20 by Robert Collins
add some documentation on options
49
                   present.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
50
create_signatures - this option controls whether bzr will always create
1442.1.20 by Robert Collins
add some documentation on options
51
                    gpg signatures, never create them, or create them if the
52
                    branch is configured to require them.
1887.2.1 by Adeodato Simó
Fix some typos and grammar issues.
53
log_format - this option sets the default log format.  Possible values are
54
             long, short, line, or a plugin can register new formats.
1553.6.2 by Erik Bågfors
documentation and NEWS
55
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
57
58
[ALIASES]
59
lastlog=log --line -r-10..-1
60
ll=log --line -r-10..-1
61
h=help
62
up=pull
1442.1.20 by Robert Collins
add some documentation on options
63
"""
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
64
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
65
import os
66
import sys
1474 by Robert Collins
Merge from Aaron Bentley.
67
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
68
from bzrlib import commands
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
69
from bzrlib.decorators import needs_write_lock
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
70
from bzrlib.lazy_import import lazy_import
71
lazy_import(globals(), """
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
72
import fnmatch
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
73
import re
2900.2.22 by Vincent Ladeuil
Polishing.
74
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.
75
76
import bzrlib
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
77
from bzrlib import (
4797.59.2 by Vincent Ladeuil
Use AtomicFile and avoid all unicode/encoding issues around transport (thanks jam).
78
    atomicfile,
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
79
    bzrdir,
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
80
    debug,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
81
    errors,
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
82
    lockdir,
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
83
    mail_client,
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
84
    mergetools,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
85
    osutils,
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
86
    registry,
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
87
    symbol_versioning,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
88
    trace,
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
89
    transport,
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
90
    ui,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
91
    urlutils,
2245.4.3 by Alexander Belchenko
config.py: changing _auto_user_id() and config_dir() to use functions from win32utils
92
    win32utils,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
93
    )
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
94
from bzrlib.util.configobj import configobj
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
95
""")
96
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
97
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
98
CHECK_IF_POSSIBLE=0
99
CHECK_ALWAYS=1
100
CHECK_NEVER=2
101
102
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
103
SIGN_WHEN_REQUIRED=0
104
SIGN_ALWAYS=1
105
SIGN_NEVER=2
106
107
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
108
POLICY_NONE = 0
109
POLICY_NORECURSE = 1
110
POLICY_APPENDPATH = 2
111
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
112
_policy_name = {
113
    POLICY_NONE: None,
114
    POLICY_NORECURSE: 'norecurse',
115
    POLICY_APPENDPATH: 'appendpath',
116
    }
117
_policy_value = {
118
    None: POLICY_NONE,
119
    'none': POLICY_NONE,
120
    'norecurse': POLICY_NORECURSE,
121
    'appendpath': POLICY_APPENDPATH,
122
    }
2120.6.4 by James Henstridge
add support for specifying policy when storing options
123
124
125
STORE_LOCATION = POLICY_NONE
126
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
127
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
128
STORE_BRANCH = 3
129
STORE_GLOBAL = 4
130
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
131
132
class ConfigObj(configobj.ConfigObj):
133
134
    def __init__(self, infile=None, **kwargs):
135
        # We define our own interpolation mechanism calling it option expansion
136
        super(ConfigObj, self).__init__(infile=infile,
137
                                        interpolation=False,
138
                                        **kwargs)
139
140
141
    def get_bool(self, section, key):
142
        return self[section].as_bool(key)
143
144
    def get_value(self, section, name):
145
        # Try [] for the old DEFAULT section.
146
        if section == "DEFAULT":
147
            try:
148
                return self[name]
149
            except KeyError:
150
                pass
151
        return self[section][name]
152
153
154
# FIXME: Until we can guarantee that each config file is loaded once and and
155
# only once for a given bzrlib session, we don't want to re-read the file every
156
# time we query for an option so we cache the value (bad ! watch out for tests
157
# needing to restore the proper value).This shouldn't be part of 2.4.0 final,
158
# yell at mgz^W vila and the RM if this is still present at that time
159
# -- vila 20110219
160
_expand_default_value = None
161
def _get_expand_default_value():
162
    global _expand_default_value
163
    if _expand_default_value is not None:
164
        return _expand_default_value
165
    conf = GlobalConfig()
166
    # Note that we must not use None for the expand value below or we'll run
167
    # into infinite recursion. Using False really would be quite silly ;)
168
    expand = conf.get_user_option_as_bool('bzr.config.expand', expand=True)
169
    if expand is None:
170
        # This is an opt-in feature, you *really* need to clearly say you want
171
        # to activate it !
172
        expand = False
173
    _expand_default_value = expand
174
    return expand
5549.1.31 by Vincent Ladeuil
Implement a default value for config option expansion (what ? No tests ?).
175
5549.1.19 by Vincent Ladeuil
Push down interpolation at the config level (make tests slightly less
176
177
class Config(object):
178
    """A configuration policy - what username, editor, gpg needs etc."""
179
180
    def __init__(self):
181
        super(Config, self).__init__()
182
183
    def config_id(self):
184
        """Returns a unique ID for the config."""
185
        raise NotImplementedError(self.config_id)
186
187
    def get_editor(self):
188
        """Get the users pop up editor."""
189
        raise NotImplementedError
190
191
    def get_change_editor(self, old_tree, new_tree):
192
        from bzrlib import diff
193
        cmd = self._get_change_editor()
194
        if cmd is None:
195
            return None
196
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
197
                                             sys.stdout)
198
199
200
    def get_mail_client(self):
201
        """Get a mail client to use"""
202
        selected_client = self.get_user_option('mail_client')
203
        _registry = mail_client.mail_client_registry
204
        try:
205
            mail_client_class = _registry.get(selected_client)
206
        except KeyError:
207
            raise errors.UnknownMailClient(selected_client)
208
        return mail_client_class(self)
209
210
    def _get_signature_checking(self):
211
        """Template method to override signature checking policy."""
212
213
    def _get_signing_policy(self):
214
        """Template method to override signature creation policy."""
215
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
216
    option_ref_re = None
217
218
    def expand_options(self, string, env=None):
219
        """Expand option references in the string in the configuration context.
220
221
        :param string: The string containing option to expand.
222
223
        :param env: An option dict defining additional configuration options or
224
            overriding existing ones.
225
226
        :returns: The expanded string.
227
        """
228
        return self._expand_options_in_string(string, env)
229
230
    def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
231
        """Expand options in  a list of strings in the configuration context.
232
233
        :param slist: A list of strings.
234
235
        :param env: An option dict defining additional configuration options or
236
            overriding existing ones.
237
238
        :param _ref_stack: Private list containing the options being
239
            expanded to detect loops.
240
241
        :returns: The flatten list of expanded strings.
242
        """
243
        # expand options in each value separately flattening lists
244
        result = []
245
        for s in slist:
246
            value = self._expand_options_in_string(s, env, _ref_stack)
247
            if isinstance(value, list):
248
                result.extend(value)
249
            else:
250
                result.append(value)
251
        return result
252
253
    def _expand_options_in_string(self, string, env=None, _ref_stack=None):
254
        """Expand options in the string in the configuration context.
255
256
        :param string: The string to be expanded.
257
258
        :param env: An option dict defining additional configuration options or
259
            overriding existing ones.
260
261
        :param _ref_stack: Private list containing the options being
262
            expanded to detect loops.
263
264
        :returns: The expanded string.
265
        """
266
        if string is None:
267
            # Not much to expand there
268
            return None
269
        if _ref_stack is None:
270
            # What references are currently resolved (to detect loops)
271
            _ref_stack = []
272
        if self.option_ref_re is None:
273
            # We want to match the most embedded reference first (i.e. for
274
            # '{{foo}}' we will get '{foo}',
275
            # for '{bar{baz}}' we will get '{baz}'
276
            self.option_ref_re = re.compile('({[^{}]+})')
277
        result = string
278
        # We need to iterate until no more refs appear ({{foo}} will need two
279
        # iterations for example).
280
        while True:
5745.1.1 by Vincent Ladeuil
Remove debug code
281
            raw_chunks = self.option_ref_re.split(result)
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
282
            if len(raw_chunks) == 1:
283
                # Shorcut the trivial case: no refs
284
                return result
285
            chunks = []
286
            list_value = False
287
            # Split will isolate refs so that every other chunk is a ref
288
            chunk_is_ref = False
289
            for chunk in raw_chunks:
290
                if not chunk_is_ref:
291
                    if chunk:
292
                        # Keep only non-empty strings (or we get bogus empty
293
                        # slots when a list value is involved).
294
                        chunks.append(chunk)
295
                    chunk_is_ref = True
296
                else:
297
                    name = chunk[1:-1]
298
                    if name in _ref_stack:
299
                        raise errors.OptionExpansionLoop(string, _ref_stack)
300
                    _ref_stack.append(name)
301
                    value = self._expand_option(name, env, _ref_stack)
302
                    if value is None:
303
                        raise errors.ExpandingUnknownOption(name, string)
304
                    if isinstance(value, list):
305
                        list_value = True
306
                        chunks.extend(value)
307
                    else:
308
                        chunks.append(value)
309
                    _ref_stack.pop()
310
                    chunk_is_ref = False
311
            if list_value:
312
                # Once a list appears as the result of an expansion, all
313
                # callers will get a list result. This allows a consistent
314
                # behavior even when some options in the expansion chain
315
                # defined as strings (no comma in their value) but their
316
                # expanded value is a list.
317
                return self._expand_options_in_list(chunks, env, _ref_stack)
318
            else:
319
                result = ''.join(chunks)
320
        return result
321
322
    def _expand_option(self, name, env, _ref_stack):
323
        if env is not None and name in env:
324
            # Special case, values provided in env takes precedence over
325
            # anything else
326
            value = env[name]
327
        else:
328
            # FIXME: This is a limited implementation, what we really need is a
329
            # way to query the bzr config for the value of an option,
330
            # respecting the scope rules (That is, once we implement fallback
331
            # configs, getting the option value should restart from the top
332
            # config, not the current one) -- vila 20101222
333
            value = self.get_user_option(name, expand=False)
334
            if isinstance(value, list):
335
                value = self._expand_options_in_list(value, env, _ref_stack)
336
            else:
337
                value = self._expand_options_in_string(value, env, _ref_stack)
338
        return value
339
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
340
    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.
341
        """Template method to provide a user option."""
342
        return None
343
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
344
    def get_user_option(self, option_name, expand=None):
345
        """Get a generic option - no special process, no default.
346
347
        :param option_name: The queried option.
348
349
        :param expand: Whether options references should be expanded.
350
351
        :returns: The value of the option.
352
        """
353
        if expand is None:
354
            expand = _get_expand_default_value()
355
        value = self._get_user_option(option_name)
356
        if expand:
357
            if isinstance(value, list):
358
                value = self._expand_options_in_list(value)
359
            elif isinstance(value, dict):
360
                trace.warning('Cannot expand "%s":'
361
                              ' Dicts do not support option expansion'
362
                              % (option_name,))
363
            else:
364
                value = self._expand_options_in_string(value)
365
        return value
366
367
    def get_user_option_as_bool(self, option_name, expand=None):
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
368
        """Get a generic option as a boolean - no special process, no default.
369
370
        :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.
371
            interpreted as a boolean. Returns True or False otherwise.
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
372
        """
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
373
        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.
374
        if s is None:
375
            # The option doesn't exist
376
            return None
4989.2.15 by Vincent Ladeuil
Fixed as per Andrew's review.
377
        val = ui.bool_from_string(s)
4989.2.12 by Vincent Ladeuil
Display a warning if an option value is not boolean.
378
        if val is None:
379
            # The value can't be interpreted as a boolean
380
            trace.warning('Value "%s" is not a boolean for "%s"',
381
                          s, option_name)
382
        return val
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
383
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
384
    def get_user_option_as_list(self, option_name, expand=None):
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
385
        """Get a generic option as a list - no special process, no default.
386
387
        :return None if the option doesn't exist. Returns the value as a list
388
            otherwise.
389
        """
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
390
        l = self.get_user_option(option_name, expand=expand)
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
391
        if isinstance(l, (str, unicode)):
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
392
            # A single value, most probably the user forgot (or didn't care to
393
            # add) the final ','
4840.2.4 by Vincent Ladeuil
Implement config.get_user_option_as_list.
394
            l = [l]
395
        return l
396
1442.1.56 by Robert Collins
gpg_signing_command configuration item
397
    def gpg_signing_command(self):
398
        """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.
399
        result = self._gpg_signing_command()
400
        if result is None:
401
            result = "gpg"
402
        return result
403
404
    def _gpg_signing_command(self):
405
        """See gpg_signing_command()."""
406
        return None
1442.1.56 by Robert Collins
gpg_signing_command configuration item
407
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
408
    def log_format(self):
409
        """What log format should be used"""
410
        result = self._log_format()
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
411
        if result is None:
412
            result = "long"
413
        return result
414
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
415
    def _log_format(self):
416
        """See log_format()."""
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
417
        return None
418
1472 by Robert Collins
post commit hook, first pass implementation
419
    def post_commit(self):
420
        """An ordered list of python functions to call.
421
422
        Each function takes branch, rev_id as parameters.
423
        """
424
        return self._post_commit()
425
426
    def _post_commit(self):
427
        """See Config.post_commit."""
428
        return None
429
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
430
    def user_email(self):
431
        """Return just the email component of a username."""
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
432
        return extract_email_address(self.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
433
434
    def username(self):
435
        """Return email-style username.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
436
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
437
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
438
5187.2.1 by Parth Malwankar
removed comment about deprecated BZREMAIL.
439
        $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
440
        the concrete policy type is checked, and finally
1185.37.2 by Jamie Wilkinson
Fix a typo and grammar in Config.username() docstring.
441
        $EMAIL is examined.
5187.2.12 by Parth Malwankar
trivial clarification in docstring.
442
        If no username can be found, errors.NoWhoami exception is raised.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
443
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
444
        TODO: Check it's reasonably well-formed.
445
        """
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
446
        v = os.environ.get('BZR_EMAIL')
447
        if v:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
448
            return v.decode(osutils.get_user_encoding())
2900.3.1 by Tim Penhey
Removed some annoying trailing whitespace.
449
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
450
        v = self._get_user_id()
451
        if v:
452
            return v
2900.3.1 by Tim Penhey
Removed some annoying trailing whitespace.
453
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
454
        v = os.environ.get('EMAIL')
455
        if v:
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
456
            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
457
5187.2.6 by Parth Malwankar
lockdir no long mandates whoami but uses unicode version of getuser
458
        raise errors.NoWhoami()
5187.2.3 by Parth Malwankar
init and init-repo now fail before creating dir if username is not set.
459
460
    def ensure_username(self):
5187.2.11 by Parth Malwankar
documentation updates
461
        """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.
462
463
        This method relies on the username() function raising the error.
464
        """
465
        self.username()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
466
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
467
    def signature_checking(self):
468
        """What is the current policy for signature checking?."""
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
469
        policy = self._get_signature_checking()
470
        if policy is not None:
471
            return policy
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
472
        return CHECK_IF_POSSIBLE
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
473
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
474
    def signing_policy(self):
475
        """What is the current policy for signature checking?."""
476
        policy = self._get_signing_policy()
477
        if policy is not None:
478
            return policy
479
        return SIGN_WHEN_REQUIRED
480
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
481
    def signature_needed(self):
482
        """Is a signature needed when committing ?."""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
483
        policy = self._get_signing_policy()
484
        if policy is None:
485
            policy = self._get_signature_checking()
486
            if policy is not None:
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
487
                trace.warning("Please use create_signatures,"
488
                              " not check_signatures to set signing policy.")
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
489
            if policy == CHECK_ALWAYS:
490
                return True
491
        elif policy == SIGN_ALWAYS:
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
492
            return True
493
        return False
494
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
495
    def get_alias(self, value):
496
        return self._get_alias(value)
497
498
    def _get_alias(self, value):
499
        pass
500
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
501
    def get_nickname(self):
502
        return self._get_nickname()
503
504
    def _get_nickname(self):
505
        return None
506
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
507
    def get_bzr_remote_path(self):
508
        try:
509
            return os.environ['BZR_REMOTE_PATH']
510
        except KeyError:
511
            path = self.get_user_option("bzr_remote_path")
512
            if path is None:
513
                path = 'bzr'
514
            return path
515
4840.2.6 by Vincent Ladeuil
Implement config.suppress_warning.
516
    def suppress_warning(self, warning):
517
        """Should the warning be suppressed or emitted.
518
519
        :param warning: The name of the warning being tested.
520
521
        :returns: True if the warning should be suppressed, False otherwise.
522
        """
523
        warnings = self.get_user_option_as_list('suppress_warnings')
524
        if warnings is None or warning not in warnings:
525
            return False
526
        else:
527
            return True
528
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
529
    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.
530
        tools = {}
5321.1.99 by Gordon Tyler
Fixes for changes to Config._get_options().
531
        for (oname, value, section, conf_id, parser) in self._get_options():
5321.2.3 by Vincent Ladeuil
Prefix mergetools option names with 'bzr.'.
532
            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.
533
                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.
534
                tools[tool_name] = value
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
535
        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.
536
        return tools
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
537
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.
538
    def find_merge_tool(self, name):
5321.1.111 by Gordon Tyler
Remove predefined merge tools from list returned by get_merge_tools.
539
        # We fake a defaults mechanism here by checking if the given name can 
540
        # be found in the known_merge_tools if it's not found in the config.
541
        # This should be done through the proposed config defaults mechanism
542
        # when it becomes available in the future.
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
543
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
544
                                             expand=False)
545
                        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.
546
        return command_line
5321.1.88 by Gordon Tyler
Moved mergetools config functions into bzrlib.config.Config.
547
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
548
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
549
class IniBasedConfig(Config):
550
    """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
551
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
552
    def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
553
                 file_name=None):
5345.2.5 by Vincent Ladeuil
Add docstring.
554
        """Base class for configuration files using an ini-like syntax.
555
556
        :param file_name: The configuration file path.
557
        """
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
558
        super(IniBasedConfig, self).__init__()
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
559
        self.file_name = file_name
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
560
        if symbol_versioning.deprecated_passed(get_filename):
561
            symbol_versioning.warn(
562
                'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
563
                ' Use file_name instead.',
564
                DeprecationWarning,
565
                stacklevel=2)
5345.1.8 by Vincent Ladeuil
Make the test_listen_to_the_last_speaker pass and fix fallouts.
566
            if get_filename is not None:
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
567
                self.file_name = get_filename()
568
        else:
569
            self.file_name = file_name
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
570
        self._content = None
4503.2.2 by Vincent Ladeuil
Get a bool or none from a config file.
571
        self._parser = None
572
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
573
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
574
    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
575
        """Create a config object from a string.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
576
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
577
        :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.
578
            be utf-8 encoded.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
579
580
        :param file_name: The configuration file path.
581
582
        :param _save: Whether the file should be saved upon creation.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
583
        """
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
584
        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
585
        conf._create_from_string(str_or_unicode, save)
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
586
        return conf
587
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
588
    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
589
        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.
590
        # Some tests use in-memory configs, some other always need the config
591
        # file to exist on disk.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
592
        if save:
5345.1.16 by Vincent Ladeuil
Allows tests to save the config file at build time.
593
            self._write_config_file()
5345.5.12 by Vincent Ladeuil
Fix fallouts from replacing '_content' by 'from_bytes' for config files.
594
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
595
    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
596
        if self._parser is not None:
597
            return self._parser
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
598
        if symbol_versioning.deprecated_passed(file):
599
            symbol_versioning.warn(
600
                '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.
601
                ' Use IniBasedConfig(_content=xxx) instead.',
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
602
                DeprecationWarning,
603
                stacklevel=2)
604
        if self._content is not None:
605
            co_input = self._content
606
        elif self.file_name is None:
607
            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
608
        else:
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
609
            co_input = self.file_name
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
610
        try:
5345.1.4 by Vincent Ladeuil
Deprecate the ``file`` parameter of the ``config._get_parser()`` method.
611
            self._parser = ConfigObj(co_input, encoding='utf-8')
1474 by Robert Collins
Merge from Aaron Bentley.
612
        except configobj.ConfigObjError, e:
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
613
            raise errors.ParseConfigError(e.errors, e.config.filename)
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
614
        # 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.
615
        self._parser.filename = self.file_name
1185.12.49 by Aaron Bentley
Switched to ConfigObj
616
        return self._parser
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
617
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
618
    def reload(self):
619
        """Reload the config file from disk."""
620
        if self.file_name is None:
621
            raise AssertionError('We need a file name to reload the config')
622
        if self._parser is not None:
623
            self._parser.reload()
624
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
625
    def _get_matching_sections(self):
626
        """Return an ordered list of (section_name, extra_path) pairs.
627
628
        If the section contains inherited configuration, extra_path is
629
        a string containing the additional path components.
630
        """
631
        section = self._get_section()
632
        if section is not None:
633
            return [(section, '')]
634
        else:
635
            return []
636
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
637
    def _get_section(self):
638
        """Override this to define the section used by the config."""
639
        return "DEFAULT"
640
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.
641
    def _get_sections(self, name=None):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
642
        """Returns an iterator of the sections specified by ``name``.
643
644
        :param name: The section name. If None is supplied, the default
645
            configurations are yielded.
646
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
647
        :return: A tuple (name, section, config_id) for all sections that will
648
            be walked by user_get_option() in the 'right' order. The first one
649
            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.
650
        """
651
        parser = self._get_parser()
652
        if name is not None:
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
653
            yield (name, parser[name], self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
654
        else:
655
            # No section name has been given so we fallback to the configobj
656
            # 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.
657
            yield (None, parser, self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
658
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.
659
    def _get_options(self, sections=None):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
660
        """Return an ordered list of (name, value, section, config_id) tuples.
661
662
        All options are returned with their associated value and the section
663
        they appeared in. ``config_id`` is a unique identifier for the
664
        configuration file the option is defined in.
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
665
666
        :param sections: Default to ``_get_matching_sections`` if not
667
            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.
668
            which sections should be searched. This is a list of (name,
669
            configobj) tuples.
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
670
        """
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
671
        opts = []
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
672
        if sections is None:
673
            parser = self._get_parser()
674
            sections = []
675
            for (section_name, _) in self._get_matching_sections():
676
                try:
677
                    section = parser[section_name]
678
                except KeyError:
679
                    # This could happen for an empty file for which we define a
680
                    # DEFAULT section. FIXME: Force callers to provide sections
681
                    # instead ? -- vila 20100930
682
                    continue
683
                sections.append((section_name, section))
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
684
        config_id = self.config_id()
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
685
        for (section_name, section) in sections:
686
            for (name, value) in section.iteritems():
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
687
                yield (name, parser._quote(value), section_name,
688
                       config_id, parser)
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
689
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
690
    def _get_option_policy(self, section, option_name):
691
        """Return the policy for the given (section, option_name) pair."""
692
        return POLICY_NONE
693
4603.1.10 by Aaron Bentley
Provide change editor via config.
694
    def _get_change_editor(self):
695
        return self.get_user_option('change_editor')
696
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
697
    def _get_signature_checking(self):
698
        """See Config._get_signature_checking."""
1474 by Robert Collins
Merge from Aaron Bentley.
699
        policy = self._get_user_option('check_signatures')
700
        if policy:
701
            return self._string_to_signature_policy(policy)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
702
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
703
    def _get_signing_policy(self):
1773.4.3 by Martin Pool
[merge] bzr.dev
704
        """See Config._get_signing_policy"""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
705
        policy = self._get_user_option('create_signatures')
706
        if policy:
707
            return self._string_to_signing_policy(policy)
708
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
709
    def _get_user_id(self):
710
        """Get the user id from the 'email' key in the current section."""
1474 by Robert Collins
Merge from Aaron Bentley.
711
        return self._get_user_option('email')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
712
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
713
    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.
714
        """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
715
        for (section, extra_path) in self._get_matching_sections():
716
            try:
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
717
                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
718
            except KeyError:
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
719
                continue
720
            policy = self._get_option_policy(section, option_name)
721
            if policy == POLICY_NONE:
722
                return value
723
            elif policy == POLICY_NORECURSE:
724
                # norecurse items only apply to the exact path
725
                if extra_path:
726
                    continue
727
                else:
728
                    return value
729
            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
730
                if extra_path:
731
                    value = urlutils.join(value, extra_path)
732
                return value
2120.6.6 by James Henstridge
fix test_set_push_location test
733
            else:
734
                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
735
        else:
1993.3.1 by James Henstridge
first go at making location config lookup recursive
736
            return None
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
737
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
738
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
739
        """See Config.gpg_signing_command."""
1472 by Robert Collins
post commit hook, first pass implementation
740
        return self._get_user_option('gpg_signing_command')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
741
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
742
    def _log_format(self):
743
        """See Config.log_format."""
744
        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
745
1472 by Robert Collins
post commit hook, first pass implementation
746
    def _post_commit(self):
747
        """See Config.post_commit."""
748
        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
749
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
750
    def _string_to_signature_policy(self, signature_string):
751
        """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
752
        if signature_string.lower() == 'check-available':
753
            return CHECK_IF_POSSIBLE
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
754
        if signature_string.lower() == 'ignore':
755
            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
756
        if signature_string.lower() == 'require':
757
            return CHECK_ALWAYS
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
758
        raise errors.BzrError("Invalid signatures policy '%s'"
759
                              % signature_string)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
760
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
761
    def _string_to_signing_policy(self, signature_string):
762
        """Convert a string to a signing policy."""
763
        if signature_string.lower() == 'when-required':
764
            return SIGN_WHEN_REQUIRED
765
        if signature_string.lower() == 'never':
766
            return SIGN_NEVER
767
        if signature_string.lower() == 'always':
768
            return SIGN_ALWAYS
769
        raise errors.BzrError("Invalid signing policy '%s'"
770
                              % signature_string)
771
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
772
    def _get_alias(self, value):
773
        try:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
774
            return self._get_parser().get_value("ALIASES",
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
775
                                                value)
776
        except KeyError:
777
            pass
778
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
779
    def _get_nickname(self):
780
        return self.get_user_option('nickname')
781
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
782
    def remove_user_option(self, option_name, section_name=None):
783
        """Remove a user option and save the configuration file.
784
785
        :param option_name: The option to be removed.
786
787
        :param section_name: The section the option is defined in, default to
788
            the default section.
789
        """
790
        self.reload()
791
        parser = self._get_parser()
792
        if section_name is None:
793
            section = parser
794
        else:
795
            section = parser[section_name]
796
        try:
797
            del section[option_name]
798
        except KeyError:
799
            raise errors.NoSuchConfigOption(option_name)
800
        self._write_config_file()
801
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
802
    def _write_config_file(self):
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
803
        if self.file_name is None:
804
            raise AssertionError('We cannot save, self.file_name is None')
5345.1.9 by Vincent Ladeuil
Refactor config dir check.
805
        conf_dir = os.path.dirname(self.file_name)
806
        ensure_config_dir_exists(conf_dir)
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
807
        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
808
        self._get_parser().write(atomic_file)
809
        atomic_file.commit()
810
        atomic_file.close()
5345.3.3 by Vincent Ladeuil
Merge bzr.dev into deprecate-get-filename resolving conflicts
811
        osutils.copy_ownership_from_path(self.file_name)
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
812
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
813
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
814
class LockableConfig(IniBasedConfig):
815
    """A configuration needing explicit locking for access.
816
817
    If several processes try to write the config file, the accesses need to be
818
    serialized.
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
819
820
    Daughter classes should decorate all methods that update a config with the
821
    ``@needs_write_lock`` decorator (they call, directly or indirectly, the
822
    ``_write_config_file()`` method. These methods (typically ``set_option()``
823
    and variants must reload the config file from disk before calling
824
    ``_write_config_file()``), this can be achieved by calling the
825
    ``self.reload()`` method. Note that the lock scope should cover both the
826
    reading and the writing of the config file which is why the decorator can't
827
    be applied to ``_write_config_file()`` only.
828
829
    This should be enough to implement the following logic:
830
    - lock for exclusive write access,
831
    - reload the config file from disk,
832
    - set the new value
833
    - unlock
834
835
    This logic guarantees that a writer can update a value without erasing an
836
    update made by another writer.
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
837
    """
838
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
839
    lock_name = 'lock'
840
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
841
    def __init__(self, file_name):
842
        super(LockableConfig, self).__init__(file_name=file_name)
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
843
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
5676.1.4 by Jelmer Vernooij
merge bzr.dev.
844
        # FIXME: It doesn't matter that we don't provide possible_transports
845
        # below since this is currently used only for local config files ;
846
        # local transports are not shared. But if/when we start using
847
        # LockableConfig for other kind of transports, we will need to reuse
848
        # whatever connection is already established -- vila 20100929
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
849
        self.transport = transport.get_transport(self.dir)
850
        self._lock = lockdir.LockDir(self.transport, 'lock')
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
851
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
852
    def _create_from_string(self, unicode_bytes, save):
853
        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.
854
        if save:
5345.1.24 by Vincent Ladeuil
Implement _save for LockableConfig too.
855
            # We need to handle the saving here (as opposed to IniBasedConfig)
856
            # to be able to lock
857
            self.lock_write()
858
            self._write_config_file()
859
            self.unlock()
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
860
861
    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.
862
        """Takes a write lock in the directory containing the config file.
863
864
        If the directory doesn't exist it is created.
865
        """
5345.5.5 by Vincent Ladeuil
Make bb.test_version.TestVersionUnicodeOutput.test_unicode_bzr_home pass.
866
        ensure_config_dir_exists(self.dir)
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
867
        return self._lock.lock_write(token)
868
869
    def unlock(self):
870
        self._lock.unlock()
871
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
872
    def break_lock(self):
873
        self._lock.break_lock()
874
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
875
    @needs_write_lock
876
    def remove_user_option(self, option_name, section_name=None):
877
        super(LockableConfig, self).remove_user_option(option_name,
878
                                                       section_name)
879
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
880
    def _write_config_file(self):
881
        if self._lock is None or not self._lock.is_held:
882
            # NB: if the following exception is raised it probably means a
883
            # missing @needs_write_lock decorator on one of the callers.
884
            raise errors.ObjectNotLocked(self)
885
        super(LockableConfig, self)._write_config_file()
886
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
887
888
class GlobalConfig(LockableConfig):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
889
    """The configuration that should be used for a specific location."""
890
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
891
    def __init__(self):
892
        super(GlobalConfig, self).__init__(file_name=config_filename())
5345.1.1 by Vincent Ladeuil
Deprecate the get_filename parameter in IniBasedConfig.
893
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
894
    def config_id(self):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
895
        return 'bazaar'
896
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
897
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
898
    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
899
        """Create a config object from a string.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
900
5345.5.13 by Vincent Ladeuil
Merge simplify-test-config-building into lockable-config-files resolving conflicts
901
        :param str_or_unicode: A string representing the file content. This
902
            will be utf-8 encoded.
5345.1.25 by Vincent Ladeuil
Move the '_save' parameter from '__init__' to 'from_bytes', fix fallouts.
903
904
        :param save: Whether the file should be saved upon creation.
905
        """
906
        conf = cls()
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
907
        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.
908
        return conf
5345.5.12 by Vincent Ladeuil
Fix fallouts from replacing '_content' by 'from_bytes' for config files.
909
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
910
    def get_editor(self):
1474 by Robert Collins
Merge from Aaron Bentley.
911
        return self._get_user_option('editor')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
912
5345.5.4 by Vincent Ladeuil
Start implementing config files locking.
913
    @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
914
    def set_user_option(self, option, value):
915
        """Save option and its value in the configuration."""
2900.3.2 by Tim Penhey
A working alias command.
916
        self._set_option(option, value, 'DEFAULT')
917
918
    def get_aliases(self):
919
        """Return the aliases section."""
920
        if 'ALIASES' in self._get_parser():
921
            return self._get_parser()['ALIASES']
922
        else:
923
            return {}
924
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
925
    @needs_write_lock
2900.3.2 by Tim Penhey
A working alias command.
926
    def set_alias(self, alias_name, alias_command):
927
        """Save the alias in the configuration."""
928
        self._set_option(alias_name, alias_command, 'ALIASES')
929
5345.5.8 by Vincent Ladeuil
More doc and ensure that the config is locked when _write_config_file is called.
930
    @needs_write_lock
2900.3.2 by Tim Penhey
A working alias command.
931
    def unset_alias(self, alias_name):
932
        """Unset an existing alias."""
5345.5.10 by Vincent Ladeuil
Add a missing config.reload().
933
        self.reload()
2900.3.2 by Tim Penhey
A working alias command.
934
        aliases = self._get_parser().get('ALIASES')
2900.3.7 by Tim Penhey
Updates from Aaron's review.
935
        if not aliases or alias_name not in aliases:
936
            raise errors.NoSuchAlias(alias_name)
2900.3.2 by Tim Penhey
A working alias command.
937
        del aliases[alias_name]
2900.3.12 by Tim Penhey
Final review comments.
938
        self._write_config_file()
2900.3.2 by Tim Penhey
A working alias command.
939
940
    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.
941
        self.reload()
2900.3.7 by Tim Penhey
Updates from Aaron's review.
942
        self._get_parser().setdefault(section, {})[option] = value
2900.3.12 by Tim Penhey
Final review comments.
943
        self._write_config_file()
2900.3.2 by Tim Penhey
A working alias command.
944
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
945
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.
946
    def _get_sections(self, name=None):
947
        """See IniBasedConfig._get_sections()."""
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
948
        parser = self._get_parser()
949
        # We don't give access to options defined outside of any section, we
950
        # used the DEFAULT section by... default.
951
        if name in (None, 'DEFAULT'):
952
            # This could happen for an empty file where the DEFAULT section
953
            # doesn't exist yet. So we force DEFAULT when yielding
954
            name = 'DEFAULT'
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
955
            if 'DEFAULT' not in parser:
956
               parser['DEFAULT']= {}
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
957
        yield (name, parser[name], self.config_id())
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
958
959
    @needs_write_lock
960
    def remove_user_option(self, option_name, section_name=None):
961
        if section_name is None:
962
            # We need to force the default section.
963
            section_name = 'DEFAULT'
964
        # We need to avoid the LockableConfig implementation or we'll lock
965
        # twice
966
        super(LockableConfig, self).remove_user_option(option_name,
967
                                                       section_name)
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
968
969
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
970
class LocationConfig(LockableConfig):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
971
    """A configuration object that gives the policy for a location."""
972
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
973
    def __init__(self, location):
5345.1.2 by Vincent Ladeuil
Get rid of 'branches.conf' references.
974
        super(LocationConfig, self).__init__(
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
975
            file_name=locations_config_filename())
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
976
        # local file locations are looked up by local path, rather than
977
        # by file url. This is because the config file is a user
978
        # file, and we would rather not expose the user to file urls.
979
        if location.startswith('file://'):
980
            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
981
        self.location = location
982
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
983
    def config_id(self):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
984
        return 'locations'
985
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
986
    @classmethod
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
987
    def from_string(cls, str_or_unicode, location, save=False):
988
        """Create a config object from a string.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
989
5345.2.9 by Vincent Ladeuil
Rename IniBaseConfig.from_bytes to from_string.
990
        :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.
991
            be utf-8 encoded.
992
993
        :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.
994
995
        :param save: Whether the file should be saved upon creation.
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
996
        """
997
        conf = cls(location)
5345.1.26 by Vincent Ladeuil
Merge lockable-config-files into remove-gratuitous-ensure-config-dir-exist-calls resolving conflicts
998
        conf._create_from_string(str_or_unicode, save)
5345.2.8 by Vincent Ladeuil
Introduce a 'from_bytes' constructor for config objects.
999
        return conf
1000
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1001
    def _get_matching_sections(self):
1002
        """Return an ordered list of section names matching this location."""
1185.12.49 by Aaron Bentley
Switched to ConfigObj
1003
        sections = self._get_parser()
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
1004
        location_names = self.location.split('/')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
1005
        if self.location.endswith('/'):
1006
            del location_names[-1]
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
1007
        matches=[]
1442.1.10 by Robert Collins
explicit over glob test passes
1008
        for section in sections:
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
1009
            # location is a local path if possible, so we need
1010
            # to convert 'file://' urls to local paths if necessary.
1011
            # This also avoids having file:///path be a more exact
1012
            # match than '/path'.
1013
            if section.startswith('file://'):
1014
                section_path = urlutils.local_path_from_url(section)
1015
            else:
1016
                section_path = section
1017
            section_names = section_path.split('/')
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
1018
            if section.endswith('/'):
1019
                del section_names[-1]
1020
            names = zip(location_names, section_names)
1021
            matched = True
1022
            for name in names:
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1023
                if not fnmatch.fnmatch(name[0], name[1]):
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
1024
                    matched = False
1025
                    break
1026
            if not matched:
1027
                continue
1028
            # so, for the common prefix they matched.
1029
            # if section is longer, no match.
1030
            if len(section_names) > len(location_names):
1031
                continue
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1032
            matches.append((len(section_names), section,
1033
                            '/'.join(location_names[len(section_names):])))
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1034
        # put the longest (aka more specific) locations first
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
1035
        matches.sort(reverse=True)
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1036
        sections = []
1037
        for (length, section, extra_path) in matches:
1038
            sections.append((section, extra_path))
1039
            # should we stop looking for parent configs here?
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1040
            try:
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1041
                if self._get_parser()[section].as_bool('ignore_parents'):
1042
                    break
1993.3.1 by James Henstridge
first go at making location config lookup recursive
1043
            except KeyError:
1044
                pass
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
1045
        return sections
1442.1.9 by Robert Collins
exact section test passes
1046
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.
1047
    def _get_sections(self, name=None):
1048
        """See IniBasedConfig._get_sections()."""
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1049
        # We ignore the name here as the only sections handled are named with
1050
        # the location path and we don't expose embedded sections either.
1051
        parser = self._get_parser()
1052
        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.
1053
            yield (name, parser[name], self.config_id())
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1054
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1055
    def _get_option_policy(self, section, option_name):
1056
        """Return the policy for the given (section, option_name) pair."""
1057
        # check for the old 'recurse=False' flag
1058
        try:
1059
            recurse = self._get_parser()[section].as_bool('recurse')
1060
        except KeyError:
1061
            recurse = True
1062
        if not recurse:
1063
            return POLICY_NORECURSE
1064
2120.6.10 by James Henstridge
Catch another deprecation warning, and more cleanup
1065
        policy_key = option_name + ':policy'
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1066
        try:
1067
            policy_name = self._get_parser()[section][policy_key]
1068
        except KeyError:
1069
            policy_name = None
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1070
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1071
        return _policy_value[policy_name]
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
1072
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1073
    def _set_option_policy(self, section, option_name, option_policy):
1074
        """Set the policy for the given option name in the given section."""
1075
        # The old recurse=False option affects all options in the
1076
        # section.  To handle multiple policies in the section, we
1077
        # need to convert it to a policy_norecurse key.
1078
        try:
1079
            recurse = self._get_parser()[section].as_bool('recurse')
1080
        except KeyError:
1081
            pass
1082
        else:
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1083
            symbol_versioning.warn(
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
1084
                'The recurse option is deprecated as of 0.14.  '
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1085
                'The section "%s" has been converted to use policies.'
1086
                % section,
1087
                DeprecationWarning)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1088
            del self._get_parser()[section]['recurse']
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1089
            if not recurse:
1090
                for key in self._get_parser()[section].keys():
1091
                    if not key.endswith(':policy'):
1092
                        self._get_parser()[section][key +
1093
                                                    ':policy'] = 'norecurse'
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1094
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
1095
        policy_key = option_name + ':policy'
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
1096
        policy_name = _policy_name[option_policy]
1097
        if policy_name is not None:
1098
            self._get_parser()[section][policy_key] = policy_name
1099
        else:
1100
            if policy_key in self._get_parser()[section]:
1101
                del self._get_parser()[section][policy_key]
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1102
5345.5.7 by Vincent Ladeuil
Make LocationConfig use a lock too.
1103
    @needs_write_lock
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1104
    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.
1105
        """Save option and its value in the configuration."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1106
        if store not in [STORE_LOCATION,
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1107
                         STORE_LOCATION_NORECURSE,
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1108
                         STORE_LOCATION_APPENDPATH]:
1109
            raise ValueError('bad storage policy %r for %r' %
1110
                (store, option))
5345.5.1 by Vincent Ladeuil
Implement config.reload and make sure we have a file name when using it.
1111
        self.reload()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1112
        location = self.location
1113
        if location.endswith('/'):
1114
            location = location[:-1]
5345.1.24 by Vincent Ladeuil
Implement _save for LockableConfig too.
1115
        parser = self._get_parser()
5345.1.21 by Vincent Ladeuil
Slight rewrite to make the method more readable.
1116
        if not location in parser and not location + '/' in parser:
1117
            parser[location] = {}
1118
        elif location + '/' in parser:
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1119
            location = location + '/'
5345.1.21 by Vincent Ladeuil
Slight rewrite to make the method more readable.
1120
        parser[location][option]=value
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1121
        # the allowed values of store match the config policies
1122
        self._set_option_policy(location, option, store)
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
1123
        self._write_config_file()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1124
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1125
1126
class BranchConfig(Config):
1127
    """A configuration object giving the policy for a branch."""
1128
5345.1.3 by Vincent Ladeuil
Make __init__ the first method in the BranchConfig class.
1129
    def __init__(self, branch):
1130
        super(BranchConfig, self).__init__()
1131
        self._location_config = None
1132
        self._branch_data_config = None
1133
        self._global_config = None
1134
        self.branch = branch
1135
        self.option_sources = (self._get_location_config,
1136
                               self._get_branch_data_config,
1137
                               self._get_global_config)
1138
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1139
    def config_id(self):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1140
        return 'branch'
1141
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1142
    def _get_branch_data_config(self):
1143
        if self._branch_data_config is None:
1144
            self._branch_data_config = TreeConfig(self.branch)
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
1145
            self._branch_data_config.config_id = self.config_id
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1146
        return self._branch_data_config
1147
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1148
    def _get_location_config(self):
1149
        if self._location_config is None:
1150
            self._location_config = LocationConfig(self.branch.base)
1151
        return self._location_config
1152
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1153
    def _get_global_config(self):
1154
        if self._global_config is None:
1155
            self._global_config = GlobalConfig()
1156
        return self._global_config
1157
1158
    def _get_best_value(self, option_name):
1159
        """This returns a user option from local, tree or global config.
1160
1161
        They are tried in that order.  Use get_safe_value if trusted values
1162
        are necessary.
1163
        """
1164
        for source in self.option_sources:
1165
            value = getattr(source(), option_name)()
1166
            if value is not None:
1167
                return value
1168
        return None
1169
1170
    def _get_safe_value(self, option_name):
1171
        """This variant of get_best_value never returns untrusted values.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1172
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1173
        It does not return values from the branch data, because the branch may
1174
        not be controlled by the user.
1175
1176
        We may wish to allow locations.conf to control whether branches are
1177
        trusted in the future.
1178
        """
1179
        for source in (self._get_location_config, self._get_global_config):
1180
            value = getattr(source(), option_name)()
1181
            if value is not None:
1182
                return value
1183
        return None
1184
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1185
    def _get_user_id(self):
1186
        """Return the full user id for the branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1187
3407.2.14 by Martin Pool
Remove more cases of getting transport via control_files
1188
        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
1189
        This is looked up in the email controlfile for the branch.
1190
        """
1191
        try:
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
1192
            return (self.branch._transport.get_bytes("email")
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
1193
                    .decode(osutils.get_user_encoding())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1194
                    .rstrip("\r\n"))
1195
        except errors.NoSuchFile, e:
1196
            pass
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1197
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1198
        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
1199
4603.1.10 by Aaron Bentley
Provide change editor via config.
1200
    def _get_change_editor(self):
1201
        return self._get_best_value('_get_change_editor')
1202
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1203
    def _get_signature_checking(self):
1204
        """See Config._get_signature_checking."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1205
        return self._get_best_value('_get_signature_checking')
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
1206
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
1207
    def _get_signing_policy(self):
1208
        """See Config._get_signing_policy."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1209
        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
1210
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
1211
    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.
1212
        """See Config._get_user_option."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1213
        for source in self.option_sources:
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
1214
            value = source()._get_user_option(option_name)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1215
            if value is not None:
1216
                return value
1217
        return None
1218
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.
1219
    def _get_sections(self, name=None):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1220
        """See IniBasedConfig.get_sections()."""
1221
        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.
1222
            for section in source()._get_sections(name):
5447.4.4 by Vincent Ladeuil
Implement config.get_sections() to clarify how sections can be used.
1223
                yield section
1224
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.
1225
    def _get_options(self, sections=None):
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1226
        opts = []
1227
        # 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.
1228
        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.
1229
            yield option
1230
        # Then the branch options
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1231
        branch_config = self._get_branch_data_config()
1232
        if sections is None:
1233
            sections = [('DEFAULT', branch_config._get_parser())]
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1234
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
1235
        # 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.
1236
        config_id = self.config_id()
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1237
        for (section_name, section) in sections:
1238
            for (name, value) in section.iteritems():
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
1239
                yield (name, value, section_name,
1240
                       config_id, branch_config._get_parser())
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
1241
        # 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.
1242
        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.
1243
            yield option
5447.4.1 by Vincent Ladeuil
Implement config.get_options_matching_regexp.
1244
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1245
    def set_user_option(self, name, value, store=STORE_BRANCH,
1246
        warn_masked=False):
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1247
        if store == STORE_BRANCH:
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
1248
            self._get_branch_data_config().set_option(value, name)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1249
        elif store == STORE_GLOBAL:
2120.6.7 by James Henstridge
Fix GlobalConfig.set_user_option() call
1250
            self._get_global_config().set_user_option(name, value)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
1251
        else:
1252
            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)
1253
        if not warn_masked:
1254
            return
1255
        if store in (STORE_GLOBAL, STORE_BRANCH):
1256
            mask_value = self._get_location_config().get_user_option(name)
1257
            if mask_value is not None:
1258
                trace.warning('Value "%s" is masked by "%s" from'
1259
                              ' locations.conf', value, mask_value)
1260
            else:
1261
                if store == STORE_GLOBAL:
1262
                    branch_config = self._get_branch_data_config()
1263
                    mask_value = branch_config.get_user_option(name)
1264
                    if mask_value is not None:
1265
                        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
1266
                                      ' branch.conf', value, mask_value)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
1267
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1268
    def remove_user_option(self, option_name, section_name=None):
1269
        self._get_branch_data_config().remove_option(option_name, section_name)
1270
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
1271
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
1272
        """See Config.gpg_signing_command."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1273
        return self._get_safe_value('_gpg_signing_command')
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1274
1472 by Robert Collins
post commit hook, first pass implementation
1275
    def _post_commit(self):
1276
        """See Config.post_commit."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1277
        return self._get_safe_value('_post_commit')
1472 by Robert Collins
post commit hook, first pass implementation
1278
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1279
    def _get_nickname(self):
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
1280
        value = self._get_explicit_nickname()
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1281
        if value is not None:
1282
            return value
2120.5.2 by Alexander Belchenko
(jam) Fix for bug #66857
1283
        return urlutils.unescape(self.branch.base.split('/')[-2])
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
1284
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
1285
    def has_explicit_nickname(self):
1286
        """Return true if a nickname has been explicitly assigned."""
1287
        return self._get_explicit_nickname() is not None
1288
1289
    def _get_explicit_nickname(self):
1290
        return self._get_best_value('_get_nickname')
1291
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
1292
    def _log_format(self):
1293
        """See Config.log_format."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1294
        return self._get_best_value('_log_format')
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1295
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
1296
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
1297
def ensure_config_dir_exists(path=None):
5519.4.4 by Neil Martinsen-Burrell
restore ensure_config_dir since XDG_CONFIG_HOME is optional
1298
    """Make sure a configuration directory exists.
1299
    This makes sure that the directory exists.
1300
    On windows, since configuration directories are 2 levels deep,
1301
    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
1302
    """
1303
    if path is None:
1304
        path = config_dir()
1305
    if not os.path.isdir(path):
5519.4.4 by Neil Martinsen-Burrell
restore ensure_config_dir since XDG_CONFIG_HOME is optional
1306
        if sys.platform == 'win32':
1307
            parent_dir = os.path.dirname(path)
1308
            if not os.path.isdir(parent_dir):
1309
                trace.mutter('creating config parent directory: %r', parent_dir)
1310
                os.mkdir(parent_dir)
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1311
        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
1312
        os.mkdir(path)
5116.2.6 by Parth Malwankar
renamed copy_ownership to copy_ownership_from_path.
1313
        osutils.copy_ownership_from_path(path)
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
1314
1532 by Robert Collins
Merge in John Meinels integration branch.
1315
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1316
def config_dir():
1317
    """Return per-user configuration directory.
1318
5519.4.1 by Neil Martinsen-Burrell
spec and first implementation, next tests
1319
    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
1320
    and Linux.  On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
1321
    that will be used instead.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1322
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1323
    TODO: Global option --config-dir to override this.
1324
    """
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1325
    base = os.environ.get('BZR_HOME', None)
1326
    if sys.platform == 'win32':
5598.2.2 by John Arbash Meinel
Change the comment slightly
1327
        # environ variables on Windows are in user encoding/mbcs. So decode
1328
        # 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.
1329
        if base is not None:
1330
            base = base.decode('mbcs')
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1331
        if base is None:
2245.4.3 by Alexander Belchenko
config.py: changing _auto_user_id() and config_dir() to use functions from win32utils
1332
            base = win32utils.get_appdata_location_unicode()
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1333
        if base is None:
1334
            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.
1335
            if base is not None:
1336
                base = base.decode('mbcs')
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1337
        if base is None:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
1338
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1339
                                  ' or HOME set')
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
1340
        return osutils.pathjoin(base, 'bazaar', '2.0')
5519.4.1 by Neil Martinsen-Burrell
spec and first implementation, next tests
1341
    elif sys.platform == 'darwin':
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1342
        if base is None:
5519.4.1 by Neil Martinsen-Burrell
spec and first implementation, next tests
1343
            # this takes into account $HOME
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
1344
            base = os.path.expanduser("~")
5519.4.1 by Neil Martinsen-Burrell
spec and first implementation, next tests
1345
        return osutils.pathjoin(base, '.bazaar')
1346
    else:
1347
        if base is None:
5519.4.3 by Neil Martinsen-Burrell
be permissive about using $XDG_CONFIG_HOME/bazaar, but dont complain
1348
1349
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
1350
            if xdg_dir is None:
1351
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
1352
            xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
1353
            if osutils.isdir(xdg_dir):
1354
                trace.mutter(
1355
                    "Using configuration in XDG directory %s." % xdg_dir)
1356
                return xdg_dir
1357
1358
            base = os.path.expanduser("~")
5519.4.4 by Neil Martinsen-Burrell
restore ensure_config_dir since XDG_CONFIG_HOME is optional
1359
        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 \
1360
1361
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1362
def config_filename():
1363
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
1364
    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.
1365
1366
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1367
def locations_config_filename():
1368
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
1369
    return osutils.pathjoin(config_dir(), 'locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
1370
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
1371
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1372
def authentication_config_filename():
1373
    """Return per-user authentication ini file filename."""
1374
    return osutils.pathjoin(config_dir(), 'authentication.conf')
1375
1376
1836.1.6 by John Arbash Meinel
Creating a helper function for getting the user ignore filename
1377
def user_ignore_config_filename():
1378
    """Return the user default ignore filename"""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
1379
    return osutils.pathjoin(config_dir(), 'ignore')
1836.1.6 by John Arbash Meinel
Creating a helper function for getting the user ignore filename
1380
1381
4584.3.4 by Martin Pool
Add crash_dir and xdg_cache_dir functions
1382
def crash_dir():
1383
    """Return the directory name to store crash files.
1384
1385
    This doesn't implicitly create it.
1386
4634.128.2 by Martin Pool
Write crash files into /var/crash where apport can see them.
1387
    On Windows it's in the config directory; elsewhere it's /var/crash
4634.128.18 by Martin Pool
Update apport crash tests
1388
    which may be monitored by apport.  It can be overridden by
1389
    $APPORT_CRASH_DIR.
4584.3.4 by Martin Pool
Add crash_dir and xdg_cache_dir functions
1390
    """
1391
    if sys.platform == 'win32':
1392
        return osutils.pathjoin(config_dir(), 'Crash')
1393
    else:
4634.128.2 by Martin Pool
Write crash files into /var/crash where apport can see them.
1394
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
1395
        # 2010-01-31
4634.128.18 by Martin Pool
Update apport crash tests
1396
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
4584.3.4 by Martin Pool
Add crash_dir and xdg_cache_dir functions
1397
1398
1399
def xdg_cache_dir():
4584.3.23 by Martin Pool
Correction to xdg_cache_dir and add a simple test
1400
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
1401
    # Possibly this should be different on Windows?
1402
    e = os.environ.get('XDG_CACHE_DIR', None)
1403
    if e:
1404
        return e
1405
    else:
1406
        return os.path.expanduser('~/.cache')
4584.3.4 by Martin Pool
Add crash_dir and xdg_cache_dir functions
1407
1408
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1409
def parse_username(username):
1410
    """Parse e-mail username and return a (name, address) tuple."""
1411
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1412
    if match is None:
1413
        return (username, '')
1414
    else:
1415
        return (match.group(1), match.group(2))
1416
1417
1185.16.52 by Martin Pool
- add extract_email_address
1418
def extract_email_address(e):
1419
    """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.
1420
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1421
    That is just the user@domain part, nothing else.
1185.16.52 by Martin Pool
- add extract_email_address
1422
    This part is required to contain only ascii characters.
1423
    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.
1424
1185.16.52 by Martin Pool
- add extract_email_address
1425
    >>> extract_email_address('Jane Tester <jane@test.com>')
1426
    "jane@test.com"
1427
    """
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1428
    name, email = parse_username(e)
1429
    if not email:
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
1430
        raise errors.NoEmailInUsername(e)
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
1431
    return email
1185.35.11 by Aaron Bentley
Added support for branch nicks
1432
1185.85.30 by John Arbash Meinel
Fixing 'bzr push' exposed that IniBasedConfig didn't handle unicode.
1433
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1434
class TreeConfig(IniBasedConfig):
1185.35.11 by Aaron Bentley
Added support for branch nicks
1435
    """Branch configuration data associated with its contents, not location"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1436
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
1437
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
1438
1185.35.11 by Aaron Bentley
Added support for branch nicks
1439
    def __init__(self, branch):
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
1440
        self._config = branch._get_config()
1185.35.11 by Aaron Bentley
Added support for branch nicks
1441
        self.branch = branch
1442
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
1443
    def _get_parser(self, file=None):
1444
        if file is not None:
1445
            return IniBasedConfig._get_parser(file)
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1446
        return self._config._get_configobj()
1185.35.11 by Aaron Bentley
Added support for branch nicks
1447
1448
    def get_option(self, name, section=None, default=None):
1449
        self.branch.lock_read()
1450
        try:
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1451
            return self._config.get_option(name, section, default)
1185.35.11 by Aaron Bentley
Added support for branch nicks
1452
        finally:
1453
            self.branch.unlock()
1454
1455
    def set_option(self, value, name, section=None):
1456
        """Set a per-branch configuration option"""
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1457
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
1458
        # higher levels providing the right lock -- vila 20101004
1185.35.11 by Aaron Bentley
Added support for branch nicks
1459
        self.branch.lock_write()
1460
        try:
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
1461
            self._config.set_option(value, name, section)
1185.35.11 by Aaron Bentley
Added support for branch nicks
1462
        finally:
1463
            self.branch.unlock()
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1464
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1465
    def remove_option(self, option_name, section_name=None):
1466
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
1467
        # higher levels providing the right lock -- vila 20101004
1468
        self.branch.lock_write()
1469
        try:
1470
            self._config.remove_option(option_name, section_name)
1471
        finally:
1472
            self.branch.unlock()
1473
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1474
1475
class AuthenticationConfig(object):
1476
    """The authentication configuration file based on a ini file.
1477
1478
    Implements the authentication.conf file described in
1479
    doc/developers/authentication-ring.txt.
1480
    """
1481
1482
    def __init__(self, _file=None):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1483
        self._config = None # The ConfigObj
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1484
        if _file is None:
2900.2.24 by Vincent Ladeuil
Review feedback.
1485
            self._filename = authentication_config_filename()
1486
            self._input = self._filename = authentication_config_filename()
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1487
        else:
2900.2.24 by Vincent Ladeuil
Review feedback.
1488
            # Tests can provide a string as _file
1489
            self._filename = None
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1490
            self._input = _file
1491
1492
    def _get_config(self):
1493
        if self._config is not None:
1494
            return self._config
1495
        try:
2900.2.22 by Vincent Ladeuil
Polishing.
1496
            # FIXME: Should we validate something here ? Includes: empty
1497
            # sections are useless, at least one of
1498
            # user/password/password_encoding should be defined, etc.
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1499
1500
            # Note: the encoding below declares that the file itself is utf-8
1501
            # encoded, but the values in the ConfigObj are always Unicode.
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1502
            self._config = ConfigObj(self._input, encoding='utf-8')
1503
        except configobj.ConfigObjError, e:
1504
            raise errors.ParseConfigError(e.errors, e.config.filename)
1505
        return self._config
1506
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1507
    def _save(self):
1508
        """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.
1509
        conf_dir = os.path.dirname(self._filename)
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1510
        ensure_config_dir_exists(conf_dir)
4708.2.2 by Martin
Workingtree changes sitting around since November, more explict closing of files in bzrlib
1511
        f = file(self._filename, 'wb')
1512
        try:
1513
            self._get_config().write(f)
1514
        finally:
1515
            f.close()
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1516
1517
    def _set_option(self, section_name, option_name, value):
1518
        """Set an authentication configuration option"""
1519
        conf = self._get_config()
1520
        section = conf.get(section_name)
1521
        if section is None:
1522
            conf[section] = {}
1523
            section = conf[section]
1524
        section[option_name] = value
1525
        self._save()
1526
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1527
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
1528
                        realm=None):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1529
        """Returns the matching credentials from authentication.conf file.
1530
1531
        :param scheme: protocol
1532
1533
        :param host: the server address
1534
1535
        :param port: the associated port (optional)
1536
1537
        :param user: login (optional)
1538
1539
        :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
1540
        
1541
        :param realm: the http authentication realm (optional)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1542
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1543
        :return: A dict containing the matching credentials or None.
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1544
           This includes:
1545
           - name: the section name of the credentials in the
1546
             authentication.conf file,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1547
           - 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.
1548
           - scheme: the server protocol,
1549
           - host: the server address,
1550
           - port: the server port (can be None),
1551
           - path: the absolute server path (can be None),
1552
           - realm: the http specific authentication realm (can be None),
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1553
           - password: the decoded password, could be None if the credential
1554
             defines only the user
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1555
           - verify_certificates: https specific, True if the server
1556
             certificate should be verified, False otherwise.
1557
        """
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1558
        credentials = None
1559
        for auth_def_name, auth_def in self._get_config().items():
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1560
            if type(auth_def) is not configobj.Section:
1561
                raise ValueError("%s defined outside a section" % auth_def_name)
1562
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1563
            a_scheme, a_host, a_user, a_path = map(
1564
                auth_def.get, ['scheme', 'host', 'user', 'path'])
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1565
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1566
            try:
1567
                a_port = auth_def.as_int('port')
1568
            except KeyError:
1569
                a_port = None
2900.2.22 by Vincent Ladeuil
Polishing.
1570
            except ValueError:
1571
                raise ValueError("'port' not numeric in %s" % auth_def_name)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1572
            try:
1573
                a_verify_certificates = auth_def.as_bool('verify_certificates')
1574
            except KeyError:
1575
                a_verify_certificates = True
2900.2.22 by Vincent Ladeuil
Polishing.
1576
            except ValueError:
1577
                raise ValueError(
1578
                    "'verify_certificates' not boolean in %s" % auth_def_name)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1579
1580
            # Attempt matching
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1581
            if a_scheme is not None and scheme != a_scheme:
1582
                continue
1583
            if a_host is not None:
1584
                if not (host == a_host
1585
                        or (a_host.startswith('.') and host.endswith(a_host))):
1586
                    continue
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1587
            if a_port is not None and port != a_port:
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1588
                continue
1589
            if (a_path is not None and path is not None
1590
                and not path.startswith(a_path)):
1591
                continue
1592
            if (a_user is not None and user is not None
1593
                and a_user != user):
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1594
                # Never contradict the caller about the user to be used
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1595
                continue
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1596
            if a_user is None:
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1597
                # Can't find a user
1598
                continue
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1599
            # Prepare a credentials dictionary with additional keys
1600
            # for the credential providers
2900.2.24 by Vincent Ladeuil
Review feedback.
1601
            credentials = dict(name=auth_def_name,
3418.4.2 by Vincent Ladeuil
Fix bug #199440 by taking into account that a section may not
1602
                               user=a_user,
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1603
                               scheme=a_scheme,
1604
                               host=host,
1605
                               port=port,
1606
                               path=path,
1607
                               realm=realm,
3418.4.2 by Vincent Ladeuil
Fix bug #199440 by taking into account that a section may not
1608
                               password=auth_def.get('password', None),
2900.2.24 by Vincent Ladeuil
Review feedback.
1609
                               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
1610
            # Decode the password in the credentials (or get one)
2900.2.22 by Vincent Ladeuil
Polishing.
1611
            self.decode_password(credentials,
1612
                                 auth_def.get('password_encoding', None))
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1613
            if 'auth' in debug.debug_flags:
1614
                trace.mutter("Using authentication section: %r", auth_def_name)
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1615
            break
1616
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1617
        if credentials is None:
1618
            # No credentials were found in authentication.conf, try the fallback
1619
            # credentials stores.
1620
            credentials = credential_store_registry.get_fallback_credentials(
1621
                scheme, host, port, user, path, realm)
1622
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1623
        return credentials
1624
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1625
    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
1626
                        port=None, path=None, verify_certificates=None,
1627
                        realm=None):
3777.3.1 by Aaron Bentley
Update docs
1628
        """Set authentication credentials for a host.
1629
1630
        Any existing credentials with matching scheme, host, port and path
1631
        will be deleted, regardless of name.
1632
1633
        :param name: An arbitrary name to describe this set of credentials.
1634
        :param host: Name of the host that accepts these credentials.
1635
        :param user: The username portion of these credentials.
1636
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1637
            to.
3777.3.2 by Aaron Bentley
Reverse order of scheme and password
1638
        :param password: Password portion of these credentials.
3777.3.1 by Aaron Bentley
Update docs
1639
        :param port: The IP port on the host that these credentials apply to.
1640
        :param path: A filesystem path on the host that these credentials
1641
            apply to.
1642
        :param verify_certificates: On https, verify server certificates if
1643
            True.
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1644
        :param realm: The http authentication realm (optional).
3777.3.1 by Aaron Bentley
Update docs
1645
        """
3777.1.8 by Aaron Bentley
Commit work-in-progress
1646
        values = {'host': host, 'user': user}
1647
        if password is not None:
1648
            values['password'] = password
1649
        if scheme is not None:
1650
            values['scheme'] = scheme
1651
        if port is not None:
1652
            values['port'] = '%d' % port
1653
        if path is not None:
1654
            values['path'] = path
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1655
        if verify_certificates is not None:
1656
            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
1657
        if realm is not None:
1658
            values['realm'] = realm
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1659
        config = self._get_config()
1660
        for_deletion = []
1661
        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
1662
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
3777.1.11 by Aaron Bentley
Ensure changed-name updates clear old values
1663
                if existing_values.get(key) != values.get(key):
1664
                    break
1665
            else:
1666
                del config[section]
1667
        config.update({name: values})
3777.1.10 by Aaron Bentley
Ensure credentials are stored
1668
        self._save()
3777.1.8 by Aaron Bentley
Commit work-in-progress
1669
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1670
    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.
1671
                 prompt=None, ask=False, default=None):
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1672
        """Get a user from authentication file.
1673
1674
        :param scheme: protocol
1675
1676
        :param host: the server address
1677
1678
        :param port: the associated port (optional)
1679
1680
        :param realm: the realm sent by the server (optional)
1681
1682
        :param path: the absolute path on the server (optional)
1683
4222.3.4 by Jelmer Vernooij
Default to getpass.getuser() in AuthenticationConfig.get_user(), but allow
1684
        :param ask: Ask the user if there is no explicitly configured username 
1685
                    (optional)
1686
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1687
        :param default: The username returned if none is defined (optional).
1688
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1689
        :return: The found user.
1690
        """
2900.2.16 by Vincent Ladeuil
Make hhtp proxy aware of AuthenticationConfig (for password).
1691
        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
1692
                                           path=path, realm=realm)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1693
        if credentials is not None:
1694
            user = credentials['user']
1695
        else:
1696
            user = None
4222.3.2 by Jelmer Vernooij
Prompt for user names if they are not in the configuration.
1697
        if user is None:
4222.3.4 by Jelmer Vernooij
Default to getpass.getuser() in AuthenticationConfig.get_user(), but allow
1698
            if ask:
1699
                if prompt is None:
1700
                    # Create a default prompt suitable for most cases
1701
                    prompt = scheme.upper() + ' %(host)s username'
1702
                # Special handling for optional fields in the prompt
1703
                if port is not None:
1704
                    prompt_host = '%s:%d' % (host, port)
1705
                else:
1706
                    prompt_host = host
1707
                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.
1708
            else:
4222.3.10 by Jelmer Vernooij
Avoid using the default username in the case of SMTP.
1709
                user = default
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1710
        return user
1711
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1712
    def get_password(self, scheme, host, user, port=None,
1713
                     realm=None, path=None, prompt=None):
1714
        """Get a password from authentication file or prompt the user for one.
1715
1716
        :param scheme: protocol
1717
1718
        :param host: the server address
1719
1720
        :param port: the associated port (optional)
1721
1722
        :param user: login
1723
1724
        :param realm: the realm sent by the server (optional)
1725
1726
        :param path: the absolute path on the server (optional)
1727
1728
        :return: The found password or the one entered by the user.
1729
        """
4081.1.1 by Jean-Francois Roy
A 'realm' optional argument was added to the get_credentials and set_credentials
1730
        credentials = self.get_credentials(scheme, host, port, user, path,
1731
                                           realm)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1732
        if credentials is not None:
1733
            password = credentials['password']
3420.1.3 by Vincent Ladeuil
John's review feedback.
1734
            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.
1735
                trace.warning('password ignored in section [%s],'
1736
                              ' use an ssh agent instead'
1737
                              % credentials['name'])
1738
                password = None
2900.2.16 by Vincent Ladeuil
Make hhtp proxy aware of AuthenticationConfig (for password).
1739
        else:
1740
            password = None
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1741
        # 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).
1742
        if password is None:
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1743
            if prompt is None:
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1744
                # Create a default prompt suitable for most cases
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1745
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1746
            # Special handling for optional fields in the prompt
1747
            if port is not None:
1748
                prompt_host = '%s:%d' % (host, port)
1749
            else:
1750
                prompt_host = host
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1751
            password = ui.ui_factory.get_password(prompt,
1752
                                                  host=prompt_host, user=user)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1753
        return password
1754
2900.2.22 by Vincent Ladeuil
Polishing.
1755
    def decode_password(self, credentials, encoding):
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1756
        try:
1757
            cs = credential_store_registry.get_credential_store(encoding)
1758
        except KeyError:
1759
            raise ValueError('%r is not a known password_encoding' % encoding)
1760
        credentials['password'] = cs.decode_password(credentials)
2900.2.22 by Vincent Ladeuil
Polishing.
1761
        return credentials
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1762
3242.3.17 by Aaron Bentley
Whitespace cleanup
1763
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1764
class CredentialStoreRegistry(registry.Registry):
1765
    """A class that registers credential stores.
1766
1767
    A credential store provides access to credentials via the password_encoding
1768
    field in authentication.conf sections.
1769
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1770
    Except for stores provided by bzr itself, most stores are expected to be
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1771
    provided by plugins that will therefore use
1772
    register_lazy(password_encoding, module_name, member_name, help=help,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1773
    fallback=fallback) to install themselves.
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1774
1775
    A fallback credential store is one that is queried if no credentials can be
1776
    found via authentication.conf.
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1777
    """
1778
1779
    def get_credential_store(self, encoding=None):
1780
        cs = self.get(encoding)
1781
        if callable(cs):
1782
            cs = cs()
1783
        return cs
1784
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1785
    def is_fallback(self, name):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1786
        """Check if the named credentials store should be used as fallback."""
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1787
        return self.get_info(name)
1788
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1789
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1790
                                 path=None, realm=None):
1791
        """Request credentials from all fallback credentials stores.
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1792
1793
        The first credentials store that can provide credentials wins.
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1794
        """
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1795
        credentials = None
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1796
        for name in self.keys():
4283.1.2 by Jelmer Vernooij
Add tests, NEWS item.
1797
            if not self.is_fallback(name):
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1798
                continue
1799
            cs = self.get_credential_store(name)
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1800
            credentials = cs.get_credentials(scheme, host, port, user,
1801
                                             path, realm)
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1802
            if credentials is not None:
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1803
                # We found some credentials
1804
                break
1805
        return credentials
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1806
1807
    def register(self, key, obj, help=None, override_existing=False,
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1808
                 fallback=False):
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1809
        """Register a new object to a name.
1810
1811
        :param key: This is the key to use to request the object later.
1812
        :param obj: The object to register.
1813
        :param help: Help text for this entry. This may be a string or
1814
                a callable. If it is a callable, it should take two
1815
                parameters (registry, key): this registry and the key that
1816
                the help was registered under.
1817
        :param override_existing: Raise KeyErorr if False and something has
1818
                already been registered for that key. If True, ignore if there
1819
                is an existing key (always register the new value).
1820
        :param fallback: Whether this credential store should be 
1821
                used as fallback.
1822
        """
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1823
        return super(CredentialStoreRegistry,
1824
                     self).register(key, obj, help, info=fallback,
1825
                                    override_existing=override_existing)
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1826
1827
    def register_lazy(self, key, module_name, member_name,
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1828
                      help=None, override_existing=False,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1829
                      fallback=False):
1830
        """Register a new credential store to be loaded on request.
1831
1832
        :param module_name: The python path to the module. Such as 'os.path'.
1833
        :param member_name: The member of the module to return.  If empty or
1834
                None, get() will return the module itself.
1835
        :param help: Help text for this entry. This may be a string or
1836
                a callable.
1837
        :param override_existing: If True, replace the existing object
1838
                with the new one. If False, if there is already something
1839
                registered with the same key, raise a KeyError
1840
        :param fallback: Whether this credential store should be 
1841
                used as fallback.
1842
        """
1843
        return super(CredentialStoreRegistry, self).register_lazy(
1844
            key, module_name, member_name, help,
1845
            info=fallback, override_existing=override_existing)
1846
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1847
1848
credential_store_registry = CredentialStoreRegistry()
1849
1850
1851
class CredentialStore(object):
1852
    """An abstract class to implement storage for credentials"""
1853
1854
    def decode_password(self, credentials):
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1855
        """Returns a clear text password for the provided credentials."""
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1856
        raise NotImplementedError(self.decode_password)
1857
4283.2.1 by Vincent Ladeuil
Add a test and cleanup some PEP8 issues.
1858
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
4283.1.1 by Jelmer Vernooij
Support fallback credential stores.
1859
                        realm=None):
1860
        """Return the matching credentials from this credential store.
1861
1862
        This method is only called on fallback credential stores.
1863
        """
1864
        raise NotImplementedError(self.get_credentials)
1865
1866
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1867
1868
class PlainTextCredentialStore(CredentialStore):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1869
    __doc__ = """Plain text credential store for the authentication.conf file"""
3757.3.1 by Vincent Ladeuil
Add credential stores plugging.
1870
1871
    def decode_password(self, credentials):
1872
        """See CredentialStore.decode_password."""
1873
        return credentials['password']
1874
1875
1876
credential_store_registry.register('plain', PlainTextCredentialStore,
1877
                                   help=PlainTextCredentialStore.__doc__)
1878
credential_store_registry.default_key = 'plain'
1879
1880
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1881
class BzrDirConfig(object):
1882
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1883
    def __init__(self, bzrdir):
1884
        self._bzrdir = bzrdir
1885
        self._config = bzrdir._get_config()
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1886
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1887
    def set_default_stack_on(self, value):
1888
        """Set the default stacking location.
1889
1890
        It may be set to a location, or None.
1891
1892
        This policy affects all branches contained by this bzrdir, except for
1893
        those under repositories.
1894
        """
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1895
        if self._config is None:
1896
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1897
        if value is None:
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1898
            self._config.set_option('', 'default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1899
        else:
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1900
            self._config.set_option(value, 'default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1901
1902
    def get_default_stack_on(self):
1903
        """Return the default stacking location.
1904
1905
        This will either be a location, or None.
1906
1907
        This policy affects all branches contained by this bzrdir, except for
1908
        those under repositories.
1909
        """
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1910
        if self._config is None:
1911
            return None
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1912
        value = self._config.get_option('default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1913
        if value == '':
1914
            value = None
1915
        return value
1916
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1917
1918
class TransportConfig(object):
3242.1.5 by Aaron Bentley
Update per review comments
1919
    """A Config that reads/writes a config file on a Transport.
3242.1.4 by Aaron Bentley
Clean-up
1920
1921
    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.
1922
    that may be associated with a section.  Assigning meaning to these values
1923
    is done at higher levels like TreeConfig.
3242.1.4 by Aaron Bentley
Clean-up
1924
    """
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1925
1926
    def __init__(self, transport, filename):
1927
        self._transport = transport
1928
        self._filename = filename
1929
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1930
    def get_option(self, name, section=None, default=None):
1931
        """Return the value associated with a named option.
1932
1933
        :param name: The name of the value
1934
        :param section: The section the option is in (if any)
1935
        :param default: The value to return if the value is not set
1936
        :return: The value or default value
1937
        """
1938
        configobj = self._get_configobj()
1939
        if section is None:
1940
            section_obj = configobj
1941
        else:
1942
            try:
1943
                section_obj = configobj[section]
1944
            except KeyError:
1945
                return default
1946
        return section_obj.get(name, default)
1947
1948
    def set_option(self, value, name, section=None):
1949
        """Set the value associated with a named option.
1950
1951
        :param value: The value to set
1952
        :param name: The name of the value to set
1953
        :param section: The section the option is in (if any)
1954
        """
1955
        configobj = self._get_configobj()
1956
        if section is None:
1957
            configobj[name] = value
1958
        else:
1959
            configobj.setdefault(section, {})[name] = value
1960
        self._set_configobj(configobj)
1961
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
1962
    def remove_option(self, option_name, section_name=None):
1963
        configobj = self._get_configobj()
1964
        if section_name is None:
1965
            del configobj[option_name]
1966
        else:
1967
            del configobj[section_name][option_name]
1968
        self._set_configobj(configobj)
1969
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
1970
    def _get_config_file(self):
1971
        try:
4852.1.10 by John Arbash Meinel
Use a StringIO instead, otherwise we get failures with smart server requests.
1972
            return StringIO(self._transport.get_bytes(self._filename))
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
1973
        except errors.NoSuchFile:
1974
            return StringIO()
1975
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1976
    def _get_configobj(self):
4708.2.1 by Martin
Ensure all files opened by bazaar proper are explicitly closed
1977
        f = self._get_config_file()
1978
        try:
1979
            return ConfigObj(f, encoding='utf-8')
1980
        finally:
1981
            f.close()
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1982
1983
    def _set_configobj(self, configobj):
1984
        out_file = StringIO()
1985
        configobj.write(out_file)
1986
        out_file.seek(0)
1987
        self._transport.put_file(self._filename, out_file)
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
1988
1989
1990
class cmd_config(commands.Command):
5447.4.19 by Vincent Ladeuil
Add some more documentation.
1991
    __doc__ = """Display, set or remove a configuration option.
1992
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
1993
    Display the active value for a given option.
1994
1995
    If --all is specified, NAME is interpreted as a regular expression and all
1996
    matching options are displayed mentioning their scope. The active value
1997
    that bzr will take into account is the first one displayed for each option.
1998
1999
    If no NAME is given, --all .* is implied.
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2000
5447.4.19 by Vincent Ladeuil
Add some more documentation.
2001
    Setting a value is achieved by using name=value without spaces. The value
2002
    is set in the most relevant scope and can be checked by displaying the
2003
    option again.
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2004
    """
2005
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2006
    takes_args = ['name?']
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2007
2008
    takes_options = [
2009
        'directory',
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2010
        # FIXME: This should be a registry option so that plugins can register
2011
        # their own config files (or not) -- vila 20101002
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2012
        commands.Option('scope', help='Reduce the scope to the specified'
2013
                        ' configuration file',
2014
                        type=unicode),
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2015
        commands.Option('all',
2016
            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.
2017
            ),
5447.4.8 by Vincent Ladeuil
Make the test properly fail and provide a fake implementation for ``bzr config --remove opt_name``.
2018
        commands.Option('remove', help='Remove the option from'
2019
                        ' the configuration file'),
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2020
        ]
2021
2022
    @commands.display_command
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2023
    def run(self, name=None, all=False, directory=None, scope=None,
2024
            remove=False):
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2025
        if directory is None:
2026
            directory = '.'
2027
        directory = urlutils.normalize_url(directory)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2028
        if remove and all:
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2029
            raise errors.BzrError(
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2030
                '--all and --remove are mutually exclusive.')
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2031
        elif remove:
2032
            # Delete the option in the given scope
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2033
            self._remove_config_option(name, directory, scope)
2034
        elif name is None:
2035
            # Defaults to all options
2036
            self._show_matching_options('.*', directory, scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2037
        else:
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2038
            try:
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2039
                name, value = name.split('=', 1)
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2040
            except ValueError:
2041
                # Display the option(s) value(s)
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2042
                if all:
2043
                    self._show_matching_options(name, directory, scope)
2044
                else:
2045
                    self._show_value(name, directory, scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2046
            else:
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2047
                if all:
2048
                    raise errors.BzrError(
2049
                        'Only one option can be set.')
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2050
                # Set the option value
2051
                self._set_config_option(name, value, directory, scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2052
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2053
    def _get_configs(self, directory, scope=None):
2054
        """Iterate the configurations specified by ``directory`` and ``scope``.
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2055
2056
        :param directory: Where the configurations are derived from.
2057
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2058
        :param scope: A specific config to start from.
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2059
        """
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2060
        if scope is not None:
2061
            if scope == 'bazaar':
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2062
                yield GlobalConfig()
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2063
            elif scope == 'locations':
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2064
                yield LocationConfig(directory)
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2065
            elif scope == 'branch':
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2066
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2067
                    directory)
2068
                yield br.get_config()
2069
        else:
2070
            try:
2071
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2072
                    directory)
2073
                yield br.get_config()
2074
            except errors.NotBranchError:
2075
                yield LocationConfig(directory)
2076
                yield GlobalConfig()
2077
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2078
    def _show_value(self, name, directory, scope):
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2079
        displayed = False
2080
        for c in self._get_configs(directory, scope):
2081
            if displayed:
2082
                break
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2083
            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
2084
                if name == oname:
5533.1.3 by Vincent Ladeuil
Tweak comment as per poolie's suggestion.
2085
                    # 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
2086
5533.1.3 by Vincent Ladeuil
Tweak comment as per poolie's suggestion.
2087
                    # FIXME: We need to use get_user_option to take policies
2088
                    # 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
2089
                    # too (hence the two for loops), this needs a better API
2090
                    # -- vila 20101117
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2091
                    value = c.get_user_option(name)
2092
                    # Quote the value appropriately
2093
                    value = parser._quote(value)
2094
                    self.outf.write('%s\n' % (value,))
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2095
                    displayed = True
2096
                    break
2097
        if not displayed:
2098
            raise errors.NoSuchConfigOption(name)
2099
2100
    def _show_matching_options(self, name, directory, scope):
2101
        name = re.compile(name)
2102
        # We want any error in the regexp to be raised *now* so we need to
2103
        # avoid the delay introduced by the lazy regexp.
2104
        name._compile_and_collapse()
2105
        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.
2106
        cur_section = None
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2107
        for c in self._get_configs(directory, scope):
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2108
            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
2109
                if name.search(oname):
2110
                    if cur_conf_id != conf_id:
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2111
                        # Explain where the options are defined
5447.4.3 by Vincent Ladeuil
Simplify code and design by only defining get_options() where relevant.
2112
                        self.outf.write('%s:\n' % (conf_id,))
2113
                        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.
2114
                        cur_section = None
2115
                    if (section not in (None, 'DEFAULT')
2116
                        and cur_section != section):
2117
                        # Display the section if it's not the default (or only)
2118
                        # one.
5533.2.1 by Vincent Ladeuil
``bzr config`` properly displays list values
2119
                        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.
2120
                        cur_section = section
5506.2.3 by Vincent Ladeuil
Take review comments into account and drive-by fix bug #670251
2121
                    self.outf.write('  %s = %s\n' % (oname, value))
5447.4.2 by Vincent Ladeuil
Implement the 'brz config' command. Read-only.
2122
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2123
    def _set_config_option(self, name, value, directory, scope):
2124
        for conf in self._get_configs(directory, scope):
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2125
            conf.set_user_option(name, value)
2126
            break
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2127
        else:
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2128
            raise errors.NoSuchConfig(scope)
5447.4.5 by Vincent Ladeuil
Implement ``bzr config option=value``.
2129
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2130
    def _remove_config_option(self, name, directory, scope):
5506.2.1 by Vincent Ladeuil
Implements ``bzr config --active option`` displaying only the value.
2131
        if name is None:
2132
            raise errors.BzrCommandError(
2133
                '--remove expects an option to remove.')
5447.4.9 by Vincent Ladeuil
Refactor under tests umbrella.
2134
        removed = False
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2135
        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.
2136
            for (section_name, section, conf_id) in conf._get_sections():
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2137
                if scope is not None and conf_id != scope:
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
2138
                    # Not the right configuration file
2139
                    continue
2140
                if name in section:
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
2141
                    if conf_id != conf.config_id():
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
2142
                        conf = self._get_configs(directory, conf_id).next()
2143
                    # We use the first section in the first config where the
2144
                    # option is defined to remove it
2145
                    conf.remove_user_option(name, section_name)
2146
                    removed = True
2147
                    break
2148
            break
2149
        else:
5447.4.17 by Vincent Ladeuil
Rename config --force to config --scope.
2150
            raise errors.NoSuchConfig(scope)
5447.4.11 by Vincent Ladeuil
Implement ``bzr config --remove <option>``.
2151
        if not removed:
2152
            raise errors.NoSuchConfigOption(name)