~bzr-pqm/bzr/bzr.dev

2323.6.2 by Martin Pool
Move responsibility for suggesting upgrades to ui object
1
# Copyright (C) 2005, 2007 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
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
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
48
                   signatures, ignore them, or check them if they are 
49
                   present.
50
create_signatures - this option controls whether bzr will always create 
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
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
68
from bzrlib.lazy_import import lazy_import
69
lazy_import(globals(), """
1474 by Robert Collins
Merge from Aaron Bentley.
70
import errno
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
71
from fnmatch import fnmatch
72
import re
2900.2.22 by Vincent Ladeuil
Polishing.
73
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.
74
75
import bzrlib
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
76
from bzrlib import (
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
77
    debug,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
78
    errors,
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
79
    mail_client,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
80
    osutils,
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
81
    symbol_versioning,
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
82
    trace,
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
83
    ui,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
84
    urlutils,
2245.4.3 by Alexander Belchenko
config.py: changing _auto_user_id() and config_dir() to use functions from win32utils
85
    win32utils,
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
86
    )
2991.2.4 by Vincent Ladeuil
Various fixes following local testing environment rebuild.
87
from bzrlib.util.configobj import configobj
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
88
""")
89
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
90
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
91
CHECK_IF_POSSIBLE=0
92
CHECK_ALWAYS=1
93
CHECK_NEVER=2
94
95
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
96
SIGN_WHEN_REQUIRED=0
97
SIGN_ALWAYS=1
98
SIGN_NEVER=2
99
100
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
101
POLICY_NONE = 0
102
POLICY_NORECURSE = 1
103
POLICY_APPENDPATH = 2
104
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
105
_policy_name = {
106
    POLICY_NONE: None,
107
    POLICY_NORECURSE: 'norecurse',
108
    POLICY_APPENDPATH: 'appendpath',
109
    }
110
_policy_value = {
111
    None: POLICY_NONE,
112
    'none': POLICY_NONE,
113
    'norecurse': POLICY_NORECURSE,
114
    'appendpath': POLICY_APPENDPATH,
115
    }
2120.6.4 by James Henstridge
add support for specifying policy when storing options
116
117
118
STORE_LOCATION = POLICY_NONE
119
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
120
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
121
STORE_BRANCH = 3
122
STORE_GLOBAL = 4
123
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
124
1474 by Robert Collins
Merge from Aaron Bentley.
125
class ConfigObj(configobj.ConfigObj):
126
127
    def get_bool(self, section, key):
1556.2.2 by Aaron Bentley
Fixed get_bool
128
        return self[section].as_bool(key)
1474 by Robert Collins
Merge from Aaron Bentley.
129
130
    def get_value(self, section, name):
131
        # Try [] for the old DEFAULT section.
132
        if section == "DEFAULT":
133
            try:
134
                return self[name]
135
            except KeyError:
136
                pass
137
        return self[section][name]
138
139
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
140
class Config(object):
141
    """A configuration policy - what username, editor, gpg needs etc."""
142
143
    def get_editor(self):
144
        """Get the users pop up editor."""
145
        raise NotImplementedError
146
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
147
    def get_mail_client(self):
148
        """Get a mail client to use"""
149
        selected_client = self.get_user_option('mail_client')
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
150
        try:
151
            mail_client_class = {
2681.3.4 by Lukáš Lalinsky
- Rename 'windows' to 'mapi'
152
                None: mail_client.DefaultMail,
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
153
                # Specific clients
3324.4.1 by Xavier Maillard
Replace mail-mode call with compose-mail from GNU Emacs.
154
                'emacsclient': mail_client.EmacsMail,
2681.2.1 by Lukáš Lalinsky
Support for Evolution mail client.
155
                'evolution': mail_client.Evolution,
2790.2.1 by Keir Mierle
Add Mutt as a supported client email program. Also rearranges various listings
156
                'kmail': mail_client.KMail,
157
                'mutt': mail_client.Mutt,
158
                'thunderbird': mail_client.Thunderbird,
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
159
                # Generic options
160
                'default': mail_client.DefaultMail,
161
                'editor': mail_client.Editor,
162
                'mapi': mail_client.MAPIClient,
2681.1.23 by Aaron Bentley
Add support for xdg-email
163
                'xdg-email': mail_client.XDGEmail,
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
164
            }[selected_client]
165
        except KeyError:
166
            raise errors.UnknownMailClient(selected_client)
167
        return mail_client_class(self)
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
168
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
169
    def _get_signature_checking(self):
170
        """Template method to override signature checking policy."""
171
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
172
    def _get_signing_policy(self):
173
        """Template method to override signature creation policy."""
174
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
175
    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.
176
        """Template method to provide a user option."""
177
        return None
178
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
179
    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.
180
        """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()
181
        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.
182
1442.1.56 by Robert Collins
gpg_signing_command configuration item
183
    def gpg_signing_command(self):
184
        """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.
185
        result = self._gpg_signing_command()
186
        if result is None:
187
            result = "gpg"
188
        return result
189
190
    def _gpg_signing_command(self):
191
        """See gpg_signing_command()."""
192
        return None
1442.1.56 by Robert Collins
gpg_signing_command configuration item
193
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
194
    def log_format(self):
195
        """What log format should be used"""
196
        result = self._log_format()
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
197
        if result is None:
198
            result = "long"
199
        return result
200
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
201
    def _log_format(self):
202
        """See log_format()."""
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
203
        return None
204
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
205
    def __init__(self):
206
        super(Config, self).__init__()
207
1472 by Robert Collins
post commit hook, first pass implementation
208
    def post_commit(self):
209
        """An ordered list of python functions to call.
210
211
        Each function takes branch, rev_id as parameters.
212
        """
213
        return self._post_commit()
214
215
    def _post_commit(self):
216
        """See Config.post_commit."""
217
        return None
218
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
219
    def user_email(self):
220
        """Return just the email component of a username."""
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
221
        return extract_email_address(self.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
222
223
    def username(self):
224
        """Return email-style username.
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
225
    
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
226
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
227
        
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
228
        $BZR_EMAIL can be set to override this (as well as the
229
        deprecated $BZREMAIL), then
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
230
        the concrete policy type is checked, and finally
1185.37.2 by Jamie Wilkinson
Fix a typo and grammar in Config.username() docstring.
231
        $EMAIL is examined.
232
        If none is found, a reasonable default is (hopefully)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
233
        created.
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
234
    
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
235
        TODO: Check it's reasonably well-formed.
236
        """
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
237
        v = os.environ.get('BZR_EMAIL')
238
        if v:
239
            return v.decode(bzrlib.user_encoding)
2900.3.1 by Tim Penhey
Removed some annoying trailing whitespace.
240
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
241
        v = self._get_user_id()
242
        if v:
243
            return v
2900.3.1 by Tim Penhey
Removed some annoying trailing whitespace.
244
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
245
        v = os.environ.get('EMAIL')
246
        if v:
247
            return v.decode(bzrlib.user_encoding)
248
249
        name, email = _auto_user_id()
250
        if name:
251
            return '%s <%s>' % (name, email)
252
        else:
253
            return email
254
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
255
    def signature_checking(self):
256
        """What is the current policy for signature checking?."""
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
257
        policy = self._get_signature_checking()
258
        if policy is not None:
259
            return policy
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
260
        return CHECK_IF_POSSIBLE
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
261
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
262
    def signing_policy(self):
263
        """What is the current policy for signature checking?."""
264
        policy = self._get_signing_policy()
265
        if policy is not None:
266
            return policy
267
        return SIGN_WHEN_REQUIRED
268
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
269
    def signature_needed(self):
270
        """Is a signature needed when committing ?."""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
271
        policy = self._get_signing_policy()
272
        if policy is None:
273
            policy = self._get_signature_checking()
274
            if policy is not None:
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
275
                trace.warning("Please use create_signatures,"
276
                              " not check_signatures to set signing policy.")
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
277
            if policy == CHECK_ALWAYS:
278
                return True
279
        elif policy == SIGN_ALWAYS:
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
280
            return True
281
        return False
282
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
283
    def get_alias(self, value):
284
        return self._get_alias(value)
285
286
    def _get_alias(self, value):
287
        pass
288
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
289
    def get_nickname(self):
290
        return self._get_nickname()
291
292
    def _get_nickname(self):
293
        return None
294
1551.18.17 by Aaron Bentley
Introduce bzr_remote_path configuration variable
295
    def get_bzr_remote_path(self):
296
        try:
297
            return os.environ['BZR_REMOTE_PATH']
298
        except KeyError:
299
            path = self.get_user_option("bzr_remote_path")
300
            if path is None:
301
                path = 'bzr'
302
            return path
303
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
304
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
305
class IniBasedConfig(Config):
306
    """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
307
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
308
    def _get_parser(self, file=None):
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
309
        if self._parser is not None:
310
            return self._parser
1185.12.49 by Aaron Bentley
Switched to ConfigObj
311
        if file is None:
312
            input = self._get_filename()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
313
        else:
1185.12.49 by Aaron Bentley
Switched to ConfigObj
314
            input = file
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
315
        try:
1551.2.20 by Aaron Bentley
Treated config files as utf-8
316
            self._parser = ConfigObj(input, encoding='utf-8')
1474 by Robert Collins
Merge from Aaron Bentley.
317
        except configobj.ConfigObjError, e:
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
318
            raise errors.ParseConfigError(e.errors, e.config.filename)
1185.12.49 by Aaron Bentley
Switched to ConfigObj
319
        return self._parser
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
320
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
321
    def _get_matching_sections(self):
322
        """Return an ordered list of (section_name, extra_path) pairs.
323
324
        If the section contains inherited configuration, extra_path is
325
        a string containing the additional path components.
326
        """
327
        section = self._get_section()
328
        if section is not None:
329
            return [(section, '')]
330
        else:
331
            return []
332
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
333
    def _get_section(self):
334
        """Override this to define the section used by the config."""
335
        return "DEFAULT"
336
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
337
    def _get_option_policy(self, section, option_name):
338
        """Return the policy for the given (section, option_name) pair."""
339
        return POLICY_NONE
340
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
341
    def _get_signature_checking(self):
342
        """See Config._get_signature_checking."""
1474 by Robert Collins
Merge from Aaron Bentley.
343
        policy = self._get_user_option('check_signatures')
344
        if policy:
345
            return self._string_to_signature_policy(policy)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
346
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
347
    def _get_signing_policy(self):
1773.4.3 by Martin Pool
[merge] bzr.dev
348
        """See Config._get_signing_policy"""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
349
        policy = self._get_user_option('create_signatures')
350
        if policy:
351
            return self._string_to_signing_policy(policy)
352
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
353
    def _get_user_id(self):
354
        """Get the user id from the 'email' key in the current section."""
1474 by Robert Collins
Merge from Aaron Bentley.
355
        return self._get_user_option('email')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
356
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
357
    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.
358
        """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
359
        for (section, extra_path) in self._get_matching_sections():
360
            try:
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
361
                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
362
            except KeyError:
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
363
                continue
364
            policy = self._get_option_policy(section, option_name)
365
            if policy == POLICY_NONE:
366
                return value
367
            elif policy == POLICY_NORECURSE:
368
                # norecurse items only apply to the exact path
369
                if extra_path:
370
                    continue
371
                else:
372
                    return value
373
            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
374
                if extra_path:
375
                    value = urlutils.join(value, extra_path)
376
                return value
2120.6.6 by James Henstridge
fix test_set_push_location test
377
            else:
378
                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
379
        else:
1993.3.1 by James Henstridge
first go at making location config lookup recursive
380
            return None
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
381
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
382
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
383
        """See Config.gpg_signing_command."""
1472 by Robert Collins
post commit hook, first pass implementation
384
        return self._get_user_option('gpg_signing_command')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
385
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
386
    def _log_format(self):
387
        """See Config.log_format."""
388
        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
389
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
390
    def __init__(self, get_filename):
391
        super(IniBasedConfig, self).__init__()
392
        self._get_filename = get_filename
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
393
        self._parser = None
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
394
        
1472 by Robert Collins
post commit hook, first pass implementation
395
    def _post_commit(self):
396
        """See Config.post_commit."""
397
        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
398
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
399
    def _string_to_signature_policy(self, signature_string):
400
        """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
401
        if signature_string.lower() == 'check-available':
402
            return CHECK_IF_POSSIBLE
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
403
        if signature_string.lower() == 'ignore':
404
            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
405
        if signature_string.lower() == 'require':
406
            return CHECK_ALWAYS
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
407
        raise errors.BzrError("Invalid signatures policy '%s'"
408
                              % signature_string)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
409
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
410
    def _string_to_signing_policy(self, signature_string):
411
        """Convert a string to a signing policy."""
412
        if signature_string.lower() == 'when-required':
413
            return SIGN_WHEN_REQUIRED
414
        if signature_string.lower() == 'never':
415
            return SIGN_NEVER
416
        if signature_string.lower() == 'always':
417
            return SIGN_ALWAYS
418
        raise errors.BzrError("Invalid signing policy '%s'"
419
                              % signature_string)
420
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
421
    def _get_alias(self, value):
422
        try:
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
423
            return self._get_parser().get_value("ALIASES", 
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
424
                                                value)
425
        except KeyError:
426
            pass
427
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
428
    def _get_nickname(self):
429
        return self.get_user_option('nickname')
430
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
431
432
class GlobalConfig(IniBasedConfig):
433
    """The configuration that should be used for a specific location."""
434
435
    def get_editor(self):
1474 by Robert Collins
Merge from Aaron Bentley.
436
        return self._get_user_option('editor')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
437
438
    def __init__(self):
439
        super(GlobalConfig, self).__init__(config_filename)
440
1816.2.1 by Robey Pointer
add set_user_option to GlobalConfig, and make /etc/passwd username lookup try harder with encodings
441
    def set_user_option(self, option, value):
442
        """Save option and its value in the configuration."""
2900.3.2 by Tim Penhey
A working alias command.
443
        self._set_option(option, value, 'DEFAULT')
444
445
    def get_aliases(self):
446
        """Return the aliases section."""
447
        if 'ALIASES' in self._get_parser():
448
            return self._get_parser()['ALIASES']
449
        else:
450
            return {}
451
452
    def set_alias(self, alias_name, alias_command):
453
        """Save the alias in the configuration."""
454
        self._set_option(alias_name, alias_command, 'ALIASES')
455
456
    def unset_alias(self, alias_name):
457
        """Unset an existing alias."""
458
        aliases = self._get_parser().get('ALIASES')
2900.3.7 by Tim Penhey
Updates from Aaron's review.
459
        if not aliases or alias_name not in aliases:
460
            raise errors.NoSuchAlias(alias_name)
2900.3.2 by Tim Penhey
A working alias command.
461
        del aliases[alias_name]
2900.3.12 by Tim Penhey
Final review comments.
462
        self._write_config_file()
2900.3.2 by Tim Penhey
A working alias command.
463
464
    def _set_option(self, option, value, section):
1816.2.1 by Robey Pointer
add set_user_option to GlobalConfig, and make /etc/passwd username lookup try harder with encodings
465
        # FIXME: RBC 20051029 This should refresh the parser and also take a
466
        # file lock on bazaar.conf.
467
        conf_dir = os.path.dirname(self._get_filename())
468
        ensure_config_dir_exists(conf_dir)
2900.3.7 by Tim Penhey
Updates from Aaron's review.
469
        self._get_parser().setdefault(section, {})[option] = value
2900.3.12 by Tim Penhey
Final review comments.
470
        self._write_config_file()
2900.3.2 by Tim Penhey
A working alias command.
471
2900.3.12 by Tim Penhey
Final review comments.
472
    def _write_config_file(self):
1816.2.1 by Robey Pointer
add set_user_option to GlobalConfig, and make /etc/passwd username lookup try harder with encodings
473
        f = open(self._get_filename(), 'wb')
474
        self._get_parser().write(f)
475
        f.close()
476
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
477
478
class LocationConfig(IniBasedConfig):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
479
    """A configuration object that gives the policy for a location."""
480
481
    def __init__(self, location):
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
482
        name_generator = locations_config_filename
2900.3.1 by Tim Penhey
Removed some annoying trailing whitespace.
483
        if (not os.path.exists(name_generator()) and
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
484
                os.path.exists(branches_config_filename())):
1830.2.1 by John Arbash Meinel
Make it clearer what config file needs to be renamed.
485
            if sys.platform == 'win32':
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
486
                trace.warning('Please rename %s to %s'
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
487
                              % (branches_config_filename(),
488
                                 locations_config_filename()))
1830.2.1 by John Arbash Meinel
Make it clearer what config file needs to be renamed.
489
            else:
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
490
                trace.warning('Please rename ~/.bazaar/branches.conf'
491
                              ' to ~/.bazaar/locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
492
            name_generator = branches_config_filename
493
        super(LocationConfig, self).__init__(name_generator)
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
494
        # local file locations are looked up by local path, rather than
495
        # by file url. This is because the config file is a user
496
        # file, and we would rather not expose the user to file urls.
497
        if location.startswith('file://'):
498
            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
499
        self.location = location
500
1993.3.1 by James Henstridge
first go at making location config lookup recursive
501
    def _get_matching_sections(self):
502
        """Return an ordered list of section names matching this location."""
1185.12.49 by Aaron Bentley
Switched to ConfigObj
503
        sections = self._get_parser()
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
504
        location_names = self.location.split('/')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
505
        if self.location.endswith('/'):
506
            del location_names[-1]
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
507
        matches=[]
1442.1.10 by Robert Collins
explicit over glob test passes
508
        for section in sections:
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
509
            # location is a local path if possible, so we need
510
            # to convert 'file://' urls to local paths if necessary.
511
            # This also avoids having file:///path be a more exact
512
            # match than '/path'.
513
            if section.startswith('file://'):
514
                section_path = urlutils.local_path_from_url(section)
515
            else:
516
                section_path = section
517
            section_names = section_path.split('/')
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
518
            if section.endswith('/'):
519
                del section_names[-1]
520
            names = zip(location_names, section_names)
521
            matched = True
522
            for name in names:
523
                if not fnmatch(name[0], name[1]):
524
                    matched = False
525
                    break
526
            if not matched:
527
                continue
528
            # so, for the common prefix they matched.
529
            # if section is longer, no match.
530
            if len(section_names) > len(location_names):
531
                continue
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
532
            matches.append((len(section_names), section,
533
                            '/'.join(location_names[len(section_names):])))
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
534
        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
535
        sections = []
536
        for (length, section, extra_path) in matches:
537
            sections.append((section, extra_path))
538
            # should we stop looking for parent configs here?
1993.3.1 by James Henstridge
first go at making location config lookup recursive
539
            try:
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
540
                if self._get_parser()[section].as_bool('ignore_parents'):
541
                    break
1993.3.1 by James Henstridge
first go at making location config lookup recursive
542
            except KeyError:
543
                pass
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
544
        return sections
1442.1.9 by Robert Collins
exact section test passes
545
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
546
    def _get_option_policy(self, section, option_name):
547
        """Return the policy for the given (section, option_name) pair."""
548
        # check for the old 'recurse=False' flag
549
        try:
550
            recurse = self._get_parser()[section].as_bool('recurse')
551
        except KeyError:
552
            recurse = True
553
        if not recurse:
554
            return POLICY_NORECURSE
555
2120.6.10 by James Henstridge
Catch another deprecation warning, and more cleanup
556
        policy_key = option_name + ':policy'
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
557
        try:
558
            policy_name = self._get_parser()[section][policy_key]
559
        except KeyError:
560
            policy_name = None
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
561
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
562
        return _policy_value[policy_name]
2120.6.1 by James Henstridge
add support for norecurse and appendpath policies when reading configuration files
563
2120.6.4 by James Henstridge
add support for specifying policy when storing options
564
    def _set_option_policy(self, section, option_name, option_policy):
565
        """Set the policy for the given option name in the given section."""
566
        # The old recurse=False option affects all options in the
567
        # section.  To handle multiple policies in the section, we
568
        # need to convert it to a policy_norecurse key.
569
        try:
570
            recurse = self._get_parser()[section].as_bool('recurse')
571
        except KeyError:
572
            pass
573
        else:
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
574
            symbol_versioning.warn(
2120.6.11 by James Henstridge
s/0.13/0.14/ in deprecation warning
575
                'The recurse option is deprecated as of 0.14.  '
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
576
                'The section "%s" has been converted to use policies.'
577
                % section,
578
                DeprecationWarning)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
579
            del self._get_parser()[section]['recurse']
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
580
            if not recurse:
581
                for key in self._get_parser()[section].keys():
582
                    if not key.endswith(':policy'):
583
                        self._get_parser()[section][key +
584
                                                    ':policy'] = 'norecurse'
2120.6.4 by James Henstridge
add support for specifying policy when storing options
585
2120.6.9 by James Henstridge
Fixes for issues brought up in John's review
586
        policy_key = option_name + ':policy'
2120.6.8 by James Henstridge
Change syntax for setting config option policies. Rather than
587
        policy_name = _policy_name[option_policy]
588
        if policy_name is not None:
589
            self._get_parser()[section][policy_key] = policy_name
590
        else:
591
            if policy_key in self._get_parser()[section]:
592
                del self._get_parser()[section][policy_key]
2120.6.4 by James Henstridge
add support for specifying policy when storing options
593
594
    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.
595
        """Save option and its value in the configuration."""
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
596
        if store not in [STORE_LOCATION,
2120.6.4 by James Henstridge
add support for specifying policy when storing options
597
                         STORE_LOCATION_NORECURSE,
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
598
                         STORE_LOCATION_APPENDPATH]:
599
            raise ValueError('bad storage policy %r for %r' %
600
                (store, option))
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
601
        # FIXME: RBC 20051029 This should refresh the parser and also take a
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
602
        # file lock on locations.conf.
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
603
        conf_dir = os.path.dirname(self._get_filename())
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
604
        ensure_config_dir_exists(conf_dir)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
605
        location = self.location
606
        if location.endswith('/'):
607
            location = location[:-1]
608
        if (not location in self._get_parser() and
609
            not location + '/' in self._get_parser()):
610
            self._get_parser()[location]={}
611
        elif location + '/' in self._get_parser():
612
            location = location + '/'
613
        self._get_parser()[location][option]=value
2120.6.4 by James Henstridge
add support for specifying policy when storing options
614
        # the allowed values of store match the config policies
615
        self._set_option_policy(location, option, store)
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
616
        self._get_parser().write(file(self._get_filename(), 'wb'))
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
617
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
618
619
class BranchConfig(Config):
620
    """A configuration object giving the policy for a branch."""
621
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
622
    def _get_branch_data_config(self):
623
        if self._branch_data_config is None:
624
            self._branch_data_config = TreeConfig(self.branch)
625
        return self._branch_data_config
626
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
627
    def _get_location_config(self):
628
        if self._location_config is None:
629
            self._location_config = LocationConfig(self.branch.base)
630
        return self._location_config
631
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
632
    def _get_global_config(self):
633
        if self._global_config is None:
634
            self._global_config = GlobalConfig()
635
        return self._global_config
636
637
    def _get_best_value(self, option_name):
638
        """This returns a user option from local, tree or global config.
639
640
        They are tried in that order.  Use get_safe_value if trusted values
641
        are necessary.
642
        """
643
        for source in self.option_sources:
644
            value = getattr(source(), option_name)()
645
            if value is not None:
646
                return value
647
        return None
648
649
    def _get_safe_value(self, option_name):
650
        """This variant of get_best_value never returns untrusted values.
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
651
        
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
652
        It does not return values from the branch data, because the branch may
653
        not be controlled by the user.
654
655
        We may wish to allow locations.conf to control whether branches are
656
        trusted in the future.
657
        """
658
        for source in (self._get_location_config, self._get_global_config):
659
            value = getattr(source(), option_name)()
660
            if value is not None:
661
                return value
662
        return None
663
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
664
    def _get_user_id(self):
665
        """Return the full user id for the branch.
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
666
    
3407.2.14 by Martin Pool
Remove more cases of getting transport via control_files
667
        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
668
        This is looked up in the email controlfile for the branch.
669
        """
670
        try:
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
671
            return (self.branch._transport.get_bytes("email")
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
672
                    .decode(bzrlib.user_encoding)
673
                    .rstrip("\r\n"))
674
        except errors.NoSuchFile, e:
675
            pass
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
676
        
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
677
        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
678
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
679
    def _get_signature_checking(self):
680
        """See Config._get_signature_checking."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
681
        return self._get_best_value('_get_signature_checking')
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
682
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
683
    def _get_signing_policy(self):
684
        """See Config._get_signing_policy."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
685
        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
686
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
687
    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.
688
        """See Config._get_user_option."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
689
        for source in self.option_sources:
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
690
            value = source()._get_user_option(option_name)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
691
            if value is not None:
692
                return value
693
        return None
694
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
695
    def set_user_option(self, name, value, store=STORE_BRANCH,
696
        warn_masked=False):
2120.6.4 by James Henstridge
add support for specifying policy when storing options
697
        if store == STORE_BRANCH:
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
698
            self._get_branch_data_config().set_option(value, name)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
699
        elif store == STORE_GLOBAL:
2120.6.7 by James Henstridge
Fix GlobalConfig.set_user_option() call
700
            self._get_global_config().set_user_option(name, value)
2120.6.4 by James Henstridge
add support for specifying policy when storing options
701
        else:
702
            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)
703
        if not warn_masked:
704
            return
705
        if store in (STORE_GLOBAL, STORE_BRANCH):
706
            mask_value = self._get_location_config().get_user_option(name)
707
            if mask_value is not None:
708
                trace.warning('Value "%s" is masked by "%s" from'
709
                              ' locations.conf', value, mask_value)
710
            else:
711
                if store == STORE_GLOBAL:
712
                    branch_config = self._get_branch_data_config()
713
                    mask_value = branch_config.get_user_option(name)
714
                    if mask_value is not None:
715
                        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
716
                                      ' branch.conf', value, mask_value)
1551.15.35 by Aaron Bentley
Warn when setting config values that will be masked (#122286)
717
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
718
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
719
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
720
        """See Config.gpg_signing_command."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
721
        return self._get_safe_value('_gpg_signing_command')
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
722
        
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
723
    def __init__(self, branch):
724
        super(BranchConfig, self).__init__()
725
        self._location_config = None
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
726
        self._branch_data_config = None
727
        self._global_config = None
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
728
        self.branch = branch
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
729
        self.option_sources = (self._get_location_config, 
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
730
                               self._get_branch_data_config,
731
                               self._get_global_config)
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
732
1472 by Robert Collins
post commit hook, first pass implementation
733
    def _post_commit(self):
734
        """See Config.post_commit."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
735
        return self._get_safe_value('_post_commit')
1472 by Robert Collins
post commit hook, first pass implementation
736
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
737
    def _get_nickname(self):
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
738
        value = self._get_explicit_nickname()
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
739
        if value is not None:
740
            return value
2120.5.2 by Alexander Belchenko
(jam) Fix for bug #66857
741
        return urlutils.unescape(self.branch.base.split('/')[-2])
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
742
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
743
    def has_explicit_nickname(self):
744
        """Return true if a nickname has been explicitly assigned."""
745
        return self._get_explicit_nickname() is not None
746
747
    def _get_explicit_nickname(self):
748
        return self._get_best_value('_get_nickname')
749
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
750
    def _log_format(self):
751
        """See Config.log_format."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
752
        return self._get_best_value('_log_format')
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
753
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
754
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
755
def ensure_config_dir_exists(path=None):
756
    """Make sure a configuration directory exists.
757
    This makes sure that the directory exists.
758
    On windows, since configuration directories are 2 levels deep,
759
    it makes sure both the directory and the parent directory exists.
760
    """
761
    if path is None:
762
        path = config_dir()
763
    if not os.path.isdir(path):
764
        if sys.platform == 'win32':
765
            parent_dir = os.path.dirname(path)
766
            if not os.path.isdir(parent_dir):
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
767
                trace.mutter('creating config parent directory: %r', parent_dir)
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
768
            os.mkdir(parent_dir)
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
769
        trace.mutter('creating config directory: %r', path)
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
770
        os.mkdir(path)
771
1532 by Robert Collins
Merge in John Meinels integration branch.
772
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
773
def config_dir():
774
    """Return per-user configuration directory.
775
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
776
    By default this is ~/.bazaar/
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
777
    
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
778
    TODO: Global option --config-dir to override this.
779
    """
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
780
    base = os.environ.get('BZR_HOME', None)
781
    if sys.platform == 'win32':
782
        if base is None:
2245.4.3 by Alexander Belchenko
config.py: changing _auto_user_id() and config_dir() to use functions from win32utils
783
            base = win32utils.get_appdata_location_unicode()
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
784
        if base is None:
785
            base = os.environ.get('HOME', None)
786
        if base is None:
2991.2.2 by Vincent Ladeuil
No tests worth adding after upgrading to configobj-4.4.0.
787
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
788
                                  ' or HOME set')
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
789
        return osutils.pathjoin(base, 'bazaar', '2.0')
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
790
    else:
791
        # cygwin, linux, and darwin all have a $HOME directory
792
        if base is None:
793
            base = os.path.expanduser("~")
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
794
        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 \
795
796
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
797
def config_filename():
798
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
799
    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.
800
801
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
802
def branches_config_filename():
803
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
804
    return osutils.pathjoin(config_dir(), 'branches.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.
805
1830.2.1 by John Arbash Meinel
Make it clearer what config file needs to be renamed.
806
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
807
def locations_config_filename():
808
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
809
    return osutils.pathjoin(config_dir(), 'locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
810
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
811
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
812
def authentication_config_filename():
813
    """Return per-user authentication ini file filename."""
814
    return osutils.pathjoin(config_dir(), 'authentication.conf')
815
816
1836.1.6 by John Arbash Meinel
Creating a helper function for getting the user ignore filename
817
def user_ignore_config_filename():
818
    """Return the user default ignore filename"""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
819
    return osutils.pathjoin(config_dir(), 'ignore')
1836.1.6 by John Arbash Meinel
Creating a helper function for getting the user ignore filename
820
821
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
822
def _auto_user_id():
823
    """Calculate automatic user identification.
824
825
    Returns (realname, email).
826
827
    Only used when none is set in the environment or the id file.
828
829
    This previously used the FQDN as the default domain, but that can
830
    be very slow on machines where DNS is broken.  So now we simply
831
    use the hostname.
832
    """
833
    import socket
834
2245.4.3 by Alexander Belchenko
config.py: changing _auto_user_id() and config_dir() to use functions from win32utils
835
    if sys.platform == 'win32':
836
        name = win32utils.get_user_name_unicode()
837
        if name is None:
838
            raise errors.BzrError("Cannot autodetect user name.\n"
839
                                  "Please, set your name with command like:\n"
840
                                  'bzr whoami "Your Name <name@domain.com>"')
841
        host = win32utils.get_host_name_unicode()
842
        if host is None:
843
            host = socket.gethostname()
844
        return name, (name + '@' + host)
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
845
846
    try:
847
        import pwd
848
        uid = os.getuid()
849
        w = pwd.getpwuid(uid)
1553.4.5 by Michael Ellerman
Produce an intelligible error if the user's /etc/passwd is not encoded in
850
1816.2.1 by Robey Pointer
add set_user_option to GlobalConfig, and make /etc/passwd username lookup try harder with encodings
851
        # we try utf-8 first, because on many variants (like Linux),
852
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
853
        # false positives.  (many users will have their user encoding set to
854
        # latin-1, which cannot raise UnicodeError.)
855
        try:
856
            gecos = w.pw_gecos.decode('utf-8')
857
            encoding = 'utf-8'
858
        except UnicodeError:
859
            try:
860
                gecos = w.pw_gecos.decode(bzrlib.user_encoding)
861
                encoding = bzrlib.user_encoding
862
            except UnicodeError:
863
                raise errors.BzrCommandError('Unable to determine your name.  '
864
                   'Use "bzr whoami" to set it.')
865
        try:
866
            username = w.pw_name.decode(encoding)
867
        except UnicodeError:
868
            raise errors.BzrCommandError('Unable to determine your name.  '
869
                'Use "bzr whoami" to set it.')
1553.4.5 by Michael Ellerman
Produce an intelligible error if the user's /etc/passwd is not encoded in
870
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
871
        comma = gecos.find(',')
872
        if comma == -1:
873
            realname = gecos
874
        else:
875
            realname = gecos[:comma]
876
        if not realname:
877
            realname = username
878
879
    except ImportError:
880
        import getpass
1553.4.5 by Michael Ellerman
Produce an intelligible error if the user's /etc/passwd is not encoded in
881
        try:
882
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
883
        except UnicodeDecodeError:
884
            raise errors.BzrError("Can't decode username as %s." % \
885
                    bzrlib.user_encoding)
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
886
887
    return realname, (username + '@' + socket.gethostname())
888
889
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
890
def parse_username(username):
891
    """Parse e-mail username and return a (name, address) tuple."""
892
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
893
    if match is None:
894
        return (username, '')
895
    else:
896
        return (match.group(1), match.group(2))
897
898
1185.16.52 by Martin Pool
- add extract_email_address
899
def extract_email_address(e):
900
    """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.
901
2900.3.9 by Tim Penhey
Remove the whitespace fix ups that shouldn't be there.
902
    That is just the user@domain part, nothing else. 
1185.16.52 by Martin Pool
- add extract_email_address
903
    This part is required to contain only ascii characters.
904
    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.
905
1185.16.52 by Martin Pool
- add extract_email_address
906
    >>> extract_email_address('Jane Tester <jane@test.com>')
907
    "jane@test.com"
908
    """
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
909
    name, email = parse_username(e)
910
    if not email:
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
911
        raise errors.NoEmailInUsername(e)
3063.3.2 by Lukáš Lalinský
Move the name and e-mail address extraction logic to config.parse_username.
912
    return email
1185.35.11 by Aaron Bentley
Added support for branch nicks
913
1185.85.30 by John Arbash Meinel
Fixing 'bzr push' exposed that IniBasedConfig didn't handle unicode.
914
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
915
class TreeConfig(IniBasedConfig):
1185.35.11 by Aaron Bentley
Added support for branch nicks
916
    """Branch configuration data associated with its contents, not location"""
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
917
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
918
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
919
1185.35.11 by Aaron Bentley
Added support for branch nicks
920
    def __init__(self, branch):
3407.2.13 by Martin Pool
Remove indirection through control_files to get transports
921
        # XXX: Really this should be asking the branch for its configuration
922
        # data, rather than relying on a Transport, so that it can work 
923
        # more cleanly with a RemoteBranch that has no transport.
3407.2.16 by Martin Pool
Remove RemoteBranch reliance on control_files._transport
924
        self._config = TransportConfig(branch._transport, 'branch.conf')
1185.35.11 by Aaron Bentley
Added support for branch nicks
925
        self.branch = branch
926
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
927
    def _get_parser(self, file=None):
928
        if file is not None:
929
            return IniBasedConfig._get_parser(file)
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
930
        return self._config._get_configobj()
1185.35.11 by Aaron Bentley
Added support for branch nicks
931
932
    def get_option(self, name, section=None, default=None):
933
        self.branch.lock_read()
934
        try:
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
935
            return self._config.get_option(name, section, default)
1185.35.11 by Aaron Bentley
Added support for branch nicks
936
        finally:
937
            self.branch.unlock()
938
        return result
939
940
    def set_option(self, value, name, section=None):
941
        """Set a per-branch configuration option"""
942
        self.branch.lock_write()
943
        try:
3242.1.2 by Aaron Bentley
Turn BzrDirConfig into TransportConfig, reduce code duplication
944
            self._config.set_option(value, name, section)
1185.35.11 by Aaron Bentley
Added support for branch nicks
945
        finally:
946
            self.branch.unlock()
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
947
948
949
class AuthenticationConfig(object):
950
    """The authentication configuration file based on a ini file.
951
952
    Implements the authentication.conf file described in
953
    doc/developers/authentication-ring.txt.
954
    """
955
956
    def __init__(self, _file=None):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
957
        self._config = None # The ConfigObj
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
958
        if _file is None:
2900.2.24 by Vincent Ladeuil
Review feedback.
959
            self._filename = authentication_config_filename()
960
            self._input = self._filename = authentication_config_filename()
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
961
        else:
2900.2.24 by Vincent Ladeuil
Review feedback.
962
            # Tests can provide a string as _file
963
            self._filename = None
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
964
            self._input = _file
965
966
    def _get_config(self):
967
        if self._config is not None:
968
            return self._config
969
        try:
2900.2.22 by Vincent Ladeuil
Polishing.
970
            # FIXME: Should we validate something here ? Includes: empty
971
            # sections are useless, at least one of
972
            # user/password/password_encoding should be defined, etc.
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
973
974
            # Note: the encoding below declares that the file itself is utf-8
975
            # encoded, but the values in the ConfigObj are always Unicode.
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
976
            self._config = ConfigObj(self._input, encoding='utf-8')
977
        except configobj.ConfigObjError, e:
978
            raise errors.ParseConfigError(e.errors, e.config.filename)
979
        return self._config
980
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
981
    def _save(self):
982
        """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.
983
        conf_dir = os.path.dirname(self._filename)
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
984
        ensure_config_dir_exists(conf_dir)
2900.2.26 by Vincent Ladeuil
Fix forgotten reference to _get_filename and duplicated code.
985
        self._get_config().write(file(self._filename, 'wb'))
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
986
987
    def _set_option(self, section_name, option_name, value):
988
        """Set an authentication configuration option"""
989
        conf = self._get_config()
990
        section = conf.get(section_name)
991
        if section is None:
992
            conf[section] = {}
993
            section = conf[section]
994
        section[option_name] = value
995
        self._save()
996
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
997
    def get_credentials(self, scheme, host, port=None, user=None, path=None):
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
998
        """Returns the matching credentials from authentication.conf file.
999
1000
        :param scheme: protocol
1001
1002
        :param host: the server address
1003
1004
        :param port: the associated port (optional)
1005
1006
        :param user: login (optional)
1007
1008
        :param path: the absolute path on the server (optional)
1009
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1010
        :return: A dict containing the matching credentials or None.
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1011
           This includes:
1012
           - name: the section name of the credentials in the
1013
             authentication.conf file,
1014
           - user: can't de different from the provided user if any,
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1015
           - password: the decoded password, could be None if the credential
1016
             defines only the user
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1017
           - verify_certificates: https specific, True if the server
1018
             certificate should be verified, False otherwise.
1019
        """
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1020
        credentials = None
1021
        for auth_def_name, auth_def in self._get_config().items():
3418.2.1 by Vincent Ladeuil
Fix #217650 by catching declarations outside sections.
1022
            if type(auth_def) is not configobj.Section:
1023
                raise ValueError("%s defined outside a section" % auth_def_name)
1024
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1025
            a_scheme, a_host, a_user, a_path = map(
1026
                auth_def.get, ['scheme', 'host', 'user', 'path'])
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1027
2900.2.5 by Vincent Ladeuil
ake ftp aware of authentication config.
1028
            try:
1029
                a_port = auth_def.as_int('port')
1030
            except KeyError:
1031
                a_port = None
2900.2.22 by Vincent Ladeuil
Polishing.
1032
            except ValueError:
1033
                raise ValueError("'port' not numeric in %s" % auth_def_name)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1034
            try:
1035
                a_verify_certificates = auth_def.as_bool('verify_certificates')
1036
            except KeyError:
1037
                a_verify_certificates = True
2900.2.22 by Vincent Ladeuil
Polishing.
1038
            except ValueError:
1039
                raise ValueError(
1040
                    "'verify_certificates' not boolean in %s" % auth_def_name)
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1041
1042
            # Attempt matching
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1043
            if a_scheme is not None and scheme != a_scheme:
1044
                continue
1045
            if a_host is not None:
1046
                if not (host == a_host
1047
                        or (a_host.startswith('.') and host.endswith(a_host))):
1048
                    continue
2900.2.4 by Vincent Ladeuil
Cosmetic changes.
1049
            if a_port is not None and port != a_port:
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1050
                continue
1051
            if (a_path is not None and path is not None
1052
                and not path.startswith(a_path)):
1053
                continue
1054
            if (a_user is not None and user is not None
1055
                and a_user != user):
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1056
                # Never contradict the caller about the user to be used
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1057
                continue
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1058
            if a_user is None:
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1059
                # Can't find a user
1060
                continue
2900.2.24 by Vincent Ladeuil
Review feedback.
1061
            credentials = dict(name=auth_def_name,
3418.4.2 by Vincent Ladeuil
Fix bug #199440 by taking into account that a section may not
1062
                               user=a_user,
1063
                               password=auth_def.get('password', None),
2900.2.24 by Vincent Ladeuil
Review feedback.
1064
                               verify_certificates=a_verify_certificates)
2900.2.22 by Vincent Ladeuil
Polishing.
1065
            self.decode_password(credentials,
1066
                                 auth_def.get('password_encoding', None))
2900.2.10 by Vincent Ladeuil
Add -Dauth handling.
1067
            if 'auth' in debug.debug_flags:
1068
                trace.mutter("Using authentication section: %r", auth_def_name)
2900.2.3 by Vincent Ladeuil
Credentials matching implementation.
1069
            break
1070
1071
        return credentials
1072
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1073
    def get_user(self, scheme, host, port=None,
1074
                 realm=None, path=None, prompt=None):
1075
        """Get a user from authentication file.
1076
1077
        :param scheme: protocol
1078
1079
        :param host: the server address
1080
1081
        :param port: the associated port (optional)
1082
1083
        :param realm: the realm sent by the server (optional)
1084
1085
        :param path: the absolute path on the server (optional)
1086
1087
        :return: The found user.
1088
        """
2900.2.16 by Vincent Ladeuil
Make hhtp proxy aware of AuthenticationConfig (for password).
1089
        credentials = self.get_credentials(scheme, host, port, user=None,
1090
                                           path=path)
2900.2.15 by Vincent Ladeuil
AuthenticationConfig can be queried for logins too (first step).
1091
        if credentials is not None:
1092
            user = credentials['user']
1093
        else:
1094
            user = None
1095
        return user
1096
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1097
    def get_password(self, scheme, host, user, port=None,
1098
                     realm=None, path=None, prompt=None):
1099
        """Get a password from authentication file or prompt the user for one.
1100
1101
        :param scheme: protocol
1102
1103
        :param host: the server address
1104
1105
        :param port: the associated port (optional)
1106
1107
        :param user: login
1108
1109
        :param realm: the realm sent by the server (optional)
1110
1111
        :param path: the absolute path on the server (optional)
1112
1113
        :return: The found password or the one entered by the user.
1114
        """
1115
        credentials = self.get_credentials(scheme, host, port, user, path)
1116
        if credentials is not None:
1117
            password = credentials['password']
3420.1.3 by Vincent Ladeuil
John's review feedback.
1118
            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.
1119
                trace.warning('password ignored in section [%s],'
1120
                              ' use an ssh agent instead'
1121
                              % credentials['name'])
1122
                password = None
2900.2.16 by Vincent Ladeuil
Make hhtp proxy aware of AuthenticationConfig (for password).
1123
        else:
1124
            password = None
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1125
        # 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).
1126
        if password is None:
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1127
            if prompt is None:
3420.1.2 by Vincent Ladeuil
Fix bug #203186 by ignoring passwords for ssh and warning user.
1128
                # Create a default prompt suitable for most cases
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1129
                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
1130
            # Special handling for optional fields in the prompt
1131
            if port is not None:
1132
                prompt_host = '%s:%d' % (host, port)
1133
            else:
1134
                prompt_host = host
2900.2.19 by Vincent Ladeuil
Mention proxy and https in the password prompts, with tests.
1135
            password = ui.ui_factory.get_password(prompt,
1136
                                                  host=prompt_host, user=user)
2900.2.12 by Vincent Ladeuil
Since all schemes query AuthenticationConfig then prompt user, make that
1137
        return password
1138
2900.2.22 by Vincent Ladeuil
Polishing.
1139
    def decode_password(self, credentials, encoding):
1140
        return credentials
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1141
3242.3.17 by Aaron Bentley
Whitespace cleanup
1142
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1143
class BzrDirConfig(object):
1144
1145
    def __init__(self, transport):
1146
        self._config = TransportConfig(transport, 'control.conf')
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1147
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1148
    def set_default_stack_on(self, value):
1149
        """Set the default stacking location.
1150
1151
        It may be set to a location, or None.
1152
1153
        This policy affects all branches contained by this bzrdir, except for
1154
        those under repositories.
1155
        """
1156
        if value is None:
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1157
            self._config.set_option('', 'default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1158
        else:
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1159
            self._config.set_option(value, 'default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1160
1161
    def get_default_stack_on(self):
1162
        """Return the default stacking location.
1163
1164
        This will either be a location, or None.
1165
1166
        This policy affects all branches contained by this bzrdir, except for
1167
        those under repositories.
1168
        """
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1169
        value = self._config.get_option('default_stack_on')
3242.3.11 by Aaron Bentley
Clean up BzrDirConfig usage
1170
        if value == '':
1171
            value = None
1172
        return value
1173
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1174
1175
class TransportConfig(object):
3242.1.5 by Aaron Bentley
Update per review comments
1176
    """A Config that reads/writes a config file on a Transport.
3242.1.4 by Aaron Bentley
Clean-up
1177
1178
    It is a low-level object that considers config data to be name/value pairs
1179
    that may be associated with a section.  Assigning meaning to the these
1180
    values is done at higher levels like TreeConfig.
1181
    """
3242.3.14 by Aaron Bentley
Make BzrDirConfig use TransportConfig
1182
1183
    def __init__(self, transport, filename):
1184
        self._transport = transport
1185
        self._filename = filename
1186
3242.1.1 by Aaron Bentley
Implement BzrDir configuration
1187
    def get_option(self, name, section=None, default=None):
1188
        """Return the value associated with a named option.
1189
1190
        :param name: The name of the value
1191
        :param section: The section the option is in (if any)
1192
        :param default: The value to return if the value is not set
1193
        :return: The value or default value
1194
        """
1195
        configobj = self._get_configobj()
1196
        if section is None:
1197
            section_obj = configobj
1198
        else:
1199
            try:
1200
                section_obj = configobj[section]
1201
            except KeyError:
1202
                return default
1203
        return section_obj.get(name, default)
1204
1205
    def set_option(self, value, name, section=None):
1206
        """Set the value associated with a named option.
1207
1208
        :param value: The value to set
1209
        :param name: The name of the value to set
1210
        :param section: The section the option is in (if any)
1211
        """
1212
        configobj = self._get_configobj()
1213
        if section is None:
1214
            configobj[name] = value
1215
        else:
1216
            configobj.setdefault(section, {})[name] = value
1217
        self._set_configobj(configobj)
1218
1219
    def _get_configobj(self):
1220
        try:
1221
            return ConfigObj(self._transport.get(self._filename),
1222
                             encoding='utf-8')
1223
        except errors.NoSuchFile:
1224
            return ConfigObj(encoding='utf-8')
1225
1226
    def _set_configobj(self, configobj):
1227
        out_file = StringIO()
1228
        configobj.write(out_file)
1229
        out_file.seek(0)
1230
        self._transport.put_file(self._filename, out_file)