~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: John Arbash Meinel
  • Date: 2006-10-16 01:25:46 UTC
  • mfrom: (2071 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2080.
  • Revision ID: john@arbash-meinel.com-20061016012546-d01a0740671b4d73
[merge] bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 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
 
 
18
"""Configuration that affects the behaviour of Bazaar.
 
19
 
 
20
Currently this configuration resides in ~/.bazaar/bazaar.conf
 
21
and ~/.bazaar/locations.conf, which is written to by bzr.
 
22
 
 
23
In bazaar.conf the following options may be set:
 
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)
 
29
gpg_signing_command=name-of-program
 
30
log_format=name-of-format
 
31
 
 
32
in locations.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 locations.conf are overridden by the locations.conf
 
35
setting.
 
36
[/home/robertc/source]
 
37
recurse=False|True(default)
 
38
email= as above
 
39
check_signatures= as above 
 
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.
 
52
log_format - this option sets the default log format.  Possible values are
 
53
             long, short, line, or a plugin can register new formats.
 
54
 
 
55
In bazaar.conf you can also define aliases in the ALIASES sections, example
 
56
 
 
57
[ALIASES]
 
58
lastlog=log --line -r-10..-1
 
59
ll=log --line -r-10..-1
 
60
h=help
 
61
up=pull
 
62
"""
 
63
 
 
64
import os
 
65
import sys
 
66
 
 
67
from bzrlib.lazy_import import lazy_import
 
68
lazy_import(globals(), """
 
69
import errno
 
70
from fnmatch import fnmatch
 
71
import re
 
72
from StringIO import StringIO
 
73
 
 
74
import bzrlib
 
75
from bzrlib import (
 
76
    errors,
 
77
    osutils,
 
78
    urlutils,
 
79
    )
 
80
import bzrlib.util.configobj.configobj as configobj
 
81
""")
 
82
 
 
83
from bzrlib.trace import mutter, warning
 
84
 
 
85
 
 
86
CHECK_IF_POSSIBLE=0
 
87
CHECK_ALWAYS=1
 
88
CHECK_NEVER=2
 
89
 
 
90
 
 
91
SIGN_WHEN_REQUIRED=0
 
92
SIGN_ALWAYS=1
 
93
SIGN_NEVER=2
 
94
 
 
95
 
 
96
class ConfigObj(configobj.ConfigObj):
 
97
 
 
98
    def get_bool(self, section, key):
 
99
        return self[section].as_bool(key)
 
100
 
 
101
    def get_value(self, section, name):
 
102
        # Try [] for the old DEFAULT section.
 
103
        if section == "DEFAULT":
 
104
            try:
 
105
                return self[name]
 
106
            except KeyError:
 
107
                pass
 
108
        return self[section][name]
 
109
 
 
110
 
 
111
class Config(object):
 
112
    """A configuration policy - what username, editor, gpg needs etc."""
 
113
 
 
114
    def get_editor(self):
 
115
        """Get the users pop up editor."""
 
116
        raise NotImplementedError
 
117
 
 
118
    def _get_signature_checking(self):
 
119
        """Template method to override signature checking policy."""
 
120
 
 
121
    def _get_signing_policy(self):
 
122
        """Template method to override signature creation policy."""
 
123
 
 
124
    def _get_user_option(self, option_name):
 
125
        """Template method to provide a user option."""
 
126
        return None
 
127
 
 
128
    def get_user_option(self, option_name):
 
129
        """Get a generic option - no special process, no default."""
 
130
        return self._get_user_option(option_name)
 
131
 
 
132
    def gpg_signing_command(self):
 
133
        """What program should be used to sign signatures?"""
 
134
        result = self._gpg_signing_command()
 
135
        if result is None:
 
136
            result = "gpg"
 
137
        return result
 
138
 
 
139
    def _gpg_signing_command(self):
 
140
        """See gpg_signing_command()."""
 
141
        return None
 
142
 
 
143
    def log_format(self):
 
144
        """What log format should be used"""
 
145
        result = self._log_format()
 
146
        if result is None:
 
147
            result = "long"
 
148
        return result
 
149
 
 
150
    def _log_format(self):
 
151
        """See log_format()."""
 
152
        return None
 
153
 
 
154
    def __init__(self):
 
155
        super(Config, self).__init__()
 
156
 
 
157
    def post_commit(self):
 
158
        """An ordered list of python functions to call.
 
159
 
 
160
        Each function takes branch, rev_id as parameters.
 
161
        """
 
162
        return self._post_commit()
 
163
 
 
164
    def _post_commit(self):
 
165
        """See Config.post_commit."""
 
166
        return None
 
167
 
 
168
    def user_email(self):
 
169
        """Return just the email component of a username."""
 
170
        return extract_email_address(self.username())
 
171
 
 
172
    def username(self):
 
173
        """Return email-style username.
 
174
    
 
175
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
176
        
 
177
        $BZR_EMAIL can be set to override this (as well as the
 
178
        deprecated $BZREMAIL), then
 
179
        the concrete policy type is checked, and finally
 
180
        $EMAIL is examined.
 
181
        If none is found, a reasonable default is (hopefully)
 
182
        created.
 
183
    
 
184
        TODO: Check it's reasonably well-formed.
 
185
        """
 
186
        v = os.environ.get('BZR_EMAIL')
 
187
        if v:
 
188
            return v.decode(bzrlib.user_encoding)
 
189
        v = os.environ.get('BZREMAIL')
 
190
        if v:
 
191
            warning('BZREMAIL is deprecated in favor of BZR_EMAIL. Please update your configuration.')
 
192
            return v.decode(bzrlib.user_encoding)
 
193
    
 
194
        v = self._get_user_id()
 
195
        if v:
 
196
            return v
 
197
        
 
198
        v = os.environ.get('EMAIL')
 
199
        if v:
 
200
            return v.decode(bzrlib.user_encoding)
 
201
 
 
202
        name, email = _auto_user_id()
 
203
        if name:
 
204
            return '%s <%s>' % (name, email)
 
205
        else:
 
206
            return email
 
207
 
 
208
    def signature_checking(self):
 
209
        """What is the current policy for signature checking?."""
 
210
        policy = self._get_signature_checking()
 
211
        if policy is not None:
 
212
            return policy
 
213
        return CHECK_IF_POSSIBLE
 
214
 
 
215
    def signing_policy(self):
 
216
        """What is the current policy for signature checking?."""
 
217
        policy = self._get_signing_policy()
 
218
        if policy is not None:
 
219
            return policy
 
220
        return SIGN_WHEN_REQUIRED
 
221
 
 
222
    def signature_needed(self):
 
223
        """Is a signature needed when committing ?."""
 
224
        policy = self._get_signing_policy()
 
225
        if policy is None:
 
226
            policy = self._get_signature_checking()
 
227
            if policy is not None:
 
228
                warning("Please use create_signatures, not check_signatures "
 
229
                        "to set signing policy.")
 
230
            if policy == CHECK_ALWAYS:
 
231
                return True
 
232
        elif policy == SIGN_ALWAYS:
 
233
            return True
 
234
        return False
 
235
 
 
236
    def get_alias(self, value):
 
237
        return self._get_alias(value)
 
238
 
 
239
    def _get_alias(self, value):
 
240
        pass
 
241
 
 
242
    def get_nickname(self):
 
243
        return self._get_nickname()
 
244
 
 
245
    def _get_nickname(self):
 
246
        return None
 
247
 
 
248
 
 
249
class IniBasedConfig(Config):
 
250
    """A configuration policy that draws from ini files."""
 
251
 
 
252
    def _get_parser(self, file=None):
 
253
        if self._parser is not None:
 
254
            return self._parser
 
255
        if file is None:
 
256
            input = self._get_filename()
 
257
        else:
 
258
            input = file
 
259
        try:
 
260
            self._parser = ConfigObj(input, encoding='utf-8')
 
261
        except configobj.ConfigObjError, e:
 
262
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
263
        return self._parser
 
264
 
 
265
    def _get_section(self):
 
266
        """Override this to define the section used by the config."""
 
267
        return "DEFAULT"
 
268
 
 
269
    def _get_signature_checking(self):
 
270
        """See Config._get_signature_checking."""
 
271
        policy = self._get_user_option('check_signatures')
 
272
        if policy:
 
273
            return self._string_to_signature_policy(policy)
 
274
 
 
275
    def _get_signing_policy(self):
 
276
        """See Config._get_signing_policy"""
 
277
        policy = self._get_user_option('create_signatures')
 
278
        if policy:
 
279
            return self._string_to_signing_policy(policy)
 
280
 
 
281
    def _get_user_id(self):
 
282
        """Get the user id from the 'email' key in the current section."""
 
283
        return self._get_user_option('email')
 
284
 
 
285
    def _get_user_option(self, option_name):
 
286
        """See Config._get_user_option."""
 
287
        try:
 
288
            return self._get_parser().get_value(self._get_section(),
 
289
                                                option_name)
 
290
        except KeyError:
 
291
            pass
 
292
 
 
293
    def _gpg_signing_command(self):
 
294
        """See Config.gpg_signing_command."""
 
295
        return self._get_user_option('gpg_signing_command')
 
296
 
 
297
    def _log_format(self):
 
298
        """See Config.log_format."""
 
299
        return self._get_user_option('log_format')
 
300
 
 
301
    def __init__(self, get_filename):
 
302
        super(IniBasedConfig, self).__init__()
 
303
        self._get_filename = get_filename
 
304
        self._parser = None
 
305
        
 
306
    def _post_commit(self):
 
307
        """See Config.post_commit."""
 
308
        return self._get_user_option('post_commit')
 
309
 
 
310
    def _string_to_signature_policy(self, signature_string):
 
311
        """Convert a string to a signing policy."""
 
312
        if signature_string.lower() == 'check-available':
 
313
            return CHECK_IF_POSSIBLE
 
314
        if signature_string.lower() == 'ignore':
 
315
            return CHECK_NEVER
 
316
        if signature_string.lower() == 'require':
 
317
            return CHECK_ALWAYS
 
318
        raise errors.BzrError("Invalid signatures policy '%s'"
 
319
                              % signature_string)
 
320
 
 
321
    def _string_to_signing_policy(self, signature_string):
 
322
        """Convert a string to a signing policy."""
 
323
        if signature_string.lower() == 'when-required':
 
324
            return SIGN_WHEN_REQUIRED
 
325
        if signature_string.lower() == 'never':
 
326
            return SIGN_NEVER
 
327
        if signature_string.lower() == 'always':
 
328
            return SIGN_ALWAYS
 
329
        raise errors.BzrError("Invalid signing policy '%s'"
 
330
                              % signature_string)
 
331
 
 
332
    def _get_alias(self, value):
 
333
        try:
 
334
            return self._get_parser().get_value("ALIASES", 
 
335
                                                value)
 
336
        except KeyError:
 
337
            pass
 
338
 
 
339
    def _get_nickname(self):
 
340
        return self.get_user_option('nickname')
 
341
 
 
342
 
 
343
class GlobalConfig(IniBasedConfig):
 
344
    """The configuration that should be used for a specific location."""
 
345
 
 
346
    def get_editor(self):
 
347
        return self._get_user_option('editor')
 
348
 
 
349
    def __init__(self):
 
350
        super(GlobalConfig, self).__init__(config_filename)
 
351
 
 
352
    def set_user_option(self, option, value):
 
353
        """Save option and its value in the configuration."""
 
354
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
355
        # file lock on bazaar.conf.
 
356
        conf_dir = os.path.dirname(self._get_filename())
 
357
        ensure_config_dir_exists(conf_dir)
 
358
        if 'DEFAULT' not in self._get_parser():
 
359
            self._get_parser()['DEFAULT'] = {}
 
360
        self._get_parser()['DEFAULT'][option] = value
 
361
        f = open(self._get_filename(), 'wb')
 
362
        self._get_parser().write(f)
 
363
        f.close()
 
364
 
 
365
 
 
366
class LocationConfig(IniBasedConfig):
 
367
    """A configuration object that gives the policy for a location."""
 
368
 
 
369
    def __init__(self, location):
 
370
        name_generator = locations_config_filename
 
371
        if (not os.path.exists(name_generator()) and 
 
372
                os.path.exists(branches_config_filename())):
 
373
            if sys.platform == 'win32':
 
374
                warning('Please rename %s to %s' 
 
375
                         % (branches_config_filename(),
 
376
                            locations_config_filename()))
 
377
            else:
 
378
                warning('Please rename ~/.bazaar/branches.conf'
 
379
                        ' to ~/.bazaar/locations.conf')
 
380
            name_generator = branches_config_filename
 
381
        super(LocationConfig, self).__init__(name_generator)
 
382
        # local file locations are looked up by local path, rather than
 
383
        # by file url. This is because the config file is a user
 
384
        # file, and we would rather not expose the user to file urls.
 
385
        if location.startswith('file://'):
 
386
            location = urlutils.local_path_from_url(location)
 
387
        self.location = location
 
388
 
 
389
    def _get_section(self):
 
390
        """Get the section we should look in for config items.
 
391
 
 
392
        Returns None if none exists. 
 
393
        TODO: perhaps return a NullSection that thunks through to the 
 
394
              global config.
 
395
        """
 
396
        sections = self._get_parser()
 
397
        location_names = self.location.split('/')
 
398
        if self.location.endswith('/'):
 
399
            del location_names[-1]
 
400
        matches=[]
 
401
        for section in sections:
 
402
            # location is a local path if possible, so we need
 
403
            # to convert 'file://' urls to local paths if necessary.
 
404
            # This also avoids having file:///path be a more exact
 
405
            # match than '/path'.
 
406
            if section.startswith('file://'):
 
407
                section_path = urlutils.local_path_from_url(section)
 
408
            else:
 
409
                section_path = section
 
410
            section_names = section_path.split('/')
 
411
            if section.endswith('/'):
 
412
                del section_names[-1]
 
413
            names = zip(location_names, section_names)
 
414
            matched = True
 
415
            for name in names:
 
416
                if not fnmatch(name[0], name[1]):
 
417
                    matched = False
 
418
                    break
 
419
            if not matched:
 
420
                continue
 
421
            # so, for the common prefix they matched.
 
422
            # if section is longer, no match.
 
423
            if len(section_names) > len(location_names):
 
424
                continue
 
425
            # if path is longer, and recurse is not true, no match
 
426
            if len(section_names) < len(location_names):
 
427
                try:
 
428
                    if not self._get_parser()[section].as_bool('recurse'):
 
429
                        continue
 
430
                except KeyError:
 
431
                    pass
 
432
            matches.append((len(section_names), section))
 
433
        if not len(matches):
 
434
            return None
 
435
        matches.sort(reverse=True)
 
436
        return matches[0][1]
 
437
 
 
438
    def set_user_option(self, option, value):
 
439
        """Save option and its value in the configuration."""
 
440
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
441
        # file lock on locations.conf.
 
442
        conf_dir = os.path.dirname(self._get_filename())
 
443
        ensure_config_dir_exists(conf_dir)
 
444
        location = self.location
 
445
        if location.endswith('/'):
 
446
            location = location[:-1]
 
447
        if (not location in self._get_parser() and
 
448
            not location + '/' in self._get_parser()):
 
449
            self._get_parser()[location]={}
 
450
        elif location + '/' in self._get_parser():
 
451
            location = location + '/'
 
452
        self._get_parser()[location][option]=value
 
453
        self._get_parser().write(file(self._get_filename(), 'wb'))
 
454
 
 
455
 
 
456
class BranchConfig(Config):
 
457
    """A configuration object giving the policy for a branch."""
 
458
 
 
459
    def _get_branch_data_config(self):
 
460
        if self._branch_data_config is None:
 
461
            self._branch_data_config = TreeConfig(self.branch)
 
462
        return self._branch_data_config
 
463
 
 
464
    def _get_location_config(self):
 
465
        if self._location_config is None:
 
466
            self._location_config = LocationConfig(self.branch.base)
 
467
        return self._location_config
 
468
 
 
469
    def _get_global_config(self):
 
470
        if self._global_config is None:
 
471
            self._global_config = GlobalConfig()
 
472
        return self._global_config
 
473
 
 
474
    def _get_best_value(self, option_name):
 
475
        """This returns a user option from local, tree or global config.
 
476
 
 
477
        They are tried in that order.  Use get_safe_value if trusted values
 
478
        are necessary.
 
479
        """
 
480
        for source in self.option_sources:
 
481
            value = getattr(source(), option_name)()
 
482
            if value is not None:
 
483
                return value
 
484
        return None
 
485
 
 
486
    def _get_safe_value(self, option_name):
 
487
        """This variant of get_best_value never returns untrusted values.
 
488
        
 
489
        It does not return values from the branch data, because the branch may
 
490
        not be controlled by the user.
 
491
 
 
492
        We may wish to allow locations.conf to control whether branches are
 
493
        trusted in the future.
 
494
        """
 
495
        for source in (self._get_location_config, self._get_global_config):
 
496
            value = getattr(source(), option_name)()
 
497
            if value is not None:
 
498
                return value
 
499
        return None
 
500
 
 
501
    def _get_user_id(self):
 
502
        """Return the full user id for the branch.
 
503
    
 
504
        e.g. "John Hacker <jhacker@foo.org>"
 
505
        This is looked up in the email controlfile for the branch.
 
506
        """
 
507
        try:
 
508
            return (self.branch.control_files.get_utf8("email") 
 
509
                    .read()
 
510
                    .decode(bzrlib.user_encoding)
 
511
                    .rstrip("\r\n"))
 
512
        except errors.NoSuchFile, e:
 
513
            pass
 
514
        
 
515
        return self._get_best_value('_get_user_id')
 
516
 
 
517
    def _get_signature_checking(self):
 
518
        """See Config._get_signature_checking."""
 
519
        return self._get_best_value('_get_signature_checking')
 
520
 
 
521
    def _get_signing_policy(self):
 
522
        """See Config._get_signing_policy."""
 
523
        return self._get_best_value('_get_signing_policy')
 
524
 
 
525
    def _get_user_option(self, option_name):
 
526
        """See Config._get_user_option."""
 
527
        for source in self.option_sources:
 
528
            value = source()._get_user_option(option_name)
 
529
            if value is not None:
 
530
                return value
 
531
        return None
 
532
 
 
533
    def set_user_option(self, name, value, local=False):
 
534
        if local is True:
 
535
            self._get_location_config().set_user_option(name, value)
 
536
        else:
 
537
            self._get_branch_data_config().set_option(value, name)
 
538
 
 
539
 
 
540
    def _gpg_signing_command(self):
 
541
        """See Config.gpg_signing_command."""
 
542
        return self._get_safe_value('_gpg_signing_command')
 
543
        
 
544
    def __init__(self, branch):
 
545
        super(BranchConfig, self).__init__()
 
546
        self._location_config = None
 
547
        self._branch_data_config = None
 
548
        self._global_config = None
 
549
        self.branch = branch
 
550
        self.option_sources = (self._get_location_config, 
 
551
                               self._get_branch_data_config,
 
552
                               self._get_global_config)
 
553
 
 
554
    def _post_commit(self):
 
555
        """See Config.post_commit."""
 
556
        return self._get_safe_value('_post_commit')
 
557
 
 
558
    def _get_nickname(self):
 
559
        value = self._get_explicit_nickname()
 
560
        if value is not None:
 
561
            return value
 
562
        return self.branch.base.split('/')[-2]
 
563
 
 
564
    def has_explicit_nickname(self):
 
565
        """Return true if a nickname has been explicitly assigned."""
 
566
        return self._get_explicit_nickname() is not None
 
567
 
 
568
    def _get_explicit_nickname(self):
 
569
        return self._get_best_value('_get_nickname')
 
570
 
 
571
    def _log_format(self):
 
572
        """See Config.log_format."""
 
573
        return self._get_best_value('_log_format')
 
574
 
 
575
 
 
576
def ensure_config_dir_exists(path=None):
 
577
    """Make sure a configuration directory exists.
 
578
    This makes sure that the directory exists.
 
579
    On windows, since configuration directories are 2 levels deep,
 
580
    it makes sure both the directory and the parent directory exists.
 
581
    """
 
582
    if path is None:
 
583
        path = config_dir()
 
584
    if not os.path.isdir(path):
 
585
        if sys.platform == 'win32':
 
586
            parent_dir = os.path.dirname(path)
 
587
            if not os.path.isdir(parent_dir):
 
588
                mutter('creating config parent directory: %r', parent_dir)
 
589
            os.mkdir(parent_dir)
 
590
        mutter('creating config directory: %r', path)
 
591
        os.mkdir(path)
 
592
 
 
593
 
 
594
def config_dir():
 
595
    """Return per-user configuration directory.
 
596
 
 
597
    By default this is ~/.bazaar/
 
598
    
 
599
    TODO: Global option --config-dir to override this.
 
600
    """
 
601
    base = os.environ.get('BZR_HOME', None)
 
602
    if sys.platform == 'win32':
 
603
        if base is None:
 
604
            base = os.environ.get('APPDATA', None)
 
605
        if base is None:
 
606
            base = os.environ.get('HOME', None)
 
607
        if base is None:
 
608
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
 
609
        return osutils.pathjoin(base, 'bazaar', '2.0')
 
610
    else:
 
611
        # cygwin, linux, and darwin all have a $HOME directory
 
612
        if base is None:
 
613
            base = os.path.expanduser("~")
 
614
        return osutils.pathjoin(base, ".bazaar")
 
615
 
 
616
 
 
617
def config_filename():
 
618
    """Return per-user configuration ini file filename."""
 
619
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
 
620
 
 
621
 
 
622
def branches_config_filename():
 
623
    """Return per-user configuration ini file filename."""
 
624
    return osutils.pathjoin(config_dir(), 'branches.conf')
 
625
 
 
626
 
 
627
def locations_config_filename():
 
628
    """Return per-user configuration ini file filename."""
 
629
    return osutils.pathjoin(config_dir(), 'locations.conf')
 
630
 
 
631
 
 
632
def user_ignore_config_filename():
 
633
    """Return the user default ignore filename"""
 
634
    return osutils.pathjoin(config_dir(), 'ignore')
 
635
 
 
636
 
 
637
def _auto_user_id():
 
638
    """Calculate automatic user identification.
 
639
 
 
640
    Returns (realname, email).
 
641
 
 
642
    Only used when none is set in the environment or the id file.
 
643
 
 
644
    This previously used the FQDN as the default domain, but that can
 
645
    be very slow on machines where DNS is broken.  So now we simply
 
646
    use the hostname.
 
647
    """
 
648
    import socket
 
649
 
 
650
    # XXX: Any good way to get real user name on win32?
 
651
 
 
652
    try:
 
653
        import pwd
 
654
        uid = os.getuid()
 
655
        w = pwd.getpwuid(uid)
 
656
 
 
657
        # we try utf-8 first, because on many variants (like Linux),
 
658
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
659
        # false positives.  (many users will have their user encoding set to
 
660
        # latin-1, which cannot raise UnicodeError.)
 
661
        try:
 
662
            gecos = w.pw_gecos.decode('utf-8')
 
663
            encoding = 'utf-8'
 
664
        except UnicodeError:
 
665
            try:
 
666
                gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
667
                encoding = bzrlib.user_encoding
 
668
            except UnicodeError:
 
669
                raise errors.BzrCommandError('Unable to determine your name.  '
 
670
                   'Use "bzr whoami" to set it.')
 
671
        try:
 
672
            username = w.pw_name.decode(encoding)
 
673
        except UnicodeError:
 
674
            raise errors.BzrCommandError('Unable to determine your name.  '
 
675
                'Use "bzr whoami" to set it.')
 
676
 
 
677
        comma = gecos.find(',')
 
678
        if comma == -1:
 
679
            realname = gecos
 
680
        else:
 
681
            realname = gecos[:comma]
 
682
        if not realname:
 
683
            realname = username
 
684
 
 
685
    except ImportError:
 
686
        import getpass
 
687
        try:
 
688
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
689
        except UnicodeDecodeError:
 
690
            raise errors.BzrError("Can't decode username as %s." % \
 
691
                    bzrlib.user_encoding)
 
692
 
 
693
    return realname, (username + '@' + socket.gethostname())
 
694
 
 
695
 
 
696
def extract_email_address(e):
 
697
    """Return just the address part of an email string.
 
698
    
 
699
    That is just the user@domain part, nothing else. 
 
700
    This part is required to contain only ascii characters.
 
701
    If it can't be extracted, raises an error.
 
702
    
 
703
    >>> extract_email_address('Jane Tester <jane@test.com>')
 
704
    "jane@test.com"
 
705
    """
 
706
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
707
    if not m:
 
708
        raise errors.NoEmailInUsername(e)
 
709
    return m.group(0)
 
710
 
 
711
 
 
712
class TreeConfig(IniBasedConfig):
 
713
    """Branch configuration data associated with its contents, not location"""
 
714
    def __init__(self, branch):
 
715
        self.branch = branch
 
716
 
 
717
    def _get_parser(self, file=None):
 
718
        if file is not None:
 
719
            return IniBasedConfig._get_parser(file)
 
720
        return self._get_config()
 
721
 
 
722
    def _get_config(self):
 
723
        try:
 
724
            obj = ConfigObj(self.branch.control_files.get('branch.conf'), 
 
725
                            encoding='utf-8')
 
726
        except errors.NoSuchFile:
 
727
            obj = ConfigObj(encoding='utf=8')
 
728
        return obj
 
729
 
 
730
    def get_option(self, name, section=None, default=None):
 
731
        self.branch.lock_read()
 
732
        try:
 
733
            obj = self._get_config()
 
734
            try:
 
735
                if section is not None:
 
736
                    obj[section]
 
737
                result = obj[name]
 
738
            except KeyError:
 
739
                result = default
 
740
        finally:
 
741
            self.branch.unlock()
 
742
        return result
 
743
 
 
744
    def set_option(self, value, name, section=None):
 
745
        """Set a per-branch configuration option"""
 
746
        self.branch.lock_write()
 
747
        try:
 
748
            cfg_obj = self._get_config()
 
749
            if section is None:
 
750
                obj = cfg_obj
 
751
            else:
 
752
                try:
 
753
                    obj = cfg_obj[section]
 
754
                except KeyError:
 
755
                    cfg_obj[section] = {}
 
756
                    obj = cfg_obj[section]
 
757
            obj[name] = value
 
758
            out_file = StringIO()
 
759
            cfg_obj.write(out_file)
 
760
            out_file.seek(0)
 
761
            self.branch.control_files.put('branch.conf', out_file)
 
762
        finally:
 
763
            self.branch.unlock()