/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Erik Bågfors
  • Date: 2006-02-04 11:36:23 UTC
  • mto: (1185.50.77 bzr-jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1554.
  • Revision ID: erik@bagfors.nu-20060204113623-016da21eeb5723ca
Support for setting the default log format at a configuration option
Also, removed the possibility for plugins to set the default formatter

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
 
 
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
 
 
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 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.
 
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
 
 
57
 
 
58
import errno
 
59
import os
 
60
import sys
 
61
from fnmatch import fnmatch
 
62
import re
 
63
 
 
64
import bzrlib
 
65
import bzrlib.errors as errors
 
66
from bzrlib.osutils import pathjoin
 
67
from bzrlib.trace import mutter
 
68
import bzrlib.util.configobj.configobj as configobj
 
69
from StringIO import StringIO
 
70
 
 
71
CHECK_IF_POSSIBLE=0
 
72
CHECK_ALWAYS=1
 
73
CHECK_NEVER=2
 
74
 
 
75
 
 
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
 
 
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
 
 
104
    def _get_signature_checking(self):
 
105
        """Template method to override signature checking policy."""
 
106
 
 
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
 
 
115
    def gpg_signing_command(self):
 
116
        """What program should be used to sign signatures?"""
 
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
 
125
 
 
126
    def log_formatter(self):
 
127
        """What log formatter should be used"""
 
128
        result = self._log_formatter()
 
129
        if result is None:
 
130
            result = "long"
 
131
        mutter('debug ' + result)
 
132
 
 
133
        return result
 
134
 
 
135
    def _log_formatter(self):
 
136
        """See log_formatter()."""
 
137
        mutter('debug2 ')
 
138
        return None
 
139
 
 
140
    def __init__(self):
 
141
        super(Config, self).__init__()
 
142
 
 
143
    def post_commit(self):
 
144
        """An ordered list of python functions to call.
 
145
 
 
146
        Each function takes branch, rev_id as parameters.
 
147
        """
 
148
        return self._post_commit()
 
149
 
 
150
    def _post_commit(self):
 
151
        """See Config.post_commit."""
 
152
        return None
 
153
 
 
154
    def user_email(self):
 
155
        """Return just the email component of a username."""
 
156
        return extract_email_address(self.username())
 
157
 
 
158
    def username(self):
 
159
        """Return email-style username.
 
160
    
 
161
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
162
        
 
163
        $BZREMAIL can be set to override this, then
 
164
        the concrete policy type is checked, and finally
 
165
        $EMAIL is examined.
 
166
        If none is found, a reasonable default is (hopefully)
 
167
        created.
 
168
    
 
169
        TODO: Check it's reasonably well-formed.
 
170
        """
 
171
        v = os.environ.get('BZREMAIL')
 
172
        if v:
 
173
            return v.decode(bzrlib.user_encoding)
 
174
    
 
175
        v = self._get_user_id()
 
176
        if v:
 
177
            return v
 
178
        
 
179
        v = os.environ.get('EMAIL')
 
180
        if v:
 
181
            return v.decode(bzrlib.user_encoding)
 
182
 
 
183
        name, email = _auto_user_id()
 
184
        if name:
 
185
            return '%s <%s>' % (name, email)
 
186
        else:
 
187
            return email
 
188
 
 
189
    def signature_checking(self):
 
190
        """What is the current policy for signature checking?."""
 
191
        policy = self._get_signature_checking()
 
192
        if policy is not None:
 
193
            return policy
 
194
        return CHECK_IF_POSSIBLE
 
195
 
 
196
    def signature_needed(self):
 
197
        """Is a signature needed when committing ?."""
 
198
        policy = self._get_signature_checking()
 
199
        if policy == CHECK_ALWAYS:
 
200
            return True
 
201
        return False
 
202
 
 
203
 
 
204
class IniBasedConfig(Config):
 
205
    """A configuration policy that draws from ini files."""
 
206
 
 
207
    def _get_parser(self, file=None):
 
208
        if self._parser is not None:
 
209
            return self._parser
 
210
        if file is None:
 
211
            input = self._get_filename()
 
212
        else:
 
213
            input = file
 
214
        try:
 
215
            self._parser = ConfigObj(input)
 
216
        except configobj.ConfigObjError, e:
 
217
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
218
        return self._parser
 
219
 
 
220
    def _get_section(self):
 
221
        """Override this to define the section used by the config."""
 
222
        return "DEFAULT"
 
223
 
 
224
    def _get_signature_checking(self):
 
225
        """See Config._get_signature_checking."""
 
226
        policy = self._get_user_option('check_signatures')
 
227
        if policy:
 
228
            return self._string_to_signature_policy(policy)
 
229
 
 
230
    def _get_user_id(self):
 
231
        """Get the user id from the 'email' key in the current section."""
 
232
        return self._get_user_option('email')
 
233
 
 
234
    def _get_user_option(self, option_name):
 
235
        """See Config._get_user_option."""
 
236
        try:
 
237
            return self._get_parser().get_value(self._get_section(),
 
238
                                                option_name)
 
239
        except KeyError:
 
240
            pass
 
241
 
 
242
    def _gpg_signing_command(self):
 
243
        """See Config.gpg_signing_command."""
 
244
        return self._get_user_option('gpg_signing_command')
 
245
 
 
246
    def _log_formatter(self):
 
247
        """See Config.log_formatter."""
 
248
        mutter('debug3 ')
 
249
        return self._get_user_option('log_formatter')
 
250
 
 
251
    def __init__(self, get_filename):
 
252
        super(IniBasedConfig, self).__init__()
 
253
        self._get_filename = get_filename
 
254
        self._parser = None
 
255
        
 
256
    def _post_commit(self):
 
257
        """See Config.post_commit."""
 
258
        return self._get_user_option('post_commit')
 
259
 
 
260
    def _string_to_signature_policy(self, signature_string):
 
261
        """Convert a string to a signing policy."""
 
262
        if signature_string.lower() == 'check-available':
 
263
            return CHECK_IF_POSSIBLE
 
264
        if signature_string.lower() == 'ignore':
 
265
            return CHECK_NEVER
 
266
        if signature_string.lower() == 'require':
 
267
            return CHECK_ALWAYS
 
268
        raise errors.BzrError("Invalid signatures policy '%s'"
 
269
                              % signature_string)
 
270
 
 
271
 
 
272
class GlobalConfig(IniBasedConfig):
 
273
    """The configuration that should be used for a specific location."""
 
274
 
 
275
    def get_editor(self):
 
276
        return self._get_user_option('editor')
 
277
 
 
278
    def __init__(self):
 
279
        super(GlobalConfig, self).__init__(config_filename)
 
280
 
 
281
 
 
282
class LocationConfig(IniBasedConfig):
 
283
    """A configuration object that gives the policy for a location."""
 
284
 
 
285
    def __init__(self, location):
 
286
        super(LocationConfig, self).__init__(branches_config_filename)
 
287
        self._global_config = None
 
288
        self.location = location
 
289
 
 
290
    def _get_global_config(self):
 
291
        if self._global_config is None:
 
292
            self._global_config = GlobalConfig()
 
293
        return self._global_config
 
294
 
 
295
    def _get_section(self):
 
296
        """Get the section we should look in for config items.
 
297
 
 
298
        Returns None if none exists. 
 
299
        TODO: perhaps return a NullSection that thunks through to the 
 
300
              global config.
 
301
        """
 
302
        sections = self._get_parser()
 
303
        location_names = self.location.split('/')
 
304
        if self.location.endswith('/'):
 
305
            del location_names[-1]
 
306
        matches=[]
 
307
        for section in sections:
 
308
            section_names = section.split('/')
 
309
            if section.endswith('/'):
 
310
                del section_names[-1]
 
311
            names = zip(location_names, section_names)
 
312
            matched = True
 
313
            for name in names:
 
314
                if not fnmatch(name[0], name[1]):
 
315
                    matched = False
 
316
                    break
 
317
            if not matched:
 
318
                continue
 
319
            # so, for the common prefix they matched.
 
320
            # if section is longer, no match.
 
321
            if len(section_names) > len(location_names):
 
322
                continue
 
323
            # if path is longer, and recurse is not true, no match
 
324
            if len(section_names) < len(location_names):
 
325
                try:
 
326
                    if not self._get_parser().get_bool(section, 'recurse'):
 
327
                        continue
 
328
                except KeyError:
 
329
                    pass
 
330
            matches.append((len(section_names), section))
 
331
        if not len(matches):
 
332
            return None
 
333
        matches.sort(reverse=True)
 
334
        return matches[0][1]
 
335
 
 
336
    def _gpg_signing_command(self):
 
337
        """See Config.gpg_signing_command."""
 
338
        command = super(LocationConfig, self)._gpg_signing_command()
 
339
        if command is not None:
 
340
            return command
 
341
        return self._get_global_config()._gpg_signing_command()
 
342
 
 
343
    def _log_formatter(self):
 
344
        """See Config.log_formatter."""
 
345
        command = super(LocationConfig, self)._log_formatter()
 
346
        if command is not None:
 
347
            return command
 
348
        return self._get_global_config()._log_formatter()
 
349
 
 
350
    def _get_user_id(self):
 
351
        user_id = super(LocationConfig, self)._get_user_id()
 
352
        if user_id is not None:
 
353
            return user_id
 
354
        return self._get_global_config()._get_user_id()
 
355
 
 
356
    def _get_user_option(self, option_name):
 
357
        """See Config._get_user_option."""
 
358
        option_value = super(LocationConfig, 
 
359
                             self)._get_user_option(option_name)
 
360
        if option_value is not None:
 
361
            return option_value
 
362
        return self._get_global_config()._get_user_option(option_name)
 
363
 
 
364
    def _get_signature_checking(self):
 
365
        """See Config._get_signature_checking."""
 
366
        check = super(LocationConfig, self)._get_signature_checking()
 
367
        if check is not None:
 
368
            return check
 
369
        return self._get_global_config()._get_signature_checking()
 
370
 
 
371
    def _post_commit(self):
 
372
        """See Config.post_commit."""
 
373
        hook = self._get_user_option('post_commit')
 
374
        if hook is not None:
 
375
            return hook
 
376
        return self._get_global_config()._post_commit()
 
377
 
 
378
    def set_user_option(self, option, value):
 
379
        """Save option and its value in the configuration."""
 
380
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
381
        # file lock on branches.conf.
 
382
        conf_dir = os.path.dirname(self._get_filename())
 
383
        ensure_config_dir_exists(conf_dir)
 
384
        location = self.location
 
385
        if location.endswith('/'):
 
386
            location = location[:-1]
 
387
        if (not location in self._get_parser() and
 
388
            not location + '/' in self._get_parser()):
 
389
            self._get_parser()[location]={}
 
390
        elif location + '/' in self._get_parser():
 
391
            location = location + '/'
 
392
        self._get_parser()[location][option]=value
 
393
        self._get_parser().write()
 
394
 
 
395
 
 
396
class BranchConfig(Config):
 
397
    """A configuration object giving the policy for a branch."""
 
398
 
 
399
    def _get_location_config(self):
 
400
        if self._location_config is None:
 
401
            self._location_config = LocationConfig(self.branch.base)
 
402
        return self._location_config
 
403
 
 
404
    def _get_user_id(self):
 
405
        """Return the full user id for the branch.
 
406
    
 
407
        e.g. "John Hacker <jhacker@foo.org>"
 
408
        This is looked up in the email controlfile for the branch.
 
409
        """
 
410
        try:
 
411
            return (self.branch.control_files.get_utf8("email") 
 
412
                    .read()
 
413
                    .decode(bzrlib.user_encoding)
 
414
                    .rstrip("\r\n"))
 
415
        except errors.NoSuchFile, e:
 
416
            pass
 
417
        
 
418
        return self._get_location_config()._get_user_id()
 
419
 
 
420
    def _get_signature_checking(self):
 
421
        """See Config._get_signature_checking."""
 
422
        return self._get_location_config()._get_signature_checking()
 
423
 
 
424
    def _get_user_option(self, option_name):
 
425
        """See Config._get_user_option."""
 
426
        return self._get_location_config()._get_user_option(option_name)
 
427
 
 
428
    def _gpg_signing_command(self):
 
429
        """See Config.gpg_signing_command."""
 
430
        return self._get_location_config()._gpg_signing_command()
 
431
        
 
432
    def __init__(self, branch):
 
433
        super(BranchConfig, self).__init__()
 
434
        self._location_config = None
 
435
        self.branch = branch
 
436
 
 
437
    def _post_commit(self):
 
438
        """See Config.post_commit."""
 
439
        return self._get_location_config()._post_commit()
 
440
 
 
441
    def _log_formatter(self):
 
442
        """See Config.log_formatter."""
 
443
        return self._get_location_config()._log_formatter()
 
444
 
 
445
def ensure_config_dir_exists(path=None):
 
446
    """Make sure a configuration directory exists.
 
447
    This makes sure that the directory exists.
 
448
    On windows, since configuration directories are 2 levels deep,
 
449
    it makes sure both the directory and the parent directory exists.
 
450
    """
 
451
    if path is None:
 
452
        path = config_dir()
 
453
    if not os.path.isdir(path):
 
454
        if sys.platform == 'win32':
 
455
            parent_dir = os.path.dirname(path)
 
456
            if not os.path.isdir(parent_dir):
 
457
                mutter('creating config parent directory: %r', parent_dir)
 
458
            os.mkdir(parent_dir)
 
459
        mutter('creating config directory: %r', path)
 
460
        os.mkdir(path)
 
461
 
 
462
 
 
463
def config_dir():
 
464
    """Return per-user configuration directory.
 
465
 
 
466
    By default this is ~/.bazaar/
 
467
    
 
468
    TODO: Global option --config-dir to override this.
 
469
    """
 
470
    base = os.environ.get('BZR_HOME', None)
 
471
    if sys.platform == 'win32':
 
472
        if base is None:
 
473
            base = os.environ.get('APPDATA', None)
 
474
        if base is None:
 
475
            base = os.environ.get('HOME', None)
 
476
        if base is None:
 
477
            raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
 
478
        return pathjoin(base, 'bazaar', '2.0')
 
479
    else:
 
480
        # cygwin, linux, and darwin all have a $HOME directory
 
481
        if base is None:
 
482
            base = os.path.expanduser("~")
 
483
        return pathjoin(base, ".bazaar")
 
484
 
 
485
 
 
486
def config_filename():
 
487
    """Return per-user configuration ini file filename."""
 
488
    return pathjoin(config_dir(), 'bazaar.conf')
 
489
 
 
490
 
 
491
def branches_config_filename():
 
492
    """Return per-user configuration ini file filename."""
 
493
    return pathjoin(config_dir(), 'branches.conf')
 
494
 
 
495
 
 
496
def _auto_user_id():
 
497
    """Calculate automatic user identification.
 
498
 
 
499
    Returns (realname, email).
 
500
 
 
501
    Only used when none is set in the environment or the id file.
 
502
 
 
503
    This previously used the FQDN as the default domain, but that can
 
504
    be very slow on machines where DNS is broken.  So now we simply
 
505
    use the hostname.
 
506
    """
 
507
    import socket
 
508
 
 
509
    # XXX: Any good way to get real user name on win32?
 
510
 
 
511
    try:
 
512
        import pwd
 
513
        uid = os.getuid()
 
514
        w = pwd.getpwuid(uid)
 
515
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
516
        username = w.pw_name.decode(bzrlib.user_encoding)
 
517
        comma = gecos.find(',')
 
518
        if comma == -1:
 
519
            realname = gecos
 
520
        else:
 
521
            realname = gecos[:comma]
 
522
        if not realname:
 
523
            realname = username
 
524
 
 
525
    except ImportError:
 
526
        import getpass
 
527
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
528
 
 
529
    return realname, (username + '@' + socket.gethostname())
 
530
 
 
531
 
 
532
def extract_email_address(e):
 
533
    """Return just the address part of an email string.
 
534
    
 
535
    That is just the user@domain part, nothing else. 
 
536
    This part is required to contain only ascii characters.
 
537
    If it can't be extracted, raises an error.
 
538
    
 
539
    >>> extract_email_address('Jane Tester <jane@test.com>')
 
540
    "jane@test.com"
 
541
    """
 
542
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
543
    if not m:
 
544
        raise errors.BzrError("%r doesn't seem to contain "
 
545
                              "a reasonable email address" % e)
 
546
    return m.group(0)
 
547
 
 
548
class TreeConfig(object):
 
549
    """Branch configuration data associated with its contents, not location"""
 
550
    def __init__(self, branch):
 
551
        self.branch = branch
 
552
 
 
553
    def _get_config(self):
 
554
        try:
 
555
            obj = ConfigObj(self.branch.control_files.get('branch.conf'
 
556
                        ).readlines())
 
557
            obj.decode('UTF-8')
 
558
        except errors.NoSuchFile:
 
559
            obj = ConfigObj()
 
560
        return obj
 
561
 
 
562
    def get_option(self, name, section=None, default=None):
 
563
        self.branch.lock_read()
 
564
        try:
 
565
            obj = self._get_config()
 
566
            try:
 
567
                if section is not None:
 
568
                    obj[section]
 
569
                result = obj[name]
 
570
            except KeyError:
 
571
                result = default
 
572
        finally:
 
573
            self.branch.unlock()
 
574
        return result
 
575
 
 
576
    def set_option(self, value, name, section=None):
 
577
        """Set a per-branch configuration option"""
 
578
        self.branch.lock_write()
 
579
        try:
 
580
            cfg_obj = self._get_config()
 
581
            if section is None:
 
582
                obj = cfg_obj
 
583
            else:
 
584
                try:
 
585
                    obj = cfg_obj[section]
 
586
                except KeyError:
 
587
                    cfg_obj[section] = {}
 
588
                    obj = cfg_obj[section]
 
589
            obj[name] = value
 
590
            cfg_obj.encode('UTF-8')
 
591
            out_file = StringIO(''.join([l+'\n' for l in cfg_obj.write()]))
 
592
            out_file.seek(0)
 
593
            self.branch.control_files.put('branch.conf', out_file)
 
594
        finally:
 
595
            self.branch.unlock()