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