/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: Robert Collins
  • Date: 2008-08-20 02:07:36 UTC
  • mfrom: (3640 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3682.
  • Revision ID: robertc@robertcollins.net-20080820020736-g2xe4921zzxtymle
Merge bzr.dev

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]
29
30
gpg_signing_command=name-of-program
30
31
log_format=name-of-format
31
32
 
32
 
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.
33
34
Wildcards may be used - * and ? as normal in shell completion. Options
34
 
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
35
36
setting.
36
37
[/home/robertc/source]
37
38
recurse=False|True(default)
38
39
email= as above
39
 
check_signatures= as abive 
 
40
check_signatures= as above 
40
41
create_signatures= as above.
41
42
 
42
43
explanation of options
49
50
create_signatures - this option controls whether bzr will always create 
50
51
                    gpg signatures, never create them, or create them if the
51
52
                    branch is configured to require them.
52
 
                    NB: This option is planned, but not implemented yet.
53
 
log_format - This options set the default log format.  Options are long, 
54
 
             short, line, or a plugin can register new formats
 
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
55
 
56
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
57
57
 
62
62
up=pull
63
63
"""
64
64
 
65
 
 
66
 
import errno
67
65
import os
68
66
import sys
 
67
 
 
68
from bzrlib.lazy_import import lazy_import
 
69
lazy_import(globals(), """
 
70
import errno
69
71
from fnmatch import fnmatch
70
72
import re
 
73
from cStringIO import StringIO
71
74
 
72
75
import bzrlib
73
 
import bzrlib.errors as errors
74
 
from bzrlib.osutils import pathjoin
75
 
from bzrlib.trace import mutter
76
 
import bzrlib.util.configobj.configobj as configobj
77
 
from StringIO import StringIO
 
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
 
78
90
 
79
91
CHECK_IF_POSSIBLE=0
80
92
CHECK_ALWAYS=1
81
93
CHECK_NEVER=2
82
94
 
83
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
 
84
125
class ConfigObj(configobj.ConfigObj):
85
126
 
86
127
    def get_bool(self, section, key):
103
144
        """Get the users pop up editor."""
104
145
        raise NotImplementedError
105
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
 
106
169
    def _get_signature_checking(self):
107
170
        """Template method to override signature checking policy."""
108
171
 
 
172
    def _get_signing_policy(self):
 
173
        """Template method to override signature creation policy."""
 
174
 
109
175
    def _get_user_option(self, option_name):
110
176
        """Template method to provide a user option."""
111
177
        return None
159
225
    
160
226
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
161
227
        
162
 
        $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
163
230
        the concrete policy type is checked, and finally
164
231
        $EMAIL is examined.
165
232
        If none is found, a reasonable default is (hopefully)
167
234
    
168
235
        TODO: Check it's reasonably well-formed.
169
236
        """
170
 
        v = os.environ.get('BZREMAIL')
 
237
        v = os.environ.get('BZR_EMAIL')
171
238
        if v:
172
239
            return v.decode(bzrlib.user_encoding)
173
 
    
 
240
 
174
241
        v = self._get_user_id()
175
242
        if v:
176
243
            return v
177
 
        
 
244
 
178
245
        v = os.environ.get('EMAIL')
179
246
        if v:
180
247
            return v.decode(bzrlib.user_encoding)
192
259
            return policy
193
260
        return CHECK_IF_POSSIBLE
194
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
 
195
269
    def signature_needed(self):
196
270
        """Is a signature needed when committing ?."""
197
 
        policy = self._get_signature_checking()
198
 
        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:
199
280
            return True
200
281
        return False
201
282
 
205
286
    def _get_alias(self, value):
206
287
        pass
207
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
 
208
304
 
209
305
class IniBasedConfig(Config):
210
306
    """A configuration policy that draws from ini files."""
222
318
            raise errors.ParseConfigError(e.errors, e.config.filename)
223
319
        return self._parser
224
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 []
 
332
 
225
333
    def _get_section(self):
226
334
        """Override this to define the section used by the config."""
227
335
        return "DEFAULT"
228
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
 
229
341
    def _get_signature_checking(self):
230
342
        """See Config._get_signature_checking."""
231
343
        policy = self._get_user_option('check_signatures')
232
344
        if policy:
233
345
            return self._string_to_signature_policy(policy)
234
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)
 
352
 
235
353
    def _get_user_id(self):
236
354
        """Get the user id from the 'email' key in the current section."""
237
355
        return self._get_user_option('email')
238
356
 
239
357
    def _get_user_option(self, option_name):
240
358
        """See Config._get_user_option."""
241
 
        try:
242
 
            return self._get_parser().get_value(self._get_section(),
243
 
                                                option_name)
244
 
        except KeyError:
245
 
            pass
 
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
246
381
 
247
382
    def _gpg_signing_command(self):
248
383
        """See Config.gpg_signing_command."""
272
407
        raise errors.BzrError("Invalid signatures policy '%s'"
273
408
                              % signature_string)
274
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
 
275
421
    def _get_alias(self, value):
276
422
        try:
277
423
            return self._get_parser().get_value("ALIASES", 
279
425
        except KeyError:
280
426
            pass
281
427
 
 
428
    def _get_nickname(self):
 
429
        return self.get_user_option('nickname')
 
430
 
282
431
 
283
432
class GlobalConfig(IniBasedConfig):
284
433
    """The configuration that should be used for a specific location."""
289
438
    def __init__(self):
290
439
        super(GlobalConfig, self).__init__(config_filename)
291
440
 
 
441
    def set_user_option(self, option, value):
 
442
        """Save option and its value in the configuration."""
 
443
        self._set_option(option, value, 'DEFAULT')
 
444
 
 
445
    def get_aliases(self):
 
446
        """Return the aliases section."""
 
447
        if 'ALIASES' in self._get_parser():
 
448
            return self._get_parser()['ALIASES']
 
449
        else:
 
450
            return {}
 
451
 
 
452
    def set_alias(self, alias_name, alias_command):
 
453
        """Save the alias in the configuration."""
 
454
        self._set_option(alias_name, alias_command, 'ALIASES')
 
455
 
 
456
    def unset_alias(self, alias_name):
 
457
        """Unset an existing alias."""
 
458
        aliases = self._get_parser().get('ALIASES')
 
459
        if not aliases or alias_name not in aliases:
 
460
            raise errors.NoSuchAlias(alias_name)
 
461
        del aliases[alias_name]
 
462
        self._write_config_file()
 
463
 
 
464
    def _set_option(self, option, value, section):
 
465
        # FIXME: RBC 20051029 This should refresh the parser and also take a
 
466
        # file lock on bazaar.conf.
 
467
        conf_dir = os.path.dirname(self._get_filename())
 
468
        ensure_config_dir_exists(conf_dir)
 
469
        self._get_parser().setdefault(section, {})[option] = value
 
470
        self._write_config_file()
 
471
 
 
472
    def _write_config_file(self):
 
473
        f = open(self._get_filename(), 'wb')
 
474
        self._get_parser().write(f)
 
475
        f.close()
 
476
 
292
477
 
293
478
class LocationConfig(IniBasedConfig):
294
479
    """A configuration object that gives the policy for a location."""
295
480
 
296
481
    def __init__(self, location):
297
 
        super(LocationConfig, self).__init__(branches_config_filename)
298
 
        self._global_config = None
 
482
        name_generator = locations_config_filename
 
483
        if (not os.path.exists(name_generator()) and
 
484
                os.path.exists(branches_config_filename())):
 
485
            if sys.platform == 'win32':
 
486
                trace.warning('Please rename %s to %s'
 
487
                              % (branches_config_filename(),
 
488
                                 locations_config_filename()))
 
489
            else:
 
490
                trace.warning('Please rename ~/.bazaar/branches.conf'
 
491
                              ' to ~/.bazaar/locations.conf')
 
492
            name_generator = branches_config_filename
 
493
        super(LocationConfig, self).__init__(name_generator)
 
494
        # local file locations are looked up by local path, rather than
 
495
        # by file url. This is because the config file is a user
 
496
        # file, and we would rather not expose the user to file urls.
 
497
        if location.startswith('file://'):
 
498
            location = urlutils.local_path_from_url(location)
299
499
        self.location = location
300
500
 
301
 
    def _get_global_config(self):
302
 
        if self._global_config is None:
303
 
            self._global_config = GlobalConfig()
304
 
        return self._global_config
305
 
 
306
 
    def _get_section(self):
307
 
        """Get the section we should look in for config items.
308
 
 
309
 
        Returns None if none exists. 
310
 
        TODO: perhaps return a NullSection that thunks through to the 
311
 
              global config.
312
 
        """
 
501
    def _get_matching_sections(self):
 
502
        """Return an ordered list of section names matching this location."""
313
503
        sections = self._get_parser()
314
504
        location_names = self.location.split('/')
315
505
        if self.location.endswith('/'):
316
506
            del location_names[-1]
317
507
        matches=[]
318
508
        for section in sections:
319
 
            section_names = section.split('/')
 
509
            # location is a local path if possible, so we need
 
510
            # to convert 'file://' urls to local paths if necessary.
 
511
            # This also avoids having file:///path be a more exact
 
512
            # match than '/path'.
 
513
            if section.startswith('file://'):
 
514
                section_path = urlutils.local_path_from_url(section)
 
515
            else:
 
516
                section_path = section
 
517
            section_names = section_path.split('/')
320
518
            if section.endswith('/'):
321
519
                del section_names[-1]
322
520
            names = zip(location_names, section_names)
331
529
            # if section is longer, no match.
332
530
            if len(section_names) > len(location_names):
333
531
                continue
334
 
            # if path is longer, and recurse is not true, no match
335
 
            if len(section_names) < len(location_names):
336
 
                try:
337
 
                    if not self._get_parser()[section].as_bool('recurse'):
338
 
                        continue
339
 
                except KeyError:
340
 
                    pass
341
 
            matches.append((len(section_names), section))
342
 
        if not len(matches):
343
 
            return None
 
532
            matches.append((len(section_names), section,
 
533
                            '/'.join(location_names[len(section_names):])))
344
534
        matches.sort(reverse=True)
345
 
        return matches[0][1]
346
 
 
347
 
    def _gpg_signing_command(self):
348
 
        """See Config.gpg_signing_command."""
349
 
        command = super(LocationConfig, self)._gpg_signing_command()
350
 
        if command is not None:
351
 
            return command
352
 
        return self._get_global_config()._gpg_signing_command()
353
 
 
354
 
    def _log_format(self):
355
 
        """See Config.log_format."""
356
 
        command = super(LocationConfig, self)._log_format()
357
 
        if command is not None:
358
 
            return command
359
 
        return self._get_global_config()._log_format()
360
 
 
361
 
    def _get_user_id(self):
362
 
        user_id = super(LocationConfig, self)._get_user_id()
363
 
        if user_id is not None:
364
 
            return user_id
365
 
        return self._get_global_config()._get_user_id()
366
 
 
367
 
    def _get_user_option(self, option_name):
368
 
        """See Config._get_user_option."""
369
 
        option_value = super(LocationConfig, 
370
 
                             self)._get_user_option(option_name)
371
 
        if option_value is not None:
372
 
            return option_value
373
 
        return self._get_global_config()._get_user_option(option_name)
374
 
 
375
 
    def _get_signature_checking(self):
376
 
        """See Config._get_signature_checking."""
377
 
        check = super(LocationConfig, self)._get_signature_checking()
378
 
        if check is not None:
379
 
            return check
380
 
        return self._get_global_config()._get_signature_checking()
381
 
 
382
 
    def _post_commit(self):
383
 
        """See Config.post_commit."""
384
 
        hook = self._get_user_option('post_commit')
385
 
        if hook is not None:
386
 
            return hook
387
 
        return self._get_global_config()._post_commit()
388
 
 
389
 
    def set_user_option(self, option, value):
 
535
        sections = []
 
536
        for (length, section, extra_path) in matches:
 
537
            sections.append((section, extra_path))
 
538
            # should we stop looking for parent configs here?
 
539
            try:
 
540
                if self._get_parser()[section].as_bool('ignore_parents'):
 
541
                    break
 
542
            except KeyError:
 
543
                pass
 
544
        return sections
 
545
 
 
546
    def _get_option_policy(self, section, option_name):
 
547
        """Return the policy for the given (section, option_name) pair."""
 
548
        # check for the old 'recurse=False' flag
 
549
        try:
 
550
            recurse = self._get_parser()[section].as_bool('recurse')
 
551
        except KeyError:
 
552
            recurse = True
 
553
        if not recurse:
 
554
            return POLICY_NORECURSE
 
555
 
 
556
        policy_key = option_name + ':policy'
 
557
        try:
 
558
            policy_name = self._get_parser()[section][policy_key]
 
559
        except KeyError:
 
560
            policy_name = None
 
561
 
 
562
        return _policy_value[policy_name]
 
563
 
 
564
    def _set_option_policy(self, section, option_name, option_policy):
 
565
        """Set the policy for the given option name in the given section."""
 
566
        # The old recurse=False option affects all options in the
 
567
        # section.  To handle multiple policies in the section, we
 
568
        # need to convert it to a policy_norecurse key.
 
569
        try:
 
570
            recurse = self._get_parser()[section].as_bool('recurse')
 
571
        except KeyError:
 
572
            pass
 
573
        else:
 
574
            symbol_versioning.warn(
 
575
                'The recurse option is deprecated as of 0.14.  '
 
576
                'The section "%s" has been converted to use policies.'
 
577
                % section,
 
578
                DeprecationWarning)
 
579
            del self._get_parser()[section]['recurse']
 
580
            if not recurse:
 
581
                for key in self._get_parser()[section].keys():
 
582
                    if not key.endswith(':policy'):
 
583
                        self._get_parser()[section][key +
 
584
                                                    ':policy'] = 'norecurse'
 
585
 
 
586
        policy_key = option_name + ':policy'
 
587
        policy_name = _policy_name[option_policy]
 
588
        if policy_name is not None:
 
589
            self._get_parser()[section][policy_key] = policy_name
 
590
        else:
 
591
            if policy_key in self._get_parser()[section]:
 
592
                del self._get_parser()[section][policy_key]
 
593
 
 
594
    def set_user_option(self, option, value, store=STORE_LOCATION):
390
595
        """Save option and its value in the configuration."""
 
596
        if store not in [STORE_LOCATION,
 
597
                         STORE_LOCATION_NORECURSE,
 
598
                         STORE_LOCATION_APPENDPATH]:
 
599
            raise ValueError('bad storage policy %r for %r' %
 
600
                (store, option))
391
601
        # FIXME: RBC 20051029 This should refresh the parser and also take a
392
 
        # file lock on branches.conf.
 
602
        # file lock on locations.conf.
393
603
        conf_dir = os.path.dirname(self._get_filename())
394
604
        ensure_config_dir_exists(conf_dir)
395
605
        location = self.location
401
611
        elif location + '/' in self._get_parser():
402
612
            location = location + '/'
403
613
        self._get_parser()[location][option]=value
 
614
        # the allowed values of store match the config policies
 
615
        self._set_option_policy(location, option, store)
404
616
        self._get_parser().write(file(self._get_filename(), 'wb'))
405
617
 
406
618
 
407
619
class BranchConfig(Config):
408
620
    """A configuration object giving the policy for a branch."""
409
621
 
 
622
    def _get_branch_data_config(self):
 
623
        if self._branch_data_config is None:
 
624
            self._branch_data_config = TreeConfig(self.branch)
 
625
        return self._branch_data_config
 
626
 
410
627
    def _get_location_config(self):
411
628
        if self._location_config is None:
412
629
            self._location_config = LocationConfig(self.branch.base)
413
630
        return self._location_config
414
631
 
 
632
    def _get_global_config(self):
 
633
        if self._global_config is None:
 
634
            self._global_config = GlobalConfig()
 
635
        return self._global_config
 
636
 
 
637
    def _get_best_value(self, option_name):
 
638
        """This returns a user option from local, tree or global config.
 
639
 
 
640
        They are tried in that order.  Use get_safe_value if trusted values
 
641
        are necessary.
 
642
        """
 
643
        for source in self.option_sources:
 
644
            value = getattr(source(), option_name)()
 
645
            if value is not None:
 
646
                return value
 
647
        return None
 
648
 
 
649
    def _get_safe_value(self, option_name):
 
650
        """This variant of get_best_value never returns untrusted values.
 
651
        
 
652
        It does not return values from the branch data, because the branch may
 
653
        not be controlled by the user.
 
654
 
 
655
        We may wish to allow locations.conf to control whether branches are
 
656
        trusted in the future.
 
657
        """
 
658
        for source in (self._get_location_config, self._get_global_config):
 
659
            value = getattr(source(), option_name)()
 
660
            if value is not None:
 
661
                return value
 
662
        return None
 
663
 
415
664
    def _get_user_id(self):
416
665
        """Return the full user id for the branch.
417
666
    
418
 
        e.g. "John Hacker <jhacker@foo.org>"
 
667
        e.g. "John Hacker <jhacker@example.com>"
419
668
        This is looked up in the email controlfile for the branch.
420
669
        """
421
670
        try:
422
 
            return (self.branch.control_files.get_utf8("email") 
423
 
                    .read()
 
671
            return (self.branch._transport.get_bytes("email")
424
672
                    .decode(bzrlib.user_encoding)
425
673
                    .rstrip("\r\n"))
426
674
        except errors.NoSuchFile, e:
427
675
            pass
428
676
        
429
 
        return self._get_location_config()._get_user_id()
 
677
        return self._get_best_value('_get_user_id')
430
678
 
431
679
    def _get_signature_checking(self):
432
680
        """See Config._get_signature_checking."""
433
 
        return self._get_location_config()._get_signature_checking()
 
681
        return self._get_best_value('_get_signature_checking')
 
682
 
 
683
    def _get_signing_policy(self):
 
684
        """See Config._get_signing_policy."""
 
685
        return self._get_best_value('_get_signing_policy')
434
686
 
435
687
    def _get_user_option(self, option_name):
436
688
        """See Config._get_user_option."""
437
 
        return self._get_location_config()._get_user_option(option_name)
 
689
        for source in self.option_sources:
 
690
            value = source()._get_user_option(option_name)
 
691
            if value is not None:
 
692
                return value
 
693
        return None
 
694
 
 
695
    def set_user_option(self, name, value, store=STORE_BRANCH,
 
696
        warn_masked=False):
 
697
        if store == STORE_BRANCH:
 
698
            self._get_branch_data_config().set_option(value, name)
 
699
        elif store == STORE_GLOBAL:
 
700
            self._get_global_config().set_user_option(name, value)
 
701
        else:
 
702
            self._get_location_config().set_user_option(name, value, store)
 
703
        if not warn_masked:
 
704
            return
 
705
        if store in (STORE_GLOBAL, STORE_BRANCH):
 
706
            mask_value = self._get_location_config().get_user_option(name)
 
707
            if mask_value is not None:
 
708
                trace.warning('Value "%s" is masked by "%s" from'
 
709
                              ' locations.conf', value, mask_value)
 
710
            else:
 
711
                if store == STORE_GLOBAL:
 
712
                    branch_config = self._get_branch_data_config()
 
713
                    mask_value = branch_config.get_user_option(name)
 
714
                    if mask_value is not None:
 
715
                        trace.warning('Value "%s" is masked by "%s" from'
 
716
                                      ' branch.conf', value, mask_value)
 
717
 
438
718
 
439
719
    def _gpg_signing_command(self):
440
720
        """See Config.gpg_signing_command."""
441
 
        return self._get_location_config()._gpg_signing_command()
 
721
        return self._get_safe_value('_gpg_signing_command')
442
722
        
443
723
    def __init__(self, branch):
444
724
        super(BranchConfig, self).__init__()
445
725
        self._location_config = None
 
726
        self._branch_data_config = None
 
727
        self._global_config = None
446
728
        self.branch = branch
 
729
        self.option_sources = (self._get_location_config, 
 
730
                               self._get_branch_data_config,
 
731
                               self._get_global_config)
447
732
 
448
733
    def _post_commit(self):
449
734
        """See Config.post_commit."""
450
 
        return self._get_location_config()._post_commit()
 
735
        return self._get_safe_value('_post_commit')
 
736
 
 
737
    def _get_nickname(self):
 
738
        value = self._get_explicit_nickname()
 
739
        if value is not None:
 
740
            return value
 
741
        return urlutils.unescape(self.branch.base.split('/')[-2])
 
742
 
 
743
    def has_explicit_nickname(self):
 
744
        """Return true if a nickname has been explicitly assigned."""
 
745
        return self._get_explicit_nickname() is not None
 
746
 
 
747
    def _get_explicit_nickname(self):
 
748
        return self._get_best_value('_get_nickname')
451
749
 
452
750
    def _log_format(self):
453
751
        """See Config.log_format."""
454
 
        return self._get_location_config()._log_format()
 
752
        return self._get_best_value('_log_format')
455
753
 
456
754
 
457
755
def ensure_config_dir_exists(path=None):
466
764
        if sys.platform == 'win32':
467
765
            parent_dir = os.path.dirname(path)
468
766
            if not os.path.isdir(parent_dir):
469
 
                mutter('creating config parent directory: %r', parent_dir)
 
767
                trace.mutter('creating config parent directory: %r', parent_dir)
470
768
            os.mkdir(parent_dir)
471
 
        mutter('creating config directory: %r', path)
 
769
        trace.mutter('creating config directory: %r', path)
472
770
        os.mkdir(path)
473
771
 
474
772
 
482
780
    base = os.environ.get('BZR_HOME', None)
483
781
    if sys.platform == 'win32':
484
782
        if base is None:
485
 
            base = os.environ.get('APPDATA', None)
 
783
            base = win32utils.get_appdata_location_unicode()
486
784
        if base is None:
487
785
            base = os.environ.get('HOME', None)
488
786
        if base is None:
489
 
            raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
490
 
        return pathjoin(base, 'bazaar', '2.0')
 
787
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
 
788
                                  ' or HOME set')
 
789
        return osutils.pathjoin(base, 'bazaar', '2.0')
491
790
    else:
492
791
        # cygwin, linux, and darwin all have a $HOME directory
493
792
        if base is None:
494
793
            base = os.path.expanduser("~")
495
 
        return pathjoin(base, ".bazaar")
 
794
        return osutils.pathjoin(base, ".bazaar")
496
795
 
497
796
 
498
797
def config_filename():
499
798
    """Return per-user configuration ini file filename."""
500
 
    return pathjoin(config_dir(), 'bazaar.conf')
 
799
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
501
800
 
502
801
 
503
802
def branches_config_filename():
504
803
    """Return per-user configuration ini file filename."""
505
 
    return pathjoin(config_dir(), 'branches.conf')
 
804
    return osutils.pathjoin(config_dir(), 'branches.conf')
 
805
 
 
806
 
 
807
def locations_config_filename():
 
808
    """Return per-user configuration ini file filename."""
 
809
    return osutils.pathjoin(config_dir(), 'locations.conf')
 
810
 
 
811
 
 
812
def authentication_config_filename():
 
813
    """Return per-user authentication ini file filename."""
 
814
    return osutils.pathjoin(config_dir(), 'authentication.conf')
 
815
 
 
816
 
 
817
def user_ignore_config_filename():
 
818
    """Return the user default ignore filename"""
 
819
    return osutils.pathjoin(config_dir(), 'ignore')
506
820
 
507
821
 
508
822
def _auto_user_id():
518
832
    """
519
833
    import socket
520
834
 
521
 
    # XXX: Any good way to get real user name on win32?
 
835
    if sys.platform == 'win32':
 
836
        name = win32utils.get_user_name_unicode()
 
837
        if name is None:
 
838
            raise errors.BzrError("Cannot autodetect user name.\n"
 
839
                                  "Please, set your name with command like:\n"
 
840
                                  'bzr whoami "Your Name <name@domain.com>"')
 
841
        host = win32utils.get_host_name_unicode()
 
842
        if host is None:
 
843
            host = socket.gethostname()
 
844
        return name, (name + '@' + host)
522
845
 
523
846
    try:
524
847
        import pwd
525
848
        uid = os.getuid()
526
849
        w = pwd.getpwuid(uid)
527
850
 
528
 
        try:
529
 
            gecos = w.pw_gecos.decode(bzrlib.user_encoding)
530
 
            username = w.pw_name.decode(bzrlib.user_encoding)
531
 
        except UnicodeDecodeError:
532
 
            # We're using pwd, therefore we're on Unix, so /etc/passwd is ok.
533
 
            raise errors.BzrError("Can't decode username in " \
534
 
                    "/etc/passwd as %s." % bzrlib.user_encoding)
 
851
        # we try utf-8 first, because on many variants (like Linux),
 
852
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
853
        # false positives.  (many users will have their user encoding set to
 
854
        # latin-1, which cannot raise UnicodeError.)
 
855
        try:
 
856
            gecos = w.pw_gecos.decode('utf-8')
 
857
            encoding = 'utf-8'
 
858
        except UnicodeError:
 
859
            try:
 
860
                gecos = w.pw_gecos.decode(bzrlib.user_encoding)
 
861
                encoding = bzrlib.user_encoding
 
862
            except UnicodeError:
 
863
                raise errors.BzrCommandError('Unable to determine your name.  '
 
864
                   'Use "bzr whoami" to set it.')
 
865
        try:
 
866
            username = w.pw_name.decode(encoding)
 
867
        except UnicodeError:
 
868
            raise errors.BzrCommandError('Unable to determine your name.  '
 
869
                'Use "bzr whoami" to set it.')
535
870
 
536
871
        comma = gecos.find(',')
537
872
        if comma == -1:
552
887
    return realname, (username + '@' + socket.gethostname())
553
888
 
554
889
 
 
890
def parse_username(username):
 
891
    """Parse e-mail username and return a (name, address) tuple."""
 
892
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
 
893
    if match is None:
 
894
        return (username, '')
 
895
    else:
 
896
        return (match.group(1), match.group(2))
 
897
 
 
898
 
555
899
def extract_email_address(e):
556
900
    """Return just the address part of an email string.
557
 
    
 
901
 
558
902
    That is just the user@domain part, nothing else. 
559
903
    This part is required to contain only ascii characters.
560
904
    If it can't be extracted, raises an error.
561
 
    
 
905
 
562
906
    >>> extract_email_address('Jane Tester <jane@test.com>')
563
907
    "jane@test.com"
564
908
    """
565
 
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
566
 
    if not m:
567
 
        raise errors.BzrError("%r doesn't seem to contain "
568
 
                              "a reasonable email address" % e)
569
 
    return m.group(0)
570
 
 
571
 
 
572
 
class TreeConfig(object):
 
909
    name, email = parse_username(e)
 
910
    if not email:
 
911
        raise errors.NoEmailInUsername(e)
 
912
    return email
 
913
 
 
914
 
 
915
class TreeConfig(IniBasedConfig):
573
916
    """Branch configuration data associated with its contents, not location"""
 
917
 
 
918
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
 
919
 
574
920
    def __init__(self, branch):
 
921
        # XXX: Really this should be asking the branch for its configuration
 
922
        # data, rather than relying on a Transport, so that it can work 
 
923
        # more cleanly with a RemoteBranch that has no transport.
 
924
        self._config = TransportConfig(branch._transport, 'branch.conf')
575
925
        self.branch = branch
576
926
 
577
 
    def _get_config(self):
578
 
        try:
579
 
            obj = ConfigObj(self.branch.control_files.get('branch.conf'), 
580
 
                            encoding='utf-8')
581
 
        except errors.NoSuchFile:
582
 
            obj = ConfigObj(encoding='utf=8')
583
 
        return obj
 
927
    def _get_parser(self, file=None):
 
928
        if file is not None:
 
929
            return IniBasedConfig._get_parser(file)
 
930
        return self._config._get_configobj()
584
931
 
585
932
    def get_option(self, name, section=None, default=None):
586
933
        self.branch.lock_read()
587
934
        try:
588
 
            obj = self._get_config()
589
 
            try:
590
 
                if section is not None:
591
 
                    obj[section]
592
 
                result = obj[name]
593
 
            except KeyError:
594
 
                result = default
 
935
            return self._config.get_option(name, section, default)
595
936
        finally:
596
937
            self.branch.unlock()
597
938
        return result
600
941
        """Set a per-branch configuration option"""
601
942
        self.branch.lock_write()
602
943
        try:
603
 
            cfg_obj = self._get_config()
604
 
            if section is None:
605
 
                obj = cfg_obj
606
 
            else:
607
 
                try:
608
 
                    obj = cfg_obj[section]
609
 
                except KeyError:
610
 
                    cfg_obj[section] = {}
611
 
                    obj = cfg_obj[section]
612
 
            obj[name] = value
613
 
            out_file = StringIO()
614
 
            cfg_obj.write(out_file)
615
 
            out_file.seek(0)
616
 
            self.branch.control_files.put('branch.conf', out_file)
 
944
            self._config.set_option(value, name, section)
617
945
        finally:
618
946
            self.branch.unlock()
 
947
 
 
948
 
 
949
class AuthenticationConfig(object):
 
950
    """The authentication configuration file based on a ini file.
 
951
 
 
952
    Implements the authentication.conf file described in
 
953
    doc/developers/authentication-ring.txt.
 
954
    """
 
955
 
 
956
    def __init__(self, _file=None):
 
957
        self._config = None # The ConfigObj
 
958
        if _file is None:
 
959
            self._filename = authentication_config_filename()
 
960
            self._input = self._filename = authentication_config_filename()
 
961
        else:
 
962
            # Tests can provide a string as _file
 
963
            self._filename = None
 
964
            self._input = _file
 
965
 
 
966
    def _get_config(self):
 
967
        if self._config is not None:
 
968
            return self._config
 
969
        try:
 
970
            # FIXME: Should we validate something here ? Includes: empty
 
971
            # sections are useless, at least one of
 
972
            # user/password/password_encoding should be defined, etc.
 
973
 
 
974
            # Note: the encoding below declares that the file itself is utf-8
 
975
            # encoded, but the values in the ConfigObj are always Unicode.
 
976
            self._config = ConfigObj(self._input, encoding='utf-8')
 
977
        except configobj.ConfigObjError, e:
 
978
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
979
        return self._config
 
980
 
 
981
    def _save(self):
 
982
        """Save the config file, only tests should use it for now."""
 
983
        conf_dir = os.path.dirname(self._filename)
 
984
        ensure_config_dir_exists(conf_dir)
 
985
        self._get_config().write(file(self._filename, 'wb'))
 
986
 
 
987
    def _set_option(self, section_name, option_name, value):
 
988
        """Set an authentication configuration option"""
 
989
        conf = self._get_config()
 
990
        section = conf.get(section_name)
 
991
        if section is None:
 
992
            conf[section] = {}
 
993
            section = conf[section]
 
994
        section[option_name] = value
 
995
        self._save()
 
996
 
 
997
    def get_credentials(self, scheme, host, port=None, user=None, path=None):
 
998
        """Returns the matching credentials from authentication.conf file.
 
999
 
 
1000
        :param scheme: protocol
 
1001
 
 
1002
        :param host: the server address
 
1003
 
 
1004
        :param port: the associated port (optional)
 
1005
 
 
1006
        :param user: login (optional)
 
1007
 
 
1008
        :param path: the absolute path on the server (optional)
 
1009
 
 
1010
        :return: A dict containing the matching credentials or None.
 
1011
           This includes:
 
1012
           - name: the section name of the credentials in the
 
1013
             authentication.conf file,
 
1014
           - user: can't de different from the provided user if any,
 
1015
           - password: the decoded password, could be None if the credential
 
1016
             defines only the user
 
1017
           - verify_certificates: https specific, True if the server
 
1018
             certificate should be verified, False otherwise.
 
1019
        """
 
1020
        credentials = None
 
1021
        for auth_def_name, auth_def in self._get_config().items():
 
1022
            if type(auth_def) is not configobj.Section:
 
1023
                raise ValueError("%s defined outside a section" % auth_def_name)
 
1024
 
 
1025
            a_scheme, a_host, a_user, a_path = map(
 
1026
                auth_def.get, ['scheme', 'host', 'user', 'path'])
 
1027
 
 
1028
            try:
 
1029
                a_port = auth_def.as_int('port')
 
1030
            except KeyError:
 
1031
                a_port = None
 
1032
            except ValueError:
 
1033
                raise ValueError("'port' not numeric in %s" % auth_def_name)
 
1034
            try:
 
1035
                a_verify_certificates = auth_def.as_bool('verify_certificates')
 
1036
            except KeyError:
 
1037
                a_verify_certificates = True
 
1038
            except ValueError:
 
1039
                raise ValueError(
 
1040
                    "'verify_certificates' not boolean in %s" % auth_def_name)
 
1041
 
 
1042
            # Attempt matching
 
1043
            if a_scheme is not None and scheme != a_scheme:
 
1044
                continue
 
1045
            if a_host is not None:
 
1046
                if not (host == a_host
 
1047
                        or (a_host.startswith('.') and host.endswith(a_host))):
 
1048
                    continue
 
1049
            if a_port is not None and port != a_port:
 
1050
                continue
 
1051
            if (a_path is not None and path is not None
 
1052
                and not path.startswith(a_path)):
 
1053
                continue
 
1054
            if (a_user is not None and user is not None
 
1055
                and a_user != user):
 
1056
                # Never contradict the caller about the user to be used
 
1057
                continue
 
1058
            if a_user is None:
 
1059
                # Can't find a user
 
1060
                continue
 
1061
            credentials = dict(name=auth_def_name,
 
1062
                               user=a_user,
 
1063
                               password=auth_def.get('password', None),
 
1064
                               verify_certificates=a_verify_certificates)
 
1065
            self.decode_password(credentials,
 
1066
                                 auth_def.get('password_encoding', None))
 
1067
            if 'auth' in debug.debug_flags:
 
1068
                trace.mutter("Using authentication section: %r", auth_def_name)
 
1069
            break
 
1070
 
 
1071
        return credentials
 
1072
 
 
1073
    def get_user(self, scheme, host, port=None,
 
1074
                 realm=None, path=None, prompt=None):
 
1075
        """Get a user from authentication file.
 
1076
 
 
1077
        :param scheme: protocol
 
1078
 
 
1079
        :param host: the server address
 
1080
 
 
1081
        :param port: the associated port (optional)
 
1082
 
 
1083
        :param realm: the realm sent by the server (optional)
 
1084
 
 
1085
        :param path: the absolute path on the server (optional)
 
1086
 
 
1087
        :return: The found user.
 
1088
        """
 
1089
        credentials = self.get_credentials(scheme, host, port, user=None,
 
1090
                                           path=path)
 
1091
        if credentials is not None:
 
1092
            user = credentials['user']
 
1093
        else:
 
1094
            user = None
 
1095
        return user
 
1096
 
 
1097
    def get_password(self, scheme, host, user, port=None,
 
1098
                     realm=None, path=None, prompt=None):
 
1099
        """Get a password from authentication file or prompt the user for one.
 
1100
 
 
1101
        :param scheme: protocol
 
1102
 
 
1103
        :param host: the server address
 
1104
 
 
1105
        :param port: the associated port (optional)
 
1106
 
 
1107
        :param user: login
 
1108
 
 
1109
        :param realm: the realm sent by the server (optional)
 
1110
 
 
1111
        :param path: the absolute path on the server (optional)
 
1112
 
 
1113
        :return: The found password or the one entered by the user.
 
1114
        """
 
1115
        credentials = self.get_credentials(scheme, host, port, user, path)
 
1116
        if credentials is not None:
 
1117
            password = credentials['password']
 
1118
            if password is not None and scheme is 'ssh':
 
1119
                trace.warning('password ignored in section [%s],'
 
1120
                              ' use an ssh agent instead'
 
1121
                              % credentials['name'])
 
1122
                password = None
 
1123
        else:
 
1124
            password = None
 
1125
        # Prompt user only if we could't find a password
 
1126
        if password is None:
 
1127
            if prompt is None:
 
1128
                # Create a default prompt suitable for most cases
 
1129
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
 
1130
            # Special handling for optional fields in the prompt
 
1131
            if port is not None:
 
1132
                prompt_host = '%s:%d' % (host, port)
 
1133
            else:
 
1134
                prompt_host = host
 
1135
            password = ui.ui_factory.get_password(prompt,
 
1136
                                                  host=prompt_host, user=user)
 
1137
        return password
 
1138
 
 
1139
    def decode_password(self, credentials, encoding):
 
1140
        return credentials
 
1141
 
 
1142
 
 
1143
class BzrDirConfig(object):
 
1144
 
 
1145
    def __init__(self, transport):
 
1146
        self._config = TransportConfig(transport, 'control.conf')
 
1147
 
 
1148
    def set_default_stack_on(self, value):
 
1149
        """Set the default stacking location.
 
1150
 
 
1151
        It may be set to a location, or None.
 
1152
 
 
1153
        This policy affects all branches contained by this bzrdir, except for
 
1154
        those under repositories.
 
1155
        """
 
1156
        if value is None:
 
1157
            self._config.set_option('', 'default_stack_on')
 
1158
        else:
 
1159
            self._config.set_option(value, 'default_stack_on')
 
1160
 
 
1161
    def get_default_stack_on(self):
 
1162
        """Return the default stacking location.
 
1163
 
 
1164
        This will either be a location, or None.
 
1165
 
 
1166
        This policy affects all branches contained by this bzrdir, except for
 
1167
        those under repositories.
 
1168
        """
 
1169
        value = self._config.get_option('default_stack_on')
 
1170
        if value == '':
 
1171
            value = None
 
1172
        return value
 
1173
 
 
1174
 
 
1175
class TransportConfig(object):
 
1176
    """A Config that reads/writes a config file on a Transport.
 
1177
 
 
1178
    It is a low-level object that considers config data to be name/value pairs
 
1179
    that may be associated with a section.  Assigning meaning to the these
 
1180
    values is done at higher levels like TreeConfig.
 
1181
    """
 
1182
 
 
1183
    def __init__(self, transport, filename):
 
1184
        self._transport = transport
 
1185
        self._filename = filename
 
1186
 
 
1187
    def get_option(self, name, section=None, default=None):
 
1188
        """Return the value associated with a named option.
 
1189
 
 
1190
        :param name: The name of the value
 
1191
        :param section: The section the option is in (if any)
 
1192
        :param default: The value to return if the value is not set
 
1193
        :return: The value or default value
 
1194
        """
 
1195
        configobj = self._get_configobj()
 
1196
        if section is None:
 
1197
            section_obj = configobj
 
1198
        else:
 
1199
            try:
 
1200
                section_obj = configobj[section]
 
1201
            except KeyError:
 
1202
                return default
 
1203
        return section_obj.get(name, default)
 
1204
 
 
1205
    def set_option(self, value, name, section=None):
 
1206
        """Set the value associated with a named option.
 
1207
 
 
1208
        :param value: The value to set
 
1209
        :param name: The name of the value to set
 
1210
        :param section: The section the option is in (if any)
 
1211
        """
 
1212
        configobj = self._get_configobj()
 
1213
        if section is None:
 
1214
            configobj[name] = value
 
1215
        else:
 
1216
            configobj.setdefault(section, {})[name] = value
 
1217
        self._set_configobj(configobj)
 
1218
 
 
1219
    def _get_configobj(self):
 
1220
        try:
 
1221
            return ConfigObj(self._transport.get(self._filename),
 
1222
                             encoding='utf-8')
 
1223
        except errors.NoSuchFile:
 
1224
            return ConfigObj(encoding='utf-8')
 
1225
 
 
1226
    def _set_configobj(self, configobj):
 
1227
        out_file = StringIO()
 
1228
        configobj.write(out_file)
 
1229
        out_file.seek(0)
 
1230
        self._transport.put_file(self._filename, out_file)