~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Robert Collins
  • Date: 2006-06-10 19:32:47 UTC
  • mto: (1767.2.2 integration)
  • mto: This revision was merged to the branch mainline in revision 1769.
  • Revision ID: robertc@robertcollins.net-20060610193247-be43e4f7c71fb77f
Teach walkdirs to walk a subdir of a tree.

Show diffs side-by-side

added added

removed removed

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