/brz/remove-bazaar

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