/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: Andrew Bennetts
  • Date: 2008-03-17 17:16:11 UTC
  • mfrom: (3290 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3756.
  • Revision ID: andrew.bennetts@canonical.com-20080317171611-o9wdrnf0m7qwo198
Merge from bzr.dev.

Show diffs side-by-side

added added

removed removed

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