~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Martin Packman
  • Date: 2011-12-08 19:00:14 UTC
  • mto: This revision was merged to the branch mainline in revision 6359.
  • Revision ID: martin.packman@canonical.com-20111208190014-mi8jm6v7jygmhb0r
Use --include-duplicates for make update-pot which already combines multiple msgid strings prettily

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2011 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
validate_signatures_in_log=true|false(default)
 
33
acceptable_keys=pattern1,pattern2
 
34
gpg_signing_key=amy@example.com
 
35
 
 
36
in locations.conf, you specify the url of a branch and options for it.
 
37
Wildcards may be used - * and ? as normal in shell completion. Options
 
38
set in both bazaar.conf and locations.conf are overridden by the locations.conf
 
39
setting.
 
40
[/home/robertc/source]
 
41
recurse=False|True(default)
 
42
email= as above
 
43
check_signatures= as above
 
44
create_signatures= as above.
 
45
validate_signatures_in_log=as above
 
46
acceptable_keys=as above
 
47
 
 
48
explanation of options
 
49
----------------------
 
50
editor - this option sets the pop up editor to use during commits.
 
51
email - this option sets the user id bzr will use when committing.
 
52
check_signatures - this option will control whether bzr will require good gpg
 
53
                   signatures, ignore them, or check them if they are
 
54
                   present.  Currently it is unused except that check_signatures
 
55
                   turns on create_signatures.
 
56
create_signatures - this option controls whether bzr will always create
 
57
                    gpg signatures or not on commits.  There is an unused
 
58
                    option which in future is expected to work if               
 
59
                    branch settings require signatures.
 
60
log_format - this option sets the default log format.  Possible values are
 
61
             long, short, line, or a plugin can register new formats.
 
62
validate_signatures_in_log - show GPG signature validity in log output
 
63
acceptable_keys - comma separated list of key patterns acceptable for
 
64
                  verify-signatures command
 
65
 
 
66
In bazaar.conf you can also define aliases in the ALIASES sections, example
 
67
 
 
68
[ALIASES]
 
69
lastlog=log --line -r-10..-1
 
70
ll=log --line -r-10..-1
 
71
h=help
 
72
up=pull
 
73
"""
 
74
 
 
75
import os
 
76
import string
 
77
import sys
 
78
 
 
79
 
 
80
import bzrlib
 
81
from bzrlib.decorators import needs_write_lock
 
82
from bzrlib.lazy_import import lazy_import
 
83
lazy_import(globals(), """
 
84
import fnmatch
 
85
import re
 
86
from cStringIO import StringIO
 
87
 
 
88
from bzrlib import (
 
89
    atomicfile,
 
90
    controldir,
 
91
    debug,
 
92
    errors,
 
93
    lazy_regex,
 
94
    library_state,
 
95
    lockdir,
 
96
    mail_client,
 
97
    mergetools,
 
98
    osutils,
 
99
    symbol_versioning,
 
100
    trace,
 
101
    transport,
 
102
    ui,
 
103
    urlutils,
 
104
    win32utils,
 
105
    )
 
106
from bzrlib.i18n import gettext
 
107
from bzrlib.util.configobj import configobj
 
108
""")
 
109
from bzrlib import (
 
110
    commands,
 
111
    hooks,
 
112
    lazy_regex,
 
113
    registry,
 
114
    )
 
115
from bzrlib.symbol_versioning import (
 
116
    deprecated_in,
 
117
    deprecated_method,
 
118
    )
 
119
 
 
120
 
 
121
CHECK_IF_POSSIBLE=0
 
122
CHECK_ALWAYS=1
 
123
CHECK_NEVER=2
 
124
 
 
125
 
 
126
SIGN_WHEN_REQUIRED=0
 
127
SIGN_ALWAYS=1
 
128
SIGN_NEVER=2
 
129
 
 
130
 
 
131
POLICY_NONE = 0
 
132
POLICY_NORECURSE = 1
 
133
POLICY_APPENDPATH = 2
 
134
 
 
135
_policy_name = {
 
136
    POLICY_NONE: None,
 
137
    POLICY_NORECURSE: 'norecurse',
 
138
    POLICY_APPENDPATH: 'appendpath',
 
139
    }
 
140
_policy_value = {
 
141
    None: POLICY_NONE,
 
142
    'none': POLICY_NONE,
 
143
    'norecurse': POLICY_NORECURSE,
 
144
    'appendpath': POLICY_APPENDPATH,
 
145
    }
 
146
 
 
147
 
 
148
STORE_LOCATION = POLICY_NONE
 
149
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
 
150
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
 
151
STORE_BRANCH = 3
 
152
STORE_GLOBAL = 4
 
153
 
 
154
 
 
155
class ConfigObj(configobj.ConfigObj):
 
156
 
 
157
    def __init__(self, infile=None, **kwargs):
 
158
        # We define our own interpolation mechanism calling it option expansion
 
159
        super(ConfigObj, self).__init__(infile=infile,
 
160
                                        interpolation=False,
 
161
                                        **kwargs)
 
162
 
 
163
    def get_bool(self, section, key):
 
164
        return self[section].as_bool(key)
 
165
 
 
166
    def get_value(self, section, name):
 
167
        # Try [] for the old DEFAULT section.
 
168
        if section == "DEFAULT":
 
169
            try:
 
170
                return self[name]
 
171
            except KeyError:
 
172
                pass
 
173
        return self[section][name]
 
174
 
 
175
 
 
176
# FIXME: Until we can guarantee that each config file is loaded once and
 
177
# only once for a given bzrlib session, we don't want to re-read the file every
 
178
# time we query for an option so we cache the value (bad ! watch out for tests
 
179
# needing to restore the proper value). -- vila 20110219
 
180
_expand_default_value = None
 
181
def _get_expand_default_value():
 
182
    global _expand_default_value
 
183
    if _expand_default_value is not None:
 
184
        return _expand_default_value
 
185
    conf = GlobalConfig()
 
186
    # Note that we must not use None for the expand value below or we'll run
 
187
    # into infinite recursion. Using False really would be quite silly ;)
 
188
    expand = conf.get_user_option_as_bool('bzr.config.expand', expand=True)
 
189
    if expand is None:
 
190
        # This is an opt-in feature, you *really* need to clearly say you want
 
191
        # to activate it !
 
192
        expand = False
 
193
    _expand_default_value = expand
 
194
    return expand
 
195
 
 
196
 
 
197
class Config(object):
 
198
    """A configuration policy - what username, editor, gpg needs etc."""
 
199
 
 
200
    def __init__(self):
 
201
        super(Config, self).__init__()
 
202
 
 
203
    def config_id(self):
 
204
        """Returns a unique ID for the config."""
 
205
        raise NotImplementedError(self.config_id)
 
206
 
 
207
    @deprecated_method(deprecated_in((2, 4, 0)))
 
208
    def get_editor(self):
 
209
        """Get the users pop up editor."""
 
210
        raise NotImplementedError
 
211
 
 
212
    def get_change_editor(self, old_tree, new_tree):
 
213
        from bzrlib import diff
 
214
        cmd = self._get_change_editor()
 
215
        if cmd is None:
 
216
            return None
 
217
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
 
218
                                             sys.stdout)
 
219
 
 
220
    def get_mail_client(self):
 
221
        """Get a mail client to use"""
 
222
        selected_client = self.get_user_option('mail_client')
 
223
        _registry = mail_client.mail_client_registry
 
224
        try:
 
225
            mail_client_class = _registry.get(selected_client)
 
226
        except KeyError:
 
227
            raise errors.UnknownMailClient(selected_client)
 
228
        return mail_client_class(self)
 
229
 
 
230
    def _get_signature_checking(self):
 
231
        """Template method to override signature checking policy."""
 
232
 
 
233
    def _get_signing_policy(self):
 
234
        """Template method to override signature creation policy."""
 
235
 
 
236
    option_ref_re = None
 
237
 
 
238
    def expand_options(self, string, env=None):
 
239
        """Expand option references in the string in the configuration context.
 
240
 
 
241
        :param string: The string containing option to expand.
 
242
 
 
243
        :param env: An option dict defining additional configuration options or
 
244
            overriding existing ones.
 
245
 
 
246
        :returns: The expanded string.
 
247
        """
 
248
        return self._expand_options_in_string(string, env)
 
249
 
 
250
    def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
 
251
        """Expand options in  a list of strings in the configuration context.
 
252
 
 
253
        :param slist: A list of strings.
 
254
 
 
255
        :param env: An option dict defining additional configuration options or
 
256
            overriding existing ones.
 
257
 
 
258
        :param _ref_stack: Private list containing the options being
 
259
            expanded to detect loops.
 
260
 
 
261
        :returns: The flatten list of expanded strings.
 
262
        """
 
263
        # expand options in each value separately flattening lists
 
264
        result = []
 
265
        for s in slist:
 
266
            value = self._expand_options_in_string(s, env, _ref_stack)
 
267
            if isinstance(value, list):
 
268
                result.extend(value)
 
269
            else:
 
270
                result.append(value)
 
271
        return result
 
272
 
 
273
    def _expand_options_in_string(self, string, env=None, _ref_stack=None):
 
274
        """Expand options in the string in the configuration context.
 
275
 
 
276
        :param string: The string to be expanded.
 
277
 
 
278
        :param env: An option dict defining additional configuration options or
 
279
            overriding existing ones.
 
280
 
 
281
        :param _ref_stack: Private list containing the options being
 
282
            expanded to detect loops.
 
283
 
 
284
        :returns: The expanded string.
 
285
        """
 
286
        if string is None:
 
287
            # Not much to expand there
 
288
            return None
 
289
        if _ref_stack is None:
 
290
            # What references are currently resolved (to detect loops)
 
291
            _ref_stack = []
 
292
        if self.option_ref_re is None:
 
293
            # We want to match the most embedded reference first (i.e. for
 
294
            # '{{foo}}' we will get '{foo}',
 
295
            # for '{bar{baz}}' we will get '{baz}'
 
296
            self.option_ref_re = re.compile('({[^{}]+})')
 
297
        result = string
 
298
        # We need to iterate until no more refs appear ({{foo}} will need two
 
299
        # iterations for example).
 
300
        while True:
 
301
            raw_chunks = self.option_ref_re.split(result)
 
302
            if len(raw_chunks) == 1:
 
303
                # Shorcut the trivial case: no refs
 
304
                return result
 
305
            chunks = []
 
306
            list_value = False
 
307
            # Split will isolate refs so that every other chunk is a ref
 
308
            chunk_is_ref = False
 
309
            for chunk in raw_chunks:
 
310
                if not chunk_is_ref:
 
311
                    if chunk:
 
312
                        # Keep only non-empty strings (or we get bogus empty
 
313
                        # slots when a list value is involved).
 
314
                        chunks.append(chunk)
 
315
                    chunk_is_ref = True
 
316
                else:
 
317
                    name = chunk[1:-1]
 
318
                    if name in _ref_stack:
 
319
                        raise errors.OptionExpansionLoop(string, _ref_stack)
 
320
                    _ref_stack.append(name)
 
321
                    value = self._expand_option(name, env, _ref_stack)
 
322
                    if value is None:
 
323
                        raise errors.ExpandingUnknownOption(name, string)
 
324
                    if isinstance(value, list):
 
325
                        list_value = True
 
326
                        chunks.extend(value)
 
327
                    else:
 
328
                        chunks.append(value)
 
329
                    _ref_stack.pop()
 
330
                    chunk_is_ref = False
 
331
            if list_value:
 
332
                # Once a list appears as the result of an expansion, all
 
333
                # callers will get a list result. This allows a consistent
 
334
                # behavior even when some options in the expansion chain
 
335
                # defined as strings (no comma in their value) but their
 
336
                # expanded value is a list.
 
337
                return self._expand_options_in_list(chunks, env, _ref_stack)
 
338
            else:
 
339
                result = ''.join(chunks)
 
340
        return result
 
341
 
 
342
    def _expand_option(self, name, env, _ref_stack):
 
343
        if env is not None and name in env:
 
344
            # Special case, values provided in env takes precedence over
 
345
            # anything else
 
346
            value = env[name]
 
347
        else:
 
348
            # FIXME: This is a limited implementation, what we really need is a
 
349
            # way to query the bzr config for the value of an option,
 
350
            # respecting the scope rules (That is, once we implement fallback
 
351
            # configs, getting the option value should restart from the top
 
352
            # config, not the current one) -- vila 20101222
 
353
            value = self.get_user_option(name, expand=False)
 
354
            if isinstance(value, list):
 
355
                value = self._expand_options_in_list(value, env, _ref_stack)
 
356
            else:
 
357
                value = self._expand_options_in_string(value, env, _ref_stack)
 
358
        return value
 
359
 
 
360
    def _get_user_option(self, option_name):
 
361
        """Template method to provide a user option."""
 
362
        return None
 
363
 
 
364
    def get_user_option(self, option_name, expand=None):
 
365
        """Get a generic option - no special process, no default.
 
366
 
 
367
        :param option_name: The queried option.
 
368
 
 
369
        :param expand: Whether options references should be expanded.
 
370
 
 
371
        :returns: The value of the option.
 
372
        """
 
373
        if expand is None:
 
374
            expand = _get_expand_default_value()
 
375
        value = self._get_user_option(option_name)
 
376
        if expand:
 
377
            if isinstance(value, list):
 
378
                value = self._expand_options_in_list(value)
 
379
            elif isinstance(value, dict):
 
380
                trace.warning('Cannot expand "%s":'
 
381
                              ' Dicts do not support option expansion'
 
382
                              % (option_name,))
 
383
            else:
 
384
                value = self._expand_options_in_string(value)
 
385
        for hook in OldConfigHooks['get']:
 
386
            hook(self, option_name, value)
 
387
        return value
 
388
 
 
389
    def get_user_option_as_bool(self, option_name, expand=None, default=None):
 
390
        """Get a generic option as a boolean.
 
391
 
 
392
        :param expand: Allow expanding references to other config values.
 
393
        :param default: Default value if nothing is configured
 
394
        :return None if the option doesn't exist or its value can't be
 
395
            interpreted as a boolean. Returns True or False otherwise.
 
396
        """
 
397
        s = self.get_user_option(option_name, expand=expand)
 
398
        if s is None:
 
399
            # The option doesn't exist
 
400
            return default
 
401
        val = ui.bool_from_string(s)
 
402
        if val is None:
 
403
            # The value can't be interpreted as a boolean
 
404
            trace.warning('Value "%s" is not a boolean for "%s"',
 
405
                          s, option_name)
 
406
        return val
 
407
 
 
408
    def get_user_option_as_list(self, option_name, expand=None):
 
409
        """Get a generic option as a list - no special process, no default.
 
410
 
 
411
        :return None if the option doesn't exist. Returns the value as a list
 
412
            otherwise.
 
413
        """
 
414
        l = self.get_user_option(option_name, expand=expand)
 
415
        if isinstance(l, (str, unicode)):
 
416
            # A single value, most probably the user forgot (or didn't care to
 
417
            # add) the final ','
 
418
            l = [l]
 
419
        return l
 
420
        
 
421
    def get_user_option_as_int_from_SI(self,  option_name,  default=None):
 
422
        """Get a generic option from a human readable size in SI units, e.g 10MB
 
423
        
 
424
        Accepted suffixes are K,M,G. It is case-insensitive and may be followed
 
425
        by a trailing b (i.e. Kb, MB). This is intended to be practical and not
 
426
        pedantic.
 
427
        
 
428
        :return Integer, expanded to its base-10 value if a proper SI unit is 
 
429
            found. If the option doesn't exist, or isn't a value in 
 
430
            SI units, return default (which defaults to None)
 
431
        """
 
432
        val = self.get_user_option(option_name)
 
433
        if isinstance(val, list):
 
434
            val = val[0]
 
435
        if val is None:
 
436
            val = default
 
437
        else:
 
438
            p = re.compile("^(\d+)([kmg])*b*$", re.IGNORECASE)
 
439
            try:
 
440
                m = p.match(val)
 
441
                if m is not None:
 
442
                    val = int(m.group(1))
 
443
                    if m.group(2) is not None:
 
444
                        if m.group(2).lower() == 'k':
 
445
                            val *= 10**3
 
446
                        elif m.group(2).lower() == 'm':
 
447
                            val *= 10**6
 
448
                        elif m.group(2).lower() == 'g':
 
449
                            val *= 10**9
 
450
                else:
 
451
                    ui.ui_factory.show_warning(gettext('Invalid config value for "{0}" '
 
452
                                               ' value {1!r} is not an SI unit.').format(
 
453
                                                option_name, val))
 
454
                    val = default
 
455
            except TypeError:
 
456
                val = default
 
457
        return val
 
458
        
 
459
 
 
460
    def gpg_signing_command(self):
 
461
        """What program should be used to sign signatures?"""
 
462
        result = self._gpg_signing_command()
 
463
        if result is None:
 
464
            result = "gpg"
 
465
        return result
 
466
 
 
467
    def _gpg_signing_command(self):
 
468
        """See gpg_signing_command()."""
 
469
        return None
 
470
 
 
471
    def log_format(self):
 
472
        """What log format should be used"""
 
473
        result = self._log_format()
 
474
        if result is None:
 
475
            result = "long"
 
476
        return result
 
477
 
 
478
    def _log_format(self):
 
479
        """See log_format()."""
 
480
        return None
 
481
 
 
482
    def validate_signatures_in_log(self):
 
483
        """Show GPG signature validity in log"""
 
484
        result = self._validate_signatures_in_log()
 
485
        if result == "true":
 
486
            result = True
 
487
        else:
 
488
            result = False
 
489
        return result
 
490
 
 
491
    def _validate_signatures_in_log(self):
 
492
        """See validate_signatures_in_log()."""
 
493
        return None
 
494
 
 
495
    def acceptable_keys(self):
 
496
        """Comma separated list of key patterns acceptable to 
 
497
        verify-signatures command"""
 
498
        result = self._acceptable_keys()
 
499
        return result
 
500
 
 
501
    def _acceptable_keys(self):
 
502
        """See acceptable_keys()."""
 
503
        return None
 
504
 
 
505
    def post_commit(self):
 
506
        """An ordered list of python functions to call.
 
507
 
 
508
        Each function takes branch, rev_id as parameters.
 
509
        """
 
510
        return self._post_commit()
 
511
 
 
512
    def _post_commit(self):
 
513
        """See Config.post_commit."""
 
514
        return None
 
515
 
 
516
    def user_email(self):
 
517
        """Return just the email component of a username."""
 
518
        return extract_email_address(self.username())
 
519
 
 
520
    def username(self):
 
521
        """Return email-style username.
 
522
 
 
523
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
524
 
 
525
        $BZR_EMAIL can be set to override this, then
 
526
        the concrete policy type is checked, and finally
 
527
        $EMAIL is examined.
 
528
        If no username can be found, errors.NoWhoami exception is raised.
 
529
        """
 
530
        v = os.environ.get('BZR_EMAIL')
 
531
        if v:
 
532
            return v.decode(osutils.get_user_encoding())
 
533
        v = self._get_user_id()
 
534
        if v:
 
535
            return v
 
536
        v = os.environ.get('EMAIL')
 
537
        if v:
 
538
            return v.decode(osutils.get_user_encoding())
 
539
        name, email = _auto_user_id()
 
540
        if name and email:
 
541
            return '%s <%s>' % (name, email)
 
542
        elif email:
 
543
            return email
 
544
        raise errors.NoWhoami()
 
545
 
 
546
    def ensure_username(self):
 
547
        """Raise errors.NoWhoami if username is not set.
 
548
 
 
549
        This method relies on the username() function raising the error.
 
550
        """
 
551
        self.username()
 
552
 
 
553
    def signature_checking(self):
 
554
        """What is the current policy for signature checking?."""
 
555
        policy = self._get_signature_checking()
 
556
        if policy is not None:
 
557
            return policy
 
558
        return CHECK_IF_POSSIBLE
 
559
 
 
560
    def signing_policy(self):
 
561
        """What is the current policy for signature checking?."""
 
562
        policy = self._get_signing_policy()
 
563
        if policy is not None:
 
564
            return policy
 
565
        return SIGN_WHEN_REQUIRED
 
566
 
 
567
    def signature_needed(self):
 
568
        """Is a signature needed when committing ?."""
 
569
        policy = self._get_signing_policy()
 
570
        if policy is None:
 
571
            policy = self._get_signature_checking()
 
572
            if policy is not None:
 
573
                #this warning should go away once check_signatures is
 
574
                #implemented (if not before)
 
575
                trace.warning("Please use create_signatures,"
 
576
                              " not check_signatures to set signing policy.")
 
577
        elif policy == SIGN_ALWAYS:
 
578
            return True
 
579
        return False
 
580
 
 
581
    def gpg_signing_key(self):
 
582
        """GPG user-id to sign commits"""
 
583
        key = self.get_user_option('gpg_signing_key')
 
584
        if key == "default" or key == None:
 
585
            return self.user_email()
 
586
        else:
 
587
            return key
 
588
 
 
589
    def get_alias(self, value):
 
590
        return self._get_alias(value)
 
591
 
 
592
    def _get_alias(self, value):
 
593
        pass
 
594
 
 
595
    def get_nickname(self):
 
596
        return self._get_nickname()
 
597
 
 
598
    def _get_nickname(self):
 
599
        return None
 
600
 
 
601
    def get_bzr_remote_path(self):
 
602
        try:
 
603
            return os.environ['BZR_REMOTE_PATH']
 
604
        except KeyError:
 
605
            path = self.get_user_option("bzr_remote_path")
 
606
            if path is None:
 
607
                path = 'bzr'
 
608
            return path
 
609
 
 
610
    def suppress_warning(self, warning):
 
611
        """Should the warning be suppressed or emitted.
 
612
 
 
613
        :param warning: The name of the warning being tested.
 
614
 
 
615
        :returns: True if the warning should be suppressed, False otherwise.
 
616
        """
 
617
        warnings = self.get_user_option_as_list('suppress_warnings')
 
618
        if warnings is None or warning not in warnings:
 
619
            return False
 
620
        else:
 
621
            return True
 
622
 
 
623
    def get_merge_tools(self):
 
624
        tools = {}
 
625
        for (oname, value, section, conf_id, parser) in self._get_options():
 
626
            if oname.startswith('bzr.mergetool.'):
 
627
                tool_name = oname[len('bzr.mergetool.'):]
 
628
                tools[tool_name] = self.get_user_option(oname)
 
629
        trace.mutter('loaded merge tools: %r' % tools)
 
630
        return tools
 
631
 
 
632
    def find_merge_tool(self, name):
 
633
        # We fake a defaults mechanism here by checking if the given name can
 
634
        # be found in the known_merge_tools if it's not found in the config.
 
635
        # This should be done through the proposed config defaults mechanism
 
636
        # when it becomes available in the future.
 
637
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
 
638
                                             expand=False)
 
639
                        or mergetools.known_merge_tools.get(name, None))
 
640
        return command_line
 
641
 
 
642
 
 
643
class _ConfigHooks(hooks.Hooks):
 
644
    """A dict mapping hook names and a list of callables for configs.
 
645
    """
 
646
 
 
647
    def __init__(self):
 
648
        """Create the default hooks.
 
649
 
 
650
        These are all empty initially, because by default nothing should get
 
651
        notified.
 
652
        """
 
653
        super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
 
654
        self.add_hook('load',
 
655
                      'Invoked when a config store is loaded.'
 
656
                      ' The signature is (store).',
 
657
                      (2, 4))
 
658
        self.add_hook('save',
 
659
                      'Invoked when a config store is saved.'
 
660
                      ' The signature is (store).',
 
661
                      (2, 4))
 
662
        # The hooks for config options
 
663
        self.add_hook('get',
 
664
                      'Invoked when a config option is read.'
 
665
                      ' The signature is (stack, name, value).',
 
666
                      (2, 4))
 
667
        self.add_hook('set',
 
668
                      'Invoked when a config option is set.'
 
669
                      ' The signature is (stack, name, value).',
 
670
                      (2, 4))
 
671
        self.add_hook('remove',
 
672
                      'Invoked when a config option is removed.'
 
673
                      ' The signature is (stack, name).',
 
674
                      (2, 4))
 
675
ConfigHooks = _ConfigHooks()
 
676
 
 
677
 
 
678
class _OldConfigHooks(hooks.Hooks):
 
679
    """A dict mapping hook names and a list of callables for configs.
 
680
    """
 
681
 
 
682
    def __init__(self):
 
683
        """Create the default hooks.
 
684
 
 
685
        These are all empty initially, because by default nothing should get
 
686
        notified.
 
687
        """
 
688
        super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
 
689
        self.add_hook('load',
 
690
                      'Invoked when a config store is loaded.'
 
691
                      ' The signature is (config).',
 
692
                      (2, 4))
 
693
        self.add_hook('save',
 
694
                      'Invoked when a config store is saved.'
 
695
                      ' The signature is (config).',
 
696
                      (2, 4))
 
697
        # The hooks for config options
 
698
        self.add_hook('get',
 
699
                      'Invoked when a config option is read.'
 
700
                      ' The signature is (config, name, value).',
 
701
                      (2, 4))
 
702
        self.add_hook('set',
 
703
                      'Invoked when a config option is set.'
 
704
                      ' The signature is (config, name, value).',
 
705
                      (2, 4))
 
706
        self.add_hook('remove',
 
707
                      'Invoked when a config option is removed.'
 
708
                      ' The signature is (config, name).',
 
709
                      (2, 4))
 
710
OldConfigHooks = _OldConfigHooks()
 
711
 
 
712
 
 
713
class IniBasedConfig(Config):
 
714
    """A configuration policy that draws from ini files."""
 
715
 
 
716
    def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
 
717
                 file_name=None):
 
718
        """Base class for configuration files using an ini-like syntax.
 
719
 
 
720
        :param file_name: The configuration file path.
 
721
        """
 
722
        super(IniBasedConfig, self).__init__()
 
723
        self.file_name = file_name
 
724
        if symbol_versioning.deprecated_passed(get_filename):
 
725
            symbol_versioning.warn(
 
726
                'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
727
                ' Use file_name instead.',
 
728
                DeprecationWarning,
 
729
                stacklevel=2)
 
730
            if get_filename is not None:
 
731
                self.file_name = get_filename()
 
732
        else:
 
733
            self.file_name = file_name
 
734
        self._content = None
 
735
        self._parser = None
 
736
 
 
737
    @classmethod
 
738
    def from_string(cls, str_or_unicode, file_name=None, save=False):
 
739
        """Create a config object from a string.
 
740
 
 
741
        :param str_or_unicode: A string representing the file content. This will
 
742
            be utf-8 encoded.
 
743
 
 
744
        :param file_name: The configuration file path.
 
745
 
 
746
        :param _save: Whether the file should be saved upon creation.
 
747
        """
 
748
        conf = cls(file_name=file_name)
 
749
        conf._create_from_string(str_or_unicode, save)
 
750
        return conf
 
751
 
 
752
    def _create_from_string(self, str_or_unicode, save):
 
753
        self._content = StringIO(str_or_unicode.encode('utf-8'))
 
754
        # Some tests use in-memory configs, some other always need the config
 
755
        # file to exist on disk.
 
756
        if save:
 
757
            self._write_config_file()
 
758
 
 
759
    def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
 
760
        if self._parser is not None:
 
761
            return self._parser
 
762
        if symbol_versioning.deprecated_passed(file):
 
763
            symbol_versioning.warn(
 
764
                'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
765
                ' Use IniBasedConfig(_content=xxx) instead.',
 
766
                DeprecationWarning,
 
767
                stacklevel=2)
 
768
        if self._content is not None:
 
769
            co_input = self._content
 
770
        elif self.file_name is None:
 
771
            raise AssertionError('We have no content to create the config')
 
772
        else:
 
773
            co_input = self.file_name
 
774
        try:
 
775
            self._parser = ConfigObj(co_input, encoding='utf-8')
 
776
        except configobj.ConfigObjError, e:
 
777
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
778
        except UnicodeDecodeError:
 
779
            raise errors.ConfigContentError(self.file_name)
 
780
        # Make sure self.reload() will use the right file name
 
781
        self._parser.filename = self.file_name
 
782
        for hook in OldConfigHooks['load']:
 
783
            hook(self)
 
784
        return self._parser
 
785
 
 
786
    def reload(self):
 
787
        """Reload the config file from disk."""
 
788
        if self.file_name is None:
 
789
            raise AssertionError('We need a file name to reload the config')
 
790
        if self._parser is not None:
 
791
            self._parser.reload()
 
792
        for hook in ConfigHooks['load']:
 
793
            hook(self)
 
794
 
 
795
    def _get_matching_sections(self):
 
796
        """Return an ordered list of (section_name, extra_path) pairs.
 
797
 
 
798
        If the section contains inherited configuration, extra_path is
 
799
        a string containing the additional path components.
 
800
        """
 
801
        section = self._get_section()
 
802
        if section is not None:
 
803
            return [(section, '')]
 
804
        else:
 
805
            return []
 
806
 
 
807
    def _get_section(self):
 
808
        """Override this to define the section used by the config."""
 
809
        return "DEFAULT"
 
810
 
 
811
    def _get_sections(self, name=None):
 
812
        """Returns an iterator of the sections specified by ``name``.
 
813
 
 
814
        :param name: The section name. If None is supplied, the default
 
815
            configurations are yielded.
 
816
 
 
817
        :return: A tuple (name, section, config_id) for all sections that will
 
818
            be walked by user_get_option() in the 'right' order. The first one
 
819
            is where set_user_option() will update the value.
 
820
        """
 
821
        parser = self._get_parser()
 
822
        if name is not None:
 
823
            yield (name, parser[name], self.config_id())
 
824
        else:
 
825
            # No section name has been given so we fallback to the configobj
 
826
            # itself which holds the variables defined outside of any section.
 
827
            yield (None, parser, self.config_id())
 
828
 
 
829
    def _get_options(self, sections=None):
 
830
        """Return an ordered list of (name, value, section, config_id) tuples.
 
831
 
 
832
        All options are returned with their associated value and the section
 
833
        they appeared in. ``config_id`` is a unique identifier for the
 
834
        configuration file the option is defined in.
 
835
 
 
836
        :param sections: Default to ``_get_matching_sections`` if not
 
837
            specified. This gives a better control to daughter classes about
 
838
            which sections should be searched. This is a list of (name,
 
839
            configobj) tuples.
 
840
        """
 
841
        opts = []
 
842
        if sections is None:
 
843
            parser = self._get_parser()
 
844
            sections = []
 
845
            for (section_name, _) in self._get_matching_sections():
 
846
                try:
 
847
                    section = parser[section_name]
 
848
                except KeyError:
 
849
                    # This could happen for an empty file for which we define a
 
850
                    # DEFAULT section. FIXME: Force callers to provide sections
 
851
                    # instead ? -- vila 20100930
 
852
                    continue
 
853
                sections.append((section_name, section))
 
854
        config_id = self.config_id()
 
855
        for (section_name, section) in sections:
 
856
            for (name, value) in section.iteritems():
 
857
                yield (name, parser._quote(value), section_name,
 
858
                       config_id, parser)
 
859
 
 
860
    def _get_option_policy(self, section, option_name):
 
861
        """Return the policy for the given (section, option_name) pair."""
 
862
        return POLICY_NONE
 
863
 
 
864
    def _get_change_editor(self):
 
865
        return self.get_user_option('change_editor')
 
866
 
 
867
    def _get_signature_checking(self):
 
868
        """See Config._get_signature_checking."""
 
869
        policy = self._get_user_option('check_signatures')
 
870
        if policy:
 
871
            return self._string_to_signature_policy(policy)
 
872
 
 
873
    def _get_signing_policy(self):
 
874
        """See Config._get_signing_policy"""
 
875
        policy = self._get_user_option('create_signatures')
 
876
        if policy:
 
877
            return self._string_to_signing_policy(policy)
 
878
 
 
879
    def _get_user_id(self):
 
880
        """Get the user id from the 'email' key in the current section."""
 
881
        return self._get_user_option('email')
 
882
 
 
883
    def _get_user_option(self, option_name):
 
884
        """See Config._get_user_option."""
 
885
        for (section, extra_path) in self._get_matching_sections():
 
886
            try:
 
887
                value = self._get_parser().get_value(section, option_name)
 
888
            except KeyError:
 
889
                continue
 
890
            policy = self._get_option_policy(section, option_name)
 
891
            if policy == POLICY_NONE:
 
892
                return value
 
893
            elif policy == POLICY_NORECURSE:
 
894
                # norecurse items only apply to the exact path
 
895
                if extra_path:
 
896
                    continue
 
897
                else:
 
898
                    return value
 
899
            elif policy == POLICY_APPENDPATH:
 
900
                if extra_path:
 
901
                    value = urlutils.join(value, extra_path)
 
902
                return value
 
903
            else:
 
904
                raise AssertionError('Unexpected config policy %r' % policy)
 
905
        else:
 
906
            return None
 
907
 
 
908
    def _gpg_signing_command(self):
 
909
        """See Config.gpg_signing_command."""
 
910
        return self._get_user_option('gpg_signing_command')
 
911
 
 
912
    def _log_format(self):
 
913
        """See Config.log_format."""
 
914
        return self._get_user_option('log_format')
 
915
 
 
916
    def _validate_signatures_in_log(self):
 
917
        """See Config.validate_signatures_in_log."""
 
918
        return self._get_user_option('validate_signatures_in_log')
 
919
 
 
920
    def _acceptable_keys(self):
 
921
        """See Config.acceptable_keys."""
 
922
        return self._get_user_option('acceptable_keys')
 
923
 
 
924
    def _post_commit(self):
 
925
        """See Config.post_commit."""
 
926
        return self._get_user_option('post_commit')
 
927
 
 
928
    def _string_to_signature_policy(self, signature_string):
 
929
        """Convert a string to a signing policy."""
 
930
        if signature_string.lower() == 'check-available':
 
931
            return CHECK_IF_POSSIBLE
 
932
        if signature_string.lower() == 'ignore':
 
933
            return CHECK_NEVER
 
934
        if signature_string.lower() == 'require':
 
935
            return CHECK_ALWAYS
 
936
        raise errors.BzrError("Invalid signatures policy '%s'"
 
937
                              % signature_string)
 
938
 
 
939
    def _string_to_signing_policy(self, signature_string):
 
940
        """Convert a string to a signing policy."""
 
941
        if signature_string.lower() == 'when-required':
 
942
            return SIGN_WHEN_REQUIRED
 
943
        if signature_string.lower() == 'never':
 
944
            return SIGN_NEVER
 
945
        if signature_string.lower() == 'always':
 
946
            return SIGN_ALWAYS
 
947
        raise errors.BzrError("Invalid signing policy '%s'"
 
948
                              % signature_string)
 
949
 
 
950
    def _get_alias(self, value):
 
951
        try:
 
952
            return self._get_parser().get_value("ALIASES",
 
953
                                                value)
 
954
        except KeyError:
 
955
            pass
 
956
 
 
957
    def _get_nickname(self):
 
958
        return self.get_user_option('nickname')
 
959
 
 
960
    def remove_user_option(self, option_name, section_name=None):
 
961
        """Remove a user option and save the configuration file.
 
962
 
 
963
        :param option_name: The option to be removed.
 
964
 
 
965
        :param section_name: The section the option is defined in, default to
 
966
            the default section.
 
967
        """
 
968
        self.reload()
 
969
        parser = self._get_parser()
 
970
        if section_name is None:
 
971
            section = parser
 
972
        else:
 
973
            section = parser[section_name]
 
974
        try:
 
975
            del section[option_name]
 
976
        except KeyError:
 
977
            raise errors.NoSuchConfigOption(option_name)
 
978
        self._write_config_file()
 
979
        for hook in OldConfigHooks['remove']:
 
980
            hook(self, option_name)
 
981
 
 
982
    def _write_config_file(self):
 
983
        if self.file_name is None:
 
984
            raise AssertionError('We cannot save, self.file_name is None')
 
985
        conf_dir = os.path.dirname(self.file_name)
 
986
        ensure_config_dir_exists(conf_dir)
 
987
        atomic_file = atomicfile.AtomicFile(self.file_name)
 
988
        self._get_parser().write(atomic_file)
 
989
        atomic_file.commit()
 
990
        atomic_file.close()
 
991
        osutils.copy_ownership_from_path(self.file_name)
 
992
        for hook in OldConfigHooks['save']:
 
993
            hook(self)
 
994
 
 
995
 
 
996
class LockableConfig(IniBasedConfig):
 
997
    """A configuration needing explicit locking for access.
 
998
 
 
999
    If several processes try to write the config file, the accesses need to be
 
1000
    serialized.
 
1001
 
 
1002
    Daughter classes should decorate all methods that update a config with the
 
1003
    ``@needs_write_lock`` decorator (they call, directly or indirectly, the
 
1004
    ``_write_config_file()`` method. These methods (typically ``set_option()``
 
1005
    and variants must reload the config file from disk before calling
 
1006
    ``_write_config_file()``), this can be achieved by calling the
 
1007
    ``self.reload()`` method. Note that the lock scope should cover both the
 
1008
    reading and the writing of the config file which is why the decorator can't
 
1009
    be applied to ``_write_config_file()`` only.
 
1010
 
 
1011
    This should be enough to implement the following logic:
 
1012
    - lock for exclusive write access,
 
1013
    - reload the config file from disk,
 
1014
    - set the new value
 
1015
    - unlock
 
1016
 
 
1017
    This logic guarantees that a writer can update a value without erasing an
 
1018
    update made by another writer.
 
1019
    """
 
1020
 
 
1021
    lock_name = 'lock'
 
1022
 
 
1023
    def __init__(self, file_name):
 
1024
        super(LockableConfig, self).__init__(file_name=file_name)
 
1025
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
 
1026
        # FIXME: It doesn't matter that we don't provide possible_transports
 
1027
        # below since this is currently used only for local config files ;
 
1028
        # local transports are not shared. But if/when we start using
 
1029
        # LockableConfig for other kind of transports, we will need to reuse
 
1030
        # whatever connection is already established -- vila 20100929
 
1031
        self.transport = transport.get_transport_from_path(self.dir)
 
1032
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
 
1033
 
 
1034
    def _create_from_string(self, unicode_bytes, save):
 
1035
        super(LockableConfig, self)._create_from_string(unicode_bytes, False)
 
1036
        if save:
 
1037
            # We need to handle the saving here (as opposed to IniBasedConfig)
 
1038
            # to be able to lock
 
1039
            self.lock_write()
 
1040
            self._write_config_file()
 
1041
            self.unlock()
 
1042
 
 
1043
    def lock_write(self, token=None):
 
1044
        """Takes a write lock in the directory containing the config file.
 
1045
 
 
1046
        If the directory doesn't exist it is created.
 
1047
        """
 
1048
        ensure_config_dir_exists(self.dir)
 
1049
        return self._lock.lock_write(token)
 
1050
 
 
1051
    def unlock(self):
 
1052
        self._lock.unlock()
 
1053
 
 
1054
    def break_lock(self):
 
1055
        self._lock.break_lock()
 
1056
 
 
1057
    @needs_write_lock
 
1058
    def remove_user_option(self, option_name, section_name=None):
 
1059
        super(LockableConfig, self).remove_user_option(option_name,
 
1060
                                                       section_name)
 
1061
 
 
1062
    def _write_config_file(self):
 
1063
        if self._lock is None or not self._lock.is_held:
 
1064
            # NB: if the following exception is raised it probably means a
 
1065
            # missing @needs_write_lock decorator on one of the callers.
 
1066
            raise errors.ObjectNotLocked(self)
 
1067
        super(LockableConfig, self)._write_config_file()
 
1068
 
 
1069
 
 
1070
class GlobalConfig(LockableConfig):
 
1071
    """The configuration that should be used for a specific location."""
 
1072
 
 
1073
    def __init__(self):
 
1074
        super(GlobalConfig, self).__init__(file_name=config_filename())
 
1075
 
 
1076
    def config_id(self):
 
1077
        return 'bazaar'
 
1078
 
 
1079
    @classmethod
 
1080
    def from_string(cls, str_or_unicode, save=False):
 
1081
        """Create a config object from a string.
 
1082
 
 
1083
        :param str_or_unicode: A string representing the file content. This
 
1084
            will be utf-8 encoded.
 
1085
 
 
1086
        :param save: Whether the file should be saved upon creation.
 
1087
        """
 
1088
        conf = cls()
 
1089
        conf._create_from_string(str_or_unicode, save)
 
1090
        return conf
 
1091
 
 
1092
    @deprecated_method(deprecated_in((2, 4, 0)))
 
1093
    def get_editor(self):
 
1094
        return self._get_user_option('editor')
 
1095
 
 
1096
    @needs_write_lock
 
1097
    def set_user_option(self, option, value):
 
1098
        """Save option and its value in the configuration."""
 
1099
        self._set_option(option, value, 'DEFAULT')
 
1100
 
 
1101
    def get_aliases(self):
 
1102
        """Return the aliases section."""
 
1103
        if 'ALIASES' in self._get_parser():
 
1104
            return self._get_parser()['ALIASES']
 
1105
        else:
 
1106
            return {}
 
1107
 
 
1108
    @needs_write_lock
 
1109
    def set_alias(self, alias_name, alias_command):
 
1110
        """Save the alias in the configuration."""
 
1111
        self._set_option(alias_name, alias_command, 'ALIASES')
 
1112
 
 
1113
    @needs_write_lock
 
1114
    def unset_alias(self, alias_name):
 
1115
        """Unset an existing alias."""
 
1116
        self.reload()
 
1117
        aliases = self._get_parser().get('ALIASES')
 
1118
        if not aliases or alias_name not in aliases:
 
1119
            raise errors.NoSuchAlias(alias_name)
 
1120
        del aliases[alias_name]
 
1121
        self._write_config_file()
 
1122
 
 
1123
    def _set_option(self, option, value, section):
 
1124
        self.reload()
 
1125
        self._get_parser().setdefault(section, {})[option] = value
 
1126
        self._write_config_file()
 
1127
        for hook in OldConfigHooks['set']:
 
1128
            hook(self, option, value)
 
1129
 
 
1130
    def _get_sections(self, name=None):
 
1131
        """See IniBasedConfig._get_sections()."""
 
1132
        parser = self._get_parser()
 
1133
        # We don't give access to options defined outside of any section, we
 
1134
        # used the DEFAULT section by... default.
 
1135
        if name in (None, 'DEFAULT'):
 
1136
            # This could happen for an empty file where the DEFAULT section
 
1137
            # doesn't exist yet. So we force DEFAULT when yielding
 
1138
            name = 'DEFAULT'
 
1139
            if 'DEFAULT' not in parser:
 
1140
               parser['DEFAULT']= {}
 
1141
        yield (name, parser[name], self.config_id())
 
1142
 
 
1143
    @needs_write_lock
 
1144
    def remove_user_option(self, option_name, section_name=None):
 
1145
        if section_name is None:
 
1146
            # We need to force the default section.
 
1147
            section_name = 'DEFAULT'
 
1148
        # We need to avoid the LockableConfig implementation or we'll lock
 
1149
        # twice
 
1150
        super(LockableConfig, self).remove_user_option(option_name,
 
1151
                                                       section_name)
 
1152
 
 
1153
def _iter_for_location_by_parts(sections, location):
 
1154
    """Keep only the sessions matching the specified location.
 
1155
 
 
1156
    :param sections: An iterable of section names.
 
1157
 
 
1158
    :param location: An url or a local path to match against.
 
1159
 
 
1160
    :returns: An iterator of (section, extra_path, nb_parts) where nb is the
 
1161
        number of path components in the section name, section is the section
 
1162
        name and extra_path is the difference between location and the section
 
1163
        name.
 
1164
 
 
1165
    ``location`` will always be a local path and never a 'file://' url but the
 
1166
    section names themselves can be in either form.
 
1167
    """
 
1168
    location_parts = location.rstrip('/').split('/')
 
1169
 
 
1170
    for section in sections:
 
1171
        # location is a local path if possible, so we need to convert 'file://'
 
1172
        # urls in section names to local paths if necessary.
 
1173
 
 
1174
        # This also avoids having file:///path be a more exact
 
1175
        # match than '/path'.
 
1176
 
 
1177
        # FIXME: This still raises an issue if a user defines both file:///path
 
1178
        # *and* /path. Should we raise an error in this case -- vila 20110505
 
1179
 
 
1180
        if section.startswith('file://'):
 
1181
            section_path = urlutils.local_path_from_url(section)
 
1182
        else:
 
1183
            section_path = section
 
1184
        section_parts = section_path.rstrip('/').split('/')
 
1185
 
 
1186
        matched = True
 
1187
        if len(section_parts) > len(location_parts):
 
1188
            # More path components in the section, they can't match
 
1189
            matched = False
 
1190
        else:
 
1191
            # Rely on zip truncating in length to the length of the shortest
 
1192
            # argument sequence.
 
1193
            names = zip(location_parts, section_parts)
 
1194
            for name in names:
 
1195
                if not fnmatch.fnmatch(name[0], name[1]):
 
1196
                    matched = False
 
1197
                    break
 
1198
        if not matched:
 
1199
            continue
 
1200
        # build the path difference between the section and the location
 
1201
        extra_path = '/'.join(location_parts[len(section_parts):])
 
1202
        yield section, extra_path, len(section_parts)
 
1203
 
 
1204
 
 
1205
class LocationConfig(LockableConfig):
 
1206
    """A configuration object that gives the policy for a location."""
 
1207
 
 
1208
    def __init__(self, location):
 
1209
        super(LocationConfig, self).__init__(
 
1210
            file_name=locations_config_filename())
 
1211
        # local file locations are looked up by local path, rather than
 
1212
        # by file url. This is because the config file is a user
 
1213
        # file, and we would rather not expose the user to file urls.
 
1214
        if location.startswith('file://'):
 
1215
            location = urlutils.local_path_from_url(location)
 
1216
        self.location = location
 
1217
 
 
1218
    def config_id(self):
 
1219
        return 'locations'
 
1220
 
 
1221
    @classmethod
 
1222
    def from_string(cls, str_or_unicode, location, save=False):
 
1223
        """Create a config object from a string.
 
1224
 
 
1225
        :param str_or_unicode: A string representing the file content. This will
 
1226
            be utf-8 encoded.
 
1227
 
 
1228
        :param location: The location url to filter the configuration.
 
1229
 
 
1230
        :param save: Whether the file should be saved upon creation.
 
1231
        """
 
1232
        conf = cls(location)
 
1233
        conf._create_from_string(str_or_unicode, save)
 
1234
        return conf
 
1235
 
 
1236
    def _get_matching_sections(self):
 
1237
        """Return an ordered list of section names matching this location."""
 
1238
        matches = list(_iter_for_location_by_parts(self._get_parser(),
 
1239
                                                   self.location))
 
1240
        # put the longest (aka more specific) locations first
 
1241
        matches.sort(
 
1242
            key=lambda (section, extra_path, length): (length, section),
 
1243
            reverse=True)
 
1244
        for (section, extra_path, length) in matches:
 
1245
            yield section, extra_path
 
1246
            # should we stop looking for parent configs here?
 
1247
            try:
 
1248
                if self._get_parser()[section].as_bool('ignore_parents'):
 
1249
                    break
 
1250
            except KeyError:
 
1251
                pass
 
1252
 
 
1253
    def _get_sections(self, name=None):
 
1254
        """See IniBasedConfig._get_sections()."""
 
1255
        # We ignore the name here as the only sections handled are named with
 
1256
        # the location path and we don't expose embedded sections either.
 
1257
        parser = self._get_parser()
 
1258
        for name, extra_path in self._get_matching_sections():
 
1259
            yield (name, parser[name], self.config_id())
 
1260
 
 
1261
    def _get_option_policy(self, section, option_name):
 
1262
        """Return the policy for the given (section, option_name) pair."""
 
1263
        # check for the old 'recurse=False' flag
 
1264
        try:
 
1265
            recurse = self._get_parser()[section].as_bool('recurse')
 
1266
        except KeyError:
 
1267
            recurse = True
 
1268
        if not recurse:
 
1269
            return POLICY_NORECURSE
 
1270
 
 
1271
        policy_key = option_name + ':policy'
 
1272
        try:
 
1273
            policy_name = self._get_parser()[section][policy_key]
 
1274
        except KeyError:
 
1275
            policy_name = None
 
1276
 
 
1277
        return _policy_value[policy_name]
 
1278
 
 
1279
    def _set_option_policy(self, section, option_name, option_policy):
 
1280
        """Set the policy for the given option name in the given section."""
 
1281
        # The old recurse=False option affects all options in the
 
1282
        # section.  To handle multiple policies in the section, we
 
1283
        # need to convert it to a policy_norecurse key.
 
1284
        try:
 
1285
            recurse = self._get_parser()[section].as_bool('recurse')
 
1286
        except KeyError:
 
1287
            pass
 
1288
        else:
 
1289
            symbol_versioning.warn(
 
1290
                'The recurse option is deprecated as of 0.14.  '
 
1291
                'The section "%s" has been converted to use policies.'
 
1292
                % section,
 
1293
                DeprecationWarning)
 
1294
            del self._get_parser()[section]['recurse']
 
1295
            if not recurse:
 
1296
                for key in self._get_parser()[section].keys():
 
1297
                    if not key.endswith(':policy'):
 
1298
                        self._get_parser()[section][key +
 
1299
                                                    ':policy'] = 'norecurse'
 
1300
 
 
1301
        policy_key = option_name + ':policy'
 
1302
        policy_name = _policy_name[option_policy]
 
1303
        if policy_name is not None:
 
1304
            self._get_parser()[section][policy_key] = policy_name
 
1305
        else:
 
1306
            if policy_key in self._get_parser()[section]:
 
1307
                del self._get_parser()[section][policy_key]
 
1308
 
 
1309
    @needs_write_lock
 
1310
    def set_user_option(self, option, value, store=STORE_LOCATION):
 
1311
        """Save option and its value in the configuration."""
 
1312
        if store not in [STORE_LOCATION,
 
1313
                         STORE_LOCATION_NORECURSE,
 
1314
                         STORE_LOCATION_APPENDPATH]:
 
1315
            raise ValueError('bad storage policy %r for %r' %
 
1316
                (store, option))
 
1317
        self.reload()
 
1318
        location = self.location
 
1319
        if location.endswith('/'):
 
1320
            location = location[:-1]
 
1321
        parser = self._get_parser()
 
1322
        if not location in parser and not location + '/' in parser:
 
1323
            parser[location] = {}
 
1324
        elif location + '/' in parser:
 
1325
            location = location + '/'
 
1326
        parser[location][option]=value
 
1327
        # the allowed values of store match the config policies
 
1328
        self._set_option_policy(location, option, store)
 
1329
        self._write_config_file()
 
1330
        for hook in OldConfigHooks['set']:
 
1331
            hook(self, option, value)
 
1332
 
 
1333
 
 
1334
class BranchConfig(Config):
 
1335
    """A configuration object giving the policy for a branch."""
 
1336
 
 
1337
    def __init__(self, branch):
 
1338
        super(BranchConfig, self).__init__()
 
1339
        self._location_config = None
 
1340
        self._branch_data_config = None
 
1341
        self._global_config = None
 
1342
        self.branch = branch
 
1343
        self.option_sources = (self._get_location_config,
 
1344
                               self._get_branch_data_config,
 
1345
                               self._get_global_config)
 
1346
 
 
1347
    def config_id(self):
 
1348
        return 'branch'
 
1349
 
 
1350
    def _get_branch_data_config(self):
 
1351
        if self._branch_data_config is None:
 
1352
            self._branch_data_config = TreeConfig(self.branch)
 
1353
            self._branch_data_config.config_id = self.config_id
 
1354
        return self._branch_data_config
 
1355
 
 
1356
    def _get_location_config(self):
 
1357
        if self._location_config is None:
 
1358
            self._location_config = LocationConfig(self.branch.base)
 
1359
        return self._location_config
 
1360
 
 
1361
    def _get_global_config(self):
 
1362
        if self._global_config is None:
 
1363
            self._global_config = GlobalConfig()
 
1364
        return self._global_config
 
1365
 
 
1366
    def _get_best_value(self, option_name):
 
1367
        """This returns a user option from local, tree or global config.
 
1368
 
 
1369
        They are tried in that order.  Use get_safe_value if trusted values
 
1370
        are necessary.
 
1371
        """
 
1372
        for source in self.option_sources:
 
1373
            value = getattr(source(), option_name)()
 
1374
            if value is not None:
 
1375
                return value
 
1376
        return None
 
1377
 
 
1378
    def _get_safe_value(self, option_name):
 
1379
        """This variant of get_best_value never returns untrusted values.
 
1380
 
 
1381
        It does not return values from the branch data, because the branch may
 
1382
        not be controlled by the user.
 
1383
 
 
1384
        We may wish to allow locations.conf to control whether branches are
 
1385
        trusted in the future.
 
1386
        """
 
1387
        for source in (self._get_location_config, self._get_global_config):
 
1388
            value = getattr(source(), option_name)()
 
1389
            if value is not None:
 
1390
                return value
 
1391
        return None
 
1392
 
 
1393
    def _get_user_id(self):
 
1394
        """Return the full user id for the branch.
 
1395
 
 
1396
        e.g. "John Hacker <jhacker@example.com>"
 
1397
        This is looked up in the email controlfile for the branch.
 
1398
        """
 
1399
        try:
 
1400
            return (self.branch._transport.get_bytes("email")
 
1401
                    .decode(osutils.get_user_encoding())
 
1402
                    .rstrip("\r\n"))
 
1403
        except (errors.NoSuchFile, errors.PermissionDenied), e:
 
1404
            pass
 
1405
 
 
1406
        return self._get_best_value('_get_user_id')
 
1407
 
 
1408
    def _get_change_editor(self):
 
1409
        return self._get_best_value('_get_change_editor')
 
1410
 
 
1411
    def _get_signature_checking(self):
 
1412
        """See Config._get_signature_checking."""
 
1413
        return self._get_best_value('_get_signature_checking')
 
1414
 
 
1415
    def _get_signing_policy(self):
 
1416
        """See Config._get_signing_policy."""
 
1417
        return self._get_best_value('_get_signing_policy')
 
1418
 
 
1419
    def _get_user_option(self, option_name):
 
1420
        """See Config._get_user_option."""
 
1421
        for source in self.option_sources:
 
1422
            value = source()._get_user_option(option_name)
 
1423
            if value is not None:
 
1424
                return value
 
1425
        return None
 
1426
 
 
1427
    def _get_sections(self, name=None):
 
1428
        """See IniBasedConfig.get_sections()."""
 
1429
        for source in self.option_sources:
 
1430
            for section in source()._get_sections(name):
 
1431
                yield section
 
1432
 
 
1433
    def _get_options(self, sections=None):
 
1434
        opts = []
 
1435
        # First the locations options
 
1436
        for option in self._get_location_config()._get_options():
 
1437
            yield option
 
1438
        # Then the branch options
 
1439
        branch_config = self._get_branch_data_config()
 
1440
        if sections is None:
 
1441
            sections = [('DEFAULT', branch_config._get_parser())]
 
1442
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
 
1443
        # Config itself has no notion of sections :( -- vila 20101001
 
1444
        config_id = self.config_id()
 
1445
        for (section_name, section) in sections:
 
1446
            for (name, value) in section.iteritems():
 
1447
                yield (name, value, section_name,
 
1448
                       config_id, branch_config._get_parser())
 
1449
        # Then the global options
 
1450
        for option in self._get_global_config()._get_options():
 
1451
            yield option
 
1452
 
 
1453
    def set_user_option(self, name, value, store=STORE_BRANCH,
 
1454
        warn_masked=False):
 
1455
        if store == STORE_BRANCH:
 
1456
            self._get_branch_data_config().set_option(value, name)
 
1457
        elif store == STORE_GLOBAL:
 
1458
            self._get_global_config().set_user_option(name, value)
 
1459
        else:
 
1460
            self._get_location_config().set_user_option(name, value, store)
 
1461
        if not warn_masked:
 
1462
            return
 
1463
        if store in (STORE_GLOBAL, STORE_BRANCH):
 
1464
            mask_value = self._get_location_config().get_user_option(name)
 
1465
            if mask_value is not None:
 
1466
                trace.warning('Value "%s" is masked by "%s" from'
 
1467
                              ' locations.conf', value, mask_value)
 
1468
            else:
 
1469
                if store == STORE_GLOBAL:
 
1470
                    branch_config = self._get_branch_data_config()
 
1471
                    mask_value = branch_config.get_user_option(name)
 
1472
                    if mask_value is not None:
 
1473
                        trace.warning('Value "%s" is masked by "%s" from'
 
1474
                                      ' branch.conf', value, mask_value)
 
1475
 
 
1476
    def remove_user_option(self, option_name, section_name=None):
 
1477
        self._get_branch_data_config().remove_option(option_name, section_name)
 
1478
 
 
1479
    def _gpg_signing_command(self):
 
1480
        """See Config.gpg_signing_command."""
 
1481
        return self._get_safe_value('_gpg_signing_command')
 
1482
 
 
1483
    def _post_commit(self):
 
1484
        """See Config.post_commit."""
 
1485
        return self._get_safe_value('_post_commit')
 
1486
 
 
1487
    def _get_nickname(self):
 
1488
        value = self._get_explicit_nickname()
 
1489
        if value is not None:
 
1490
            return value
 
1491
        return urlutils.unescape(self.branch.base.split('/')[-2])
 
1492
 
 
1493
    def has_explicit_nickname(self):
 
1494
        """Return true if a nickname has been explicitly assigned."""
 
1495
        return self._get_explicit_nickname() is not None
 
1496
 
 
1497
    def _get_explicit_nickname(self):
 
1498
        return self._get_best_value('_get_nickname')
 
1499
 
 
1500
    def _log_format(self):
 
1501
        """See Config.log_format."""
 
1502
        return self._get_best_value('_log_format')
 
1503
 
 
1504
    def _validate_signatures_in_log(self):
 
1505
        """See Config.validate_signatures_in_log."""
 
1506
        return self._get_best_value('_validate_signatures_in_log')
 
1507
 
 
1508
    def _acceptable_keys(self):
 
1509
        """See Config.acceptable_keys."""
 
1510
        return self._get_best_value('_acceptable_keys')
 
1511
 
 
1512
 
 
1513
def ensure_config_dir_exists(path=None):
 
1514
    """Make sure a configuration directory exists.
 
1515
    This makes sure that the directory exists.
 
1516
    On windows, since configuration directories are 2 levels deep,
 
1517
    it makes sure both the directory and the parent directory exists.
 
1518
    """
 
1519
    if path is None:
 
1520
        path = config_dir()
 
1521
    if not os.path.isdir(path):
 
1522
        if sys.platform == 'win32':
 
1523
            parent_dir = os.path.dirname(path)
 
1524
            if not os.path.isdir(parent_dir):
 
1525
                trace.mutter('creating config parent directory: %r', parent_dir)
 
1526
                os.mkdir(parent_dir)
 
1527
        trace.mutter('creating config directory: %r', path)
 
1528
        os.mkdir(path)
 
1529
        osutils.copy_ownership_from_path(path)
 
1530
 
 
1531
 
 
1532
def config_dir():
 
1533
    """Return per-user configuration directory.
 
1534
 
 
1535
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
 
1536
    and Linux.  On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
 
1537
    that will be used instead.
 
1538
 
 
1539
    TODO: Global option --config-dir to override this.
 
1540
    """
 
1541
    base = os.environ.get('BZR_HOME', None)
 
1542
    if sys.platform == 'win32':
 
1543
        # environ variables on Windows are in user encoding/mbcs. So decode
 
1544
        # before using one
 
1545
        if base is not None:
 
1546
            base = base.decode('mbcs')
 
1547
        if base is None:
 
1548
            base = win32utils.get_appdata_location_unicode()
 
1549
        if base is None:
 
1550
            base = os.environ.get('HOME', None)
 
1551
            if base is not None:
 
1552
                base = base.decode('mbcs')
 
1553
        if base is None:
 
1554
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
 
1555
                                  ' or HOME set')
 
1556
        return osutils.pathjoin(base, 'bazaar', '2.0')
 
1557
    else:
 
1558
        if base is not None:
 
1559
            base = base.decode(osutils._fs_enc)
 
1560
    if sys.platform == 'darwin':
 
1561
        if base is None:
 
1562
            # this takes into account $HOME
 
1563
            base = os.path.expanduser("~")
 
1564
        return osutils.pathjoin(base, '.bazaar')
 
1565
    else:
 
1566
        if base is None:
 
1567
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
 
1568
            if xdg_dir is None:
 
1569
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
 
1570
            xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
 
1571
            if osutils.isdir(xdg_dir):
 
1572
                trace.mutter(
 
1573
                    "Using configuration in XDG directory %s." % xdg_dir)
 
1574
                return xdg_dir
 
1575
            base = os.path.expanduser("~")
 
1576
        return osutils.pathjoin(base, ".bazaar")
 
1577
 
 
1578
 
 
1579
def config_filename():
 
1580
    """Return per-user configuration ini file filename."""
 
1581
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
 
1582
 
 
1583
 
 
1584
def locations_config_filename():
 
1585
    """Return per-user configuration ini file filename."""
 
1586
    return osutils.pathjoin(config_dir(), 'locations.conf')
 
1587
 
 
1588
 
 
1589
def authentication_config_filename():
 
1590
    """Return per-user authentication ini file filename."""
 
1591
    return osutils.pathjoin(config_dir(), 'authentication.conf')
 
1592
 
 
1593
 
 
1594
def user_ignore_config_filename():
 
1595
    """Return the user default ignore filename"""
 
1596
    return osutils.pathjoin(config_dir(), 'ignore')
 
1597
 
 
1598
 
 
1599
def crash_dir():
 
1600
    """Return the directory name to store crash files.
 
1601
 
 
1602
    This doesn't implicitly create it.
 
1603
 
 
1604
    On Windows it's in the config directory; elsewhere it's /var/crash
 
1605
    which may be monitored by apport.  It can be overridden by
 
1606
    $APPORT_CRASH_DIR.
 
1607
    """
 
1608
    if sys.platform == 'win32':
 
1609
        return osutils.pathjoin(config_dir(), 'Crash')
 
1610
    else:
 
1611
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
 
1612
        # 2010-01-31
 
1613
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
 
1614
 
 
1615
 
 
1616
def xdg_cache_dir():
 
1617
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
 
1618
    # Possibly this should be different on Windows?
 
1619
    e = os.environ.get('XDG_CACHE_DIR', None)
 
1620
    if e:
 
1621
        return e
 
1622
    else:
 
1623
        return os.path.expanduser('~/.cache')
 
1624
 
 
1625
 
 
1626
def _get_default_mail_domain():
 
1627
    """If possible, return the assumed default email domain.
 
1628
 
 
1629
    :returns: string mail domain, or None.
 
1630
    """
 
1631
    if sys.platform == 'win32':
 
1632
        # No implementation yet; patches welcome
 
1633
        return None
 
1634
    try:
 
1635
        f = open('/etc/mailname')
 
1636
    except (IOError, OSError), e:
 
1637
        return None
 
1638
    try:
 
1639
        domain = f.read().strip()
 
1640
        return domain
 
1641
    finally:
 
1642
        f.close()
 
1643
 
 
1644
 
 
1645
def _auto_user_id():
 
1646
    """Calculate automatic user identification.
 
1647
 
 
1648
    :returns: (realname, email), either of which may be None if they can't be
 
1649
    determined.
 
1650
 
 
1651
    Only used when none is set in the environment or the id file.
 
1652
 
 
1653
    This only returns an email address if we can be fairly sure the 
 
1654
    address is reasonable, ie if /etc/mailname is set on unix.
 
1655
 
 
1656
    This doesn't use the FQDN as the default domain because that may be 
 
1657
    slow, and it doesn't use the hostname alone because that's not normally 
 
1658
    a reasonable address.
 
1659
    """
 
1660
    if sys.platform == 'win32':
 
1661
        # No implementation to reliably determine Windows default mail
 
1662
        # address; please add one.
 
1663
        return None, None
 
1664
 
 
1665
    default_mail_domain = _get_default_mail_domain()
 
1666
    if not default_mail_domain:
 
1667
        return None, None
 
1668
 
 
1669
    import pwd
 
1670
    uid = os.getuid()
 
1671
    try:
 
1672
        w = pwd.getpwuid(uid)
 
1673
    except KeyError:
 
1674
        trace.mutter('no passwd entry for uid %d?' % uid)
 
1675
        return None, None
 
1676
 
 
1677
    # we try utf-8 first, because on many variants (like Linux),
 
1678
    # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
1679
    # false positives.  (many users will have their user encoding set to
 
1680
    # latin-1, which cannot raise UnicodeError.)
 
1681
    try:
 
1682
        gecos = w.pw_gecos.decode('utf-8')
 
1683
        encoding = 'utf-8'
 
1684
    except UnicodeError:
 
1685
        try:
 
1686
            encoding = osutils.get_user_encoding()
 
1687
            gecos = w.pw_gecos.decode(encoding)
 
1688
        except UnicodeError, e:
 
1689
            trace.mutter("cannot decode passwd entry %s" % w)
 
1690
            return None, None
 
1691
    try:
 
1692
        username = w.pw_name.decode(encoding)
 
1693
    except UnicodeError, e:
 
1694
        trace.mutter("cannot decode passwd entry %s" % w)
 
1695
        return None, None
 
1696
 
 
1697
    comma = gecos.find(',')
 
1698
    if comma == -1:
 
1699
        realname = gecos
 
1700
    else:
 
1701
        realname = gecos[:comma]
 
1702
 
 
1703
    return realname, (username + '@' + default_mail_domain)
 
1704
 
 
1705
 
 
1706
def parse_username(username):
 
1707
    """Parse e-mail username and return a (name, address) tuple."""
 
1708
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
 
1709
    if match is None:
 
1710
        return (username, '')
 
1711
    else:
 
1712
        return (match.group(1), match.group(2))
 
1713
 
 
1714
 
 
1715
def extract_email_address(e):
 
1716
    """Return just the address part of an email string.
 
1717
 
 
1718
    That is just the user@domain part, nothing else.
 
1719
    This part is required to contain only ascii characters.
 
1720
    If it can't be extracted, raises an error.
 
1721
 
 
1722
    >>> extract_email_address('Jane Tester <jane@test.com>')
 
1723
    "jane@test.com"
 
1724
    """
 
1725
    name, email = parse_username(e)
 
1726
    if not email:
 
1727
        raise errors.NoEmailInUsername(e)
 
1728
    return email
 
1729
 
 
1730
 
 
1731
class TreeConfig(IniBasedConfig):
 
1732
    """Branch configuration data associated with its contents, not location"""
 
1733
 
 
1734
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
 
1735
 
 
1736
    def __init__(self, branch):
 
1737
        self._config = branch._get_config()
 
1738
        self.branch = branch
 
1739
 
 
1740
    def _get_parser(self, file=None):
 
1741
        if file is not None:
 
1742
            return IniBasedConfig._get_parser(file)
 
1743
        return self._config._get_configobj()
 
1744
 
 
1745
    def get_option(self, name, section=None, default=None):
 
1746
        self.branch.lock_read()
 
1747
        try:
 
1748
            return self._config.get_option(name, section, default)
 
1749
        finally:
 
1750
            self.branch.unlock()
 
1751
 
 
1752
    def set_option(self, value, name, section=None):
 
1753
        """Set a per-branch configuration option"""
 
1754
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1755
        # higher levels providing the right lock -- vila 20101004
 
1756
        self.branch.lock_write()
 
1757
        try:
 
1758
            self._config.set_option(value, name, section)
 
1759
        finally:
 
1760
            self.branch.unlock()
 
1761
 
 
1762
    def remove_option(self, option_name, section_name=None):
 
1763
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1764
        # higher levels providing the right lock -- vila 20101004
 
1765
        self.branch.lock_write()
 
1766
        try:
 
1767
            self._config.remove_option(option_name, section_name)
 
1768
        finally:
 
1769
            self.branch.unlock()
 
1770
 
 
1771
 
 
1772
class AuthenticationConfig(object):
 
1773
    """The authentication configuration file based on a ini file.
 
1774
 
 
1775
    Implements the authentication.conf file described in
 
1776
    doc/developers/authentication-ring.txt.
 
1777
    """
 
1778
 
 
1779
    def __init__(self, _file=None):
 
1780
        self._config = None # The ConfigObj
 
1781
        if _file is None:
 
1782
            self._filename = authentication_config_filename()
 
1783
            self._input = self._filename = authentication_config_filename()
 
1784
        else:
 
1785
            # Tests can provide a string as _file
 
1786
            self._filename = None
 
1787
            self._input = _file
 
1788
 
 
1789
    def _get_config(self):
 
1790
        if self._config is not None:
 
1791
            return self._config
 
1792
        try:
 
1793
            # FIXME: Should we validate something here ? Includes: empty
 
1794
            # sections are useless, at least one of
 
1795
            # user/password/password_encoding should be defined, etc.
 
1796
 
 
1797
            # Note: the encoding below declares that the file itself is utf-8
 
1798
            # encoded, but the values in the ConfigObj are always Unicode.
 
1799
            self._config = ConfigObj(self._input, encoding='utf-8')
 
1800
        except configobj.ConfigObjError, e:
 
1801
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
1802
        except UnicodeError:
 
1803
            raise errors.ConfigContentError(self._filename)
 
1804
        return self._config
 
1805
 
 
1806
    def _save(self):
 
1807
        """Save the config file, only tests should use it for now."""
 
1808
        conf_dir = os.path.dirname(self._filename)
 
1809
        ensure_config_dir_exists(conf_dir)
 
1810
        f = file(self._filename, 'wb')
 
1811
        try:
 
1812
            self._get_config().write(f)
 
1813
        finally:
 
1814
            f.close()
 
1815
 
 
1816
    def _set_option(self, section_name, option_name, value):
 
1817
        """Set an authentication configuration option"""
 
1818
        conf = self._get_config()
 
1819
        section = conf.get(section_name)
 
1820
        if section is None:
 
1821
            conf[section] = {}
 
1822
            section = conf[section]
 
1823
        section[option_name] = value
 
1824
        self._save()
 
1825
 
 
1826
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
 
1827
                        realm=None):
 
1828
        """Returns the matching credentials from authentication.conf file.
 
1829
 
 
1830
        :param scheme: protocol
 
1831
 
 
1832
        :param host: the server address
 
1833
 
 
1834
        :param port: the associated port (optional)
 
1835
 
 
1836
        :param user: login (optional)
 
1837
 
 
1838
        :param path: the absolute path on the server (optional)
 
1839
        
 
1840
        :param realm: the http authentication realm (optional)
 
1841
 
 
1842
        :return: A dict containing the matching credentials or None.
 
1843
           This includes:
 
1844
           - name: the section name of the credentials in the
 
1845
             authentication.conf file,
 
1846
           - user: can't be different from the provided user if any,
 
1847
           - scheme: the server protocol,
 
1848
           - host: the server address,
 
1849
           - port: the server port (can be None),
 
1850
           - path: the absolute server path (can be None),
 
1851
           - realm: the http specific authentication realm (can be None),
 
1852
           - password: the decoded password, could be None if the credential
 
1853
             defines only the user
 
1854
           - verify_certificates: https specific, True if the server
 
1855
             certificate should be verified, False otherwise.
 
1856
        """
 
1857
        credentials = None
 
1858
        for auth_def_name, auth_def in self._get_config().items():
 
1859
            if type(auth_def) is not configobj.Section:
 
1860
                raise ValueError("%s defined outside a section" % auth_def_name)
 
1861
 
 
1862
            a_scheme, a_host, a_user, a_path = map(
 
1863
                auth_def.get, ['scheme', 'host', 'user', 'path'])
 
1864
 
 
1865
            try:
 
1866
                a_port = auth_def.as_int('port')
 
1867
            except KeyError:
 
1868
                a_port = None
 
1869
            except ValueError:
 
1870
                raise ValueError("'port' not numeric in %s" % auth_def_name)
 
1871
            try:
 
1872
                a_verify_certificates = auth_def.as_bool('verify_certificates')
 
1873
            except KeyError:
 
1874
                a_verify_certificates = True
 
1875
            except ValueError:
 
1876
                raise ValueError(
 
1877
                    "'verify_certificates' not boolean in %s" % auth_def_name)
 
1878
 
 
1879
            # Attempt matching
 
1880
            if a_scheme is not None and scheme != a_scheme:
 
1881
                continue
 
1882
            if a_host is not None:
 
1883
                if not (host == a_host
 
1884
                        or (a_host.startswith('.') and host.endswith(a_host))):
 
1885
                    continue
 
1886
            if a_port is not None and port != a_port:
 
1887
                continue
 
1888
            if (a_path is not None and path is not None
 
1889
                and not path.startswith(a_path)):
 
1890
                continue
 
1891
            if (a_user is not None and user is not None
 
1892
                and a_user != user):
 
1893
                # Never contradict the caller about the user to be used
 
1894
                continue
 
1895
            if a_user is None:
 
1896
                # Can't find a user
 
1897
                continue
 
1898
            # Prepare a credentials dictionary with additional keys
 
1899
            # for the credential providers
 
1900
            credentials = dict(name=auth_def_name,
 
1901
                               user=a_user,
 
1902
                               scheme=a_scheme,
 
1903
                               host=host,
 
1904
                               port=port,
 
1905
                               path=path,
 
1906
                               realm=realm,
 
1907
                               password=auth_def.get('password', None),
 
1908
                               verify_certificates=a_verify_certificates)
 
1909
            # Decode the password in the credentials (or get one)
 
1910
            self.decode_password(credentials,
 
1911
                                 auth_def.get('password_encoding', None))
 
1912
            if 'auth' in debug.debug_flags:
 
1913
                trace.mutter("Using authentication section: %r", auth_def_name)
 
1914
            break
 
1915
 
 
1916
        if credentials is None:
 
1917
            # No credentials were found in authentication.conf, try the fallback
 
1918
            # credentials stores.
 
1919
            credentials = credential_store_registry.get_fallback_credentials(
 
1920
                scheme, host, port, user, path, realm)
 
1921
 
 
1922
        return credentials
 
1923
 
 
1924
    def set_credentials(self, name, host, user, scheme=None, password=None,
 
1925
                        port=None, path=None, verify_certificates=None,
 
1926
                        realm=None):
 
1927
        """Set authentication credentials for a host.
 
1928
 
 
1929
        Any existing credentials with matching scheme, host, port and path
 
1930
        will be deleted, regardless of name.
 
1931
 
 
1932
        :param name: An arbitrary name to describe this set of credentials.
 
1933
        :param host: Name of the host that accepts these credentials.
 
1934
        :param user: The username portion of these credentials.
 
1935
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
 
1936
            to.
 
1937
        :param password: Password portion of these credentials.
 
1938
        :param port: The IP port on the host that these credentials apply to.
 
1939
        :param path: A filesystem path on the host that these credentials
 
1940
            apply to.
 
1941
        :param verify_certificates: On https, verify server certificates if
 
1942
            True.
 
1943
        :param realm: The http authentication realm (optional).
 
1944
        """
 
1945
        values = {'host': host, 'user': user}
 
1946
        if password is not None:
 
1947
            values['password'] = password
 
1948
        if scheme is not None:
 
1949
            values['scheme'] = scheme
 
1950
        if port is not None:
 
1951
            values['port'] = '%d' % port
 
1952
        if path is not None:
 
1953
            values['path'] = path
 
1954
        if verify_certificates is not None:
 
1955
            values['verify_certificates'] = str(verify_certificates)
 
1956
        if realm is not None:
 
1957
            values['realm'] = realm
 
1958
        config = self._get_config()
 
1959
        for_deletion = []
 
1960
        for section, existing_values in config.items():
 
1961
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
 
1962
                if existing_values.get(key) != values.get(key):
 
1963
                    break
 
1964
            else:
 
1965
                del config[section]
 
1966
        config.update({name: values})
 
1967
        self._save()
 
1968
 
 
1969
    def get_user(self, scheme, host, port=None, realm=None, path=None,
 
1970
                 prompt=None, ask=False, default=None):
 
1971
        """Get a user from authentication file.
 
1972
 
 
1973
        :param scheme: protocol
 
1974
 
 
1975
        :param host: the server address
 
1976
 
 
1977
        :param port: the associated port (optional)
 
1978
 
 
1979
        :param realm: the realm sent by the server (optional)
 
1980
 
 
1981
        :param path: the absolute path on the server (optional)
 
1982
 
 
1983
        :param ask: Ask the user if there is no explicitly configured username 
 
1984
                    (optional)
 
1985
 
 
1986
        :param default: The username returned if none is defined (optional).
 
1987
 
 
1988
        :return: The found user.
 
1989
        """
 
1990
        credentials = self.get_credentials(scheme, host, port, user=None,
 
1991
                                           path=path, realm=realm)
 
1992
        if credentials is not None:
 
1993
            user = credentials['user']
 
1994
        else:
 
1995
            user = None
 
1996
        if user is None:
 
1997
            if ask:
 
1998
                if prompt is None:
 
1999
                    # Create a default prompt suitable for most cases
 
2000
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
 
2001
                # Special handling for optional fields in the prompt
 
2002
                if port is not None:
 
2003
                    prompt_host = '%s:%d' % (host, port)
 
2004
                else:
 
2005
                    prompt_host = host
 
2006
                user = ui.ui_factory.get_username(prompt, host=prompt_host)
 
2007
            else:
 
2008
                user = default
 
2009
        return user
 
2010
 
 
2011
    def get_password(self, scheme, host, user, port=None,
 
2012
                     realm=None, path=None, prompt=None):
 
2013
        """Get a password from authentication file or prompt the user for one.
 
2014
 
 
2015
        :param scheme: protocol
 
2016
 
 
2017
        :param host: the server address
 
2018
 
 
2019
        :param port: the associated port (optional)
 
2020
 
 
2021
        :param user: login
 
2022
 
 
2023
        :param realm: the realm sent by the server (optional)
 
2024
 
 
2025
        :param path: the absolute path on the server (optional)
 
2026
 
 
2027
        :return: The found password or the one entered by the user.
 
2028
        """
 
2029
        credentials = self.get_credentials(scheme, host, port, user, path,
 
2030
                                           realm)
 
2031
        if credentials is not None:
 
2032
            password = credentials['password']
 
2033
            if password is not None and scheme is 'ssh':
 
2034
                trace.warning('password ignored in section [%s],'
 
2035
                              ' use an ssh agent instead'
 
2036
                              % credentials['name'])
 
2037
                password = None
 
2038
        else:
 
2039
            password = None
 
2040
        # Prompt user only if we could't find a password
 
2041
        if password is None:
 
2042
            if prompt is None:
 
2043
                # Create a default prompt suitable for most cases
 
2044
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
 
2045
            # Special handling for optional fields in the prompt
 
2046
            if port is not None:
 
2047
                prompt_host = '%s:%d' % (host, port)
 
2048
            else:
 
2049
                prompt_host = host
 
2050
            password = ui.ui_factory.get_password(prompt,
 
2051
                                                  host=prompt_host, user=user)
 
2052
        return password
 
2053
 
 
2054
    def decode_password(self, credentials, encoding):
 
2055
        try:
 
2056
            cs = credential_store_registry.get_credential_store(encoding)
 
2057
        except KeyError:
 
2058
            raise ValueError('%r is not a known password_encoding' % encoding)
 
2059
        credentials['password'] = cs.decode_password(credentials)
 
2060
        return credentials
 
2061
 
 
2062
 
 
2063
class CredentialStoreRegistry(registry.Registry):
 
2064
    """A class that registers credential stores.
 
2065
 
 
2066
    A credential store provides access to credentials via the password_encoding
 
2067
    field in authentication.conf sections.
 
2068
 
 
2069
    Except for stores provided by bzr itself, most stores are expected to be
 
2070
    provided by plugins that will therefore use
 
2071
    register_lazy(password_encoding, module_name, member_name, help=help,
 
2072
    fallback=fallback) to install themselves.
 
2073
 
 
2074
    A fallback credential store is one that is queried if no credentials can be
 
2075
    found via authentication.conf.
 
2076
    """
 
2077
 
 
2078
    def get_credential_store(self, encoding=None):
 
2079
        cs = self.get(encoding)
 
2080
        if callable(cs):
 
2081
            cs = cs()
 
2082
        return cs
 
2083
 
 
2084
    def is_fallback(self, name):
 
2085
        """Check if the named credentials store should be used as fallback."""
 
2086
        return self.get_info(name)
 
2087
 
 
2088
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
 
2089
                                 path=None, realm=None):
 
2090
        """Request credentials from all fallback credentials stores.
 
2091
 
 
2092
        The first credentials store that can provide credentials wins.
 
2093
        """
 
2094
        credentials = None
 
2095
        for name in self.keys():
 
2096
            if not self.is_fallback(name):
 
2097
                continue
 
2098
            cs = self.get_credential_store(name)
 
2099
            credentials = cs.get_credentials(scheme, host, port, user,
 
2100
                                             path, realm)
 
2101
            if credentials is not None:
 
2102
                # We found some credentials
 
2103
                break
 
2104
        return credentials
 
2105
 
 
2106
    def register(self, key, obj, help=None, override_existing=False,
 
2107
                 fallback=False):
 
2108
        """Register a new object to a name.
 
2109
 
 
2110
        :param key: This is the key to use to request the object later.
 
2111
        :param obj: The object to register.
 
2112
        :param help: Help text for this entry. This may be a string or
 
2113
                a callable. If it is a callable, it should take two
 
2114
                parameters (registry, key): this registry and the key that
 
2115
                the help was registered under.
 
2116
        :param override_existing: Raise KeyErorr if False and something has
 
2117
                already been registered for that key. If True, ignore if there
 
2118
                is an existing key (always register the new value).
 
2119
        :param fallback: Whether this credential store should be 
 
2120
                used as fallback.
 
2121
        """
 
2122
        return super(CredentialStoreRegistry,
 
2123
                     self).register(key, obj, help, info=fallback,
 
2124
                                    override_existing=override_existing)
 
2125
 
 
2126
    def register_lazy(self, key, module_name, member_name,
 
2127
                      help=None, override_existing=False,
 
2128
                      fallback=False):
 
2129
        """Register a new credential store to be loaded on request.
 
2130
 
 
2131
        :param module_name: The python path to the module. Such as 'os.path'.
 
2132
        :param member_name: The member of the module to return.  If empty or
 
2133
                None, get() will return the module itself.
 
2134
        :param help: Help text for this entry. This may be a string or
 
2135
                a callable.
 
2136
        :param override_existing: If True, replace the existing object
 
2137
                with the new one. If False, if there is already something
 
2138
                registered with the same key, raise a KeyError
 
2139
        :param fallback: Whether this credential store should be 
 
2140
                used as fallback.
 
2141
        """
 
2142
        return super(CredentialStoreRegistry, self).register_lazy(
 
2143
            key, module_name, member_name, help,
 
2144
            info=fallback, override_existing=override_existing)
 
2145
 
 
2146
 
 
2147
credential_store_registry = CredentialStoreRegistry()
 
2148
 
 
2149
 
 
2150
class CredentialStore(object):
 
2151
    """An abstract class to implement storage for credentials"""
 
2152
 
 
2153
    def decode_password(self, credentials):
 
2154
        """Returns a clear text password for the provided credentials."""
 
2155
        raise NotImplementedError(self.decode_password)
 
2156
 
 
2157
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
 
2158
                        realm=None):
 
2159
        """Return the matching credentials from this credential store.
 
2160
 
 
2161
        This method is only called on fallback credential stores.
 
2162
        """
 
2163
        raise NotImplementedError(self.get_credentials)
 
2164
 
 
2165
 
 
2166
 
 
2167
class PlainTextCredentialStore(CredentialStore):
 
2168
    __doc__ = """Plain text credential store for the authentication.conf file"""
 
2169
 
 
2170
    def decode_password(self, credentials):
 
2171
        """See CredentialStore.decode_password."""
 
2172
        return credentials['password']
 
2173
 
 
2174
 
 
2175
credential_store_registry.register('plain', PlainTextCredentialStore,
 
2176
                                   help=PlainTextCredentialStore.__doc__)
 
2177
credential_store_registry.default_key = 'plain'
 
2178
 
 
2179
 
 
2180
class BzrDirConfig(object):
 
2181
 
 
2182
    def __init__(self, bzrdir):
 
2183
        self._bzrdir = bzrdir
 
2184
        self._config = bzrdir._get_config()
 
2185
 
 
2186
    def set_default_stack_on(self, value):
 
2187
        """Set the default stacking location.
 
2188
 
 
2189
        It may be set to a location, or None.
 
2190
 
 
2191
        This policy affects all branches contained by this bzrdir, except for
 
2192
        those under repositories.
 
2193
        """
 
2194
        if self._config is None:
 
2195
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
 
2196
        if value is None:
 
2197
            self._config.set_option('', 'default_stack_on')
 
2198
        else:
 
2199
            self._config.set_option(value, 'default_stack_on')
 
2200
 
 
2201
    def get_default_stack_on(self):
 
2202
        """Return the default stacking location.
 
2203
 
 
2204
        This will either be a location, or None.
 
2205
 
 
2206
        This policy affects all branches contained by this bzrdir, except for
 
2207
        those under repositories.
 
2208
        """
 
2209
        if self._config is None:
 
2210
            return None
 
2211
        value = self._config.get_option('default_stack_on')
 
2212
        if value == '':
 
2213
            value = None
 
2214
        return value
 
2215
 
 
2216
 
 
2217
class TransportConfig(object):
 
2218
    """A Config that reads/writes a config file on a Transport.
 
2219
 
 
2220
    It is a low-level object that considers config data to be name/value pairs
 
2221
    that may be associated with a section.  Assigning meaning to these values
 
2222
    is done at higher levels like TreeConfig.
 
2223
    """
 
2224
 
 
2225
    def __init__(self, transport, filename):
 
2226
        self._transport = transport
 
2227
        self._filename = filename
 
2228
 
 
2229
    def get_option(self, name, section=None, default=None):
 
2230
        """Return the value associated with a named option.
 
2231
 
 
2232
        :param name: The name of the value
 
2233
        :param section: The section the option is in (if any)
 
2234
        :param default: The value to return if the value is not set
 
2235
        :return: The value or default value
 
2236
        """
 
2237
        configobj = self._get_configobj()
 
2238
        if section is None:
 
2239
            section_obj = configobj
 
2240
        else:
 
2241
            try:
 
2242
                section_obj = configobj[section]
 
2243
            except KeyError:
 
2244
                return default
 
2245
        value = section_obj.get(name, default)
 
2246
        for hook in OldConfigHooks['get']:
 
2247
            hook(self, name, value)
 
2248
        return value
 
2249
 
 
2250
    def set_option(self, value, name, section=None):
 
2251
        """Set the value associated with a named option.
 
2252
 
 
2253
        :param value: The value to set
 
2254
        :param name: The name of the value to set
 
2255
        :param section: The section the option is in (if any)
 
2256
        """
 
2257
        configobj = self._get_configobj()
 
2258
        if section is None:
 
2259
            configobj[name] = value
 
2260
        else:
 
2261
            configobj.setdefault(section, {})[name] = value
 
2262
        for hook in OldConfigHooks['set']:
 
2263
            hook(self, name, value)
 
2264
        self._set_configobj(configobj)
 
2265
 
 
2266
    def remove_option(self, option_name, section_name=None):
 
2267
        configobj = self._get_configobj()
 
2268
        if section_name is None:
 
2269
            del configobj[option_name]
 
2270
        else:
 
2271
            del configobj[section_name][option_name]
 
2272
        for hook in OldConfigHooks['remove']:
 
2273
            hook(self, option_name)
 
2274
        self._set_configobj(configobj)
 
2275
 
 
2276
    def _get_config_file(self):
 
2277
        try:
 
2278
            f = StringIO(self._transport.get_bytes(self._filename))
 
2279
            for hook in OldConfigHooks['load']:
 
2280
                hook(self)
 
2281
            return f
 
2282
        except errors.NoSuchFile:
 
2283
            return StringIO()
 
2284
        except errors.PermissionDenied, e:
 
2285
            trace.warning("Permission denied while trying to open "
 
2286
                "configuration file %s.", urlutils.unescape_for_display(
 
2287
                urlutils.join(self._transport.base, self._filename), "utf-8"))
 
2288
            return StringIO()
 
2289
 
 
2290
    def _external_url(self):
 
2291
        return urlutils.join(self._transport.external_url(), self._filename)
 
2292
 
 
2293
    def _get_configobj(self):
 
2294
        f = self._get_config_file()
 
2295
        try:
 
2296
            try:
 
2297
                conf = ConfigObj(f, encoding='utf-8')
 
2298
            except configobj.ConfigObjError, e:
 
2299
                raise errors.ParseConfigError(e.errors, self._external_url())
 
2300
            except UnicodeDecodeError:
 
2301
                raise errors.ConfigContentError(self._external_url())
 
2302
        finally:
 
2303
            f.close()
 
2304
        return conf
 
2305
 
 
2306
    def _set_configobj(self, configobj):
 
2307
        out_file = StringIO()
 
2308
        configobj.write(out_file)
 
2309
        out_file.seek(0)
 
2310
        self._transport.put_file(self._filename, out_file)
 
2311
        for hook in OldConfigHooks['save']:
 
2312
            hook(self)
 
2313
 
 
2314
 
 
2315
class Option(object):
 
2316
    """An option definition.
 
2317
 
 
2318
    The option *values* are stored in config files and found in sections.
 
2319
 
 
2320
    Here we define various properties about the option itself, its default
 
2321
    value, how to convert it from stores, what to do when invalid values are
 
2322
    encoutered, in which config files it can be stored.
 
2323
    """
 
2324
 
 
2325
    def __init__(self, name, default=None, default_from_env=None,
 
2326
                 help=None,
 
2327
                 from_unicode=None, invalid=None):
 
2328
        """Build an option definition.
 
2329
 
 
2330
        :param name: the name used to refer to the option.
 
2331
 
 
2332
        :param default: the default value to use when none exist in the config
 
2333
            stores. This is either a string that ``from_unicode`` will convert
 
2334
            into the proper type or a python object that can be stringified (so
 
2335
            only the empty list is supported for example).
 
2336
 
 
2337
        :param default_from_env: A list of environment variables which can
 
2338
           provide a default value. 'default' will be used only if none of the
 
2339
           variables specified here are set in the environment.
 
2340
 
 
2341
        :param help: a doc string to explain the option to the user.
 
2342
 
 
2343
        :param from_unicode: a callable to convert the unicode string
 
2344
            representing the option value in a store. This is not called for
 
2345
            the default value.
 
2346
 
 
2347
        :param invalid: the action to be taken when an invalid value is
 
2348
            encountered in a store. This is called only when from_unicode is
 
2349
            invoked to convert a string and returns None or raise ValueError or
 
2350
            TypeError. Accepted values are: None (ignore invalid values),
 
2351
            'warning' (emit a warning), 'error' (emit an error message and
 
2352
            terminates).
 
2353
        """
 
2354
        if default_from_env is None:
 
2355
            default_from_env = []
 
2356
        self.name = name
 
2357
        # Convert the default value to a unicode string so all values are
 
2358
        # strings internally before conversion (via from_unicode) is attempted.
 
2359
        if default is None:
 
2360
            self.default = None
 
2361
        elif isinstance(default, list):
 
2362
            # Only the empty list is supported
 
2363
            if default:
 
2364
                raise AssertionError(
 
2365
                    'Only empty lists are supported as default values')
 
2366
            self.default = u','
 
2367
        elif isinstance(default, (str, unicode, bool, int, float)):
 
2368
            # Rely on python to convert strings, booleans and integers
 
2369
            self.default = u'%s' % (default,)
 
2370
        else:
 
2371
            # other python objects are not expected
 
2372
            raise AssertionError('%r is not supported as a default value'
 
2373
                                 % (default,))
 
2374
        self.default_from_env = default_from_env
 
2375
        self.help = help
 
2376
        self.from_unicode = from_unicode
 
2377
        if invalid and invalid not in ('warning', 'error'):
 
2378
            raise AssertionError("%s not supported for 'invalid'" % (invalid,))
 
2379
        self.invalid = invalid
 
2380
 
 
2381
    def convert_from_unicode(self, unicode_value):
 
2382
        if self.from_unicode is None or unicode_value is None:
 
2383
            # Don't convert or nothing to convert
 
2384
            return unicode_value
 
2385
        try:
 
2386
            converted = self.from_unicode(unicode_value)
 
2387
        except (ValueError, TypeError):
 
2388
            # Invalid values are ignored
 
2389
            converted = None
 
2390
        if converted is None and self.invalid is not None:
 
2391
            # The conversion failed
 
2392
            if self.invalid == 'warning':
 
2393
                trace.warning('Value "%s" is not valid for "%s"',
 
2394
                              unicode_value, self.name)
 
2395
            elif self.invalid == 'error':
 
2396
                raise errors.ConfigOptionValueError(self.name, unicode_value)
 
2397
        return converted
 
2398
 
 
2399
    def get_default(self):
 
2400
        value = None
 
2401
        for var in self.default_from_env:
 
2402
            try:
 
2403
                # If the env variable is defined, its value is the default one
 
2404
                value = os.environ[var]
 
2405
                break
 
2406
            except KeyError:
 
2407
                continue
 
2408
        if value is None:
 
2409
            # Otherwise, fallback to the value defined at registration
 
2410
            value = self.default
 
2411
        return value
 
2412
 
 
2413
    def get_help_text(self, additional_see_also=None, plain=True):
 
2414
        result = self.help
 
2415
        from bzrlib import help_topics
 
2416
        result += help_topics._format_see_also(additional_see_also)
 
2417
        if plain:
 
2418
            result = help_topics.help_as_plain_text(result)
 
2419
        return result
 
2420
 
 
2421
 
 
2422
# Predefined converters to get proper values from store
 
2423
 
 
2424
def bool_from_store(unicode_str):
 
2425
    return ui.bool_from_string(unicode_str)
 
2426
 
 
2427
 
 
2428
def int_from_store(unicode_str):
 
2429
    return int(unicode_str)
 
2430
 
 
2431
 
 
2432
def float_from_store(unicode_str):
 
2433
    return float(unicode_str)
 
2434
 
 
2435
 
 
2436
 
 
2437
# Use a an empty dict to initialize an empty configobj avoiding all
 
2438
# parsing and encoding checks
 
2439
_list_converter_config = configobj.ConfigObj(
 
2440
    {}, encoding='utf-8', list_values=True, interpolation=False)
 
2441
 
 
2442
 
 
2443
def list_from_store(unicode_str):
 
2444
    if not isinstance(unicode_str, basestring):
 
2445
        raise TypeError
 
2446
    # Now inject our string directly as unicode. All callers got their value
 
2447
    # from configobj, so values that need to be quoted are already properly
 
2448
    # quoted.
 
2449
    _list_converter_config.reset()
 
2450
    _list_converter_config._parse([u"list=%s" % (unicode_str,)])
 
2451
    maybe_list = _list_converter_config['list']
 
2452
    # ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
 
2453
    if isinstance(maybe_list, basestring):
 
2454
        if maybe_list:
 
2455
            # A single value, most probably the user forgot (or didn't care to
 
2456
            # add) the final ','
 
2457
            l = [maybe_list]
 
2458
        else:
 
2459
            # The empty string, convert to empty list
 
2460
            l = []
 
2461
    else:
 
2462
        # We rely on ConfigObj providing us with a list already
 
2463
        l = maybe_list
 
2464
    return l
 
2465
 
 
2466
 
 
2467
class OptionRegistry(registry.Registry):
 
2468
    """Register config options by their name.
 
2469
 
 
2470
    This overrides ``registry.Registry`` to simplify registration by acquiring
 
2471
    some information from the option object itself.
 
2472
    """
 
2473
 
 
2474
    def register(self, option):
 
2475
        """Register a new option to its name.
 
2476
 
 
2477
        :param option: The option to register. Its name is used as the key.
 
2478
        """
 
2479
        super(OptionRegistry, self).register(option.name, option,
 
2480
                                             help=option.help)
 
2481
 
 
2482
    def register_lazy(self, key, module_name, member_name):
 
2483
        """Register a new option to be loaded on request.
 
2484
 
 
2485
        :param key: the key to request the option later. Since the registration
 
2486
            is lazy, it should be provided and match the option name.
 
2487
 
 
2488
        :param module_name: the python path to the module. Such as 'os.path'.
 
2489
 
 
2490
        :param member_name: the member of the module to return.  If empty or 
 
2491
                None, get() will return the module itself.
 
2492
        """
 
2493
        super(OptionRegistry, self).register_lazy(key,
 
2494
                                                  module_name, member_name)
 
2495
 
 
2496
    def get_help(self, key=None):
 
2497
        """Get the help text associated with the given key"""
 
2498
        option = self.get(key)
 
2499
        the_help = option.help
 
2500
        if callable(the_help):
 
2501
            return the_help(self, key)
 
2502
        return the_help
 
2503
 
 
2504
 
 
2505
option_registry = OptionRegistry()
 
2506
 
 
2507
 
 
2508
# Registered options in lexicographical order
 
2509
 
 
2510
option_registry.register(
 
2511
    Option('bzr.workingtree.worth_saving_limit', default=10,
 
2512
           from_unicode=int_from_store,  invalid='warning',
 
2513
           help='''\
 
2514
How many changes before saving the dirstate.
 
2515
 
 
2516
-1 means that we will never rewrite the dirstate file for only
 
2517
stat-cache changes. Regardless of this setting, we will always rewrite
 
2518
the dirstate file if a file is added/removed/renamed/etc. This flag only
 
2519
affects the behavior of updating the dirstate file after we notice that
 
2520
a file has been touched.
 
2521
'''))
 
2522
option_registry.register(
 
2523
    Option('dirstate.fdatasync', default=True,
 
2524
           from_unicode=bool_from_store,
 
2525
           help='''\
 
2526
Flush dirstate changes onto physical disk?
 
2527
 
 
2528
If true (default), working tree metadata changes are flushed through the
 
2529
OS buffers to physical disk.  This is somewhat slower, but means data
 
2530
should not be lost if the machine crashes.  See also repository.fdatasync.
 
2531
'''))
 
2532
option_registry.register(
 
2533
    Option('debug_flags', default=[], from_unicode=list_from_store,
 
2534
           help='Debug flags to activate.'))
 
2535
option_registry.register(
 
2536
    Option('default_format', default='2a',
 
2537
           help='Format used when creating branches.'))
 
2538
option_registry.register(
 
2539
    Option('dpush_strict', default=None,
 
2540
           from_unicode=bool_from_store,
 
2541
           help='''\
 
2542
The default value for ``dpush --strict``.
 
2543
 
 
2544
If present, defines the ``--strict`` option default value for checking
 
2545
uncommitted changes before pushing into a different VCS without any
 
2546
custom bzr metadata.
 
2547
'''))
 
2548
option_registry.register(
 
2549
    Option('editor',
 
2550
           help='The command called to launch an editor to enter a message.'))
 
2551
option_registry.register(
 
2552
    Option('ignore_missing_extensions', default=False,
 
2553
           from_unicode=bool_from_store,
 
2554
           help='''\
 
2555
Control the missing extensions warning display.
 
2556
 
 
2557
The warning will not be emitted if set to True.
 
2558
'''))
 
2559
option_registry.register(
 
2560
    Option('language',
 
2561
           help='Language to translate messages into.'))
 
2562
option_registry.register(
 
2563
    Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
 
2564
           help='''\
 
2565
Steal locks that appears to be dead.
 
2566
 
 
2567
If set to True, bzr will check if a lock is supposed to be held by an
 
2568
active process from the same user on the same machine. If the user and
 
2569
machine match, but no process with the given PID is active, then bzr
 
2570
will automatically break the stale lock, and create a new lock for
 
2571
this process.
 
2572
Otherwise, bzr will prompt as normal to break the lock.
 
2573
'''))
 
2574
option_registry.register(
 
2575
    Option('log_format', default='long',
 
2576
           help= '''\
 
2577
Log format to use when displaying revisions.
 
2578
 
 
2579
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
 
2580
may be provided by plugins.
 
2581
'''))
 
2582
option_registry.register(
 
2583
    Option('output_encoding',
 
2584
           help= 'Unicode encoding for output'
 
2585
           ' (terminal encoding if not specified).'))
 
2586
option_registry.register(
 
2587
    Option('push_strict', default=None,
 
2588
           from_unicode=bool_from_store,
 
2589
           help='''\
 
2590
The default value for ``push --strict``.
 
2591
 
 
2592
If present, defines the ``--strict`` option default value for checking
 
2593
uncommitted changes before sending a merge directive.
 
2594
'''))
 
2595
option_registry.register(
 
2596
    Option('repository.fdatasync', default=True,
 
2597
           from_unicode=bool_from_store,
 
2598
           help='''\
 
2599
Flush repository changes onto physical disk?
 
2600
 
 
2601
If true (default), repository changes are flushed through the OS buffers
 
2602
to physical disk.  This is somewhat slower, but means data should not be
 
2603
lost if the machine crashes.  See also dirstate.fdatasync.
 
2604
'''))
 
2605
 
 
2606
option_registry.register(
 
2607
    Option('selftest.timeout',
 
2608
        default='600',
 
2609
        from_unicode=int_from_store,
 
2610
        help='Abort selftest if one test takes longer than this many seconds',
 
2611
        ))
 
2612
 
 
2613
option_registry.register(
 
2614
    Option('send_strict', default=None,
 
2615
           from_unicode=bool_from_store,
 
2616
           help='''\
 
2617
The default value for ``send --strict``.
 
2618
 
 
2619
If present, defines the ``--strict`` option default value for checking
 
2620
uncommitted changes before pushing.
 
2621
'''))
 
2622
 
 
2623
option_registry.register(
 
2624
    Option('serve.client_timeout',
 
2625
           default=300.0, from_unicode=float_from_store,
 
2626
           help="If we wait for a new request from a client for more than"
 
2627
                " X seconds, consider the client idle, and hangup."))
 
2628
 
 
2629
 
 
2630
class Section(object):
 
2631
    """A section defines a dict of option name => value.
 
2632
 
 
2633
    This is merely a read-only dict which can add some knowledge about the
 
2634
    options. It is *not* a python dict object though and doesn't try to mimic
 
2635
    its API.
 
2636
    """
 
2637
 
 
2638
    def __init__(self, section_id, options):
 
2639
        self.id = section_id
 
2640
        # We re-use the dict-like object received
 
2641
        self.options = options
 
2642
 
 
2643
    def get(self, name, default=None, expand=True):
 
2644
        return self.options.get(name, default)
 
2645
 
 
2646
    def iter_option_names(self):
 
2647
        for k in self.options.iterkeys():
 
2648
            yield k
 
2649
 
 
2650
    def __repr__(self):
 
2651
        # Mostly for debugging use
 
2652
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
 
2653
 
 
2654
 
 
2655
_NewlyCreatedOption = object()
 
2656
"""Was the option created during the MutableSection lifetime"""
 
2657
 
 
2658
 
 
2659
class MutableSection(Section):
 
2660
    """A section allowing changes and keeping track of the original values."""
 
2661
 
 
2662
    def __init__(self, section_id, options):
 
2663
        super(MutableSection, self).__init__(section_id, options)
 
2664
        self.orig = {}
 
2665
 
 
2666
    def set(self, name, value):
 
2667
        if name not in self.options:
 
2668
            # This is a new option
 
2669
            self.orig[name] = _NewlyCreatedOption
 
2670
        elif name not in self.orig:
 
2671
            self.orig[name] = self.get(name, None)
 
2672
        self.options[name] = value
 
2673
 
 
2674
    def remove(self, name):
 
2675
        if name not in self.orig:
 
2676
            self.orig[name] = self.get(name, None)
 
2677
        del self.options[name]
 
2678
 
 
2679
 
 
2680
class Store(object):
 
2681
    """Abstract interface to persistent storage for configuration options."""
 
2682
 
 
2683
    readonly_section_class = Section
 
2684
    mutable_section_class = MutableSection
 
2685
 
 
2686
    def is_loaded(self):
 
2687
        """Returns True if the Store has been loaded.
 
2688
 
 
2689
        This is used to implement lazy loading and ensure the persistent
 
2690
        storage is queried only when needed.
 
2691
        """
 
2692
        raise NotImplementedError(self.is_loaded)
 
2693
 
 
2694
    def load(self):
 
2695
        """Loads the Store from persistent storage."""
 
2696
        raise NotImplementedError(self.load)
 
2697
 
 
2698
    def _load_from_string(self, bytes):
 
2699
        """Create a store from a string in configobj syntax.
 
2700
 
 
2701
        :param bytes: A string representing the file content.
 
2702
        """
 
2703
        raise NotImplementedError(self._load_from_string)
 
2704
 
 
2705
    def unload(self):
 
2706
        """Unloads the Store.
 
2707
 
 
2708
        This should make is_loaded() return False. This is used when the caller
 
2709
        knows that the persistent storage has changed or may have change since
 
2710
        the last load.
 
2711
        """
 
2712
        raise NotImplementedError(self.unload)
 
2713
 
 
2714
    def save(self):
 
2715
        """Saves the Store to persistent storage."""
 
2716
        raise NotImplementedError(self.save)
 
2717
 
 
2718
    def external_url(self):
 
2719
        raise NotImplementedError(self.external_url)
 
2720
 
 
2721
    def get_sections(self):
 
2722
        """Returns an ordered iterable of existing sections.
 
2723
 
 
2724
        :returns: An iterable of (store, section).
 
2725
        """
 
2726
        raise NotImplementedError(self.get_sections)
 
2727
 
 
2728
    def get_mutable_section(self, section_id=None):
 
2729
        """Returns the specified mutable section.
 
2730
 
 
2731
        :param section_id: The section identifier
 
2732
        """
 
2733
        raise NotImplementedError(self.get_mutable_section)
 
2734
 
 
2735
    def __repr__(self):
 
2736
        # Mostly for debugging use
 
2737
        return "<config.%s(%s)>" % (self.__class__.__name__,
 
2738
                                    self.external_url())
 
2739
 
 
2740
 
 
2741
class CommandLineStore(Store):
 
2742
    "A store to carry command line overrides for the config options."""
 
2743
 
 
2744
    def __init__(self, opts=None):
 
2745
        super(CommandLineStore, self).__init__()
 
2746
        if opts is None:
 
2747
            opts = {}
 
2748
        self.options = {}
 
2749
 
 
2750
    def _reset(self):
 
2751
        # The dict should be cleared but not replaced so it can be shared.
 
2752
        self.options.clear()
 
2753
 
 
2754
    def _from_cmdline(self, overrides):
 
2755
        # Reset before accepting new definitions
 
2756
        self._reset()
 
2757
        for over in overrides:
 
2758
            try:
 
2759
                name, value = over.split('=', 1)
 
2760
            except ValueError:
 
2761
                raise errors.BzrCommandError(
 
2762
                    gettext("Invalid '%s', should be of the form 'name=value'")
 
2763
                    % (over,))
 
2764
            self.options[name] = value
 
2765
 
 
2766
    def external_url(self):
 
2767
        # Not an url but it makes debugging easier and is never needed
 
2768
        # otherwise
 
2769
        return 'cmdline'
 
2770
 
 
2771
    def get_sections(self):
 
2772
        yield self,  self.readonly_section_class('cmdline_overrides',
 
2773
                                                 self.options)
 
2774
 
 
2775
 
 
2776
class IniFileStore(Store):
 
2777
    """A config Store using ConfigObj for storage.
 
2778
 
 
2779
    :ivar transport: The transport object where the config file is located.
 
2780
 
 
2781
    :ivar file_name: The config file basename in the transport directory.
 
2782
 
 
2783
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
 
2784
        serialize/deserialize the config file.
 
2785
    """
 
2786
 
 
2787
    def __init__(self):
 
2788
        """A config Store using ConfigObj for storage.
 
2789
        """
 
2790
        super(IniFileStore, self).__init__()
 
2791
        self._config_obj = None
 
2792
 
 
2793
    def is_loaded(self):
 
2794
        return self._config_obj != None
 
2795
 
 
2796
    def unload(self):
 
2797
        self._config_obj = None
 
2798
 
 
2799
    def _load_content(self):
 
2800
        """Load the config file bytes.
 
2801
 
 
2802
        This should be provided by subclasses
 
2803
 
 
2804
        :return: Byte string
 
2805
        """
 
2806
        raise NotImplementedError(self._load_content)
 
2807
 
 
2808
    def _save_content(self, content):
 
2809
        """Save the config file bytes.
 
2810
 
 
2811
        This should be provided by subclasses
 
2812
 
 
2813
        :param content: Config file bytes to write
 
2814
        """
 
2815
        raise NotImplementedError(self._save_content)
 
2816
 
 
2817
    def load(self):
 
2818
        """Load the store from the associated file."""
 
2819
        if self.is_loaded():
 
2820
            return
 
2821
        content = self._load_content()
 
2822
        self._load_from_string(content)
 
2823
        for hook in ConfigHooks['load']:
 
2824
            hook(self)
 
2825
 
 
2826
    def _load_from_string(self, bytes):
 
2827
        """Create a config store from a string.
 
2828
 
 
2829
        :param bytes: A string representing the file content.
 
2830
        """
 
2831
        if self.is_loaded():
 
2832
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
 
2833
        co_input = StringIO(bytes)
 
2834
        try:
 
2835
            # The config files are always stored utf8-encoded
 
2836
            self._config_obj = ConfigObj(co_input, encoding='utf-8',
 
2837
                                         list_values=False)
 
2838
        except configobj.ConfigObjError, e:
 
2839
            self._config_obj = None
 
2840
            raise errors.ParseConfigError(e.errors, self.external_url())
 
2841
        except UnicodeDecodeError:
 
2842
            raise errors.ConfigContentError(self.external_url())
 
2843
 
 
2844
    def save(self):
 
2845
        if not self.is_loaded():
 
2846
            # Nothing to save
 
2847
            return
 
2848
        out = StringIO()
 
2849
        self._config_obj.write(out)
 
2850
        self._save_content(out.getvalue())
 
2851
        for hook in ConfigHooks['save']:
 
2852
            hook(self)
 
2853
 
 
2854
    def get_sections(self):
 
2855
        """Get the configobj section in the file order.
 
2856
 
 
2857
        :returns: An iterable of (store, section).
 
2858
        """
 
2859
        # We need a loaded store
 
2860
        try:
 
2861
            self.load()
 
2862
        except (errors.NoSuchFile, errors.PermissionDenied):
 
2863
            # If the file can't be read, there is no sections
 
2864
            return
 
2865
        cobj = self._config_obj
 
2866
        if cobj.scalars:
 
2867
            yield self, self.readonly_section_class(None, cobj)
 
2868
        for section_name in cobj.sections:
 
2869
            yield (self,
 
2870
                   self.readonly_section_class(section_name,
 
2871
                                               cobj[section_name]))
 
2872
 
 
2873
    def get_mutable_section(self, section_id=None):
 
2874
        # We need a loaded store
 
2875
        try:
 
2876
            self.load()
 
2877
        except errors.NoSuchFile:
 
2878
            # The file doesn't exist, let's pretend it was empty
 
2879
            self._load_from_string('')
 
2880
        if section_id is None:
 
2881
            section = self._config_obj
 
2882
        else:
 
2883
            section = self._config_obj.setdefault(section_id, {})
 
2884
        return self.mutable_section_class(section_id, section)
 
2885
 
 
2886
 
 
2887
class TransportIniFileStore(IniFileStore):
 
2888
    """IniFileStore that loads files from a transport.
 
2889
    """
 
2890
 
 
2891
    def __init__(self, transport, file_name):
 
2892
        """A Store using a ini file on a Transport
 
2893
 
 
2894
        :param transport: The transport object where the config file is located.
 
2895
        :param file_name: The config file basename in the transport directory.
 
2896
        """
 
2897
        super(TransportIniFileStore, self).__init__()
 
2898
        self.transport = transport
 
2899
        self.file_name = file_name
 
2900
 
 
2901
    def _load_content(self):
 
2902
        try:
 
2903
            return self.transport.get_bytes(self.file_name)
 
2904
        except errors.PermissionDenied:
 
2905
            trace.warning("Permission denied while trying to load "
 
2906
                          "configuration store %s.", self.external_url())
 
2907
            raise
 
2908
 
 
2909
    def _save_content(self, content):
 
2910
        self.transport.put_bytes(self.file_name, content)
 
2911
 
 
2912
    def external_url(self):
 
2913
        # FIXME: external_url should really accepts an optional relpath
 
2914
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
2915
        # The following will do in the interim but maybe we don't want to
 
2916
        # expose a path here but rather a config ID and its associated
 
2917
        # object </hand wawe>.
 
2918
        return urlutils.join(self.transport.external_url(), self.file_name)
 
2919
 
 
2920
 
 
2921
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
 
2922
# unlockable stores for use with objects that can already ensure the locking
 
2923
# (think branches). If different stores (not based on ConfigObj) are created,
 
2924
# they may face the same issue.
 
2925
 
 
2926
 
 
2927
class LockableIniFileStore(TransportIniFileStore):
 
2928
    """A ConfigObjStore using locks on save to ensure store integrity."""
 
2929
 
 
2930
    def __init__(self, transport, file_name, lock_dir_name=None):
 
2931
        """A config Store using ConfigObj for storage.
 
2932
 
 
2933
        :param transport: The transport object where the config file is located.
 
2934
 
 
2935
        :param file_name: The config file basename in the transport directory.
 
2936
        """
 
2937
        if lock_dir_name is None:
 
2938
            lock_dir_name = 'lock'
 
2939
        self.lock_dir_name = lock_dir_name
 
2940
        super(LockableIniFileStore, self).__init__(transport, file_name)
 
2941
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
 
2942
 
 
2943
    def lock_write(self, token=None):
 
2944
        """Takes a write lock in the directory containing the config file.
 
2945
 
 
2946
        If the directory doesn't exist it is created.
 
2947
        """
 
2948
        # FIXME: This doesn't check the ownership of the created directories as
 
2949
        # ensure_config_dir_exists does. It should if the transport is local
 
2950
        # -- vila 2011-04-06
 
2951
        self.transport.create_prefix()
 
2952
        return self._lock.lock_write(token)
 
2953
 
 
2954
    def unlock(self):
 
2955
        self._lock.unlock()
 
2956
 
 
2957
    def break_lock(self):
 
2958
        self._lock.break_lock()
 
2959
 
 
2960
    @needs_write_lock
 
2961
    def save(self):
 
2962
        # We need to be able to override the undecorated implementation
 
2963
        self.save_without_locking()
 
2964
 
 
2965
    def save_without_locking(self):
 
2966
        super(LockableIniFileStore, self).save()
 
2967
 
 
2968
 
 
2969
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
 
2970
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
 
2971
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
 
2972
 
 
2973
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
 
2974
# functions or a registry will make it easier and clearer for tests, focusing
 
2975
# on the relevant parts of the API that needs testing -- vila 20110503 (based
 
2976
# on a poolie's remark)
 
2977
class GlobalStore(LockableIniFileStore):
 
2978
 
 
2979
    def __init__(self, possible_transports=None):
 
2980
        t = transport.get_transport_from_path(
 
2981
            config_dir(), possible_transports=possible_transports)
 
2982
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
2983
        self.id = 'bazaar'
 
2984
 
 
2985
 
 
2986
class LocationStore(LockableIniFileStore):
 
2987
 
 
2988
    def __init__(self, possible_transports=None):
 
2989
        t = transport.get_transport_from_path(
 
2990
            config_dir(), possible_transports=possible_transports)
 
2991
        super(LocationStore, self).__init__(t, 'locations.conf')
 
2992
        self.id = 'locations'
 
2993
 
 
2994
 
 
2995
class BranchStore(TransportIniFileStore):
 
2996
 
 
2997
    def __init__(self, branch):
 
2998
        super(BranchStore, self).__init__(branch.control_transport,
 
2999
                                          'branch.conf')
 
3000
        self.branch = branch
 
3001
        self.id = 'branch'
 
3002
 
 
3003
    def lock_write(self, token=None):
 
3004
        return self.branch.lock_write(token)
 
3005
 
 
3006
    def unlock(self):
 
3007
        return self.branch.unlock()
 
3008
 
 
3009
    @needs_write_lock
 
3010
    def save(self):
 
3011
        # We need to be able to override the undecorated implementation
 
3012
        self.save_without_locking()
 
3013
 
 
3014
    def save_without_locking(self):
 
3015
        super(BranchStore, self).save()
 
3016
 
 
3017
 
 
3018
class ControlStore(LockableIniFileStore):
 
3019
 
 
3020
    def __init__(self, bzrdir):
 
3021
        super(ControlStore, self).__init__(bzrdir.transport,
 
3022
                                          'control.conf',
 
3023
                                           lock_dir_name='branch_lock')
 
3024
 
 
3025
 
 
3026
class SectionMatcher(object):
 
3027
    """Select sections into a given Store.
 
3028
 
 
3029
    This is intended to be used to postpone getting an iterable of sections
 
3030
    from a store.
 
3031
    """
 
3032
 
 
3033
    def __init__(self, store):
 
3034
        self.store = store
 
3035
 
 
3036
    def get_sections(self):
 
3037
        # This is where we require loading the store so we can see all defined
 
3038
        # sections.
 
3039
        sections = self.store.get_sections()
 
3040
        # Walk the revisions in the order provided
 
3041
        for store, s in sections:
 
3042
            if self.match(s):
 
3043
                yield store, s
 
3044
 
 
3045
    def match(self, section):
 
3046
        """Does the proposed section match.
 
3047
 
 
3048
        :param section: A Section object.
 
3049
 
 
3050
        :returns: True if the section matches, False otherwise.
 
3051
        """
 
3052
        raise NotImplementedError(self.match)
 
3053
 
 
3054
 
 
3055
class NameMatcher(SectionMatcher):
 
3056
 
 
3057
    def __init__(self, store, section_id):
 
3058
        super(NameMatcher, self).__init__(store)
 
3059
        self.section_id = section_id
 
3060
 
 
3061
    def match(self, section):
 
3062
        return section.id == self.section_id
 
3063
 
 
3064
 
 
3065
class LocationSection(Section):
 
3066
 
 
3067
    def __init__(self, section, length, extra_path):
 
3068
        super(LocationSection, self).__init__(section.id, section.options)
 
3069
        self.length = length
 
3070
        self.extra_path = extra_path
 
3071
        self.locals = {'relpath': extra_path,
 
3072
                       'basename': urlutils.basename(extra_path)}
 
3073
 
 
3074
    def get(self, name, default=None, expand=True):
 
3075
        value = super(LocationSection, self).get(name, default)
 
3076
        if value is not None and expand:
 
3077
            policy_name = self.get(name + ':policy', None)
 
3078
            policy = _policy_value.get(policy_name, POLICY_NONE)
 
3079
            if policy == POLICY_APPENDPATH:
 
3080
                value = urlutils.join(value, self.extra_path)
 
3081
            # expand section local options right now (since POLICY_APPENDPATH
 
3082
            # will never add options references, it's ok to expand after it).
 
3083
            chunks = []
 
3084
            for is_ref, chunk in iter_option_refs(value):
 
3085
                if not is_ref:
 
3086
                    chunks.append(chunk)
 
3087
                else:
 
3088
                    ref = chunk[1:-1]
 
3089
                    if ref in self.locals:
 
3090
                        chunks.append(self.locals[ref])
 
3091
                    else:
 
3092
                        chunks.append(chunk)
 
3093
            value = ''.join(chunks)
 
3094
        return value
 
3095
 
 
3096
 
 
3097
class LocationMatcher(SectionMatcher):
 
3098
 
 
3099
    def __init__(self, store, location):
 
3100
        super(LocationMatcher, self).__init__(store)
 
3101
        if location.startswith('file://'):
 
3102
            location = urlutils.local_path_from_url(location)
 
3103
        self.location = location
 
3104
 
 
3105
    def _get_matching_sections(self):
 
3106
        """Get all sections matching ``location``."""
 
3107
        # We slightly diverge from LocalConfig here by allowing the no-name
 
3108
        # section as the most generic one and the lower priority.
 
3109
        no_name_section = None
 
3110
        all_sections = []
 
3111
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
3112
        # used (it assumes all sections have a name).
 
3113
        for _, section in self.store.get_sections():
 
3114
            if section.id is None:
 
3115
                no_name_section = section
 
3116
            else:
 
3117
                all_sections.append(section)
 
3118
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
3119
        # we have to resync.
 
3120
        filtered_sections = _iter_for_location_by_parts(
 
3121
            [s.id for s in all_sections], self.location)
 
3122
        iter_all_sections = iter(all_sections)
 
3123
        matching_sections = []
 
3124
        if no_name_section is not None:
 
3125
            matching_sections.append(
 
3126
                LocationSection(no_name_section, 0, self.location))
 
3127
        for section_id, extra_path, length in filtered_sections:
 
3128
            # a section id is unique for a given store so it's safe to take the
 
3129
            # first matching section while iterating. Also, all filtered
 
3130
            # sections are part of 'all_sections' and will always be found
 
3131
            # there.
 
3132
            while True:
 
3133
                section = iter_all_sections.next()
 
3134
                if section_id == section.id:
 
3135
                    matching_sections.append(
 
3136
                        LocationSection(section, length, extra_path))
 
3137
                    break
 
3138
        return matching_sections
 
3139
 
 
3140
    def get_sections(self):
 
3141
        # Override the default implementation as we want to change the order
 
3142
        matching_sections = self._get_matching_sections()
 
3143
        # We want the longest (aka more specific) locations first
 
3144
        sections = sorted(matching_sections,
 
3145
                          key=lambda section: (section.length, section.id),
 
3146
                          reverse=True)
 
3147
        # Sections mentioning 'ignore_parents' restrict the selection
 
3148
        for section in sections:
 
3149
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
 
3150
            ignore = section.get('ignore_parents', None)
 
3151
            if ignore is not None:
 
3152
                ignore = ui.bool_from_string(ignore)
 
3153
            if ignore:
 
3154
                break
 
3155
            # Finally, we have a valid section
 
3156
            yield self.store, section
 
3157
 
 
3158
 
 
3159
_option_ref_re = lazy_regex.lazy_compile('({[^{}]+})')
 
3160
"""Describes an expandable option reference.
 
3161
 
 
3162
We want to match the most embedded reference first.
 
3163
 
 
3164
I.e. for '{{foo}}' we will get '{foo}',
 
3165
for '{bar{baz}}' we will get '{baz}'
 
3166
"""
 
3167
 
 
3168
def iter_option_refs(string):
 
3169
    # Split isolate refs so every other chunk is a ref
 
3170
    is_ref = False
 
3171
    for chunk  in _option_ref_re.split(string):
 
3172
        yield is_ref, chunk
 
3173
        is_ref = not is_ref
 
3174
 
 
3175
 
 
3176
class Stack(object):
 
3177
    """A stack of configurations where an option can be defined"""
 
3178
 
 
3179
    def __init__(self, sections_def, store=None, mutable_section_id=None):
 
3180
        """Creates a stack of sections with an optional store for changes.
 
3181
 
 
3182
        :param sections_def: A list of Section or callables that returns an
 
3183
            iterable of Section. This defines the Sections for the Stack and
 
3184
            can be called repeatedly if needed.
 
3185
 
 
3186
        :param store: The optional Store where modifications will be
 
3187
            recorded. If none is specified, no modifications can be done.
 
3188
 
 
3189
        :param mutable_section_id: The id of the MutableSection where changes
 
3190
            are recorded. This requires the ``store`` parameter to be
 
3191
            specified.
 
3192
        """
 
3193
        self.sections_def = sections_def
 
3194
        self.store = store
 
3195
        self.mutable_section_id = mutable_section_id
 
3196
 
 
3197
    def get(self, name, expand=None):
 
3198
        """Return the *first* option value found in the sections.
 
3199
 
 
3200
        This is where we guarantee that sections coming from Store are loaded
 
3201
        lazily: the loading is delayed until we need to either check that an
 
3202
        option exists or get its value, which in turn may require to discover
 
3203
        in which sections it can be defined. Both of these (section and option
 
3204
        existence) require loading the store (even partially).
 
3205
 
 
3206
        :param name: The queried option.
 
3207
 
 
3208
        :param expand: Whether options references should be expanded.
 
3209
 
 
3210
        :returns: The value of the option.
 
3211
        """
 
3212
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
3213
        if expand is None:
 
3214
            expand = _get_expand_default_value()
 
3215
        value = None
 
3216
        # Ensuring lazy loading is achieved by delaying section matching (which
 
3217
        # implies querying the persistent storage) until it can't be avoided
 
3218
        # anymore by using callables to describe (possibly empty) section
 
3219
        # lists.
 
3220
        for sections in self.sections_def:
 
3221
            for store, section in sections():
 
3222
                value = section.get(name)
 
3223
                if value is not None:
 
3224
                    break
 
3225
            if value is not None:
 
3226
                break
 
3227
        # If the option is registered, it may provide additional info about
 
3228
        # value handling
 
3229
        try:
 
3230
            opt = option_registry.get(name)
 
3231
        except KeyError:
 
3232
            # Not registered
 
3233
            opt = None
 
3234
        def expand_and_convert(val):
 
3235
            # This may need to be called twice if the value is None or ends up
 
3236
            # being None during expansion or conversion.
 
3237
            if val is not None:
 
3238
                if expand:
 
3239
                    if isinstance(val, basestring):
 
3240
                        val = self._expand_options_in_string(val)
 
3241
                    else:
 
3242
                        trace.warning('Cannot expand "%s":'
 
3243
                                      ' %s does not support option expansion'
 
3244
                                      % (name, type(val)))
 
3245
                if opt is not None:
 
3246
                    val = opt.convert_from_unicode(val)
 
3247
            return val
 
3248
        value = expand_and_convert(value)
 
3249
        if opt is not None and value is None:
 
3250
            # If the option is registered, it may provide a default value
 
3251
            value = opt.get_default()
 
3252
            value = expand_and_convert(value)
 
3253
        for hook in ConfigHooks['get']:
 
3254
            hook(self, name, value)
 
3255
        return value
 
3256
 
 
3257
    def expand_options(self, string, env=None):
 
3258
        """Expand option references in the string in the configuration context.
 
3259
 
 
3260
        :param string: The string containing option(s) to expand.
 
3261
 
 
3262
        :param env: An option dict defining additional configuration options or
 
3263
            overriding existing ones.
 
3264
 
 
3265
        :returns: The expanded string.
 
3266
        """
 
3267
        return self._expand_options_in_string(string, env)
 
3268
 
 
3269
    def _expand_options_in_string(self, string, env=None, _refs=None):
 
3270
        """Expand options in the string in the configuration context.
 
3271
 
 
3272
        :param string: The string to be expanded.
 
3273
 
 
3274
        :param env: An option dict defining additional configuration options or
 
3275
            overriding existing ones.
 
3276
 
 
3277
        :param _refs: Private list (FIFO) containing the options being expanded
 
3278
            to detect loops.
 
3279
 
 
3280
        :returns: The expanded string.
 
3281
        """
 
3282
        if string is None:
 
3283
            # Not much to expand there
 
3284
            return None
 
3285
        if _refs is None:
 
3286
            # What references are currently resolved (to detect loops)
 
3287
            _refs = []
 
3288
        result = string
 
3289
        # We need to iterate until no more refs appear ({{foo}} will need two
 
3290
        # iterations for example).
 
3291
        expanded = True
 
3292
        while expanded:
 
3293
            expanded = False
 
3294
            chunks = []
 
3295
            for is_ref, chunk in iter_option_refs(result):
 
3296
                if not is_ref:
 
3297
                    chunks.append(chunk)
 
3298
                else:
 
3299
                    expanded = True
 
3300
                    name = chunk[1:-1]
 
3301
                    if name in _refs:
 
3302
                        raise errors.OptionExpansionLoop(string, _refs)
 
3303
                    _refs.append(name)
 
3304
                    value = self._expand_option(name, env, _refs)
 
3305
                    if value is None:
 
3306
                        raise errors.ExpandingUnknownOption(name, string)
 
3307
                    chunks.append(value)
 
3308
                    _refs.pop()
 
3309
            result = ''.join(chunks)
 
3310
        return result
 
3311
 
 
3312
    def _expand_option(self, name, env, _refs):
 
3313
        if env is not None and name in env:
 
3314
            # Special case, values provided in env takes precedence over
 
3315
            # anything else
 
3316
            value = env[name]
 
3317
        else:
 
3318
            value = self.get(name, expand=False)
 
3319
            value = self._expand_options_in_string(value, env, _refs)
 
3320
        return value
 
3321
 
 
3322
    def _get_mutable_section(self):
 
3323
        """Get the MutableSection for the Stack.
 
3324
 
 
3325
        This is where we guarantee that the mutable section is lazily loaded:
 
3326
        this means we won't load the corresponding store before setting a value
 
3327
        or deleting an option. In practice the store will often be loaded but
 
3328
        this helps catching some programming errors.
 
3329
        """
 
3330
        section = self.store.get_mutable_section(self.mutable_section_id)
 
3331
        return section
 
3332
 
 
3333
    def set(self, name, value):
 
3334
        """Set a new value for the option."""
 
3335
        section = self._get_mutable_section()
 
3336
        section.set(name, value)
 
3337
        for hook in ConfigHooks['set']:
 
3338
            hook(self, name, value)
 
3339
 
 
3340
    def remove(self, name):
 
3341
        """Remove an existing option."""
 
3342
        section = self._get_mutable_section()
 
3343
        section.remove(name)
 
3344
        for hook in ConfigHooks['remove']:
 
3345
            hook(self, name)
 
3346
 
 
3347
    def __repr__(self):
 
3348
        # Mostly for debugging use
 
3349
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
 
3350
 
 
3351
    def _get_overrides(self):
 
3352
        # Hack around library_state.initialize never called
 
3353
        if bzrlib.global_state is not None:
 
3354
            return bzrlib.global_state.cmdline_overrides.get_sections()
 
3355
        return []
 
3356
 
 
3357
 
 
3358
class _CompatibleStack(Stack):
 
3359
    """Place holder for compatibility with previous design.
 
3360
 
 
3361
    This is intended to ease the transition from the Config-based design to the
 
3362
    Stack-based design and should not be used nor relied upon by plugins.
 
3363
 
 
3364
    One assumption made here is that the daughter classes will all use Stores
 
3365
    derived from LockableIniFileStore).
 
3366
 
 
3367
    It implements set() and remove () by re-loading the store before applying
 
3368
    the modification and saving it.
 
3369
 
 
3370
    The long term plan being to implement a single write by store to save
 
3371
    all modifications, this class should not be used in the interim.
 
3372
    """
 
3373
 
 
3374
    def set(self, name, value):
 
3375
        # Force a reload
 
3376
        self.store.unload()
 
3377
        super(_CompatibleStack, self).set(name, value)
 
3378
        # Force a write to persistent storage
 
3379
        self.store.save()
 
3380
 
 
3381
    def remove(self, name):
 
3382
        # Force a reload
 
3383
        self.store.unload()
 
3384
        super(_CompatibleStack, self).remove(name)
 
3385
        # Force a write to persistent storage
 
3386
        self.store.save()
 
3387
 
 
3388
 
 
3389
class GlobalStack(_CompatibleStack):
 
3390
    """Global options only stack."""
 
3391
 
 
3392
    def __init__(self):
 
3393
        # Get a GlobalStore
 
3394
        gstore = GlobalStore()
 
3395
        super(GlobalStack, self).__init__(
 
3396
            [self._get_overrides, NameMatcher(gstore, 'DEFAULT').get_sections],
 
3397
            gstore, mutable_section_id='DEFAULT')
 
3398
 
 
3399
 
 
3400
class LocationStack(_CompatibleStack):
 
3401
    """Per-location options falling back to global options stack."""
 
3402
 
 
3403
    def __init__(self, location):
 
3404
        """Make a new stack for a location and global configuration.
 
3405
        
 
3406
        :param location: A URL prefix to """
 
3407
        lstore = LocationStore()
 
3408
        if location.startswith('file://'):
 
3409
            location = urlutils.local_path_from_url(location)
 
3410
        matcher = LocationMatcher(lstore, location)
 
3411
        gstore = GlobalStore()
 
3412
        super(LocationStack, self).__init__(
 
3413
            [self._get_overrides,
 
3414
             matcher.get_sections, NameMatcher(gstore, 'DEFAULT').get_sections],
 
3415
            lstore, mutable_section_id=location)
 
3416
 
 
3417
 
 
3418
class BranchStack(_CompatibleStack):
 
3419
    """Per-location options falling back to branch then global options stack."""
 
3420
 
 
3421
    def __init__(self, branch):
 
3422
        bstore = branch._get_config_store()
 
3423
        lstore = LocationStore()
 
3424
        matcher = LocationMatcher(lstore, branch.base)
 
3425
        gstore = GlobalStore()
 
3426
        super(BranchStack, self).__init__(
 
3427
            [self._get_overrides,
 
3428
             matcher.get_sections, bstore.get_sections,
 
3429
             NameMatcher(gstore, 'DEFAULT').get_sections],
 
3430
            bstore)
 
3431
        self.branch = branch
 
3432
 
 
3433
 
 
3434
class RemoteControlStack(_CompatibleStack):
 
3435
    """Remote control-only options stack."""
 
3436
 
 
3437
    # FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
 
3438
    # with the stack used for remote bzr dirs. RemoteControlStack only uses
 
3439
    # control.conf and is used only for stack options.
 
3440
 
 
3441
    def __init__(self, bzrdir):
 
3442
        cstore = bzrdir._get_config_store()
 
3443
        super(RemoteControlStack, self).__init__(
 
3444
            [cstore.get_sections],
 
3445
            cstore)
 
3446
        self.bzrdir = bzrdir
 
3447
 
 
3448
 
 
3449
class RemoteBranchStack(_CompatibleStack):
 
3450
    """Remote branch-only options stack."""
 
3451
 
 
3452
    # FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
 
3453
    # with the stack used for remote branches. RemoteBranchStack only uses
 
3454
    # branch.conf and is used only for the stack options.
 
3455
 
 
3456
    def __init__(self, branch):
 
3457
        bstore = branch._get_config_store()
 
3458
        super(RemoteBranchStack, self).__init__(
 
3459
            [bstore.get_sections],
 
3460
            bstore)
 
3461
        self.branch = branch
 
3462
 
 
3463
# Use a an empty dict to initialize an empty configobj avoiding all
 
3464
# parsing and encoding checks
 
3465
_quoting_config = configobj.ConfigObj(
 
3466
    {}, encoding='utf-8', interpolation=False)
 
3467
 
 
3468
class cmd_config(commands.Command):
 
3469
    __doc__ = """Display, set or remove a configuration option.
 
3470
 
 
3471
    Display the active value for a given option.
 
3472
 
 
3473
    If --all is specified, NAME is interpreted as a regular expression and all
 
3474
    matching options are displayed mentioning their scope. The active value
 
3475
    that bzr will take into account is the first one displayed for each option.
 
3476
 
 
3477
    If no NAME is given, --all .* is implied.
 
3478
 
 
3479
    Setting a value is achieved by using name=value without spaces. The value
 
3480
    is set in the most relevant scope and can be checked by displaying the
 
3481
    option again.
 
3482
    """
 
3483
 
 
3484
    takes_args = ['name?']
 
3485
 
 
3486
    takes_options = [
 
3487
        'directory',
 
3488
        # FIXME: This should be a registry option so that plugins can register
 
3489
        # their own config files (or not) and will also address
 
3490
        # http://pad.lv/788991 -- vila 20101115
 
3491
        commands.Option('scope', help='Reduce the scope to the specified'
 
3492
                        ' configuration file.',
 
3493
                        type=unicode),
 
3494
        commands.Option('all',
 
3495
            help='Display all the defined values for the matching options.',
 
3496
            ),
 
3497
        commands.Option('remove', help='Remove the option from'
 
3498
                        ' the configuration file.'),
 
3499
        ]
 
3500
 
 
3501
    _see_also = ['configuration']
 
3502
 
 
3503
    @commands.display_command
 
3504
    def run(self, name=None, all=False, directory=None, scope=None,
 
3505
            remove=False):
 
3506
        if directory is None:
 
3507
            directory = '.'
 
3508
        directory = urlutils.normalize_url(directory)
 
3509
        if remove and all:
 
3510
            raise errors.BzrError(
 
3511
                '--all and --remove are mutually exclusive.')
 
3512
        elif remove:
 
3513
            # Delete the option in the given scope
 
3514
            self._remove_config_option(name, directory, scope)
 
3515
        elif name is None:
 
3516
            # Defaults to all options
 
3517
            self._show_matching_options('.*', directory, scope)
 
3518
        else:
 
3519
            try:
 
3520
                name, value = name.split('=', 1)
 
3521
            except ValueError:
 
3522
                # Display the option(s) value(s)
 
3523
                if all:
 
3524
                    self._show_matching_options(name, directory, scope)
 
3525
                else:
 
3526
                    self._show_value(name, directory, scope)
 
3527
            else:
 
3528
                if all:
 
3529
                    raise errors.BzrError(
 
3530
                        'Only one option can be set.')
 
3531
                # Set the option value
 
3532
                self._set_config_option(name, value, directory, scope)
 
3533
 
 
3534
    def _get_stack(self, directory, scope=None):
 
3535
        """Get the configuration stack specified by ``directory`` and ``scope``.
 
3536
 
 
3537
        :param directory: Where the configurations are derived from.
 
3538
 
 
3539
        :param scope: A specific config to start from.
 
3540
        """
 
3541
        # FIXME: scope should allow access to plugin-specific stacks (even
 
3542
        # reduced to the plugin-specific store), related to
 
3543
        # http://pad.lv/788991 -- vila 2011-11-15
 
3544
        if scope is not None:
 
3545
            if scope == 'bazaar':
 
3546
                return GlobalStack()
 
3547
            elif scope == 'locations':
 
3548
                return LocationStack(directory)
 
3549
            elif scope == 'branch':
 
3550
                (_, br, _) = (
 
3551
                    controldir.ControlDir.open_containing_tree_or_branch(
 
3552
                        directory))
 
3553
                return br.get_config_stack()
 
3554
            raise errors.NoSuchConfig(scope)
 
3555
        else:
 
3556
            try:
 
3557
                (_, br, _) = (
 
3558
                    controldir.ControlDir.open_containing_tree_or_branch(
 
3559
                        directory))
 
3560
                return br.get_config_stack()
 
3561
            except errors.NotBranchError:
 
3562
                return LocationStack(directory)
 
3563
 
 
3564
    def _show_value(self, name, directory, scope):
 
3565
        conf = self._get_stack(directory, scope)
 
3566
        value = conf.get(name, expand=True)
 
3567
        if value is not None:
 
3568
            # Quote the value appropriately
 
3569
            value = _quoting_config._quote(value)
 
3570
            self.outf.write('%s\n' % (value,))
 
3571
        else:
 
3572
            raise errors.NoSuchConfigOption(name)
 
3573
 
 
3574
    def _show_matching_options(self, name, directory, scope):
 
3575
        name = lazy_regex.lazy_compile(name)
 
3576
        # We want any error in the regexp to be raised *now* so we need to
 
3577
        # avoid the delay introduced by the lazy regexp.  But, we still do
 
3578
        # want the nicer errors raised by lazy_regex.
 
3579
        name._compile_and_collapse()
 
3580
        cur_store_id = None
 
3581
        cur_section = None
 
3582
        conf = self._get_stack(directory, scope)
 
3583
        for sections in conf.sections_def:
 
3584
            for store, section in sections():
 
3585
                for oname in section.iter_option_names():
 
3586
                    if name.search(oname):
 
3587
                        if cur_store_id != store.id:
 
3588
                            # Explain where the options are defined
 
3589
                            self.outf.write('%s:\n' % (store.id,))
 
3590
                            cur_store_id = store.id
 
3591
                            cur_section = None
 
3592
                        if (section.id not in (None, 'DEFAULT')
 
3593
                            and cur_section != section.id):
 
3594
                            # Display the section if it's not the default (or
 
3595
                            # only) one.
 
3596
                            self.outf.write('  [%s]\n' % (section.id,))
 
3597
                            cur_section = section.id
 
3598
                        value = section.get(oname, expand=False)
 
3599
                        value = _quoting_config._quote(value)
 
3600
                        self.outf.write('  %s = %s\n' % (oname, value))
 
3601
 
 
3602
    def _set_config_option(self, name, value, directory, scope):
 
3603
        conf = self._get_stack(directory, scope)
 
3604
        conf.set(name, value)
 
3605
 
 
3606
    def _remove_config_option(self, name, directory, scope):
 
3607
        if name is None:
 
3608
            raise errors.BzrCommandError(
 
3609
                '--remove expects an option to remove.')
 
3610
        conf = self._get_stack(directory, scope)
 
3611
        try:
 
3612
            conf.remove(name)
 
3613
        except KeyError:
 
3614
            raise errors.NoSuchConfigOption(name)
 
3615
 
 
3616
 
 
3617
# Test registries
 
3618
#
 
3619
# We need adapters that can build a Store or a Stack in a test context. Test
 
3620
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
3621
# themselves. The builder will receive a test instance and should return a
 
3622
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
3623
# register themselves here to be tested against the tests defined in
 
3624
# bzrlib.tests.test_config. Note that the builder can be called multiple times
 
3625
# for the same test.
 
3626
 
 
3627
# The registered object should be a callable receiving a test instance
 
3628
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
3629
# object.
 
3630
test_store_builder_registry = registry.Registry()
 
3631
 
 
3632
# The registered object should be a callable receiving a test instance
 
3633
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
3634
# object.
 
3635
test_stack_builder_registry = registry.Registry()