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