~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Martin Pool
  • Date: 2005-09-05 05:35:25 UTC
  • mfrom: (974.1.55)
  • Revision ID: mbp@sourcefrog.net-20050905053525-2112bac069dbe331
- merge various bug fixes from aaron

aaron.bentley@utoronto.ca-20050905020131-a2d5b7711dd6cd98

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
 
from util.configobj.configobj import ConfigObj, ConfigObjError
55
 
import os
56
 
from fnmatch import fnmatch
57
 
import errno
58
 
import re
59
 
 
60
 
import bzrlib
61
 
import bzrlib.errors as errors
62
 
 
63
 
 
64
 
CHECK_IF_POSSIBLE=0
65
 
CHECK_ALWAYS=1
66
 
CHECK_NEVER=2
67
 
 
68
 
 
69
 
class Config(object):
70
 
    """A configuration policy - what username, editor, gpg needs etc."""
71
 
 
72
 
    def get_editor(self):
73
 
        """Get the users pop up editor."""
74
 
        raise NotImplementedError
75
 
 
76
 
    def _get_signature_checking(self):
77
 
        """Template method to override signature checking policy."""
78
 
 
79
 
    def _get_user_option(self, option_name):
80
 
        """Template method to provide a user option."""
81
 
        return None
82
 
 
83
 
    def get_user_option(self, option_name):
84
 
        """Get a generic option - no special process, no default."""
85
 
        return self._get_user_option(option_name)
86
 
 
87
 
    def gpg_signing_command(self):
88
 
        """What program should be used to sign signatures?"""
89
 
        result = self._gpg_signing_command()
90
 
        if result is None:
91
 
            result = "gpg"
92
 
        return result
93
 
 
94
 
    def _gpg_signing_command(self):
95
 
        """See gpg_signing_command()."""
96
 
        return None
97
 
 
98
 
    def __init__(self):
99
 
        super(Config, self).__init__()
100
 
 
101
 
    def user_email(self):
102
 
        """Return just the email component of a username."""
103
 
        e = self.username()
104
 
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
105
 
        if not m:
106
 
            raise BzrError("%r doesn't seem to contain "
107
 
                           "a reasonable email address" % e)
108
 
        return m.group(0)
109
 
 
110
 
    def username(self):
111
 
        """Return email-style username.
112
 
    
113
 
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
114
 
        
115
 
        $BZREMAIL can be set to override this, then
116
 
        the concrete policy type is checked, and finally
117
 
        $EMAIL is examinged.
118
 
        but if none is found, a reasonable default is (hopefully)
119
 
        created.
120
 
    
121
 
        TODO: Check it's reasonably well-formed.
122
 
        """
123
 
        v = os.environ.get('BZREMAIL')
124
 
        if v:
125
 
            return v.decode(bzrlib.user_encoding)
126
 
    
127
 
        v = self._get_user_id()
128
 
        if v:
129
 
            return v
130
 
        
131
 
        v = os.environ.get('EMAIL')
132
 
        if v:
133
 
            return v.decode(bzrlib.user_encoding)
134
 
 
135
 
        name, email = _auto_user_id()
136
 
        if name:
137
 
            return '%s <%s>' % (name, email)
138
 
        else:
139
 
            return email
140
 
 
141
 
    def signature_checking(self):
142
 
        """What is the current policy for signature checking?."""
143
 
        policy = self._get_signature_checking()
144
 
        if policy is not None:
145
 
            return policy
146
 
        return CHECK_IF_POSSIBLE
147
 
 
148
 
    def signature_needed(self):
149
 
        """Is a signature needed when committing ?."""
150
 
        policy = self._get_signature_checking()
151
 
        if policy == CHECK_ALWAYS:
152
 
            return True
153
 
        return False
154
 
 
155
 
 
156
 
class IniBasedConfig(Config):
157
 
    """A configuration policy that draws from ini files."""
158
 
 
159
 
    def _get_parser(self, file=None):
160
 
        if self._parser is not None:
161
 
            return self._parser
162
 
        if file is None:
163
 
            input = self._get_filename()
164
 
        else:
165
 
            input = file
166
 
        try:
167
 
            self._parser = ConfigObj(input)
168
 
        except ConfigObjError, e:
169
 
            raise errors.ParseConfigError(e.errors, e.config.filename)
170
 
        return self._parser
171
 
 
172
 
    def _get_section(self):
173
 
        """Override this to define the section used by the config."""
174
 
        return "DEFAULT"
175
 
 
176
 
    def _config_val(self, name, section=None):
177
 
        if section is None:
178
 
            section = self._get_section()
179
 
        if section is None:
180
 
            raise KeyError(name)
181
 
        # Throw KeyError if name or section not present
182
 
        if section == "DEFAULT":
183
 
            try:
184
 
                return self._get_parser()[name]
185
 
            except KeyError:
186
 
                pass
187
 
        return self._get_parser()[section][name]
188
 
 
189
 
    def _config_bool(self, name, section=None):
190
 
        val = self._config_val(name, section).lower()
191
 
        if val in ('1', 'yes', 'true', 'on'):
192
 
            return True
193
 
        elif val in ('0', 'no', 'false', 'off'):
194
 
            return False
195
 
        else:
196
 
            raise ValueError("Value %r is not boolean" % val)
197
 
 
198
 
        
199
 
 
200
 
    def _get_signature_checking(self):
201
 
        """See Config._get_signature_checking."""
202
 
        try:
203
 
            policy = self._config_val('check_signatures')
204
 
        except KeyError:
205
 
            return None
206
 
        return self._string_to_signature_policy(policy)
207
 
 
208
 
    def _get_user_id(self):
209
 
        """Get the user id from the 'email' key in the current section."""
210
 
        try:
211
 
            return self._config_val('email')
212
 
        except KeyError:
213
 
            pass
214
 
 
215
 
    def _get_user_option(self, option_name):
216
 
        """See Config._get_user_option."""
217
 
        try:
218
 
            return self._config_val(option_name)
219
 
        except KeyError:
220
 
            pass
221
 
 
222
 
    def _gpg_signing_command(self):
223
 
        """See Config.gpg_signing_command."""
224
 
        try:
225
 
            return self._config_val('gpg_signing_command')
226
 
        except KeyError:
227
 
            pass
228
 
 
229
 
    def __init__(self, get_filename):
230
 
        super(IniBasedConfig, self).__init__()
231
 
        self._get_filename = get_filename
232
 
        self._parser = None
233
 
 
234
 
    def _string_to_signature_policy(self, signature_string):
235
 
        """Convert a string to a signing policy."""
236
 
        if signature_string.lower() == 'check-available':
237
 
            return CHECK_IF_POSSIBLE
238
 
        if signature_string.lower() == 'ignore':
239
 
            return CHECK_NEVER
240
 
        if signature_string.lower() == 'require':
241
 
            return CHECK_ALWAYS
242
 
        raise errors.BzrError("Invalid signatures policy '%s'"
243
 
                              % signature_string)
244
 
 
245
 
 
246
 
class GlobalConfig(IniBasedConfig):
247
 
    """The configuration that should be used for a specific location."""
248
 
 
249
 
    def get_editor(self):
250
 
        try:
251
 
            return self._config_val('editor')
252
 
        except KeyError:
253
 
            pass
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._config_bool('recurse', section=section):
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
 
 
342
 
class BranchConfig(Config):
343
 
    """A configuration object giving the policy for a branch."""
344
 
 
345
 
    def _get_location_config(self):
346
 
        if self._location_config is None:
347
 
            self._location_config = LocationConfig(self.branch.base)
348
 
        return self._location_config
349
 
 
350
 
    def _get_user_id(self):
351
 
        """Return the full user id for the branch.
352
 
    
353
 
        e.g. "John Hacker <jhacker@foo.org>"
354
 
        This is looked up in the email controlfile for the branch.
355
 
        """
356
 
        try:
357
 
            return (self.branch.controlfile("email", "r") 
358
 
                    .read()
359
 
                    .decode(bzrlib.user_encoding)
360
 
                    .rstrip("\r\n"))
361
 
        except errors.NoSuchFile, e:
362
 
            pass
363
 
        
364
 
        return self._get_location_config()._get_user_id()
365
 
 
366
 
    def _get_signature_checking(self):
367
 
        """See Config._get_signature_checking."""
368
 
        return self._get_location_config()._get_signature_checking()
369
 
 
370
 
    def _get_user_option(self, option_name):
371
 
        """See Config._get_user_option."""
372
 
        return self._get_location_config()._get_user_option(option_name)
373
 
 
374
 
    def _gpg_signing_command(self):
375
 
        """See Config.gpg_signing_command."""
376
 
        return self._get_location_config()._gpg_signing_command()
377
 
        
378
 
    def __init__(self, branch):
379
 
        super(BranchConfig, self).__init__()
380
 
        self._location_config = None
381
 
        self.branch = branch
382
 
 
383
 
 
384
 
def config_dir():
385
 
    """Return per-user configuration directory.
386
 
 
387
 
    By default this is ~/.bazaar/
388
 
    
389
 
    TODO: Global option --config-dir to override this.
390
 
    """
391
 
    return os.path.join(os.path.expanduser("~"), ".bazaar")
392
 
 
393
 
 
394
 
def config_filename():
395
 
    """Return per-user configuration ini file filename."""
396
 
    return os.path.join(config_dir(), 'bazaar.conf')
397
 
 
398
 
 
399
 
def branches_config_filename():
400
 
    """Return per-user configuration ini file filename."""
401
 
    return os.path.join(config_dir(), 'branches.conf')
402
 
 
403
 
 
404
 
def _auto_user_id():
405
 
    """Calculate automatic user identification.
406
 
 
407
 
    Returns (realname, email).
408
 
 
409
 
    Only used when none is set in the environment or the id file.
410
 
 
411
 
    This previously used the FQDN as the default domain, but that can
412
 
    be very slow on machines where DNS is broken.  So now we simply
413
 
    use the hostname.
414
 
    """
415
 
    import socket
416
 
 
417
 
    # XXX: Any good way to get real user name on win32?
418
 
 
419
 
    try:
420
 
        import pwd
421
 
        uid = os.getuid()
422
 
        w = pwd.getpwuid(uid)
423
 
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
424
 
        username = w.pw_name.decode(bzrlib.user_encoding)
425
 
        comma = gecos.find(',')
426
 
        if comma == -1:
427
 
            realname = gecos
428
 
        else:
429
 
            realname = gecos[:comma]
430
 
        if not realname:
431
 
            realname = username
432
 
 
433
 
    except ImportError:
434
 
        import getpass
435
 
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
436
 
 
437
 
    return realname, (username + '@' + socket.gethostname())
438
 
 
439
 
 
440
 
def extract_email_address(e):
441
 
    """Return just the address part of an email string.
442
 
    
443
 
    That is just the user@domain part, nothing else. 
444
 
    This part is required to contain only ascii characters.
445
 
    If it can't be extracted, raises an error.
446
 
    
447
 
    >>> extract_email_address('Jane Tester <jane@test.com>')
448
 
    "jane@test.com"
449
 
    """
450
 
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
451
 
    if not m:
452
 
        raise BzrError("%r doesn't seem to contain "
453
 
                       "a reasonable email address" % e)
454
 
    return m.group(0)