~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Robert Collins
  • Date: 2005-10-20 04:09:18 UTC
  • Revision ID: robertc@robertcollins.net-20051020040918-4498d0a87aa37c87
update NEWS for post_commit

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
31
30
 
32
31
in branches.conf, you specify the url of a branch and options for it.
33
32
Wildcards may be used - * and ? as normal in shell completion. Options
50
49
                    gpg signatures, never create them, or create them if the
51
50
                    branch is configured to require them.
52
51
                    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
63
52
"""
64
53
 
65
54
 
66
55
import errno
67
56
import os
68
 
import sys
69
57
from fnmatch import fnmatch
70
58
import re
71
59
 
72
60
import bzrlib
73
61
import bzrlib.errors as errors
74
 
from bzrlib.osutils import pathjoin
75
 
from bzrlib.trace import mutter
76
62
import bzrlib.util.configobj.configobj as configobj
77
 
from StringIO import StringIO
 
63
 
78
64
 
79
65
CHECK_IF_POSSIBLE=0
80
66
CHECK_ALWAYS=1
84
70
class ConfigObj(configobj.ConfigObj):
85
71
 
86
72
    def get_bool(self, section, key):
87
 
        return self[section].as_bool(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)
88
80
 
89
81
    def get_value(self, section, name):
90
82
        # Try [] for the old DEFAULT section.
125
117
        """See gpg_signing_command()."""
126
118
        return None
127
119
 
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
 
 
139
120
    def __init__(self):
140
121
        super(Config, self).__init__()
141
122
 
152
133
 
153
134
    def user_email(self):
154
135
        """Return just the email component of a username."""
155
 
        return extract_email_address(self.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)
156
142
 
157
143
    def username(self):
158
144
        """Return email-style username.
161
147
        
162
148
        $BZREMAIL can be set to override this, then
163
149
        the concrete policy type is checked, and finally
164
 
        $EMAIL is examined.
165
 
        If none is found, a reasonable default is (hopefully)
 
150
        $EMAIL is examinged.
 
151
        but if none is found, a reasonable default is (hopefully)
166
152
        created.
167
153
    
168
154
        TODO: Check it's reasonably well-formed.
199
185
            return True
200
186
        return False
201
187
 
202
 
    def get_alias(self, value):
203
 
        return self._get_alias(value)
204
 
 
205
 
    def _get_alias(self, value):
206
 
        pass
207
 
 
208
188
 
209
189
class IniBasedConfig(Config):
210
190
    """A configuration policy that draws from ini files."""
217
197
        else:
218
198
            input = file
219
199
        try:
220
 
            self._parser = ConfigObj(input, encoding='utf-8')
 
200
            self._parser = ConfigObj(input)
221
201
        except configobj.ConfigObjError, e:
222
202
            raise errors.ParseConfigError(e.errors, e.config.filename)
223
203
        return self._parser
248
228
        """See Config.gpg_signing_command."""
249
229
        return self._get_user_option('gpg_signing_command')
250
230
 
251
 
    def _log_format(self):
252
 
        """See Config.log_format."""
253
 
        return self._get_user_option('log_format')
254
 
 
255
231
    def __init__(self, get_filename):
256
232
        super(IniBasedConfig, self).__init__()
257
233
        self._get_filename = get_filename
272
248
        raise errors.BzrError("Invalid signatures policy '%s'"
273
249
                              % signature_string)
274
250
 
275
 
    def _get_alias(self, value):
276
 
        try:
277
 
            return self._get_parser().get_value("ALIASES", 
278
 
                                                value)
279
 
        except KeyError:
280
 
            pass
281
 
 
282
251
 
283
252
class GlobalConfig(IniBasedConfig):
284
253
    """The configuration that should be used for a specific location."""
334
303
            # if path is longer, and recurse is not true, no match
335
304
            if len(section_names) < len(location_names):
336
305
                try:
337
 
                    if not self._get_parser()[section].as_bool('recurse'):
 
306
                    if not self._get_parser().get_bool(section, 'recurse'):
338
307
                        continue
339
308
                except KeyError:
340
309
                    pass
351
320
            return command
352
321
        return self._get_global_config()._gpg_signing_command()
353
322
 
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
 
 
361
323
    def _get_user_id(self):
362
324
        user_id = super(LocationConfig, self)._get_user_id()
363
325
        if user_id is not None:
386
348
            return hook
387
349
        return self._get_global_config()._post_commit()
388
350
 
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
 
 
406
351
 
407
352
class BranchConfig(Config):
408
353
    """A configuration object giving the policy for a branch."""
419
364
        This is looked up in the email controlfile for the branch.
420
365
        """
421
366
        try:
422
 
            return (self.branch.control_files.get_utf8("email") 
 
367
            return (self.branch.controlfile("email", "r") 
423
368
                    .read()
424
369
                    .decode(bzrlib.user_encoding)
425
370
                    .rstrip("\r\n"))
449
394
        """See Config.post_commit."""
450
395
        return self._get_location_config()._post_commit()
451
396
 
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
 
 
474
397
 
475
398
def config_dir():
476
399
    """Return per-user configuration directory.
479
402
    
480
403
    TODO: Global option --config-dir to override this.
481
404
    """
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")
 
405
    return os.path.join(os.path.expanduser("~"), ".bazaar")
496
406
 
497
407
 
498
408
def config_filename():
499
409
    """Return per-user configuration ini file filename."""
500
 
    return pathjoin(config_dir(), 'bazaar.conf')
 
410
    return os.path.join(config_dir(), 'bazaar.conf')
501
411
 
502
412
 
503
413
def branches_config_filename():
504
414
    """Return per-user configuration ini file filename."""
505
 
    return pathjoin(config_dir(), 'branches.conf')
 
415
    return os.path.join(config_dir(), 'branches.conf')
506
416
 
507
417
 
508
418
def _auto_user_id():
524
434
        import pwd
525
435
        uid = os.getuid()
526
436
        w = pwd.getpwuid(uid)
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
 
 
 
437
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
438
        username = w.pw_name.decode(bzrlib.user_encoding)
536
439
        comma = gecos.find(',')
537
440
        if comma == -1:
538
441
            realname = gecos
543
446
 
544
447
    except ImportError:
545
448
        import getpass
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)
 
449
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
551
450
 
552
451
    return realname, (username + '@' + socket.gethostname())
553
452
 
564
463
    """
565
464
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
566
465
    if not m:
567
 
        raise errors.BzrError("%r doesn't seem to contain "
568
 
                              "a reasonable email address" % e)
 
466
        raise BzrError("%r doesn't seem to contain "
 
467
                       "a reasonable email address" % e)
569
468
    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()