~bzr-pqm/bzr/bzr.dev

1442.1.1 by Robert Collins
move config_dir into bzrlib.config
1
# Copyright (C) 2005 by Canonical Ltd
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
1442.1.20 by Robert Collins
add some documentation on options
18
"""Configuration that affects the behaviour of Bazaar.
19
20
Currently this configuration resides in ~/.bazaar/bazaar.conf
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
21
and ~/.bazaar/locations.conf, which is written to by bzr.
1442.1.20 by Robert Collins
add some documentation on options
22
1461 by Robert Collins
Typo in config.py (Thanks Fabbione)
23
In bazaar.conf the following options may be set:
1442.1.20 by Robert Collins
add some documentation on options
24
[DEFAULT]
25
editor=name-of-program
26
email=Your Name <your@email.address>
27
check_signatures=require|ignore|check-available(default)
28
create_signatures=always|never|when-required(default)
1442.1.56 by Robert Collins
gpg_signing_command configuration item
29
gpg_signing_command=name-of-program
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
30
log_format=name-of-format
1442.1.20 by Robert Collins
add some documentation on options
31
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
32
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
33
Wildcards may be used - * and ? as normal in shell completion. Options
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
34
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
35
setting.
36
[/home/robertc/source]
37
recurse=False|True(default)
38
email= as above
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
39
check_signatures= as above 
1442.1.20 by Robert Collins
add some documentation on options
40
create_signatures= as above.
41
42
explanation of options
43
----------------------
44
editor - this option sets the pop up editor to use during commits.
45
email - this option sets the user id bzr will use when committing.
46
check_signatures - this option controls whether bzr will require good gpg
47
                   signatures, ignore them, or check them if they are 
48
                   present.
49
create_signatures - this option controls whether bzr will always create 
50
                    gpg signatures, never create them, or create them if the
51
                    branch is configured to require them.
1887.2.1 by Adeodato Simó
Fix some typos and grammar issues.
52
log_format - this option sets the default log format.  Possible values are
53
             long, short, line, or a plugin can register new formats.
1553.6.2 by Erik Bågfors
documentation and NEWS
54
55
In bazaar.conf you can also define aliases in the ALIASES sections, example
56
57
[ALIASES]
58
lastlog=log --line -r-10..-1
59
ll=log --line -r-10..-1
60
h=help
61
up=pull
1442.1.20 by Robert Collins
add some documentation on options
62
"""
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
63
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
64
import os
65
import sys
1474 by Robert Collins
Merge from Aaron Bentley.
66
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
67
from bzrlib.lazy_import import lazy_import
68
lazy_import(globals(), """
1474 by Robert Collins
Merge from Aaron Bentley.
69
import errno
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
70
from fnmatch import fnmatch
71
import re
72
from StringIO 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.
73
74
import bzrlib
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
75
from bzrlib import (
76
    errors,
77
    osutils,
78
    urlutils,
79
    )
80
import bzrlib.util.configobj.configobj as configobj
81
""")
82
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
83
from bzrlib.trace import mutter, warning
84
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
85
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
86
CHECK_IF_POSSIBLE=0
87
CHECK_ALWAYS=1
88
CHECK_NEVER=2
89
90
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
91
SIGN_WHEN_REQUIRED=0
92
SIGN_ALWAYS=1
93
SIGN_NEVER=2
94
95
1474 by Robert Collins
Merge from Aaron Bentley.
96
class ConfigObj(configobj.ConfigObj):
97
98
    def get_bool(self, section, key):
1556.2.2 by Aaron Bentley
Fixed get_bool
99
        return self[section].as_bool(key)
1474 by Robert Collins
Merge from Aaron Bentley.
100
101
    def get_value(self, section, name):
102
        # Try [] for the old DEFAULT section.
103
        if section == "DEFAULT":
104
            try:
105
                return self[name]
106
            except KeyError:
107
                pass
108
        return self[section][name]
109
110
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
111
class Config(object):
112
    """A configuration policy - what username, editor, gpg needs etc."""
113
114
    def get_editor(self):
115
        """Get the users pop up editor."""
116
        raise NotImplementedError
117
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
118
    def _get_signature_checking(self):
119
        """Template method to override signature checking policy."""
120
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
121
    def _get_signing_policy(self):
122
        """Template method to override signature creation policy."""
123
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
124
    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.
125
        """Template method to provide a user option."""
126
        return None
127
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
128
    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.
129
        """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()
130
        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.
131
1442.1.56 by Robert Collins
gpg_signing_command configuration item
132
    def gpg_signing_command(self):
133
        """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.
134
        result = self._gpg_signing_command()
135
        if result is None:
136
            result = "gpg"
137
        return result
138
139
    def _gpg_signing_command(self):
140
        """See gpg_signing_command()."""
141
        return None
1442.1.56 by Robert Collins
gpg_signing_command configuration item
142
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
143
    def log_format(self):
144
        """What log format should be used"""
145
        result = self._log_format()
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
146
        if result is None:
147
            result = "long"
148
        return result
149
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
150
    def _log_format(self):
151
        """See log_format()."""
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
152
        return None
153
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
154
    def __init__(self):
155
        super(Config, self).__init__()
156
1472 by Robert Collins
post commit hook, first pass implementation
157
    def post_commit(self):
158
        """An ordered list of python functions to call.
159
160
        Each function takes branch, rev_id as parameters.
161
        """
162
        return self._post_commit()
163
164
    def _post_commit(self):
165
        """See Config.post_commit."""
166
        return None
167
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
168
    def user_email(self):
169
        """Return just the email component of a username."""
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
170
        return extract_email_address(self.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
171
172
    def username(self):
173
        """Return email-style username.
174
    
175
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
176
        
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
177
        $BZR_EMAIL can be set to override this (as well as the
178
        deprecated $BZREMAIL), then
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
179
        the concrete policy type is checked, and finally
1185.37.2 by Jamie Wilkinson
Fix a typo and grammar in Config.username() docstring.
180
        $EMAIL is examined.
181
        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
182
        created.
183
    
184
        TODO: Check it's reasonably well-formed.
185
        """
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
186
        v = os.environ.get('BZR_EMAIL')
187
        if v:
188
            return v.decode(bzrlib.user_encoding)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
189
        v = os.environ.get('BZREMAIL')
190
        if v:
1861.4.1 by Matthieu Moy
BZREMAIL renamed to BZR_EMAIL.
191
            warning('BZREMAIL is deprecated in favor of BZR_EMAIL. Please update your configuration.')
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
192
            return v.decode(bzrlib.user_encoding)
193
    
194
        v = self._get_user_id()
195
        if v:
196
            return v
197
        
198
        v = os.environ.get('EMAIL')
199
        if v:
200
            return v.decode(bzrlib.user_encoding)
201
202
        name, email = _auto_user_id()
203
        if name:
204
            return '%s <%s>' % (name, email)
205
        else:
206
            return email
207
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
208
    def signature_checking(self):
209
        """What is the current policy for signature checking?."""
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
210
        policy = self._get_signature_checking()
211
        if policy is not None:
212
            return policy
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
213
        return CHECK_IF_POSSIBLE
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
214
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
215
    def signing_policy(self):
216
        """What is the current policy for signature checking?."""
217
        policy = self._get_signing_policy()
218
        if policy is not None:
219
            return policy
220
        return SIGN_WHEN_REQUIRED
221
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
222
    def signature_needed(self):
223
        """Is a signature needed when committing ?."""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
224
        policy = self._get_signing_policy()
225
        if policy is None:
226
            policy = self._get_signature_checking()
227
            if policy is not None:
228
                warning("Please use create_signatures, not check_signatures "
229
                        "to set signing policy.")
230
            if policy == CHECK_ALWAYS:
231
                return True
232
        elif policy == SIGN_ALWAYS:
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
233
            return True
234
        return False
235
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
236
    def get_alias(self, value):
237
        return self._get_alias(value)
238
239
    def _get_alias(self, value):
240
        pass
241
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
242
    def get_nickname(self):
243
        return self._get_nickname()
244
245
    def _get_nickname(self):
246
        return None
247
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
248
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
249
class IniBasedConfig(Config):
250
    """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
251
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
252
    def _get_parser(self, file=None):
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
253
        if self._parser is not None:
254
            return self._parser
1185.12.49 by Aaron Bentley
Switched to ConfigObj
255
        if file is None:
256
            input = self._get_filename()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
257
        else:
1185.12.49 by Aaron Bentley
Switched to ConfigObj
258
            input = file
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
259
        try:
1551.2.20 by Aaron Bentley
Treated config files as utf-8
260
            self._parser = ConfigObj(input, encoding='utf-8')
1474 by Robert Collins
Merge from Aaron Bentley.
261
        except configobj.ConfigObjError, e:
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
262
            raise errors.ParseConfigError(e.errors, e.config.filename)
1185.12.49 by Aaron Bentley
Switched to ConfigObj
263
        return self._parser
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
264
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
265
    def _get_matching_sections(self):
266
        """Return an ordered list of (section_name, extra_path) pairs.
267
268
        If the section contains inherited configuration, extra_path is
269
        a string containing the additional path components.
270
        """
271
        section = self._get_section()
272
        if section is not None:
273
            return [(section, '')]
274
        else:
275
            return []
276
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
277
    def _get_section(self):
278
        """Override this to define the section used by the config."""
279
        return "DEFAULT"
280
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
281
    def _get_signature_checking(self):
282
        """See Config._get_signature_checking."""
1474 by Robert Collins
Merge from Aaron Bentley.
283
        policy = self._get_user_option('check_signatures')
284
        if policy:
285
            return self._string_to_signature_policy(policy)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
286
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
287
    def _get_signing_policy(self):
1773.4.3 by Martin Pool
[merge] bzr.dev
288
        """See Config._get_signing_policy"""
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
289
        policy = self._get_user_option('create_signatures')
290
        if policy:
291
            return self._string_to_signing_policy(policy)
292
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
293
    def _get_user_id(self):
294
        """Get the user id from the 'email' key in the current section."""
1474 by Robert Collins
Merge from Aaron Bentley.
295
        return self._get_user_option('email')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
296
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
297
    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.
298
        """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
299
        for (section, extra_path) in self._get_matching_sections():
300
            try:
301
                return self._get_parser().get_value(section, option_name)
302
            except KeyError:
303
                pass
304
        else:
1993.3.1 by James Henstridge
first go at making location config lookup recursive
305
            return None
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
306
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
307
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
308
        """See Config.gpg_signing_command."""
1472 by Robert Collins
post commit hook, first pass implementation
309
        return self._get_user_option('gpg_signing_command')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
310
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
311
    def _log_format(self):
312
        """See Config.log_format."""
313
        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
314
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
315
    def __init__(self, get_filename):
316
        super(IniBasedConfig, self).__init__()
317
        self._get_filename = get_filename
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
318
        self._parser = None
1472 by Robert Collins
post commit hook, first pass implementation
319
        
320
    def _post_commit(self):
321
        """See Config.post_commit."""
322
        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
323
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
324
    def _string_to_signature_policy(self, signature_string):
325
        """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
326
        if signature_string.lower() == 'check-available':
327
            return CHECK_IF_POSSIBLE
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
328
        if signature_string.lower() == 'ignore':
329
            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
330
        if signature_string.lower() == 'require':
331
            return CHECK_ALWAYS
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
332
        raise errors.BzrError("Invalid signatures policy '%s'"
333
                              % signature_string)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
334
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
335
    def _string_to_signing_policy(self, signature_string):
336
        """Convert a string to a signing policy."""
337
        if signature_string.lower() == 'when-required':
338
            return SIGN_WHEN_REQUIRED
339
        if signature_string.lower() == 'never':
340
            return SIGN_NEVER
341
        if signature_string.lower() == 'always':
342
            return SIGN_ALWAYS
343
        raise errors.BzrError("Invalid signing policy '%s'"
344
                              % signature_string)
345
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
346
    def _get_alias(self, value):
347
        try:
348
            return self._get_parser().get_value("ALIASES", 
349
                                                value)
350
        except KeyError:
351
            pass
352
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
353
    def _get_nickname(self):
354
        return self.get_user_option('nickname')
355
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
356
357
class GlobalConfig(IniBasedConfig):
358
    """The configuration that should be used for a specific location."""
359
360
    def get_editor(self):
1474 by Robert Collins
Merge from Aaron Bentley.
361
        return self._get_user_option('editor')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
362
363
    def __init__(self):
364
        super(GlobalConfig, self).__init__(config_filename)
365
1816.2.1 by Robey Pointer
add set_user_option to GlobalConfig, and make /etc/passwd username lookup try harder with encodings
366
    def set_user_option(self, option, value):
367
        """Save option and its value in the configuration."""
368
        # FIXME: RBC 20051029 This should refresh the parser and also take a
369
        # file lock on bazaar.conf.
370
        conf_dir = os.path.dirname(self._get_filename())
371
        ensure_config_dir_exists(conf_dir)
372
        if 'DEFAULT' not in self._get_parser():
373
            self._get_parser()['DEFAULT'] = {}
374
        self._get_parser()['DEFAULT'][option] = value
375
        f = open(self._get_filename(), 'wb')
376
        self._get_parser().write(f)
377
        f.close()
378
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
379
380
class LocationConfig(IniBasedConfig):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
381
    """A configuration object that gives the policy for a location."""
382
383
    def __init__(self, location):
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
384
        name_generator = locations_config_filename
385
        if (not os.path.exists(name_generator()) and 
386
                os.path.exists(branches_config_filename())):
1830.2.1 by John Arbash Meinel
Make it clearer what config file needs to be renamed.
387
            if sys.platform == 'win32':
388
                warning('Please rename %s to %s' 
389
                         % (branches_config_filename(),
390
                            locations_config_filename()))
391
            else:
392
                warning('Please rename ~/.bazaar/branches.conf'
393
                        ' to ~/.bazaar/locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
394
            name_generator = branches_config_filename
395
        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)
396
        # local file locations are looked up by local path, rather than
397
        # by file url. This is because the config file is a user
398
        # file, and we would rather not expose the user to file urls.
399
        if location.startswith('file://'):
400
            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
401
        self.location = location
402
1993.3.1 by James Henstridge
first go at making location config lookup recursive
403
    def _get_matching_sections(self):
404
        """Return an ordered list of section names matching this location."""
1185.12.49 by Aaron Bentley
Switched to ConfigObj
405
        sections = self._get_parser()
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
406
        location_names = self.location.split('/')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
407
        if self.location.endswith('/'):
408
            del location_names[-1]
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
409
        matches=[]
1442.1.10 by Robert Collins
explicit over glob test passes
410
        for section in sections:
1878.1.1 by John Arbash Meinel
Entries in locations.conf should prefer local paths if available (bug #53653)
411
            # location is a local path if possible, so we need
412
            # to convert 'file://' urls to local paths if necessary.
413
            # This also avoids having file:///path be a more exact
414
            # match than '/path'.
415
            if section.startswith('file://'):
416
                section_path = urlutils.local_path_from_url(section)
417
            else:
418
                section_path = section
419
            section_names = section_path.split('/')
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
420
            if section.endswith('/'):
421
                del section_names[-1]
422
            names = zip(location_names, section_names)
423
            matched = True
424
            for name in names:
425
                if not fnmatch(name[0], name[1]):
426
                    matched = False
427
                    break
428
            if not matched:
429
                continue
430
            # so, for the common prefix they matched.
431
            # if section is longer, no match.
432
            if len(section_names) > len(location_names):
433
                continue
1993.3.5 by James Henstridge
add back recurse=False option to config file
434
            # if path is longer, and recurse is not true, no match
435
            if len(section_names) < len(location_names):
436
                try:
437
                    if not self._get_parser()[section].as_bool('recurse'):
438
                        continue
439
                except KeyError:
440
                    pass
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
441
            matches.append((len(section_names), section,
442
                            '/'.join(location_names[len(section_names):])))
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
443
        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
444
        sections = []
445
        for (length, section, extra_path) in matches:
446
            sections.append((section, extra_path))
447
            # should we stop looking for parent configs here?
1993.3.1 by James Henstridge
first go at making location config lookup recursive
448
            try:
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
449
                if self._get_parser()[section].as_bool('ignore_parents'):
450
                    break
1993.3.1 by James Henstridge
first go at making location config lookup recursive
451
            except KeyError:
452
                pass
1993.3.3 by James Henstridge
make _get_matching_sections() return (section, extra_path) tuples, and adjust other code to match
453
        return sections
1442.1.9 by Robert Collins
exact section test passes
454
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
455
    def set_user_option(self, option, value):
456
        """Save option and its value in the configuration."""
457
        # FIXME: RBC 20051029 This should refresh the parser and also take a
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
458
        # file lock on locations.conf.
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
459
        conf_dir = os.path.dirname(self._get_filename())
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
460
        ensure_config_dir_exists(conf_dir)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
461
        location = self.location
462
        if location.endswith('/'):
463
            location = location[:-1]
464
        if (not location in self._get_parser() and
465
            not location + '/' in self._get_parser()):
466
            self._get_parser()[location]={}
467
        elif location + '/' in self._get_parser():
468
            location = location + '/'
469
        self._get_parser()[location][option]=value
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
470
        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.
471
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
472
473
class BranchConfig(Config):
474
    """A configuration object giving the policy for a branch."""
475
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
476
    def _get_branch_data_config(self):
477
        if self._branch_data_config is None:
478
            self._branch_data_config = TreeConfig(self.branch)
479
        return self._branch_data_config
480
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
481
    def _get_location_config(self):
482
        if self._location_config is None:
483
            self._location_config = LocationConfig(self.branch.base)
484
        return self._location_config
485
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
486
    def _get_global_config(self):
487
        if self._global_config is None:
488
            self._global_config = GlobalConfig()
489
        return self._global_config
490
491
    def _get_best_value(self, option_name):
492
        """This returns a user option from local, tree or global config.
493
494
        They are tried in that order.  Use get_safe_value if trusted values
495
        are necessary.
496
        """
497
        for source in self.option_sources:
498
            value = getattr(source(), option_name)()
499
            if value is not None:
500
                return value
501
        return None
502
503
    def _get_safe_value(self, option_name):
504
        """This variant of get_best_value never returns untrusted values.
505
        
506
        It does not return values from the branch data, because the branch may
507
        not be controlled by the user.
508
509
        We may wish to allow locations.conf to control whether branches are
510
        trusted in the future.
511
        """
512
        for source in (self._get_location_config, self._get_global_config):
513
            value = getattr(source(), option_name)()
514
            if value is not None:
515
                return value
516
        return None
517
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
518
    def _get_user_id(self):
519
        """Return the full user id for the branch.
520
    
521
        e.g. "John Hacker <jhacker@foo.org>"
522
        This is looked up in the email controlfile for the branch.
523
        """
524
        try:
1185.65.29 by Robert Collins
Implement final review suggestions.
525
            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
526
                    .read()
527
                    .decode(bzrlib.user_encoding)
528
                    .rstrip("\r\n"))
529
        except errors.NoSuchFile, e:
530
            pass
531
        
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
532
        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
533
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
534
    def _get_signature_checking(self):
535
        """See Config._get_signature_checking."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
536
        return self._get_best_value('_get_signature_checking')
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
537
1770.2.1 by Aaron Bentley
Use create_signature for signing policy, deprecate check_signatures for this
538
    def _get_signing_policy(self):
539
        """See Config._get_signing_policy."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
540
        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
541
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
542
    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.
543
        """See Config._get_user_option."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
544
        for source in self.option_sources:
1993.3.6 by James Henstridge
get rid of the recurse argument to get_user_option()
545
            value = source()._get_user_option(option_name)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
546
            if value is not None:
547
                return value
548
        return None
549
550
    def set_user_option(self, name, value, local=False):
551
        if local is True:
552
            self._get_location_config().set_user_option(name, value)
553
        else:
1770.2.6 by Aaron Bentley
Ensure branch.conf works properly
554
            self._get_branch_data_config().set_option(value, name)
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
555
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
556
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
557
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
558
        """See Config.gpg_signing_command."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
559
        return self._get_safe_value('_gpg_signing_command')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
560
        
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
561
    def __init__(self, branch):
562
        super(BranchConfig, self).__init__()
563
        self._location_config = None
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
564
        self._branch_data_config = None
565
        self._global_config = None
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
566
        self.branch = branch
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
567
        self.option_sources = (self._get_location_config, 
568
                               self._get_branch_data_config,
569
                               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.
570
1472 by Robert Collins
post commit hook, first pass implementation
571
    def _post_commit(self):
572
        """See Config.post_commit."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
573
        return self._get_safe_value('_post_commit')
1472 by Robert Collins
post commit hook, first pass implementation
574
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
575
    def _get_nickname(self):
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
576
        value = self._get_explicit_nickname()
1770.2.7 by Aaron Bentley
Set/get nickname using BranchConfig
577
        if value is not None:
578
            return value
579
        return self.branch.base.split('/')[-2]
580
1824.1.1 by Robert Collins
Add BranchConfig.has_explicit_nickname call.
581
    def has_explicit_nickname(self):
582
        """Return true if a nickname has been explicitly assigned."""
583
        return self._get_explicit_nickname() is not None
584
585
    def _get_explicit_nickname(self):
586
        return self._get_best_value('_get_nickname')
587
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
588
    def _log_format(self):
589
        """See Config.log_format."""
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
590
        return self._get_best_value('_log_format')
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
591
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
592
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
593
def ensure_config_dir_exists(path=None):
594
    """Make sure a configuration directory exists.
595
    This makes sure that the directory exists.
596
    On windows, since configuration directories are 2 levels deep,
597
    it makes sure both the directory and the parent directory exists.
598
    """
599
    if path is None:
600
        path = config_dir()
601
    if not os.path.isdir(path):
602
        if sys.platform == 'win32':
603
            parent_dir = os.path.dirname(path)
604
            if not os.path.isdir(parent_dir):
605
                mutter('creating config parent directory: %r', parent_dir)
606
            os.mkdir(parent_dir)
607
        mutter('creating config directory: %r', path)
608
        os.mkdir(path)
609
1532 by Robert Collins
Merge in John Meinels integration branch.
610
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
611
def config_dir():
612
    """Return per-user configuration directory.
613
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
614
    By default this is ~/.bazaar/
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
615
    
616
    TODO: Global option --config-dir to override this.
617
    """
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
618
    base = os.environ.get('BZR_HOME', None)
619
    if sys.platform == 'win32':
620
        if base is None:
621
            base = os.environ.get('APPDATA', None)
622
        if base is None:
623
            base = os.environ.get('HOME', None)
624
        if base is None:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
625
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
626
        return osutils.pathjoin(base, 'bazaar', '2.0')
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
627
    else:
628
        # cygwin, linux, and darwin all have a $HOME directory
629
        if base is None:
630
            base = os.path.expanduser("~")
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
631
        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 \
632
633
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
634
def config_filename():
635
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
636
    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.
637
638
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
639
def branches_config_filename():
640
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
641
    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.
642
1830.2.1 by John Arbash Meinel
Make it clearer what config file needs to be renamed.
643
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
644
def locations_config_filename():
645
    """Return per-user configuration ini file filename."""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
646
    return osutils.pathjoin(config_dir(), 'locations.conf')
1770.2.2 by Aaron Bentley
Rename branches.conf to locations.conf
647
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
648
1836.1.6 by John Arbash Meinel
Creating a helper function for getting the user ignore filename
649
def user_ignore_config_filename():
650
    """Return the user default ignore filename"""
1996.3.31 by John Arbash Meinel
Make bzrlib.config use lazy importing
651
    return osutils.pathjoin(config_dir(), 'ignore')
1836.1.6 by John Arbash Meinel
Creating a helper function for getting the user ignore filename
652
653
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
654
def _auto_user_id():
655
    """Calculate automatic user identification.
656
657
    Returns (realname, email).
658
659
    Only used when none is set in the environment or the id file.
660
661
    This previously used the FQDN as the default domain, but that can
662
    be very slow on machines where DNS is broken.  So now we simply
663
    use the hostname.
664
    """
665
    import socket
666
667
    # XXX: Any good way to get real user name on win32?
668
669
    try:
670
        import pwd
671
        uid = os.getuid()
672
        w = pwd.getpwuid(uid)
1553.4.5 by Michael Ellerman
Produce an intelligible error if the user's /etc/passwd is not encoded in
673
1816.2.1 by Robey Pointer
add set_user_option to GlobalConfig, and make /etc/passwd username lookup try harder with encodings
674
        # we try utf-8 first, because on many variants (like Linux),
675
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
676
        # false positives.  (many users will have their user encoding set to
677
        # latin-1, which cannot raise UnicodeError.)
678
        try:
679
            gecos = w.pw_gecos.decode('utf-8')
680
            encoding = 'utf-8'
681
        except UnicodeError:
682
            try:
683
                gecos = w.pw_gecos.decode(bzrlib.user_encoding)
684
                encoding = bzrlib.user_encoding
685
            except UnicodeError:
686
                raise errors.BzrCommandError('Unable to determine your name.  '
687
                   'Use "bzr whoami" to set it.')
688
        try:
689
            username = w.pw_name.decode(encoding)
690
        except UnicodeError:
691
            raise errors.BzrCommandError('Unable to determine your name.  '
692
                '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
693
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
694
        comma = gecos.find(',')
695
        if comma == -1:
696
            realname = gecos
697
        else:
698
            realname = gecos[:comma]
699
        if not realname:
700
            realname = username
701
702
    except ImportError:
703
        import getpass
1553.4.5 by Michael Ellerman
Produce an intelligible error if the user's /etc/passwd is not encoded in
704
        try:
705
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
706
        except UnicodeDecodeError:
707
            raise errors.BzrError("Can't decode username as %s." % \
708
                    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.
709
710
    return realname, (username + '@' + socket.gethostname())
711
712
1185.16.52 by Martin Pool
- add extract_email_address
713
def extract_email_address(e):
714
    """Return just the address part of an email string.
715
    
716
    That is just the user@domain part, nothing else. 
717
    This part is required to contain only ascii characters.
718
    If it can't be extracted, raises an error.
719
    
720
    >>> extract_email_address('Jane Tester <jane@test.com>')
721
    "jane@test.com"
722
    """
723
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
724
    if not m:
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
725
        raise errors.NoEmailInUsername(e)
1185.16.52 by Martin Pool
- add extract_email_address
726
    return m.group(0)
1185.35.11 by Aaron Bentley
Added support for branch nicks
727
1185.85.30 by John Arbash Meinel
Fixing 'bzr push' exposed that IniBasedConfig didn't handle unicode.
728
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
729
class TreeConfig(IniBasedConfig):
1185.35.11 by Aaron Bentley
Added support for branch nicks
730
    """Branch configuration data associated with its contents, not location"""
731
    def __init__(self, branch):
732
        self.branch = branch
733
1770.2.5 by Aaron Bentley
Integrate branch.conf into BranchConfig
734
    def _get_parser(self, file=None):
735
        if file is not None:
736
            return IniBasedConfig._get_parser(file)
737
        return self._get_config()
738
1185.35.11 by Aaron Bentley
Added support for branch nicks
739
    def _get_config(self):
740
        try:
1556.2.1 by Aaron Bentley
Switched to ConfigObj 4.2.0
741
            obj = ConfigObj(self.branch.control_files.get('branch.conf'), 
742
                            encoding='utf-8')
1185.35.11 by Aaron Bentley
Added support for branch nicks
743
        except errors.NoSuchFile:
1556.2.1 by Aaron Bentley
Switched to ConfigObj 4.2.0
744
            obj = ConfigObj(encoding='utf=8')
1185.35.11 by Aaron Bentley
Added support for branch nicks
745
        return obj
746
747
    def get_option(self, name, section=None, default=None):
748
        self.branch.lock_read()
749
        try:
750
            obj = self._get_config()
751
            try:
752
                if section is not None:
753
                    obj[section]
754
                result = obj[name]
755
            except KeyError:
756
                result = default
757
        finally:
758
            self.branch.unlock()
759
        return result
760
761
    def set_option(self, value, name, section=None):
762
        """Set a per-branch configuration option"""
763
        self.branch.lock_write()
764
        try:
765
            cfg_obj = self._get_config()
766
            if section is None:
767
                obj = cfg_obj
768
            else:
769
                try:
770
                    obj = cfg_obj[section]
771
                except KeyError:
772
                    cfg_obj[section] = {}
773
                    obj = cfg_obj[section]
774
            obj[name] = value
1556.2.1 by Aaron Bentley
Switched to ConfigObj 4.2.0
775
            out_file = StringIO()
776
            cfg_obj.write(out_file)
1185.35.11 by Aaron Bentley
Added support for branch nicks
777
            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.
778
            self.branch.control_files.put('branch.conf', out_file)
1185.35.11 by Aaron Bentley
Added support for branch nicks
779
        finally:
780
            self.branch.unlock()