/brz/remove-bazaar

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