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