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