~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-04-19 00:23:05 UTC
  • mfrom: (3373.1.1 jam-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080419002305-25ayhxp3m0b95e9c
(jam) Trivial update to warning message when a user has not run
        lp-login

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Ltd
 
1
# Copyright (C) 2005, 2007 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
 
3
#            and others
3
4
#
4
5
# This program is free software; you can redistribute it and/or modify
5
6
# it under the terms of the GNU General Public License as published by
18
19
"""Configuration that affects the behaviour of Bazaar.
19
20
 
20
21
Currently this configuration resides in ~/.bazaar/bazaar.conf
21
 
and ~/.bazaar/branches.conf, which is written to by bzr.
 
22
and ~/.bazaar/locations.conf, which is written to by bzr.
22
23
 
23
24
In bazaar.conf the following options may be set:
24
25
[DEFAULT]
27
28
check_signatures=require|ignore|check-available(default)
28
29
create_signatures=always|never|when-required(default)
29
30
gpg_signing_command=name-of-program
 
31
log_format=name-of-format
30
32
 
31
 
in branches.conf, you specify the url of a branch and options for it.
 
33
in locations.conf, you specify the url of a branch and options for it.
32
34
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
 
35
set in both bazaar.conf and locations.conf are overridden by the locations.conf
34
36
setting.
35
37
[/home/robertc/source]
36
38
recurse=False|True(default)
37
39
email= as above
38
 
check_signatures= as abive 
 
40
check_signatures= as above 
39
41
create_signatures= as above.
40
42
 
41
43
explanation of options
48
50
create_signatures - this option controls whether bzr will always create 
49
51
                    gpg signatures, never create them, or create them if the
50
52
                    branch is configured to require them.
51
 
                    NB: This option is planned, but not implemented yet.
 
53
log_format - this option sets the default log format.  Possible values are
 
54
             long, short, line, or a plugin can register new formats.
 
55
 
 
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
 
57
 
 
58
[ALIASES]
 
59
lastlog=log --line -r-10..-1
 
60
ll=log --line -r-10..-1
 
61
h=help
 
62
up=pull
52
63
"""
53
64
 
54
 
from ConfigParser import ConfigParser
55
65
import os
 
66
import sys
 
67
 
 
68
from bzrlib.lazy_import import lazy_import
 
69
lazy_import(globals(), """
 
70
import errno
56
71
from fnmatch import fnmatch
57
 
import errno
58
72
import re
 
73
from cStringIO import StringIO
59
74
 
60
75
import bzrlib
61
 
import bzrlib.errors as errors
 
76
from bzrlib import (
 
77
    debug,
 
78
    errors,
 
79
    mail_client,
 
80
    osutils,
 
81
    symbol_versioning,
 
82
    trace,
 
83
    ui,
 
84
    urlutils,
 
85
    win32utils,
 
86
    )
 
87
from bzrlib.util.configobj import configobj
 
88
""")
62
89
 
63
90
 
64
91
CHECK_IF_POSSIBLE=0
66
93
CHECK_NEVER=2
67
94
 
68
95
 
 
96
SIGN_WHEN_REQUIRED=0
 
97
SIGN_ALWAYS=1
 
98
SIGN_NEVER=2
 
99
 
 
100
 
 
101
POLICY_NONE = 0
 
102
POLICY_NORECURSE = 1
 
103
POLICY_APPENDPATH = 2
 
104
 
 
105
_policy_name = {
 
106
    POLICY_NONE: None,
 
107
    POLICY_NORECURSE: 'norecurse',
 
108
    POLICY_APPENDPATH: 'appendpath',
 
109
    }
 
110
_policy_value = {
 
111
    None: POLICY_NONE,
 
112
    'none': POLICY_NONE,
 
113
    'norecurse': POLICY_NORECURSE,
 
114
    'appendpath': POLICY_APPENDPATH,
 
115
    }
 
116
 
 
117
 
 
118
STORE_LOCATION = POLICY_NONE
 
119
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
 
120
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
 
121
STORE_BRANCH = 3
 
122
STORE_GLOBAL = 4
 
123
 
 
124
 
 
125
class ConfigObj(configobj.ConfigObj):
 
126
 
 
127
    def get_bool(self, section, key):
 
128
        return self[section].as_bool(key)
 
129
 
 
130
    def get_value(self, section, name):
 
131
        # Try [] for the old DEFAULT section.
 
132
        if section == "DEFAULT":
 
133
            try:
 
134
                return self[name]
 
135
            except KeyError:
 
136
                pass
 
137
        return self[section][name]
 
138
 
 
139
 
69
140
class Config(object):
70
141
    """A configuration policy - what username, editor, gpg needs etc."""
71
142
 
73
144
        """Get the users pop up editor."""
74
145
        raise NotImplementedError
75
146
 
 
147
    def get_mail_client(self):
 
148
        """Get a mail client to use"""
 
149
        selected_client = self.get_user_option('mail_client')
 
150
        try:
 
151
            mail_client_class = {
 
152
                None: mail_client.DefaultMail,
 
153
                # Specific clients
 
154
                'emacsclient': mail_client.EmacsMail,
 
155
                'evolution': mail_client.Evolution,
 
156
                'kmail': mail_client.KMail,
 
157
                'mutt': mail_client.Mutt,
 
158
                'thunderbird': mail_client.Thunderbird,
 
159
                # Generic options
 
160
                'default': mail_client.DefaultMail,
 
161
                'editor': mail_client.Editor,
 
162
                'mapi': mail_client.MAPIClient,
 
163
                'xdg-email': mail_client.XDGEmail,
 
164
            }[selected_client]
 
165
        except KeyError:
 
166
            raise errors.UnknownMailClient(selected_client)
 
167
        return mail_client_class(self)
 
168
 
76
169
    def _get_signature_checking(self):
77
170
        """Template method to override signature checking policy."""
78
171
 
 
172
    def _get_signing_policy(self):
 
173
        """Template method to override signature creation policy."""
 
174
 
79
175
    def _get_user_option(self, option_name):
80
176
        """Template method to provide a user option."""
81
177
        return None
95
191
        """See gpg_signing_command()."""
96
192
        return None
97
193
 
 
194
    def log_format(self):
 
195
        """What log format should be used"""
 
196
        result = self._log_format()
 
197
        if result is None:
 
198
            result = "long"
 
199
        return result
 
200
 
 
201
    def _log_format(self):
 
202
        """See log_format()."""
 
203
        return None
 
204
 
98
205
    def __init__(self):
99
206
        super(Config, self).__init__()
100
207
 
 
208
    def post_commit(self):
 
209
        """An ordered list of python functions to call.
 
210
 
 
211
        Each function takes branch, rev_id as parameters.
 
212
        """
 
213
        return self._post_commit()
 
214
 
 
215
    def _post_commit(self):
 
216
        """See Config.post_commit."""
 
217
        return None
 
218
 
101
219
    def user_email(self):
102
220
        """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)
 
221
        return extract_email_address(self.username())
109
222
 
110
223
    def username(self):
111
224
        """Return email-style username.
112
225
    
113
226
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
114
227
        
115
 
        $BZREMAIL can be set to override this, then
 
228
        $BZR_EMAIL can be set to override this (as well as the
 
229
        deprecated $BZREMAIL), then
116
230
        the concrete policy type is checked, and finally
117
 
        $EMAIL is examinged.
118
 
        but if none is found, a reasonable default is (hopefully)
 
231
        $EMAIL is examined.
 
232
        If none is found, a reasonable default is (hopefully)
119
233
        created.
120
234
    
121
235
        TODO: Check it's reasonably well-formed.
122
236
        """
123
 
        v = os.environ.get('BZREMAIL')
 
237
        v = os.environ.get('BZR_EMAIL')
124
238
        if v:
125
239
            return v.decode(bzrlib.user_encoding)
126
 
    
 
240
 
127
241
        v = self._get_user_id()
128
242
        if v:
129
243
            return v
130
 
        
 
244
 
131
245
        v = os.environ.get('EMAIL')
132
246
        if v:
133
247
            return v.decode(bzrlib.user_encoding)
145
259
            return policy
146
260
        return CHECK_IF_POSSIBLE
147
261
 
 
262
    def signing_policy(self):
 
263
        """What is the current policy for signature checking?."""
 
264
        policy = self._get_signing_policy()
 
265
        if policy is not None:
 
266
            return policy
 
267
        return SIGN_WHEN_REQUIRED
 
268
 
148
269
    def signature_needed(self):
149
270
        """Is a signature needed when committing ?."""
150
 
        policy = self._get_signature_checking()
151
 
        if policy == CHECK_ALWAYS:
 
271
        policy = self._get_signing_policy()
 
272
        if policy is None:
 
273
            policy = self._get_signature_checking()
 
274
            if policy is not None:
 
275
                trace.warning("Please use create_signatures,"
 
276
                              " not check_signatures to set signing policy.")
 
277
            if policy == CHECK_ALWAYS:
 
278
                return True
 
279
        elif policy == SIGN_ALWAYS:
152
280
            return True
153
281
        return False
154
282
 
 
283
    def get_alias(self, value):
 
284
        return self._get_alias(value)
 
285
 
 
286
    def _get_alias(self, value):
 
287
        pass
 
288
 
 
289
    def get_nickname(self):
 
290
        return self._get_nickname()
 
291
 
 
292
    def _get_nickname(self):
 
293
        return None
 
294
 
 
295
    def get_bzr_remote_path(self):
 
296
        try:
 
297
            return os.environ['BZR_REMOTE_PATH']
 
298
        except KeyError:
 
299
            path = self.get_user_option("bzr_remote_path")
 
300
            if path is None:
 
301
                path = 'bzr'
 
302
            return path
 
303
 
155
304
 
156
305
class IniBasedConfig(Config):
157
306
    """A configuration policy that draws from ini files."""
159
308
    def _get_parser(self, file=None):
160
309
        if self._parser is not None:
161
310
            return self._parser
162
 
        parser = ConfigParser()
163
 
        if file is not None:
164
 
            parser.readfp(file)
165
 
        else:
166
 
            parser.read([self._get_filename()])
167
 
        self._parser = parser
168
 
        return parser
 
311
        if file is None:
 
312
            input = self._get_filename()
 
313
        else:
 
314
            input = file
 
315
        try:
 
316
            self._parser = ConfigObj(input, encoding='utf-8')
 
317
        except configobj.ConfigObjError, e:
 
318
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
319
        return self._parser
 
320
 
 
321
    def _get_matching_sections(self):
 
322
        """Return an ordered list of (section_name, extra_path) pairs.
 
323
 
 
324
        If the section contains inherited configuration, extra_path is
 
325
        a string containing the additional path components.
 
326
        """
 
327
        section = self._get_section()
 
328
        if section is not None:
 
329
            return [(section, '')]
 
330
        else:
 
331
            return []
169
332
 
170
333
    def _get_section(self):
171
334
        """Override this to define the section used by the config."""
172
335
        return "DEFAULT"
173
336
 
 
337
    def _get_option_policy(self, section, option_name):
 
338
        """Return the policy for the given (section, option_name) pair."""
 
339
        return POLICY_NONE
 
340
 
174
341
    def _get_signature_checking(self):
175
342
        """See Config._get_signature_checking."""
176
 
        section = self._get_section()
177
 
        if section is None:
178
 
            return None
179
 
        if self._get_parser().has_option(section, 'check_signatures'):
180
 
            return self._string_to_signature_policy(
181
 
                self._get_parser().get(section, 'check_signatures'))
 
343
        policy = self._get_user_option('check_signatures')
 
344
        if policy:
 
345
            return self._string_to_signature_policy(policy)
 
346
 
 
347
    def _get_signing_policy(self):
 
348
        """See Config._get_signing_policy"""
 
349
        policy = self._get_user_option('create_signatures')
 
350
        if policy:
 
351
            return self._string_to_signing_policy(policy)
182
352
 
183
353
    def _get_user_id(self):
184
354
        """Get the user id from the 'email' key in the current section."""
185
 
        section = self._get_section()
186
 
        if section is not None:
187
 
            if self._get_parser().has_option(section, 'email'):
188
 
                return self._get_parser().get(section, 'email')
 
355
        return self._get_user_option('email')
189
356
 
190
357
    def _get_user_option(self, option_name):
191
358
        """See Config._get_user_option."""
192
 
        section = self._get_section()
193
 
        if section is not None:
194
 
            if self._get_parser().has_option(section, option_name):
195
 
                return self._get_parser().get(section, option_name)
 
359
        for (section, extra_path) in self._get_matching_sections():
 
360
            try:
 
361
                value = self._get_parser().get_value(section, option_name)
 
362
            except KeyError:
 
363
                continue
 
364
            policy = self._get_option_policy(section, option_name)
 
365
            if policy == POLICY_NONE:
 
366
                return value
 
367
            elif policy == POLICY_NORECURSE:
 
368
                # norecurse items only apply to the exact path
 
369
                if extra_path:
 
370
                    continue
 
371
                else:
 
372
                    return value
 
373
            elif policy == POLICY_APPENDPATH:
 
374
                if extra_path:
 
375
                    value = urlutils.join(value, extra_path)
 
376
                return value
 
377
            else:
 
378
                raise AssertionError('Unexpected config policy %r' % policy)
 
379
        else:
 
380
            return None
196
381
 
197
382
    def _gpg_signing_command(self):
198
383
        """See Config.gpg_signing_command."""
199
 
        section = self._get_section()
200
 
        if section is not None:
201
 
            if self._get_parser().has_option(section, 'gpg_signing_command'):
202
 
                return self._get_parser().get(section, 'gpg_signing_command')
 
384
        return self._get_user_option('gpg_signing_command')
 
385
 
 
386
    def _log_format(self):
 
387
        """See Config.log_format."""
 
388
        return self._get_user_option('log_format')
203
389
 
204
390
    def __init__(self, get_filename):
205
391
        super(IniBasedConfig, self).__init__()
206
392
        self._get_filename = get_filename
207
393
        self._parser = None
 
394
        
 
395
    def _post_commit(self):
 
396
        """See Config.post_commit."""
 
397
        return self._get_user_option('post_commit')
208
398
 
209
399
    def _string_to_signature_policy(self, signature_string):
210
400
        """Convert a string to a signing policy."""
217
407
        raise errors.BzrError("Invalid signatures policy '%s'"
218
408
                              % signature_string)
219
409
 
 
410
    def _string_to_signing_policy(self, signature_string):
 
411
        """Convert a string to a signing policy."""
 
412
        if signature_string.lower() == 'when-required':
 
413
            return SIGN_WHEN_REQUIRED
 
414
        if signature_string.lower() == 'never':
 
415
            return SIGN_NEVER
 
416
        if signature_string.lower() == 'always':
 
417
            return SIGN_ALWAYS
 
418
        raise errors.BzrError("Invalid signing policy '%s'"
 
419
                              % signature_string)
 
420
 
 
421
    def _get_alias(self, value):
 
422
        try:
 
423
            return self._get_parser().get_value("ALIASES", 
 
424
                                                value)
 
425
        except KeyError:
 
426
            pass
 
427
 
 
428
    def _get_nickname(self):
 
429
        return self.get_user_option('nickname')
 
430
 
220
431
 
221
432
class GlobalConfig(IniBasedConfig):
222
433
    """The configuration that should be used for a specific location."""
223
434
 
224
435
    def get_editor(self):
225
 
        if self._get_parser().has_option(self._get_section(), 'editor'):
226
 
            return self._get_parser().get(self._get_section(), 'editor')
 
436
        return self._get_user_option('editor')
227
437
 
228
438
    def __init__(self):
229
439
        super(GlobalConfig, self).__init__(config_filename)
230
440
 
 
441
    def set_user_option(self, option, value):
 
442
        """Save option and its value in the configuration."""
 
443
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
444
        # file lock on bazaar.conf.
 
445
        conf_dir = os.path.dirname(self._get_filename())
 
446
        ensure_config_dir_exists(conf_dir)
 
447
        if 'DEFAULT' not in self._get_parser():
 
448
            self._get_parser()['DEFAULT'] = {}
 
449
        self._get_parser()['DEFAULT'][option] = value
 
450
        f = open(self._get_filename(), 'wb')
 
451
        self._get_parser().write(f)
 
452
        f.close()
 
453
 
231
454
 
232
455
class LocationConfig(IniBasedConfig):
233
456
    """A configuration object that gives the policy for a location."""
234
457
 
235
458
    def __init__(self, location):
236
 
        super(LocationConfig, self).__init__(branches_config_filename)
237
 
        self._global_config = None
 
459
        name_generator = locations_config_filename
 
460
        if (not os.path.exists(name_generator()) and
 
461
                os.path.exists(branches_config_filename())):
 
462
            if sys.platform == 'win32':
 
463
                trace.warning('Please rename %s to %s'
 
464
                              % (branches_config_filename(),
 
465
                                 locations_config_filename()))
 
466
            else:
 
467
                trace.warning('Please rename ~/.bazaar/branches.conf'
 
468
                              ' to ~/.bazaar/locations.conf')
 
469
            name_generator = branches_config_filename
 
470
        super(LocationConfig, self).__init__(name_generator)
 
471
        # local file locations are looked up by local path, rather than
 
472
        # by file url. This is because the config file is a user
 
473
        # file, and we would rather not expose the user to file urls.
 
474
        if location.startswith('file://'):
 
475
            location = urlutils.local_path_from_url(location)
238
476
        self.location = location
239
477
 
240
 
    def _get_global_config(self):
241
 
        if self._global_config is None:
242
 
            self._global_config = GlobalConfig()
243
 
        return self._global_config
244
 
 
245
 
    def _get_section(self):
246
 
        """Get the section we should look in for config items.
247
 
 
248
 
        Returns None if none exists. 
249
 
        TODO: perhaps return a NullSection that thunks through to the 
250
 
              global config.
251
 
        """
252
 
        sections = self._get_parser().sections()
 
478
    def _get_matching_sections(self):
 
479
        """Return an ordered list of section names matching this location."""
 
480
        sections = self._get_parser()
253
481
        location_names = self.location.split('/')
254
482
        if self.location.endswith('/'):
255
483
            del location_names[-1]
256
484
        matches=[]
257
485
        for section in sections:
258
 
            section_names = section.split('/')
 
486
            # location is a local path if possible, so we need
 
487
            # to convert 'file://' urls to local paths if necessary.
 
488
            # This also avoids having file:///path be a more exact
 
489
            # match than '/path'.
 
490
            if section.startswith('file://'):
 
491
                section_path = urlutils.local_path_from_url(section)
 
492
            else:
 
493
                section_path = section
 
494
            section_names = section_path.split('/')
259
495
            if section.endswith('/'):
260
496
                del section_names[-1]
261
497
            names = zip(location_names, section_names)
270
506
            # if section is longer, no match.
271
507
            if len(section_names) > len(location_names):
272
508
                continue
273
 
            # if path is longer, and recurse is not true, no match
274
 
            if len(section_names) < len(location_names):
275
 
                if (self._get_parser().has_option(section, 'recurse')
276
 
                    and not self._get_parser().getboolean(section, 'recurse')):
277
 
                    continue
278
 
            matches.append((len(section_names), section))
279
 
        if not len(matches):
280
 
            return None
 
509
            matches.append((len(section_names), section,
 
510
                            '/'.join(location_names[len(section_names):])))
281
511
        matches.sort(reverse=True)
282
 
        return matches[0][1]
283
 
 
284
 
    def _gpg_signing_command(self):
285
 
        """See Config.gpg_signing_command."""
286
 
        command = super(LocationConfig, self)._gpg_signing_command()
287
 
        if command is not None:
288
 
            return command
289
 
        return self._get_global_config()._gpg_signing_command()
290
 
 
291
 
    def _get_user_id(self):
292
 
        user_id = super(LocationConfig, self)._get_user_id()
293
 
        if user_id is not None:
294
 
            return user_id
295
 
        return self._get_global_config()._get_user_id()
296
 
 
297
 
    def _get_user_option(self, option_name):
298
 
        """See Config._get_user_option."""
299
 
        option_value = super(LocationConfig, 
300
 
                             self)._get_user_option(option_name)
301
 
        if option_value is not None:
302
 
            return option_value
303
 
        return self._get_global_config()._get_user_option(option_name)
304
 
 
305
 
    def _get_signature_checking(self):
306
 
        """See Config._get_signature_checking."""
307
 
        check = super(LocationConfig, self)._get_signature_checking()
308
 
        if check is not None:
309
 
            return check
310
 
        return self._get_global_config()._get_signature_checking()
 
512
        sections = []
 
513
        for (length, section, extra_path) in matches:
 
514
            sections.append((section, extra_path))
 
515
            # should we stop looking for parent configs here?
 
516
            try:
 
517
                if self._get_parser()[section].as_bool('ignore_parents'):
 
518
                    break
 
519
            except KeyError:
 
520
                pass
 
521
        return sections
 
522
 
 
523
    def _get_option_policy(self, section, option_name):
 
524
        """Return the policy for the given (section, option_name) pair."""
 
525
        # check for the old 'recurse=False' flag
 
526
        try:
 
527
            recurse = self._get_parser()[section].as_bool('recurse')
 
528
        except KeyError:
 
529
            recurse = True
 
530
        if not recurse:
 
531
            return POLICY_NORECURSE
 
532
 
 
533
        policy_key = option_name + ':policy'
 
534
        try:
 
535
            policy_name = self._get_parser()[section][policy_key]
 
536
        except KeyError:
 
537
            policy_name = None
 
538
 
 
539
        return _policy_value[policy_name]
 
540
 
 
541
    def _set_option_policy(self, section, option_name, option_policy):
 
542
        """Set the policy for the given option name in the given section."""
 
543
        # The old recurse=False option affects all options in the
 
544
        # section.  To handle multiple policies in the section, we
 
545
        # need to convert it to a policy_norecurse key.
 
546
        try:
 
547
            recurse = self._get_parser()[section].as_bool('recurse')
 
548
        except KeyError:
 
549
            pass
 
550
        else:
 
551
            symbol_versioning.warn(
 
552
                'The recurse option is deprecated as of 0.14.  '
 
553
                'The section "%s" has been converted to use policies.'
 
554
                % section,
 
555
                DeprecationWarning)
 
556
            del self._get_parser()[section]['recurse']
 
557
            if not recurse:
 
558
                for key in self._get_parser()[section].keys():
 
559
                    if not key.endswith(':policy'):
 
560
                        self._get_parser()[section][key +
 
561
                                                    ':policy'] = 'norecurse'
 
562
 
 
563
        policy_key = option_name + ':policy'
 
564
        policy_name = _policy_name[option_policy]
 
565
        if policy_name is not None:
 
566
            self._get_parser()[section][policy_key] = policy_name
 
567
        else:
 
568
            if policy_key in self._get_parser()[section]:
 
569
                del self._get_parser()[section][policy_key]
 
570
 
 
571
    def set_user_option(self, option, value, store=STORE_LOCATION):
 
572
        """Save option and its value in the configuration."""
 
573
        assert store in [STORE_LOCATION,
 
574
                         STORE_LOCATION_NORECURSE,
 
575
                         STORE_LOCATION_APPENDPATH], 'bad storage policy'
 
576
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
577
        # file lock on locations.conf.
 
578
        conf_dir = os.path.dirname(self._get_filename())
 
579
        ensure_config_dir_exists(conf_dir)
 
580
        location = self.location
 
581
        if location.endswith('/'):
 
582
            location = location[:-1]
 
583
        if (not location in self._get_parser() and
 
584
            not location + '/' in self._get_parser()):
 
585
            self._get_parser()[location]={}
 
586
        elif location + '/' in self._get_parser():
 
587
            location = location + '/'
 
588
        self._get_parser()[location][option]=value
 
589
        # the allowed values of store match the config policies
 
590
        self._set_option_policy(location, option, store)
 
591
        self._get_parser().write(file(self._get_filename(), 'wb'))
311
592
 
312
593
 
313
594
class BranchConfig(Config):
314
595
    """A configuration object giving the policy for a branch."""
315
596
 
 
597
    def _get_branch_data_config(self):
 
598
        if self._branch_data_config is None:
 
599
            self._branch_data_config = TreeConfig(self.branch)
 
600
        return self._branch_data_config
 
601
 
316
602
    def _get_location_config(self):
317
603
        if self._location_config is None:
318
604
            self._location_config = LocationConfig(self.branch.base)
319
605
        return self._location_config
320
606
 
 
607
    def _get_global_config(self):
 
608
        if self._global_config is None:
 
609
            self._global_config = GlobalConfig()
 
610
        return self._global_config
 
611
 
 
612
    def _get_best_value(self, option_name):
 
613
        """This returns a user option from local, tree or global config.
 
614
 
 
615
        They are tried in that order.  Use get_safe_value if trusted values
 
616
        are necessary.
 
617
        """
 
618
        for source in self.option_sources:
 
619
            value = getattr(source(), option_name)()
 
620
            if value is not None:
 
621
                return value
 
622
        return None
 
623
 
 
624
    def _get_safe_value(self, option_name):
 
625
        """This variant of get_best_value never returns untrusted values.
 
626
        
 
627
        It does not return values from the branch data, because the branch may
 
628
        not be controlled by the user.
 
629
 
 
630
        We may wish to allow locations.conf to control whether branches are
 
631
        trusted in the future.
 
632
        """
 
633
        for source in (self._get_location_config, self._get_global_config):
 
634
            value = getattr(source(), option_name)()
 
635
            if value is not None:
 
636
                return value
 
637
        return None
 
638
 
321
639
    def _get_user_id(self):
322
640
        """Return the full user id for the branch.
323
641
    
325
643
        This is looked up in the email controlfile for the branch.
326
644
        """
327
645
        try:
328
 
            return (self.branch.controlfile("email", "r") 
 
646
            return (self.branch.control_files.get_utf8("email") 
329
647
                    .read()
330
648
                    .decode(bzrlib.user_encoding)
331
649
                    .rstrip("\r\n"))
332
650
        except errors.NoSuchFile, e:
333
651
            pass
334
652
        
335
 
        return self._get_location_config()._get_user_id()
 
653
        return self._get_best_value('_get_user_id')
336
654
 
337
655
    def _get_signature_checking(self):
338
656
        """See Config._get_signature_checking."""
339
 
        return self._get_location_config()._get_signature_checking()
 
657
        return self._get_best_value('_get_signature_checking')
 
658
 
 
659
    def _get_signing_policy(self):
 
660
        """See Config._get_signing_policy."""
 
661
        return self._get_best_value('_get_signing_policy')
340
662
 
341
663
    def _get_user_option(self, option_name):
342
664
        """See Config._get_user_option."""
343
 
        return self._get_location_config()._get_user_option(option_name)
 
665
        for source in self.option_sources:
 
666
            value = source()._get_user_option(option_name)
 
667
            if value is not None:
 
668
                return value
 
669
        return None
 
670
 
 
671
    def set_user_option(self, name, value, store=STORE_BRANCH,
 
672
        warn_masked=False):
 
673
        if store == STORE_BRANCH:
 
674
            self._get_branch_data_config().set_option(value, name)
 
675
        elif store == STORE_GLOBAL:
 
676
            self._get_global_config().set_user_option(name, value)
 
677
        else:
 
678
            self._get_location_config().set_user_option(name, value, store)
 
679
        if not warn_masked:
 
680
            return
 
681
        if store in (STORE_GLOBAL, STORE_BRANCH):
 
682
            mask_value = self._get_location_config().get_user_option(name)
 
683
            if mask_value is not None:
 
684
                trace.warning('Value "%s" is masked by "%s" from'
 
685
                              ' locations.conf', value, mask_value)
 
686
            else:
 
687
                if store == STORE_GLOBAL:
 
688
                    branch_config = self._get_branch_data_config()
 
689
                    mask_value = branch_config.get_user_option(name)
 
690
                    if mask_value is not None:
 
691
                        trace.warning('Value "%s" is masked by "%s" from'
 
692
                                      ' branch.conf', value, mask_value)
 
693
 
344
694
 
345
695
    def _gpg_signing_command(self):
346
696
        """See Config.gpg_signing_command."""
347
 
        return self._get_location_config()._gpg_signing_command()
 
697
        return self._get_safe_value('_gpg_signing_command')
348
698
        
349
699
    def __init__(self, branch):
350
700
        super(BranchConfig, self).__init__()
351
701
        self._location_config = None
 
702
        self._branch_data_config = None
 
703
        self._global_config = None
352
704
        self.branch = branch
 
705
        self.option_sources = (self._get_location_config, 
 
706
                               self._get_branch_data_config,
 
707
                               self._get_global_config)
 
708
 
 
709
    def _post_commit(self):
 
710
        """See Config.post_commit."""
 
711
        return self._get_safe_value('_post_commit')
 
712
 
 
713
    def _get_nickname(self):
 
714
        value = self._get_explicit_nickname()
 
715
        if value is not None:
 
716
            return value
 
717
        return urlutils.unescape(self.branch.base.split('/')[-2])
 
718
 
 
719
    def has_explicit_nickname(self):
 
720
        """Return true if a nickname has been explicitly assigned."""
 
721
        return self._get_explicit_nickname() is not None
 
722
 
 
723
    def _get_explicit_nickname(self):
 
724
        return self._get_best_value('_get_nickname')
 
725
 
 
726
    def _log_format(self):
 
727
        """See Config.log_format."""
 
728
        return self._get_best_value('_log_format')
 
729
 
 
730
 
 
731
def ensure_config_dir_exists(path=None):
 
732
    """Make sure a configuration directory exists.
 
733
    This makes sure that the directory exists.
 
734
    On windows, since configuration directories are 2 levels deep,
 
735
    it makes sure both the directory and the parent directory exists.
 
736
    """
 
737
    if path is None:
 
738
        path = config_dir()
 
739
    if not os.path.isdir(path):
 
740
        if sys.platform == 'win32':
 
741
            parent_dir = os.path.dirname(path)
 
742
            if not os.path.isdir(parent_dir):
 
743
                trace.mutter('creating config parent directory: %r', parent_dir)
 
744
            os.mkdir(parent_dir)
 
745
        trace.mutter('creating config directory: %r', path)
 
746
        os.mkdir(path)
353
747
 
354
748
 
355
749
def config_dir():
359
753
    
360
754
    TODO: Global option --config-dir to override this.
361
755
    """
362
 
    return os.path.join(os.path.expanduser("~"), ".bazaar")
 
756
    base = os.environ.get('BZR_HOME', None)
 
757
    if sys.platform == 'win32':
 
758
        if base is None:
 
759
            base = win32utils.get_appdata_location_unicode()
 
760
        if base is None:
 
761
            base = os.environ.get('HOME', None)
 
762
        if base is None:
 
763
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
 
764
                                  ' or HOME set')
 
765
        return osutils.pathjoin(base, 'bazaar', '2.0')
 
766
    else:
 
767
        # cygwin, linux, and darwin all have a $HOME directory
 
768
        if base is None:
 
769
            base = os.path.expanduser("~")
 
770
        return osutils.pathjoin(base, ".bazaar")
363
771
 
364
772
 
365
773
def config_filename():
366
774
    """Return per-user configuration ini file filename."""
367
 
    return os.path.join(config_dir(), 'bazaar.conf')
 
775
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
368
776
 
369
777
 
370
778
def branches_config_filename():
371
779
    """Return per-user configuration ini file filename."""
372
 
    return os.path.join(config_dir(), 'branches.conf')
 
780
    return osutils.pathjoin(config_dir(), 'branches.conf')
 
781
 
 
782
 
 
783
def locations_config_filename():
 
784
    """Return per-user configuration ini file filename."""
 
785
    return osutils.pathjoin(config_dir(), 'locations.conf')
 
786
 
 
787
 
 
788
def authentication_config_filename():
 
789
    """Return per-user authentication ini file filename."""
 
790
    return osutils.pathjoin(config_dir(), 'authentication.conf')
 
791
 
 
792
 
 
793
def user_ignore_config_filename():
 
794
    """Return the user default ignore filename"""
 
795
    return osutils.pathjoin(config_dir(), 'ignore')
373
796
 
374
797
 
375
798
def _auto_user_id():
385
808
    """
386
809
    import socket
387
810
 
388
 
    # XXX: Any good way to get real user name on win32?
 
811
    if sys.platform == 'win32':
 
812
        name = win32utils.get_user_name_unicode()
 
813
        if name is None:
 
814
            raise errors.BzrError("Cannot autodetect user name.\n"
 
815
                                  "Please, set your name with command like:\n"
 
816
                                  'bzr whoami "Your Name <name@domain.com>"')
 
817
        host = win32utils.get_host_name_unicode()
 
818
        if host is None:
 
819
            host = socket.gethostname()
 
820
        return name, (name + '@' + host)
389
821
 
390
822
    try:
391
823
        import pwd
392
824
        uid = os.getuid()
393
825
        w = pwd.getpwuid(uid)
394
 
        gecos = w.pw_gecos.decode(bzrlib.user_encoding)
395
 
        username = w.pw_name.decode(bzrlib.user_encoding)
 
826
 
 
827
        # we try utf-8 first, because on many variants (like Linux),
 
828
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
829
        # false positives.  (many users will have their user encoding set to
 
830
        # latin-1, which cannot raise UnicodeError.)
 
831
        try:
 
832
            gecos = w.pw_gecos.decode('utf-8')
 
833
            encoding = 'utf-8'
 
834
        except UnicodeError:
 
835
            try:
 
836
                gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
837
                encoding = bzrlib.user_encoding
 
838
            except UnicodeError:
 
839
                raise errors.BzrCommandError('Unable to determine your name.  '
 
840
                   'Use "bzr whoami" to set it.')
 
841
        try:
 
842
            username = w.pw_name.decode(encoding)
 
843
        except UnicodeError:
 
844
            raise errors.BzrCommandError('Unable to determine your name.  '
 
845
                'Use "bzr whoami" to set it.')
 
846
 
396
847
        comma = gecos.find(',')
397
848
        if comma == -1:
398
849
            realname = gecos
403
854
 
404
855
    except ImportError:
405
856
        import getpass
406
 
        realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
857
        try:
 
858
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
859
        except UnicodeDecodeError:
 
860
            raise errors.BzrError("Can't decode username as %s." % \
 
861
                    bzrlib.user_encoding)
407
862
 
408
863
    return realname, (username + '@' + socket.gethostname())
409
864
 
410
865
 
 
866
def parse_username(username):
 
867
    """Parse e-mail username and return a (name, address) tuple."""
 
868
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
 
869
    if match is None:
 
870
        return (username, '')
 
871
    else:
 
872
        return (match.group(1), match.group(2))
 
873
 
 
874
 
411
875
def extract_email_address(e):
412
876
    """Return just the address part of an email string.
413
 
    
 
877
 
414
878
    That is just the user@domain part, nothing else. 
415
879
    This part is required to contain only ascii characters.
416
880
    If it can't be extracted, raises an error.
417
 
    
 
881
 
418
882
    >>> extract_email_address('Jane Tester <jane@test.com>')
419
883
    "jane@test.com"
420
884
    """
421
 
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
422
 
    if not m:
423
 
        raise BzrError("%r doesn't seem to contain "
424
 
                       "a reasonable email address" % e)
425
 
    return m.group(0)
 
885
    name, email = parse_username(e)
 
886
    if not email:
 
887
        raise errors.NoEmailInUsername(e)
 
888
    return email
 
889
 
 
890
 
 
891
class TreeConfig(IniBasedConfig):
 
892
    """Branch configuration data associated with its contents, not location"""
 
893
 
 
894
    def __init__(self, branch):
 
895
        transport = branch.control_files._transport
 
896
        self._config = TransportConfig(transport, 'branch.conf')
 
897
        self.branch = branch
 
898
 
 
899
    def _get_parser(self, file=None):
 
900
        if file is not None:
 
901
            return IniBasedConfig._get_parser(file)
 
902
        return self._config._get_configobj()
 
903
 
 
904
    def get_option(self, name, section=None, default=None):
 
905
        self.branch.lock_read()
 
906
        try:
 
907
            return self._config.get_option(name, section, default)
 
908
        finally:
 
909
            self.branch.unlock()
 
910
        return result
 
911
 
 
912
    def set_option(self, value, name, section=None):
 
913
        """Set a per-branch configuration option"""
 
914
        self.branch.lock_write()
 
915
        try:
 
916
            self._config.set_option(value, name, section)
 
917
        finally:
 
918
            self.branch.unlock()
 
919
 
 
920
 
 
921
class AuthenticationConfig(object):
 
922
    """The authentication configuration file based on a ini file.
 
923
 
 
924
    Implements the authentication.conf file described in
 
925
    doc/developers/authentication-ring.txt.
 
926
    """
 
927
 
 
928
    def __init__(self, _file=None):
 
929
        self._config = None # The ConfigObj
 
930
        if _file is None:
 
931
            self._filename = authentication_config_filename()
 
932
            self._input = self._filename = authentication_config_filename()
 
933
        else:
 
934
            # Tests can provide a string as _file
 
935
            self._filename = None
 
936
            self._input = _file
 
937
 
 
938
    def _get_config(self):
 
939
        if self._config is not None:
 
940
            return self._config
 
941
        try:
 
942
            # FIXME: Should we validate something here ? Includes: empty
 
943
            # sections are useless, at least one of
 
944
            # user/password/password_encoding should be defined, etc.
 
945
 
 
946
            # Note: the encoding below declares that the file itself is utf-8
 
947
            # encoded, but the values in the ConfigObj are always Unicode.
 
948
            self._config = ConfigObj(self._input, encoding='utf-8')
 
949
        except configobj.ConfigObjError, e:
 
950
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
951
        return self._config
 
952
 
 
953
    def _save(self):
 
954
        """Save the config file, only tests should use it for now."""
 
955
        conf_dir = os.path.dirname(self._filename)
 
956
        ensure_config_dir_exists(conf_dir)
 
957
        self._get_config().write(file(self._filename, 'wb'))
 
958
 
 
959
    def _set_option(self, section_name, option_name, value):
 
960
        """Set an authentication configuration option"""
 
961
        conf = self._get_config()
 
962
        section = conf.get(section_name)
 
963
        if section is None:
 
964
            conf[section] = {}
 
965
            section = conf[section]
 
966
        section[option_name] = value
 
967
        self._save()
 
968
 
 
969
    def get_credentials(self, scheme, host, port=None, user=None, path=None):
 
970
        """Returns the matching credentials from authentication.conf file.
 
971
 
 
972
        :param scheme: protocol
 
973
 
 
974
        :param host: the server address
 
975
 
 
976
        :param port: the associated port (optional)
 
977
 
 
978
        :param user: login (optional)
 
979
 
 
980
        :param path: the absolute path on the server (optional)
 
981
 
 
982
        :return: A dict containing the matching credentials or None.
 
983
           This includes:
 
984
           - name: the section name of the credentials in the
 
985
             authentication.conf file,
 
986
           - user: can't de different from the provided user if any,
 
987
           - password: the decoded password, could be None if the credential
 
988
             defines only the user
 
989
           - verify_certificates: https specific, True if the server
 
990
             certificate should be verified, False otherwise.
 
991
        """
 
992
        credentials = None
 
993
        for auth_def_name, auth_def in self._get_config().items():
 
994
            a_scheme, a_host, a_user, a_path = map(
 
995
                auth_def.get, ['scheme', 'host', 'user', 'path'])
 
996
 
 
997
            try:
 
998
                a_port = auth_def.as_int('port')
 
999
            except KeyError:
 
1000
                a_port = None
 
1001
            except ValueError:
 
1002
                raise ValueError("'port' not numeric in %s" % auth_def_name)
 
1003
            try:
 
1004
                a_verify_certificates = auth_def.as_bool('verify_certificates')
 
1005
            except KeyError:
 
1006
                a_verify_certificates = True
 
1007
            except ValueError:
 
1008
                raise ValueError(
 
1009
                    "'verify_certificates' not boolean in %s" % auth_def_name)
 
1010
 
 
1011
            # Attempt matching
 
1012
            if a_scheme is not None and scheme != a_scheme:
 
1013
                continue
 
1014
            if a_host is not None:
 
1015
                if not (host == a_host
 
1016
                        or (a_host.startswith('.') and host.endswith(a_host))):
 
1017
                    continue
 
1018
            if a_port is not None and port != a_port:
 
1019
                continue
 
1020
            if (a_path is not None and path is not None
 
1021
                and not path.startswith(a_path)):
 
1022
                continue
 
1023
            if (a_user is not None and user is not None
 
1024
                and a_user != user):
 
1025
                # Never contradict the caller about the user to be used
 
1026
                continue
 
1027
            if a_user is None:
 
1028
                # Can't find a user
 
1029
                continue
 
1030
            credentials = dict(name=auth_def_name,
 
1031
                               user=a_user, password=auth_def['password'],
 
1032
                               verify_certificates=a_verify_certificates)
 
1033
            self.decode_password(credentials,
 
1034
                                 auth_def.get('password_encoding', None))
 
1035
            if 'auth' in debug.debug_flags:
 
1036
                trace.mutter("Using authentication section: %r", auth_def_name)
 
1037
            break
 
1038
 
 
1039
        return credentials
 
1040
 
 
1041
    def get_user(self, scheme, host, port=None,
 
1042
                 realm=None, path=None, prompt=None):
 
1043
        """Get a user from authentication file.
 
1044
 
 
1045
        :param scheme: protocol
 
1046
 
 
1047
        :param host: the server address
 
1048
 
 
1049
        :param port: the associated port (optional)
 
1050
 
 
1051
        :param realm: the realm sent by the server (optional)
 
1052
 
 
1053
        :param path: the absolute path on the server (optional)
 
1054
 
 
1055
        :return: The found user.
 
1056
        """
 
1057
        credentials = self.get_credentials(scheme, host, port, user=None,
 
1058
                                           path=path)
 
1059
        if credentials is not None:
 
1060
            user = credentials['user']
 
1061
        else:
 
1062
            user = None
 
1063
        return user
 
1064
 
 
1065
    def get_password(self, scheme, host, user, port=None,
 
1066
                     realm=None, path=None, prompt=None):
 
1067
        """Get a password from authentication file or prompt the user for one.
 
1068
 
 
1069
        :param scheme: protocol
 
1070
 
 
1071
        :param host: the server address
 
1072
 
 
1073
        :param port: the associated port (optional)
 
1074
 
 
1075
        :param user: login
 
1076
 
 
1077
        :param realm: the realm sent by the server (optional)
 
1078
 
 
1079
        :param path: the absolute path on the server (optional)
 
1080
 
 
1081
        :return: The found password or the one entered by the user.
 
1082
        """
 
1083
        credentials = self.get_credentials(scheme, host, port, user, path)
 
1084
        if credentials is not None:
 
1085
            password = credentials['password']
 
1086
        else:
 
1087
            password = None
 
1088
        # Prompt user only if we could't find a password
 
1089
        if password is None:
 
1090
            if prompt is None:
 
1091
                # Create a default prompt suitable for most of the cases
 
1092
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
1093
            # Special handling for optional fields in the prompt
 
1094
            if port is not None:
 
1095
                prompt_host = '%s:%d' % (host, port)
 
1096
            else:
 
1097
                prompt_host = host
 
1098
            password = ui.ui_factory.get_password(prompt,
 
1099
                                                  host=prompt_host, user=user)
 
1100
        return password
 
1101
 
 
1102
    def decode_password(self, credentials, encoding):
 
1103
        return credentials
 
1104
 
 
1105
 
 
1106
class TransportConfig(object):
 
1107
    """A Config that reads/writes a config file on a Transport.
 
1108
 
 
1109
    It is a low-level object that considers config data to be name/value pairs
 
1110
    that may be associated with a section.  Assigning meaning to the these
 
1111
    values is done at higher levels like TreeConfig.
 
1112
    """
 
1113
 
 
1114
    def __init__(self, transport, filename):
 
1115
        self._transport = transport
 
1116
        self._filename = filename
 
1117
 
 
1118
    def get_option(self, name, section=None, default=None):
 
1119
        """Return the value associated with a named option.
 
1120
 
 
1121
        :param name: The name of the value
 
1122
        :param section: The section the option is in (if any)
 
1123
        :param default: The value to return if the value is not set
 
1124
        :return: The value or default value
 
1125
        """
 
1126
        configobj = self._get_configobj()
 
1127
        if section is None:
 
1128
            section_obj = configobj
 
1129
        else:
 
1130
            try:
 
1131
                section_obj = configobj[section]
 
1132
            except KeyError:
 
1133
                return default
 
1134
        return section_obj.get(name, default)
 
1135
 
 
1136
    def set_option(self, value, name, section=None):
 
1137
        """Set the value associated with a named option.
 
1138
 
 
1139
        :param value: The value to set
 
1140
        :param name: The name of the value to set
 
1141
        :param section: The section the option is in (if any)
 
1142
        """
 
1143
        configobj = self._get_configobj()
 
1144
        if section is None:
 
1145
            configobj[name] = value
 
1146
        else:
 
1147
            configobj.setdefault(section, {})[name] = value
 
1148
        self._set_configobj(configobj)
 
1149
 
 
1150
    def _get_configobj(self):
 
1151
        try:
 
1152
            return ConfigObj(self._transport.get(self._filename),
 
1153
                             encoding='utf-8')
 
1154
        except errors.NoSuchFile:
 
1155
            return ConfigObj(encoding='utf-8')
 
1156
 
 
1157
    def _set_configobj(self, configobj):
 
1158
        out_file = StringIO()
 
1159
        configobj.write(out_file)
 
1160
        out_file.seek(0)
 
1161
        self._transport.put_file(self._filename, out_file)