/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: John Arbash Meinel
  • Date: 2005-12-01 18:16:47 UTC
  • mto: (1185.50.19 bzr-jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1532.
  • Revision ID: john@arbash-meinel.com-20051201181647-2d65af900f14ba6a
Switched os.path.abspath and os.path.realpath to osutils.* (still passes on cygwin)

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