~ubuntu-branches/ubuntu/hardy/bzr/hardy-updates

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Bazaar Package Importer
  • Author(s): Jeff Bailey
  • Date: 2005-11-07 13:17:53 UTC
  • Revision ID: james.westby@ubuntu.com-20051107131753-qsy145z1rfug5i27
Tags: upstream-0.6.2
ImportĀ upstreamĀ versionĀ 0.6.2

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
from fnmatch import fnmatch
 
58
import re
 
59
 
 
60
import bzrlib
 
61
import bzrlib.errors as errors
 
62
import bzrlib.util.configobj.configobj as configobj
 
63
 
 
64
 
 
65
CHECK_IF_POSSIBLE=0
 
66
CHECK_ALWAYS=1
 
67
CHECK_NEVER=2
 
68
 
 
69
 
 
70
class ConfigObj(configobj.ConfigObj):
 
71
 
 
72
    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)
 
80
 
 
81
    def get_value(self, section, name):
 
82
        # Try [] for the old DEFAULT section.
 
83
        if section == "DEFAULT":
 
84
            try:
 
85
                return self[name]
 
86
            except KeyError:
 
87
                pass
 
88
        return self[section][name]
 
89
 
 
90
 
 
91
class Config(object):
 
92
    """A configuration policy - what username, editor, gpg needs etc."""
 
93
 
 
94
    def get_editor(self):
 
95
        """Get the users pop up editor."""
 
96
        raise NotImplementedError
 
97
 
 
98
    def _get_signature_checking(self):
 
99
        """Template method to override signature checking policy."""
 
100
 
 
101
    def _get_user_option(self, option_name):
 
102
        """Template method to provide a user option."""
 
103
        return None
 
104
 
 
105
    def get_user_option(self, option_name):
 
106
        """Get a generic option - no special process, no default."""
 
107
        return self._get_user_option(option_name)
 
108
 
 
109
    def gpg_signing_command(self):
 
110
        """What program should be used to sign signatures?"""
 
111
        result = self._gpg_signing_command()
 
112
        if result is None:
 
113
            result = "gpg"
 
114
        return result
 
115
 
 
116
    def _gpg_signing_command(self):
 
117
        """See gpg_signing_command()."""
 
118
        return None
 
119
 
 
120
    def __init__(self):
 
121
        super(Config, self).__init__()
 
122
 
 
123
    def post_commit(self):
 
124
        """An ordered list of python functions to call.
 
125
 
 
126
        Each function takes branch, rev_id as parameters.
 
127
        """
 
128
        return self._post_commit()
 
129
 
 
130
    def _post_commit(self):
 
131
        """See Config.post_commit."""
 
132
        return None
 
133
 
 
134
    def user_email(self):
 
135
        """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)
 
142
 
 
143
    def username(self):
 
144
        """Return email-style username.
 
145
    
 
146
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
147
        
 
148
        $BZREMAIL can be set to override this, then
 
149
        the concrete policy type is checked, and finally
 
150
        $EMAIL is examinged.
 
151
        but if none is found, a reasonable default is (hopefully)
 
152
        created.
 
153
    
 
154
        TODO: Check it's reasonably well-formed.
 
155
        """
 
156
        v = os.environ.get('BZREMAIL')
 
157
        if v:
 
158
            return v.decode(bzrlib.user_encoding)
 
159
    
 
160
        v = self._get_user_id()
 
161
        if v:
 
162
            return v
 
163
        
 
164
        v = os.environ.get('EMAIL')
 
165
        if v:
 
166
            return v.decode(bzrlib.user_encoding)
 
167
 
 
168
        name, email = _auto_user_id()
 
169
        if name:
 
170
            return '%s <%s>' % (name, email)
 
171
        else:
 
172
            return email
 
173
 
 
174
    def signature_checking(self):
 
175
        """What is the current policy for signature checking?."""
 
176
        policy = self._get_signature_checking()
 
177
        if policy is not None:
 
178
            return policy
 
179
        return CHECK_IF_POSSIBLE
 
180
 
 
181
    def signature_needed(self):
 
182
        """Is a signature needed when committing ?."""
 
183
        policy = self._get_signature_checking()
 
184
        if policy == CHECK_ALWAYS:
 
185
            return True
 
186
        return False
 
187
 
 
188
 
 
189
class IniBasedConfig(Config):
 
190
    """A configuration policy that draws from ini files."""
 
191
 
 
192
    def _get_parser(self, file=None):
 
193
        if self._parser is not None:
 
194
            return self._parser
 
195
        if file is None:
 
196
            input = self._get_filename()
 
197
        else:
 
198
            input = file
 
199
        try:
 
200
            self._parser = ConfigObj(input)
 
201
        except configobj.ConfigObjError, e:
 
202
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
203
        return self._parser
 
204
 
 
205
    def _get_section(self):
 
206
        """Override this to define the section used by the config."""
 
207
        return "DEFAULT"
 
208
 
 
209
    def _get_signature_checking(self):
 
210
        """See Config._get_signature_checking."""
 
211
        policy = self._get_user_option('check_signatures')
 
212
        if policy:
 
213
            return self._string_to_signature_policy(policy)
 
214
 
 
215
    def _get_user_id(self):
 
216
        """Get the user id from the 'email' key in the current section."""
 
217
        return self._get_user_option('email')
 
218
 
 
219
    def _get_user_option(self, option_name):
 
220
        """See Config._get_user_option."""
 
221
        try:
 
222
            return self._get_parser().get_value(self._get_section(),
 
223
                                                option_name)
 
224
        except KeyError:
 
225
            pass
 
226
 
 
227
    def _gpg_signing_command(self):
 
228
        """See Config.gpg_signing_command."""
 
229
        return self._get_user_option('gpg_signing_command')
 
230
 
 
231
    def __init__(self, get_filename):
 
232
        super(IniBasedConfig, self).__init__()
 
233
        self._get_filename = get_filename
 
234
        self._parser = None
 
235
        
 
236
    def _post_commit(self):
 
237
        """See Config.post_commit."""
 
238
        return self._get_user_option('post_commit')
 
239
 
 
240
    def _string_to_signature_policy(self, signature_string):
 
241
        """Convert a string to a signing policy."""
 
242
        if signature_string.lower() == 'check-available':
 
243
            return CHECK_IF_POSSIBLE
 
244
        if signature_string.lower() == 'ignore':
 
245
            return CHECK_NEVER
 
246
        if signature_string.lower() == 'require':
 
247
            return CHECK_ALWAYS
 
248
        raise errors.BzrError("Invalid signatures policy '%s'"
 
249
                              % signature_string)
 
250
 
 
251
 
 
252
class GlobalConfig(IniBasedConfig):
 
253
    """The configuration that should be used for a specific location."""
 
254
 
 
255
    def get_editor(self):
 
256
        return self._get_user_option('editor')
 
257
 
 
258
    def __init__(self):
 
259
        super(GlobalConfig, self).__init__(config_filename)
 
260
 
 
261
 
 
262
class LocationConfig(IniBasedConfig):
 
263
    """A configuration object that gives the policy for a location."""
 
264
 
 
265
    def __init__(self, location):
 
266
        super(LocationConfig, self).__init__(branches_config_filename)
 
267
        self._global_config = None
 
268
        self.location = location
 
269
 
 
270
    def _get_global_config(self):
 
271
        if self._global_config is None:
 
272
            self._global_config = GlobalConfig()
 
273
        return self._global_config
 
274
 
 
275
    def _get_section(self):
 
276
        """Get the section we should look in for config items.
 
277
 
 
278
        Returns None if none exists. 
 
279
        TODO: perhaps return a NullSection that thunks through to the 
 
280
              global config.
 
281
        """
 
282
        sections = self._get_parser()
 
283
        location_names = self.location.split('/')
 
284
        if self.location.endswith('/'):
 
285
            del location_names[-1]
 
286
        matches=[]
 
287
        for section in sections:
 
288
            section_names = section.split('/')
 
289
            if section.endswith('/'):
 
290
                del section_names[-1]
 
291
            names = zip(location_names, section_names)
 
292
            matched = True
 
293
            for name in names:
 
294
                if not fnmatch(name[0], name[1]):
 
295
                    matched = False
 
296
                    break
 
297
            if not matched:
 
298
                continue
 
299
            # so, for the common prefix they matched.
 
300
            # if section is longer, no match.
 
301
            if len(section_names) > len(location_names):
 
302
                continue
 
303
            # if path is longer, and recurse is not true, no match
 
304
            if len(section_names) < len(location_names):
 
305
                try:
 
306
                    if not self._get_parser().get_bool(section, 'recurse'):
 
307
                        continue
 
308
                except KeyError:
 
309
                    pass
 
310
            matches.append((len(section_names), section))
 
311
        if not len(matches):
 
312
            return None
 
313
        matches.sort(reverse=True)
 
314
        return matches[0][1]
 
315
 
 
316
    def _gpg_signing_command(self):
 
317
        """See Config.gpg_signing_command."""
 
318
        command = super(LocationConfig, self)._gpg_signing_command()
 
319
        if command is not None:
 
320
            return command
 
321
        return self._get_global_config()._gpg_signing_command()
 
322
 
 
323
    def _get_user_id(self):
 
324
        user_id = super(LocationConfig, self)._get_user_id()
 
325
        if user_id is not None:
 
326
            return user_id
 
327
        return self._get_global_config()._get_user_id()
 
328
 
 
329
    def _get_user_option(self, option_name):
 
330
        """See Config._get_user_option."""
 
331
        option_value = super(LocationConfig, 
 
332
                             self)._get_user_option(option_name)
 
333
        if option_value is not None:
 
334
            return option_value
 
335
        return self._get_global_config()._get_user_option(option_name)
 
336
 
 
337
    def _get_signature_checking(self):
 
338
        """See Config._get_signature_checking."""
 
339
        check = super(LocationConfig, self)._get_signature_checking()
 
340
        if check is not None:
 
341
            return check
 
342
        return self._get_global_config()._get_signature_checking()
 
343
 
 
344
    def _post_commit(self):
 
345
        """See Config.post_commit."""
 
346
        hook = self._get_user_option('post_commit')
 
347
        if hook is not None:
 
348
            return hook
 
349
        return self._get_global_config()._post_commit()
 
350
 
 
351
 
 
352
class BranchConfig(Config):
 
353
    """A configuration object giving the policy for a branch."""
 
354
 
 
355
    def _get_location_config(self):
 
356
        if self._location_config is None:
 
357
            self._location_config = LocationConfig(self.branch.base)
 
358
        return self._location_config
 
359
 
 
360
    def _get_user_id(self):
 
361
        """Return the full user id for the branch.
 
362
    
 
363
        e.g. "John Hacker <jhacker@foo.org>"
 
364
        This is looked up in the email controlfile for the branch.
 
365
        """
 
366
        try:
 
367
            return (self.branch.controlfile("email", "r") 
 
368
                    .read()
 
369
                    .decode(bzrlib.user_encoding)
 
370
                    .rstrip("\r\n"))
 
371
        except errors.NoSuchFile, e:
 
372
            pass
 
373
        
 
374
        return self._get_location_config()._get_user_id()
 
375
 
 
376
    def _get_signature_checking(self):
 
377
        """See Config._get_signature_checking."""
 
378
        return self._get_location_config()._get_signature_checking()
 
379
 
 
380
    def _get_user_option(self, option_name):
 
381
        """See Config._get_user_option."""
 
382
        return self._get_location_config()._get_user_option(option_name)
 
383
 
 
384
    def _gpg_signing_command(self):
 
385
        """See Config.gpg_signing_command."""
 
386
        return self._get_location_config()._gpg_signing_command()
 
387
        
 
388
    def __init__(self, branch):
 
389
        super(BranchConfig, self).__init__()
 
390
        self._location_config = None
 
391
        self.branch = branch
 
392
 
 
393
    def _post_commit(self):
 
394
        """See Config.post_commit."""
 
395
        return self._get_location_config()._post_commit()
 
396
 
 
397
 
 
398
def config_dir():
 
399
    """Return per-user configuration directory.
 
400
 
 
401
    By default this is ~/.bazaar/
 
402
    
 
403
    TODO: Global option --config-dir to override this.
 
404
    """
 
405
    return os.path.join(os.path.expanduser("~"), ".bazaar")
 
406
 
 
407
 
 
408
def config_filename():
 
409
    """Return per-user configuration ini file filename."""
 
410
    return os.path.join(config_dir(), 'bazaar.conf')
 
411
 
 
412
 
 
413
def branches_config_filename():
 
414
    """Return per-user configuration ini file filename."""
 
415
    return os.path.join(config_dir(), 'branches.conf')
 
416
 
 
417
 
 
418
def _auto_user_id():
 
419
    """Calculate automatic user identification.
 
420
 
 
421
    Returns (realname, email).
 
422
 
 
423
    Only used when none is set in the environment or the id file.
 
424
 
 
425
    This previously used the FQDN as the default domain, but that can
 
426
    be very slow on machines where DNS is broken.  So now we simply
 
427
    use the hostname.
 
428
    """
 
429
    import socket
 
430
 
 
431
    # XXX: Any good way to get real user name on win32?
 
432
 
 
433
    try:
 
434
        import pwd
 
435
        uid = os.getuid()
 
436
        w = pwd.getpwuid(uid)
 
437
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
438
        username = w.pw_name.decode(bzrlib.user_encoding)
 
439
        comma = gecos.find(',')
 
440
        if comma == -1:
 
441
            realname = gecos
 
442
        else:
 
443
            realname = gecos[:comma]
 
444
        if not realname:
 
445
            realname = username
 
446
 
 
447
    except ImportError:
 
448
        import getpass
 
449
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
450
 
 
451
    return realname, (username + '@' + socket.gethostname())
 
452
 
 
453
 
 
454
def extract_email_address(e):
 
455
    """Return just the address part of an email string.
 
456
    
 
457
    That is just the user@domain part, nothing else. 
 
458
    This part is required to contain only ascii characters.
 
459
    If it can't be extracted, raises an error.
 
460
    
 
461
    >>> extract_email_address('Jane Tester <jane@test.com>')
 
462
    "jane@test.com"
 
463
    """
 
464
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
465
    if not m:
 
466
        raise BzrError("%r doesn't seem to contain "
 
467
                       "a reasonable email address" % e)
 
468
    return m.group(0)