/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: Vincent Ladeuil
  • Date: 2007-10-23 07:15:13 UTC
  • mfrom: (2926 +trunk)
  • mto: (2961.1.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 2962.
  • Revision ID: v.ladeuil+lp@free.fr-20071023071513-elryt6g2at34d2ur
merge bzr.dev

Show diffs side-by-side

added added

removed removed

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