/brz/remove-bazaar

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