/brz/remove-bazaar

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