~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
21
and ~/.bazaar/branches.conf, which is written to by bzr.
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
32
in branches.conf, you specify the url of a branch and options for it.
33
Wildcards may be used - * and ? as normal in shell completion. Options
34
set in both bazaar.conf and branches.conf are overriden by the branches.conf
35
setting.
36
[/home/robertc/source]
37
recurse=False|True(default)
38
email= as above
39
check_signatures= as abive 
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.
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
52
                    NB: This option is planned, but not implemented yet.
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
53
log_format - This options set the default log format.  Options are long, 
54
             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
1474 by Robert Collins
Merge from Aaron Bentley.
65
66
import errno
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
67
import os
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
68
import sys
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
69
from fnmatch import fnmatch
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
70
import re
71
72
import bzrlib
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
73
import bzrlib.errors as errors
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 \
74
from bzrlib.osutils import pathjoin
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
75
from bzrlib.trace import mutter
1474 by Robert Collins
Merge from Aaron Bentley.
76
import bzrlib.util.configobj.configobj as configobj
1185.35.11 by Aaron Bentley
Added support for branch nicks
77
from StringIO import StringIO
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
78
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
79
CHECK_IF_POSSIBLE=0
80
CHECK_ALWAYS=1
81
CHECK_NEVER=2
82
83
1474 by Robert Collins
Merge from Aaron Bentley.
84
class ConfigObj(configobj.ConfigObj):
85
86
    def get_bool(self, section, key):
1556.2.2 by Aaron Bentley
Fixed get_bool
87
        return self[section].as_bool(key)
1474 by Robert Collins
Merge from Aaron Bentley.
88
89
    def get_value(self, section, name):
90
        # Try [] for the old DEFAULT section.
91
        if section == "DEFAULT":
92
            try:
93
                return self[name]
94
            except KeyError:
95
                pass
96
        return self[section][name]
97
98
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
99
class Config(object):
100
    """A configuration policy - what username, editor, gpg needs etc."""
101
102
    def get_editor(self):
103
        """Get the users pop up editor."""
104
        raise NotImplementedError
105
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
106
    def _get_signature_checking(self):
107
        """Template method to override signature checking policy."""
108
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
109
    def _get_user_option(self, option_name):
110
        """Template method to provide a user option."""
111
        return None
112
113
    def get_user_option(self, option_name):
114
        """Get a generic option - no special process, no default."""
115
        return self._get_user_option(option_name)
116
1442.1.56 by Robert Collins
gpg_signing_command configuration item
117
    def gpg_signing_command(self):
118
        """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.
119
        result = self._gpg_signing_command()
120
        if result is None:
121
            result = "gpg"
122
        return result
123
124
    def _gpg_signing_command(self):
125
        """See gpg_signing_command()."""
126
        return None
1442.1.56 by Robert Collins
gpg_signing_command configuration item
127
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
128
    def log_format(self):
129
        """What log format should be used"""
130
        result = self._log_format()
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
131
        if result is None:
132
            result = "long"
133
        return result
134
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
135
    def _log_format(self):
136
        """See log_format()."""
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
137
        return None
138
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
139
    def __init__(self):
140
        super(Config, self).__init__()
141
1472 by Robert Collins
post commit hook, first pass implementation
142
    def post_commit(self):
143
        """An ordered list of python functions to call.
144
145
        Each function takes branch, rev_id as parameters.
146
        """
147
        return self._post_commit()
148
149
    def _post_commit(self):
150
        """See Config.post_commit."""
151
        return None
152
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
153
    def user_email(self):
154
        """Return just the email component of a username."""
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
155
        return extract_email_address(self.username())
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
156
157
    def username(self):
158
        """Return email-style username.
159
    
160
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
161
        
162
        $BZREMAIL can be set to override this, then
163
        the concrete policy type is checked, and finally
1185.37.2 by Jamie Wilkinson
Fix a typo and grammar in Config.username() docstring.
164
        $EMAIL is examined.
165
        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
166
        created.
167
    
168
        TODO: Check it's reasonably well-formed.
169
        """
170
        v = os.environ.get('BZREMAIL')
171
        if v:
172
            return v.decode(bzrlib.user_encoding)
173
    
174
        v = self._get_user_id()
175
        if v:
176
            return v
177
        
178
        v = os.environ.get('EMAIL')
179
        if v:
180
            return v.decode(bzrlib.user_encoding)
181
182
        name, email = _auto_user_id()
183
        if name:
184
            return '%s <%s>' % (name, email)
185
        else:
186
            return email
187
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
188
    def signature_checking(self):
189
        """What is the current policy for signature checking?."""
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
190
        policy = self._get_signature_checking()
191
        if policy is not None:
192
            return policy
1442.1.14 by Robert Collins
Create a default signature checking policy of CHECK_IF_POSSIBLE
193
        return CHECK_IF_POSSIBLE
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
194
1442.1.21 by Robert Collins
create signature_needed() call for commit to trigger creating signatures
195
    def signature_needed(self):
196
        """Is a signature needed when committing ?."""
197
        policy = self._get_signature_checking()
198
        if policy == CHECK_ALWAYS:
199
            return True
200
        return False
201
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
202
    def get_alias(self, value):
203
        return self._get_alias(value)
204
205
    def _get_alias(self, value):
206
        pass
207
1442.1.15 by Robert Collins
make getting the signature checking policy a template method
208
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
209
class IniBasedConfig(Config):
210
    """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
211
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
212
    def _get_parser(self, file=None):
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
213
        if self._parser is not None:
214
            return self._parser
1185.12.49 by Aaron Bentley
Switched to ConfigObj
215
        if file is None:
216
            input = self._get_filename()
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
217
        else:
1185.12.49 by Aaron Bentley
Switched to ConfigObj
218
            input = file
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
219
        try:
1551.2.20 by Aaron Bentley
Treated config files as utf-8
220
            self._parser = ConfigObj(input, encoding='utf-8')
1474 by Robert Collins
Merge from Aaron Bentley.
221
        except configobj.ConfigObjError, e:
1185.12.51 by Aaron Bentley
Allowed second call of _get_parser() to not require a file
222
            raise errors.ParseConfigError(e.errors, e.config.filename)
1185.12.49 by Aaron Bentley
Switched to ConfigObj
223
        return self._parser
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
224
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
225
    def _get_section(self):
226
        """Override this to define the section used by the config."""
227
        return "DEFAULT"
228
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
229
    def _get_signature_checking(self):
230
        """See Config._get_signature_checking."""
1474 by Robert Collins
Merge from Aaron Bentley.
231
        policy = self._get_user_option('check_signatures')
232
        if policy:
233
            return self._string_to_signature_policy(policy)
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
234
235
    def _get_user_id(self):
236
        """Get the user id from the 'email' key in the current section."""
1474 by Robert Collins
Merge from Aaron Bentley.
237
        return self._get_user_option('email')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
238
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
239
    def _get_user_option(self, option_name):
240
        """See Config._get_user_option."""
1185.12.53 by Aaron Bentley
Merged more from Robert
241
        try:
1474 by Robert Collins
Merge from Aaron Bentley.
242
            return self._get_parser().get_value(self._get_section(),
243
                                                option_name)
1185.12.53 by Aaron Bentley
Merged more from Robert
244
        except KeyError:
245
            pass
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
246
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
247
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
248
        """See Config.gpg_signing_command."""
1472 by Robert Collins
post commit hook, first pass implementation
249
        return self._get_user_option('gpg_signing_command')
1442.1.56 by Robert Collins
gpg_signing_command configuration item
250
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
251
    def _log_format(self):
252
        """See Config.log_format."""
253
        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
254
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
255
    def __init__(self, get_filename):
256
        super(IniBasedConfig, self).__init__()
257
        self._get_filename = get_filename
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
258
        self._parser = None
1472 by Robert Collins
post commit hook, first pass implementation
259
        
260
    def _post_commit(self):
261
        """See Config.post_commit."""
262
        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
263
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
264
    def _string_to_signature_policy(self, signature_string):
265
        """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
266
        if signature_string.lower() == 'check-available':
267
            return CHECK_IF_POSSIBLE
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
268
        if signature_string.lower() == 'ignore':
269
            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
270
        if signature_string.lower() == 'require':
271
            return CHECK_ALWAYS
1442.1.16 by Robert Collins
allow global overriding of signature policy to never check
272
        raise errors.BzrError("Invalid signatures policy '%s'"
273
                              % signature_string)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
274
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
275
    def _get_alias(self, value):
276
        try:
277
            return self._get_parser().get_value("ALIASES", 
278
                                                value)
279
        except KeyError:
280
            pass
281
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
282
283
class GlobalConfig(IniBasedConfig):
284
    """The configuration that should be used for a specific location."""
285
286
    def get_editor(self):
1474 by Robert Collins
Merge from Aaron Bentley.
287
        return self._get_user_option('editor')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
288
289
    def __init__(self):
290
        super(GlobalConfig, self).__init__(config_filename)
291
292
293
class LocationConfig(IniBasedConfig):
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
294
    """A configuration object that gives the policy for a location."""
295
296
    def __init__(self, location):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
297
        super(LocationConfig, self).__init__(branches_config_filename)
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
298
        self._global_config = None
299
        self.location = location
300
301
    def _get_global_config(self):
302
        if self._global_config is None:
303
            self._global_config = GlobalConfig()
304
        return self._global_config
305
1442.1.9 by Robert Collins
exact section test passes
306
    def _get_section(self):
307
        """Get the section we should look in for config items.
308
309
        Returns None if none exists. 
310
        TODO: perhaps return a NullSection that thunks through to the 
311
              global config.
312
        """
1185.12.49 by Aaron Bentley
Switched to ConfigObj
313
        sections = self._get_parser()
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
314
        location_names = self.location.split('/')
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
315
        if self.location.endswith('/'):
316
            del location_names[-1]
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
317
        matches=[]
1442.1.10 by Robert Collins
explicit over glob test passes
318
        for section in sections:
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
319
            section_names = section.split('/')
320
            if section.endswith('/'):
321
                del section_names[-1]
322
            names = zip(location_names, section_names)
323
            matched = True
324
            for name in names:
325
                if not fnmatch(name[0], name[1]):
326
                    matched = False
327
                    break
328
            if not matched:
329
                continue
330
            # so, for the common prefix they matched.
331
            # if section is longer, no match.
332
            if len(section_names) > len(location_names):
333
                continue
334
            # if path is longer, and recurse is not true, no match
335
            if len(section_names) < len(location_names):
1185.12.49 by Aaron Bentley
Switched to ConfigObj
336
                try:
1551.2.20 by Aaron Bentley
Treated config files as utf-8
337
                    if not self._get_parser()[section].as_bool('recurse'):
1185.12.49 by Aaron Bentley
Switched to ConfigObj
338
                        continue
339
                except KeyError:
340
                    pass
1442.1.12 by Robert Collins
LocationConfig section retrieval falls into my lap
341
            matches.append((len(section_names), section))
342
        if not len(matches):
343
            return None
344
        matches.sort(reverse=True)
345
        return matches[0][1]
1442.1.9 by Robert Collins
exact section test passes
346
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
347
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
348
        """See Config.gpg_signing_command."""
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
349
        command = super(LocationConfig, self)._gpg_signing_command()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
350
        if command is not None:
351
            return command
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
352
        return self._get_global_config()._gpg_signing_command()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
353
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
354
    def _log_format(self):
355
        """See Config.log_format."""
356
        command = super(LocationConfig, self)._log_format()
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
357
        if command is not None:
358
            return command
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
359
        return self._get_global_config()._log_format()
1553.2.4 by Erik Bågfors
Support for setting the default log format at a configuration option
360
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
361
    def _get_user_id(self):
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
362
        user_id = super(LocationConfig, self)._get_user_id()
363
        if user_id is not None:
364
            return user_id
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
365
        return self._get_global_config()._get_user_id()
366
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
367
    def _get_user_option(self, option_name):
368
        """See Config._get_user_option."""
369
        option_value = super(LocationConfig, 
370
                             self)._get_user_option(option_name)
371
        if option_value is not None:
372
            return option_value
373
        return self._get_global_config()._get_user_option(option_name)
374
1442.1.18 by Robert Collins
permit per branch location overriding of signature checking policy
375
    def _get_signature_checking(self):
376
        """See Config._get_signature_checking."""
377
        check = super(LocationConfig, self)._get_signature_checking()
378
        if check is not None:
379
            return check
380
        return self._get_global_config()._get_signature_checking()
381
1472 by Robert Collins
post commit hook, first pass implementation
382
    def _post_commit(self):
383
        """See Config.post_commit."""
384
        hook = self._get_user_option('post_commit')
385
        if hook is not None:
386
            return hook
387
        return self._get_global_config()._post_commit()
388
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
389
    def set_user_option(self, option, value):
390
        """Save option and its value in the configuration."""
391
        # FIXME: RBC 20051029 This should refresh the parser and also take a
392
        # file lock on branches.conf.
1185.31.39 by John Arbash Meinel
Replacing os.getcwdu() with osutils.getcwd(),
393
        conf_dir = os.path.dirname(self._get_filename())
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
394
        ensure_config_dir_exists(conf_dir)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
395
        location = self.location
396
        if location.endswith('/'):
397
            location = location[:-1]
398
        if (not location in self._get_parser() and
399
            not location + '/' in self._get_parser()):
400
            self._get_parser()[location]={}
401
        elif location + '/' in self._get_parser():
402
            location = location + '/'
403
        self._get_parser()[location][option]=value
1551.2.49 by abentley
Made ConfigObj output binary-identical files on win32 and *nix
404
        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.
405
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
406
407
class BranchConfig(Config):
408
    """A configuration object giving the policy for a branch."""
409
410
    def _get_location_config(self):
411
        if self._location_config is None:
412
            self._location_config = LocationConfig(self.branch.base)
413
        return self._location_config
414
415
    def _get_user_id(self):
416
        """Return the full user id for the branch.
417
    
418
        e.g. "John Hacker <jhacker@foo.org>"
419
        This is looked up in the email controlfile for the branch.
420
        """
421
        try:
1185.65.29 by Robert Collins
Implement final review suggestions.
422
            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
423
                    .read()
424
                    .decode(bzrlib.user_encoding)
425
                    .rstrip("\r\n"))
426
        except errors.NoSuchFile, e:
427
            pass
428
        
429
        return self._get_location_config()._get_user_id()
430
1442.1.19 by Robert Collins
BranchConfigs inherit signature_checking policy from their LocationConfig.
431
    def _get_signature_checking(self):
432
        """See Config._get_signature_checking."""
433
        return self._get_location_config()._get_signature_checking()
434
1442.1.69 by Robert Collins
config.Config has a 'get_user_option' call that accepts an option name.
435
    def _get_user_option(self, option_name):
436
        """See Config._get_user_option."""
437
        return self._get_location_config()._get_user_option(option_name)
438
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
439
    def _gpg_signing_command(self):
1442.1.56 by Robert Collins
gpg_signing_command configuration item
440
        """See Config.gpg_signing_command."""
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
441
        return self._get_location_config()._gpg_signing_command()
1442.1.56 by Robert Collins
gpg_signing_command configuration item
442
        
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
443
    def __init__(self, branch):
444
        super(BranchConfig, self).__init__()
445
        self._location_config = None
446
        self.branch = branch
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
447
1472 by Robert Collins
post commit hook, first pass implementation
448
    def _post_commit(self):
449
        """See Config.post_commit."""
450
        return self._get_location_config()._post_commit()
451
1553.2.9 by Erik Bågfors
log_formatter => log_format for "named" formatters
452
    def _log_format(self):
453
        """See Config.log_format."""
454
        return self._get_location_config()._log_format()
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
455
1553.6.12 by Erik Bågfors
remove AliasConfig, based on input from abentley
456
1185.31.43 by John Arbash Meinel
Reintroduced ensure_config_dir_exists() for sftp
457
def ensure_config_dir_exists(path=None):
458
    """Make sure a configuration directory exists.
459
    This makes sure that the directory exists.
460
    On windows, since configuration directories are 2 levels deep,
461
    it makes sure both the directory and the parent directory exists.
462
    """
463
    if path is None:
464
        path = config_dir()
465
    if not os.path.isdir(path):
466
        if sys.platform == 'win32':
467
            parent_dir = os.path.dirname(path)
468
            if not os.path.isdir(parent_dir):
469
                mutter('creating config parent directory: %r', parent_dir)
470
            os.mkdir(parent_dir)
471
        mutter('creating config directory: %r', path)
472
        os.mkdir(path)
473
1532 by Robert Collins
Merge in John Meinels integration branch.
474
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
475
def config_dir():
476
    """Return per-user configuration directory.
477
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
478
    By default this is ~/.bazaar/
1442.1.1 by Robert Collins
move config_dir into bzrlib.config
479
    
480
    TODO: Global option --config-dir to override this.
481
    """
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
482
    base = os.environ.get('BZR_HOME', None)
483
    if sys.platform == 'win32':
484
        if base is None:
485
            base = os.environ.get('APPDATA', None)
486
        if base is None:
487
            base = os.environ.get('HOME', None)
488
        if base is None:
489
            raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
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 \
490
        return pathjoin(base, 'bazaar', '2.0')
1185.38.1 by John Arbash Meinel
Adding my win32 patch for moving the home directory.
491
    else:
492
        # cygwin, linux, and darwin all have a $HOME directory
493
        if base is None:
494
            base = os.path.expanduser("~")
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 \
495
        return pathjoin(base, ".bazaar")
496
497
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
498
def config_filename():
499
    """Return per-user configuration ini file filename."""
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 \
500
    return 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.
501
502
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
503
def branches_config_filename():
504
    """Return per-user configuration ini file filename."""
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 \
505
    return 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.
506
507
508
def _auto_user_id():
509
    """Calculate automatic user identification.
510
511
    Returns (realname, email).
512
513
    Only used when none is set in the environment or the id file.
514
515
    This previously used the FQDN as the default domain, but that can
516
    be very slow on machines where DNS is broken.  So now we simply
517
    use the hostname.
518
    """
519
    import socket
520
521
    # XXX: Any good way to get real user name on win32?
522
523
    try:
524
        import pwd
525
        uid = os.getuid()
526
        w = pwd.getpwuid(uid)
1553.4.5 by Michael Ellerman
Produce an intelligible error if the user's /etc/passwd is not encoded in
527
528
        try:
529
            gecos = w.pw_gecos.decode(bzrlib.user_encoding)
530
            username = w.pw_name.decode(bzrlib.user_encoding)
531
        except UnicodeDecodeError:
532
            # We're using pwd, therefore we're on Unix, so /etc/passwd is ok.
533
            raise errors.BzrError("Can't decode username in " \
534
                    "/etc/passwd as %s." % bzrlib.user_encoding)
535
1442.1.2 by Robert Collins
create a config module - there is enough config logic to make this worthwhile, and start testing config processing.
536
        comma = gecos.find(',')
537
        if comma == -1:
538
            realname = gecos
539
        else:
540
            realname = gecos[:comma]
541
        if not realname:
542
            realname = username
543
544
    except ImportError:
545
        import getpass
1553.4.5 by Michael Ellerman
Produce an intelligible error if the user's /etc/passwd is not encoded in
546
        try:
547
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
548
        except UnicodeDecodeError:
549
            raise errors.BzrError("Can't decode username as %s." % \
550
                    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.
551
552
    return realname, (username + '@' + socket.gethostname())
553
554
1185.16.52 by Martin Pool
- add extract_email_address
555
def extract_email_address(e):
556
    """Return just the address part of an email string.
557
    
558
    That is just the user@domain part, nothing else. 
559
    This part is required to contain only ascii characters.
560
    If it can't be extracted, raises an error.
561
    
562
    >>> extract_email_address('Jane Tester <jane@test.com>')
563
    "jane@test.com"
564
    """
565
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
566
    if not m:
1185.33.31 by Martin Pool
Make annotate cope better with revisions committed without a valid
567
        raise errors.BzrError("%r doesn't seem to contain "
568
                              "a reasonable email address" % e)
1185.16.52 by Martin Pool
- add extract_email_address
569
    return m.group(0)
1185.35.11 by Aaron Bentley
Added support for branch nicks
570
571
class TreeConfig(object):
572
    """Branch configuration data associated with its contents, not location"""
573
    def __init__(self, branch):
574
        self.branch = branch
575
576
    def _get_config(self):
577
        try:
1556.2.1 by Aaron Bentley
Switched to ConfigObj 4.2.0
578
            obj = ConfigObj(self.branch.control_files.get('branch.conf'), 
579
                            encoding='utf-8')
1185.35.11 by Aaron Bentley
Added support for branch nicks
580
        except errors.NoSuchFile:
1556.2.1 by Aaron Bentley
Switched to ConfigObj 4.2.0
581
            obj = ConfigObj(encoding='utf=8')
1185.35.11 by Aaron Bentley
Added support for branch nicks
582
        return obj
583
584
    def get_option(self, name, section=None, default=None):
585
        self.branch.lock_read()
586
        try:
587
            obj = self._get_config()
588
            try:
589
                if section is not None:
590
                    obj[section]
591
                result = obj[name]
592
            except KeyError:
593
                result = default
594
        finally:
595
            self.branch.unlock()
596
        return result
597
598
    def set_option(self, value, name, section=None):
599
        """Set a per-branch configuration option"""
600
        self.branch.lock_write()
601
        try:
602
            cfg_obj = self._get_config()
603
            if section is None:
604
                obj = cfg_obj
605
            else:
606
                try:
607
                    obj = cfg_obj[section]
608
                except KeyError:
609
                    cfg_obj[section] = {}
610
                    obj = cfg_obj[section]
611
            obj[name] = value
1556.2.1 by Aaron Bentley
Switched to ConfigObj 4.2.0
612
            out_file = StringIO()
613
            cfg_obj.write(out_file)
1185.35.11 by Aaron Bentley
Added support for branch nicks
614
            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.
615
            self.branch.control_files.put('branch.conf', out_file)
1185.35.11 by Aaron Bentley
Added support for branch nicks
616
        finally:
617
            self.branch.unlock()