/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: Tim Penhey
  • Date: 2008-05-30 10:47:49 UTC
  • mto: (3473.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 3474.
  • Revision ID: tim@penhey.net-20080530104749-qfb4l7ykcdr84zu3
Fixed the output in the tests.

Show diffs side-by-side

added added

removed removed

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