/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: Aaron Bentley
  • Date: 2005-10-19 02:40:58 UTC
  • mto: (1185.19.1)
  • mto: This revision was merged to the branch mainline in revision 1474.
  • Revision ID: aaron.bentley@utoronto.ca-20051019024058-4562b385778ee490
Added --show-base to merge

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.config 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
 
 
30
in branches.conf, you specify the url of a branch and options for it.
 
31
Wildcards may be used - * and ? as normal in shell completion. Options
 
32
set in both bazaar.conf and branches.conf are overriden by the branches.conf
 
33
setting.
 
34
[/home/robertc/source]
 
35
recurse=False|True(default)
 
36
email= as above
 
37
check_signatures= as abive 
 
38
create_signatures= as above.
 
39
 
 
40
explanation of options
 
41
----------------------
 
42
editor - this option sets the pop up editor to use during commits.
 
43
email - this option sets the user id bzr will use when committing.
 
44
check_signatures - this option controls whether bzr will require good gpg
 
45
                   signatures, ignore them, or check them if they are 
 
46
                   present.
 
47
create_signatures - this option controls whether bzr will always create 
 
48
                    gpg signatures, never create them, or create them if the
 
49
                    branch is configured to require them.
 
50
                    NB: This option is planned, but not implemented yet.
 
51
"""
 
52
 
 
53
from util.configobj.configobj import ConfigObj, ConfigObjError
 
54
import os
 
55
from fnmatch import fnmatch
 
56
import errno
 
57
import re
 
58
 
 
59
import bzrlib
 
60
import bzrlib.errors as errors
 
61
 
 
62
 
 
63
CHECK_IF_POSSIBLE=0
 
64
CHECK_ALWAYS=1
 
65
CHECK_NEVER=2
 
66
 
 
67
 
 
68
class Config(object):
 
69
    """A configuration policy - what username, editor, gpg needs etc."""
 
70
 
 
71
    def get_editor(self):
 
72
        """Get the users pop up editor."""
 
73
        raise NotImplementedError
 
74
 
 
75
    def _get_signature_checking(self):
 
76
        """Template method to override signature checking policy."""
 
77
 
 
78
    def __init__(self):
 
79
        super(Config, self).__init__()
 
80
 
 
81
    def user_email(self):
 
82
        """Return just the email component of a username."""
 
83
        e = self.username()
 
84
        m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
85
        if not m:
 
86
            raise BzrError("%r doesn't seem to contain "
 
87
                           "a reasonable email address" % e)
 
88
        return m.group(0)
 
89
 
 
90
    def username(self):
 
91
        """Return email-style username.
 
92
    
 
93
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
94
        
 
95
        $BZREMAIL can be set to override this, then
 
96
        the concrete policy type is checked, and finally
 
97
        $EMAIL is examinged.
 
98
        but if none is found, a reasonable default is (hopefully)
 
99
        created.
 
100
    
 
101
        TODO: Check it's reasonably well-formed.
 
102
        """
 
103
        v = os.environ.get('BZREMAIL')
 
104
        if v:
 
105
            return v.decode(bzrlib.user_encoding)
 
106
    
 
107
        v = self._get_user_id()
 
108
        if v:
 
109
            return v
 
110
        
 
111
        v = os.environ.get('EMAIL')
 
112
        if v:
 
113
            return v.decode(bzrlib.user_encoding)
 
114
 
 
115
        name, email = _auto_user_id()
 
116
        if name:
 
117
            return '%s <%s>' % (name, email)
 
118
        else:
 
119
            return email
 
120
 
 
121
    def signature_checking(self):
 
122
        """What is the current policy for signature checking?."""
 
123
        policy = self._get_signature_checking()
 
124
        if policy is not None:
 
125
            return policy
 
126
        return CHECK_IF_POSSIBLE
 
127
 
 
128
    def signature_needed(self):
 
129
        """Is a signature needed when committing ?."""
 
130
        policy = self._get_signature_checking()
 
131
        if policy == CHECK_ALWAYS:
 
132
            return True
 
133
        return False
 
134
 
 
135
 
 
136
class IniBasedConfig(Config):
 
137
    """A configuration policy that draws from ini files."""
 
138
 
 
139
    def _get_parser(self, file=None):
 
140
        if self._parser is not None:
 
141
            return self._parser
 
142
        if file is None:
 
143
            input = self._get_filename()
 
144
        else:
 
145
            input = file
 
146
        try:
 
147
            self._parser = ConfigObj(input)
 
148
        except ConfigObjError, e:
 
149
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
150
        return self._parser
 
151
 
 
152
    def _get_section(self):
 
153
        """Override this to define the section used by the config."""
 
154
        return "DEFAULT"
 
155
 
 
156
    def _config_val(self, name, section=None):
 
157
        if section is None:
 
158
            section = self._get_section()
 
159
        if section is None:
 
160
            raise KeyError(name)
 
161
        # Throw KeyError if name or section not present
 
162
        if section == "DEFAULT":
 
163
            try:
 
164
                return self._get_parser()[name]
 
165
            except KeyError:
 
166
                pass
 
167
        return self._get_parser()[section][name]
 
168
 
 
169
    def _config_bool(self, name, section=None):
 
170
        val = self._config_val(name, section).lower()
 
171
        if val in ('1', 'yes', 'true', 'on'):
 
172
            return True
 
173
        elif val in ('0', 'no', 'false', 'off'):
 
174
            return False
 
175
        else:
 
176
            raise ValueError("Value %r is not boolean" % val)
 
177
 
 
178
        
 
179
 
 
180
    def _get_signature_checking(self):
 
181
        """See Config._get_signature_checking."""
 
182
        try:
 
183
            policy = self._config_val('check_signatures')
 
184
        except KeyError:
 
185
            return None
 
186
        return self._string_to_signature_policy(policy)
 
187
 
 
188
    def _get_user_id(self):
 
189
        """Get the user id from the 'email' key in the current section."""
 
190
        try:
 
191
            return self._config_val('email')
 
192
        except KeyError:
 
193
            pass
 
194
 
 
195
    def __init__(self, get_filename):
 
196
        super(IniBasedConfig, self).__init__()
 
197
        self._get_filename = get_filename
 
198
        self._parser = None
 
199
 
 
200
    def _string_to_signature_policy(self, signature_string):
 
201
        """Convert a string to a signing policy."""
 
202
        if signature_string.lower() == 'check-available':
 
203
            return CHECK_IF_POSSIBLE
 
204
        if signature_string.lower() == 'ignore':
 
205
            return CHECK_NEVER
 
206
        if signature_string.lower() == 'require':
 
207
            return CHECK_ALWAYS
 
208
        raise errors.BzrError("Invalid signatures policy '%s'"
 
209
                              % signature_string)
 
210
 
 
211
 
 
212
class GlobalConfig(IniBasedConfig):
 
213
    """The configuration that should be used for a specific location."""
 
214
 
 
215
    def get_editor(self):
 
216
        try:
 
217
            return self._config_val('editor')
 
218
        except KeyError:
 
219
            pass
 
220
 
 
221
    def __init__(self):
 
222
        super(GlobalConfig, self).__init__(config_filename)
 
223
 
 
224
 
 
225
class LocationConfig(IniBasedConfig):
 
226
    """A configuration object that gives the policy for a location."""
 
227
 
 
228
    def __init__(self, location):
 
229
        super(LocationConfig, self).__init__(branches_config_filename)
 
230
        self._global_config = None
 
231
        self.location = location
 
232
 
 
233
    def _get_global_config(self):
 
234
        if self._global_config is None:
 
235
            self._global_config = GlobalConfig()
 
236
        return self._global_config
 
237
 
 
238
    def _get_section(self):
 
239
        """Get the section we should look in for config items.
 
240
 
 
241
        Returns None if none exists. 
 
242
        TODO: perhaps return a NullSection that thunks through to the 
 
243
              global config.
 
244
        """
 
245
        sections = self._get_parser()
 
246
        location_names = self.location.split('/')
 
247
        if self.location.endswith('/'):
 
248
            del location_names[-1]
 
249
        matches=[]
 
250
        for section in sections:
 
251
            section_names = section.split('/')
 
252
            if section.endswith('/'):
 
253
                del section_names[-1]
 
254
            names = zip(location_names, section_names)
 
255
            matched = True
 
256
            for name in names:
 
257
                if not fnmatch(name[0], name[1]):
 
258
                    matched = False
 
259
                    break
 
260
            if not matched:
 
261
                continue
 
262
            # so, for the common prefix they matched.
 
263
            # if section is longer, no match.
 
264
            if len(section_names) > len(location_names):
 
265
                continue
 
266
            # if path is longer, and recurse is not true, no match
 
267
            if len(section_names) < len(location_names):
 
268
                try:
 
269
                    if not self._config_bool('recurse', section=section):
 
270
                        continue
 
271
                except KeyError:
 
272
                    pass
 
273
            matches.append((len(section_names), section))
 
274
        if not len(matches):
 
275
            return None
 
276
        matches.sort(reverse=True)
 
277
        return matches[0][1]
 
278
 
 
279
    def _get_user_id(self):
 
280
        user_id = super(LocationConfig, self)._get_user_id()
 
281
        if user_id is not None:
 
282
            return user_id
 
283
        return self._get_global_config()._get_user_id()
 
284
 
 
285
    def _get_signature_checking(self):
 
286
        """See Config._get_signature_checking."""
 
287
        check = super(LocationConfig, self)._get_signature_checking()
 
288
        if check is not None:
 
289
            return check
 
290
        return self._get_global_config()._get_signature_checking()
 
291
 
 
292
 
 
293
class BranchConfig(Config):
 
294
    """A configuration object giving the policy for a branch."""
 
295
 
 
296
    def _get_location_config(self):
 
297
        if self._location_config is None:
 
298
            self._location_config = LocationConfig(self.branch.base)
 
299
        return self._location_config
 
300
 
 
301
    def _get_user_id(self):
 
302
        """Return the full user id for the branch.
 
303
    
 
304
        e.g. "John Hacker <jhacker@foo.org>"
 
305
        This is looked up in the email controlfile for the branch.
 
306
        """
 
307
        try:
 
308
            return (self.branch.controlfile("email", "r") 
 
309
                    .read()
 
310
                    .decode(bzrlib.user_encoding)
 
311
                    .rstrip("\r\n"))
 
312
        except errors.NoSuchFile, e:
 
313
            pass
 
314
        
 
315
        return self._get_location_config()._get_user_id()
 
316
 
 
317
    def _get_signature_checking(self):
 
318
        """See Config._get_signature_checking."""
 
319
        return self._get_location_config()._get_signature_checking()
 
320
 
 
321
    def __init__(self, branch):
 
322
        super(BranchConfig, self).__init__()
 
323
        self._location_config = None
 
324
        self.branch = branch
 
325
 
 
326
 
 
327
def config_dir():
 
328
    """Return per-user configuration directory.
 
329
 
 
330
    By default this is ~/.bazaar/
 
331
    
 
332
    TODO: Global option --config-dir to override this.
 
333
    """
 
334
    return os.path.join(os.path.expanduser("~"), ".bazaar")
 
335
 
 
336
 
 
337
def config_filename():
 
338
    """Return per-user configuration ini file filename."""
 
339
    return os.path.join(config_dir(), 'bazaar.conf')
 
340
 
 
341
 
 
342
def branches_config_filename():
 
343
    """Return per-user configuration ini file filename."""
 
344
    return os.path.join(config_dir(), 'branches.conf')
 
345
 
 
346
 
 
347
def _auto_user_id():
 
348
    """Calculate automatic user identification.
 
349
 
 
350
    Returns (realname, email).
 
351
 
 
352
    Only used when none is set in the environment or the id file.
 
353
 
 
354
    This previously used the FQDN as the default domain, but that can
 
355
    be very slow on machines where DNS is broken.  So now we simply
 
356
    use the hostname.
 
357
    """
 
358
    import socket
 
359
 
 
360
    # XXX: Any good way to get real user name on win32?
 
361
 
 
362
    try:
 
363
        import pwd
 
364
        uid = os.getuid()
 
365
        w = pwd.getpwuid(uid)
 
366
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
367
        username = w.pw_name.decode(bzrlib.user_encoding)
 
368
        comma = gecos.find(',')
 
369
        if comma == -1:
 
370
            realname = gecos
 
371
        else:
 
372
            realname = gecos[:comma]
 
373
        if not realname:
 
374
            realname = username
 
375
 
 
376
    except ImportError:
 
377
        import getpass
 
378
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
379
 
 
380
    return realname, (username + '@' + socket.gethostname())
 
381
 
 
382
 
 
383
def extract_email_address(e):
 
384
    """Return just the address part of an email string.
 
385
    
 
386
    That is just the user@domain part, nothing else. 
 
387
    This part is required to contain only ascii characters.
 
388
    If it can't be extracted, raises an error.
 
389
    
 
390
    >>> extract_email_address('Jane Tester <jane@test.com>')
 
391
    "jane@test.com"
 
392
    """
 
393
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
 
394
    if not m:
 
395
        raise BzrError("%r doesn't seem to contain "
 
396
                       "a reasonable email address" % e)
 
397
    return m.group(0)