~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

Late bind to PatienceSequenceMatcher to allow plugin to override.

Show diffs side-by-side

added added

removed removed

Lines of Context:
27
27
check_signatures=require|ignore|check-available(default)
28
28
create_signatures=always|never|when-required(default)
29
29
gpg_signing_command=name-of-program
 
30
log_format=name-of-format
30
31
 
31
32
in branches.conf, you specify the url of a branch and options for it.
32
33
Wildcards may be used - * and ? as normal in shell completion. Options
49
50
                    gpg signatures, never create them, or create them if the
50
51
                    branch is configured to require them.
51
52
                    NB: This option is planned, but not implemented yet.
 
53
log_format - This options set the default log format.  Options are long, 
 
54
             short, line, or a plugin can register new formats
 
55
 
 
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
 
57
 
 
58
[ALIASES]
 
59
lastlog=log --line -r-10..-1
 
60
ll=log --line -r-10..-1
 
61
h=help
 
62
up=pull
52
63
"""
53
64
 
54
65
 
55
66
import errno
56
67
import os
 
68
import sys
57
69
from fnmatch import fnmatch
58
70
import re
59
71
 
60
72
import bzrlib
61
73
import bzrlib.errors as errors
 
74
from bzrlib.osutils import pathjoin
 
75
from bzrlib.trace import mutter
62
76
import bzrlib.util.configobj.configobj as configobj
63
 
 
 
77
from StringIO import StringIO
64
78
 
65
79
CHECK_IF_POSSIBLE=0
66
80
CHECK_ALWAYS=1
70
84
class ConfigObj(configobj.ConfigObj):
71
85
 
72
86
    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)
 
87
        return self[section].as_bool(key)
80
88
 
81
89
    def get_value(self, section, name):
82
90
        # Try [] for the old DEFAULT section.
117
125
        """See gpg_signing_command()."""
118
126
        return None
119
127
 
 
128
    def log_format(self):
 
129
        """What log format should be used"""
 
130
        result = self._log_format()
 
131
        if result is None:
 
132
            result = "long"
 
133
        return result
 
134
 
 
135
    def _log_format(self):
 
136
        """See log_format()."""
 
137
        return None
 
138
 
120
139
    def __init__(self):
121
140
        super(Config, self).__init__()
122
141
 
133
152
 
134
153
    def user_email(self):
135
154
        """Return just the email component of a username."""
136
 
        e = self.username()
137
 
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
138
 
        if not m:
139
 
            raise BzrError("%r doesn't seem to contain "
140
 
                           "a reasonable email address" % e)
141
 
        return m.group(0)
 
155
        return extract_email_address(self.username())
142
156
 
143
157
    def username(self):
144
158
        """Return email-style username.
147
161
        
148
162
        $BZREMAIL can be set to override this, then
149
163
        the concrete policy type is checked, and finally
150
 
        $EMAIL is examinged.
151
 
        but if none is found, a reasonable default is (hopefully)
 
164
        $EMAIL is examined.
 
165
        If none is found, a reasonable default is (hopefully)
152
166
        created.
153
167
    
154
168
        TODO: Check it's reasonably well-formed.
185
199
            return True
186
200
        return False
187
201
 
 
202
    def get_alias(self, value):
 
203
        return self._get_alias(value)
 
204
 
 
205
    def _get_alias(self, value):
 
206
        pass
 
207
 
188
208
 
189
209
class IniBasedConfig(Config):
190
210
    """A configuration policy that draws from ini files."""
197
217
        else:
198
218
            input = file
199
219
        try:
200
 
            self._parser = ConfigObj(input)
 
220
            self._parser = ConfigObj(input, encoding='utf-8')
201
221
        except configobj.ConfigObjError, e:
202
222
            raise errors.ParseConfigError(e.errors, e.config.filename)
203
223
        return self._parser
228
248
        """See Config.gpg_signing_command."""
229
249
        return self._get_user_option('gpg_signing_command')
230
250
 
 
251
    def _log_format(self):
 
252
        """See Config.log_format."""
 
253
        return self._get_user_option('log_format')
 
254
 
231
255
    def __init__(self, get_filename):
232
256
        super(IniBasedConfig, self).__init__()
233
257
        self._get_filename = get_filename
248
272
        raise errors.BzrError("Invalid signatures policy '%s'"
249
273
                              % signature_string)
250
274
 
 
275
    def _get_alias(self, value):
 
276
        try:
 
277
            return self._get_parser().get_value("ALIASES", 
 
278
                                                value)
 
279
        except KeyError:
 
280
            pass
 
281
 
251
282
 
252
283
class GlobalConfig(IniBasedConfig):
253
284
    """The configuration that should be used for a specific location."""
303
334
            # if path is longer, and recurse is not true, no match
304
335
            if len(section_names) < len(location_names):
305
336
                try:
306
 
                    if not self._get_parser().get_bool(section, 'recurse'):
 
337
                    if not self._get_parser()[section].as_bool('recurse'):
307
338
                        continue
308
339
                except KeyError:
309
340
                    pass
320
351
            return command
321
352
        return self._get_global_config()._gpg_signing_command()
322
353
 
 
354
    def _log_format(self):
 
355
        """See Config.log_format."""
 
356
        command = super(LocationConfig, self)._log_format()
 
357
        if command is not None:
 
358
            return command
 
359
        return self._get_global_config()._log_format()
 
360
 
323
361
    def _get_user_id(self):
324
362
        user_id = super(LocationConfig, self)._get_user_id()
325
363
        if user_id is not None:
348
386
            return hook
349
387
        return self._get_global_config()._post_commit()
350
388
 
 
389
    def set_user_option(self, option, value):
 
390
        """Save option and its value in the configuration."""
 
391
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
392
        # file lock on branches.conf.
 
393
        conf_dir = os.path.dirname(self._get_filename())
 
394
        ensure_config_dir_exists(conf_dir)
 
395
        location = self.location
 
396
        if location.endswith('/'):
 
397
            location = location[:-1]
 
398
        if (not location in self._get_parser() and
 
399
            not location + '/' in self._get_parser()):
 
400
            self._get_parser()[location]={}
 
401
        elif location + '/' in self._get_parser():
 
402
            location = location + '/'
 
403
        self._get_parser()[location][option]=value
 
404
        self._get_parser().write(file(self._get_filename(), 'wb'))
 
405
 
351
406
 
352
407
class BranchConfig(Config):
353
408
    """A configuration object giving the policy for a branch."""
364
419
        This is looked up in the email controlfile for the branch.
365
420
        """
366
421
        try:
367
 
            return (self.branch.controlfile("email", "r") 
 
422
            return (self.branch.control_files.get_utf8("email") 
368
423
                    .read()
369
424
                    .decode(bzrlib.user_encoding)
370
425
                    .rstrip("\r\n"))
394
449
        """See Config.post_commit."""
395
450
        return self._get_location_config()._post_commit()
396
451
 
 
452
    def _log_format(self):
 
453
        """See Config.log_format."""
 
454
        return self._get_location_config()._log_format()
 
455
 
 
456
 
 
457
def ensure_config_dir_exists(path=None):
 
458
    """Make sure a configuration directory exists.
 
459
    This makes sure that the directory exists.
 
460
    On windows, since configuration directories are 2 levels deep,
 
461
    it makes sure both the directory and the parent directory exists.
 
462
    """
 
463
    if path is None:
 
464
        path = config_dir()
 
465
    if not os.path.isdir(path):
 
466
        if sys.platform == 'win32':
 
467
            parent_dir = os.path.dirname(path)
 
468
            if not os.path.isdir(parent_dir):
 
469
                mutter('creating config parent directory: %r', parent_dir)
 
470
            os.mkdir(parent_dir)
 
471
        mutter('creating config directory: %r', path)
 
472
        os.mkdir(path)
 
473
 
397
474
 
398
475
def config_dir():
399
476
    """Return per-user configuration directory.
402
479
    
403
480
    TODO: Global option --config-dir to override this.
404
481
    """
405
 
    return os.path.join(os.path.expanduser("~"), ".bazaar")
 
482
    base = os.environ.get('BZR_HOME', None)
 
483
    if sys.platform == 'win32':
 
484
        if base is None:
 
485
            base = os.environ.get('APPDATA', None)
 
486
        if base is None:
 
487
            base = os.environ.get('HOME', None)
 
488
        if base is None:
 
489
            raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
 
490
        return pathjoin(base, 'bazaar', '2.0')
 
491
    else:
 
492
        # cygwin, linux, and darwin all have a $HOME directory
 
493
        if base is None:
 
494
            base = os.path.expanduser("~")
 
495
        return pathjoin(base, ".bazaar")
406
496
 
407
497
 
408
498
def config_filename():
409
499
    """Return per-user configuration ini file filename."""
410
 
    return os.path.join(config_dir(), 'bazaar.conf')
 
500
    return pathjoin(config_dir(), 'bazaar.conf')
411
501
 
412
502
 
413
503
def branches_config_filename():
414
504
    """Return per-user configuration ini file filename."""
415
 
    return os.path.join(config_dir(), 'branches.conf')
 
505
    return pathjoin(config_dir(), 'branches.conf')
416
506
 
417
507
 
418
508
def _auto_user_id():
434
524
        import pwd
435
525
        uid = os.getuid()
436
526
        w = pwd.getpwuid(uid)
437
 
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
438
 
        username = w.pw_name.decode(bzrlib.user_encoding)
 
527
 
 
528
        try:
 
529
            gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
530
            username = w.pw_name.decode(bzrlib.user_encoding)
 
531
        except UnicodeDecodeError:
 
532
            # We're using pwd, therefore we're on Unix, so /etc/passwd is ok.
 
533
            raise errors.BzrError("Can't decode username in " \
 
534
                    "/etc/passwd as %s." % bzrlib.user_encoding)
 
535
 
439
536
        comma = gecos.find(',')
440
537
        if comma == -1:
441
538
            realname = gecos
446
543
 
447
544
    except ImportError:
448
545
        import getpass
449
 
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
546
        try:
 
547
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
548
        except UnicodeDecodeError:
 
549
            raise errors.BzrError("Can't decode username as %s." % \
 
550
                    bzrlib.user_encoding)
450
551
 
451
552
    return realname, (username + '@' + socket.gethostname())
452
553
 
463
564
    """
464
565
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
465
566
    if not m:
466
 
        raise BzrError("%r doesn't seem to contain "
467
 
                       "a reasonable email address" % e)
 
567
        raise errors.BzrError("%r doesn't seem to contain "
 
568
                              "a reasonable email address" % e)
468
569
    return m.group(0)
 
570
 
 
571
class TreeConfig(object):
 
572
    """Branch configuration data associated with its contents, not location"""
 
573
    def __init__(self, branch):
 
574
        self.branch = branch
 
575
 
 
576
    def _get_config(self):
 
577
        try:
 
578
            obj = ConfigObj(self.branch.control_files.get('branch.conf'), 
 
579
                            encoding='utf-8')
 
580
        except errors.NoSuchFile:
 
581
            obj = ConfigObj(encoding='utf=8')
 
582
        return obj
 
583
 
 
584
    def get_option(self, name, section=None, default=None):
 
585
        self.branch.lock_read()
 
586
        try:
 
587
            obj = self._get_config()
 
588
            try:
 
589
                if section is not None:
 
590
                    obj[section]
 
591
                result = obj[name]
 
592
            except KeyError:
 
593
                result = default
 
594
        finally:
 
595
            self.branch.unlock()
 
596
        return result
 
597
 
 
598
    def set_option(self, value, name, section=None):
 
599
        """Set a per-branch configuration option"""
 
600
        self.branch.lock_write()
 
601
        try:
 
602
            cfg_obj = self._get_config()
 
603
            if section is None:
 
604
                obj = cfg_obj
 
605
            else:
 
606
                try:
 
607
                    obj = cfg_obj[section]
 
608
                except KeyError:
 
609
                    cfg_obj[section] = {}
 
610
                    obj = cfg_obj[section]
 
611
            obj[name] = value
 
612
            out_file = StringIO()
 
613
            cfg_obj.write(out_file)
 
614
            out_file.seek(0)
 
615
            self.branch.control_files.put('branch.conf', out_file)
 
616
        finally:
 
617
            self.branch.unlock()