/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Andrew Bennetts
  • Date: 2011-06-09 07:38:32 UTC
  • mto: This revision was merged to the branch mainline in revision 5964.
  • Revision ID: andrew.bennetts@canonical.com-20110609073832-dt6oww033iexli4l
Fix thinko in wording regarding stacking invariants and revisions with multiple parents.

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
 
 
33
in locations.conf, you specify the url of a branch and options for it.
 
34
Wildcards may be used - * and ? as normal in shell completion. Options
 
35
set in both bazaar.conf and locations.conf are overridden by the locations.conf
 
36
setting.
 
37
[/home/robertc/source]
 
38
recurse=False|True(default)
 
39
email= as above
 
40
check_signatures= as above
 
41
create_signatures= as above.
 
42
 
 
43
explanation of options
 
44
----------------------
 
45
editor - this option sets the pop up editor to use during commits.
 
46
email - this option sets the user id bzr will use when committing.
 
47
check_signatures - this option controls whether bzr will require good gpg
 
48
                   signatures, ignore them, or check them if they are
 
49
                   present.
 
50
create_signatures - this option controls whether bzr will always create
 
51
                    gpg signatures, never create them, or create them if the
 
52
                    branch is configured to require them.
 
53
log_format - this option sets the default log format.  Possible values are
 
54
             long, short, line, or a plugin can register new formats.
 
55
 
 
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
 
57
 
 
58
[ALIASES]
 
59
lastlog=log --line -r-10..-1
 
60
ll=log --line -r-10..-1
 
61
h=help
 
62
up=pull
 
63
"""
 
64
 
 
65
import os
 
66
import string
 
67
import sys
 
68
import weakref
 
69
 
 
70
from bzrlib import commands
 
71
from bzrlib.decorators import needs_write_lock
 
72
from bzrlib.lazy_import import lazy_import
 
73
lazy_import(globals(), """
 
74
import fnmatch
 
75
import re
 
76
from cStringIO import StringIO
 
77
 
 
78
import bzrlib
 
79
from bzrlib import (
 
80
    atomicfile,
 
81
    bzrdir,
 
82
    debug,
 
83
    errors,
 
84
    lockdir,
 
85
    mail_client,
 
86
    mergetools,
 
87
    osutils,
 
88
    symbol_versioning,
 
89
    trace,
 
90
    transport,
 
91
    ui,
 
92
    urlutils,
 
93
    win32utils,
 
94
    )
 
95
from bzrlib.util.configobj import configobj
 
96
""")
 
97
from bzrlib import (
 
98
    registry,
 
99
    )
 
100
from bzrlib.symbol_versioning import (
 
101
    deprecated_in,
 
102
    deprecated_method,
 
103
    )
 
104
 
 
105
 
 
106
CHECK_IF_POSSIBLE=0
 
107
CHECK_ALWAYS=1
 
108
CHECK_NEVER=2
 
109
 
 
110
 
 
111
SIGN_WHEN_REQUIRED=0
 
112
SIGN_ALWAYS=1
 
113
SIGN_NEVER=2
 
114
 
 
115
 
 
116
POLICY_NONE = 0
 
117
POLICY_NORECURSE = 1
 
118
POLICY_APPENDPATH = 2
 
119
 
 
120
_policy_name = {
 
121
    POLICY_NONE: None,
 
122
    POLICY_NORECURSE: 'norecurse',
 
123
    POLICY_APPENDPATH: 'appendpath',
 
124
    }
 
125
_policy_value = {
 
126
    None: POLICY_NONE,
 
127
    'none': POLICY_NONE,
 
128
    'norecurse': POLICY_NORECURSE,
 
129
    'appendpath': POLICY_APPENDPATH,
 
130
    }
 
131
 
 
132
 
 
133
STORE_LOCATION = POLICY_NONE
 
134
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
 
135
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
 
136
STORE_BRANCH = 3
 
137
STORE_GLOBAL = 4
 
138
 
 
139
 
 
140
class ConfigObj(configobj.ConfigObj):
 
141
 
 
142
    def __init__(self, infile=None, **kwargs):
 
143
        # We define our own interpolation mechanism calling it option expansion
 
144
        super(ConfigObj, self).__init__(infile=infile,
 
145
                                        interpolation=False,
 
146
                                        **kwargs)
 
147
 
 
148
 
 
149
    def get_bool(self, section, key):
 
150
        return self[section].as_bool(key)
 
151
 
 
152
    def get_value(self, section, name):
 
153
        # Try [] for the old DEFAULT section.
 
154
        if section == "DEFAULT":
 
155
            try:
 
156
                return self[name]
 
157
            except KeyError:
 
158
                pass
 
159
        return self[section][name]
 
160
 
 
161
 
 
162
# FIXME: Until we can guarantee that each config file is loaded once and and
 
163
# only once for a given bzrlib session, we don't want to re-read the file every
 
164
# time we query for an option so we cache the value (bad ! watch out for tests
 
165
# needing to restore the proper value).This shouldn't be part of 2.4.0 final,
 
166
# yell at mgz^W vila and the RM if this is still present at that time
 
167
# -- vila 20110219
 
168
_expand_default_value = None
 
169
def _get_expand_default_value():
 
170
    global _expand_default_value
 
171
    if _expand_default_value is not None:
 
172
        return _expand_default_value
 
173
    conf = GlobalConfig()
 
174
    # Note that we must not use None for the expand value below or we'll run
 
175
    # into infinite recursion. Using False really would be quite silly ;)
 
176
    expand = conf.get_user_option_as_bool('bzr.config.expand', expand=True)
 
177
    if expand is None:
 
178
        # This is an opt-in feature, you *really* need to clearly say you want
 
179
        # to activate it !
 
180
        expand = False
 
181
    _expand_default_value = expand
 
182
    return expand
 
183
 
 
184
 
 
185
class Config(object):
 
186
    """A configuration policy - what username, editor, gpg needs etc."""
 
187
 
 
188
    def __init__(self):
 
189
        super(Config, self).__init__()
 
190
 
 
191
    def config_id(self):
 
192
        """Returns a unique ID for the config."""
 
193
        raise NotImplementedError(self.config_id)
 
194
 
 
195
    @deprecated_method(deprecated_in((2, 4, 0)))
 
196
    def get_editor(self):
 
197
        """Get the users pop up editor."""
 
198
        raise NotImplementedError
 
199
 
 
200
    def get_change_editor(self, old_tree, new_tree):
 
201
        from bzrlib import diff
 
202
        cmd = self._get_change_editor()
 
203
        if cmd is None:
 
204
            return None
 
205
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
 
206
                                             sys.stdout)
 
207
 
 
208
    def get_mail_client(self):
 
209
        """Get a mail client to use"""
 
210
        selected_client = self.get_user_option('mail_client')
 
211
        _registry = mail_client.mail_client_registry
 
212
        try:
 
213
            mail_client_class = _registry.get(selected_client)
 
214
        except KeyError:
 
215
            raise errors.UnknownMailClient(selected_client)
 
216
        return mail_client_class(self)
 
217
 
 
218
    def _get_signature_checking(self):
 
219
        """Template method to override signature checking policy."""
 
220
 
 
221
    def _get_signing_policy(self):
 
222
        """Template method to override signature creation policy."""
 
223
 
 
224
    option_ref_re = None
 
225
 
 
226
    def expand_options(self, string, env=None):
 
227
        """Expand option references in the string in the configuration context.
 
228
 
 
229
        :param string: The string containing option to expand.
 
230
 
 
231
        :param env: An option dict defining additional configuration options or
 
232
            overriding existing ones.
 
233
 
 
234
        :returns: The expanded string.
 
235
        """
 
236
        return self._expand_options_in_string(string, env)
 
237
 
 
238
    def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
 
239
        """Expand options in  a list of strings in the configuration context.
 
240
 
 
241
        :param slist: A list of strings.
 
242
 
 
243
        :param env: An option dict defining additional configuration options or
 
244
            overriding existing ones.
 
245
 
 
246
        :param _ref_stack: Private list containing the options being
 
247
            expanded to detect loops.
 
248
 
 
249
        :returns: The flatten list of expanded strings.
 
250
        """
 
251
        # expand options in each value separately flattening lists
 
252
        result = []
 
253
        for s in slist:
 
254
            value = self._expand_options_in_string(s, env, _ref_stack)
 
255
            if isinstance(value, list):
 
256
                result.extend(value)
 
257
            else:
 
258
                result.append(value)
 
259
        return result
 
260
 
 
261
    def _expand_options_in_string(self, string, env=None, _ref_stack=None):
 
262
        """Expand options in the string in the configuration context.
 
263
 
 
264
        :param string: The string to be expanded.
 
265
 
 
266
        :param env: An option dict defining additional configuration options or
 
267
            overriding existing ones.
 
268
 
 
269
        :param _ref_stack: Private list containing the options being
 
270
            expanded to detect loops.
 
271
 
 
272
        :returns: The expanded string.
 
273
        """
 
274
        if string is None:
 
275
            # Not much to expand there
 
276
            return None
 
277
        if _ref_stack is None:
 
278
            # What references are currently resolved (to detect loops)
 
279
            _ref_stack = []
 
280
        if self.option_ref_re is None:
 
281
            # We want to match the most embedded reference first (i.e. for
 
282
            # '{{foo}}' we will get '{foo}',
 
283
            # for '{bar{baz}}' we will get '{baz}'
 
284
            self.option_ref_re = re.compile('({[^{}]+})')
 
285
        result = string
 
286
        # We need to iterate until no more refs appear ({{foo}} will need two
 
287
        # iterations for example).
 
288
        while True:
 
289
            raw_chunks = self.option_ref_re.split(result)
 
290
            if len(raw_chunks) == 1:
 
291
                # Shorcut the trivial case: no refs
 
292
                return result
 
293
            chunks = []
 
294
            list_value = False
 
295
            # Split will isolate refs so that every other chunk is a ref
 
296
            chunk_is_ref = False
 
297
            for chunk in raw_chunks:
 
298
                if not chunk_is_ref:
 
299
                    if chunk:
 
300
                        # Keep only non-empty strings (or we get bogus empty
 
301
                        # slots when a list value is involved).
 
302
                        chunks.append(chunk)
 
303
                    chunk_is_ref = True
 
304
                else:
 
305
                    name = chunk[1:-1]
 
306
                    if name in _ref_stack:
 
307
                        raise errors.OptionExpansionLoop(string, _ref_stack)
 
308
                    _ref_stack.append(name)
 
309
                    value = self._expand_option(name, env, _ref_stack)
 
310
                    if value is None:
 
311
                        raise errors.ExpandingUnknownOption(name, string)
 
312
                    if isinstance(value, list):
 
313
                        list_value = True
 
314
                        chunks.extend(value)
 
315
                    else:
 
316
                        chunks.append(value)
 
317
                    _ref_stack.pop()
 
318
                    chunk_is_ref = False
 
319
            if list_value:
 
320
                # Once a list appears as the result of an expansion, all
 
321
                # callers will get a list result. This allows a consistent
 
322
                # behavior even when some options in the expansion chain
 
323
                # defined as strings (no comma in their value) but their
 
324
                # expanded value is a list.
 
325
                return self._expand_options_in_list(chunks, env, _ref_stack)
 
326
            else:
 
327
                result = ''.join(chunks)
 
328
        return result
 
329
 
 
330
    def _expand_option(self, name, env, _ref_stack):
 
331
        if env is not None and name in env:
 
332
            # Special case, values provided in env takes precedence over
 
333
            # anything else
 
334
            value = env[name]
 
335
        else:
 
336
            # FIXME: This is a limited implementation, what we really need is a
 
337
            # way to query the bzr config for the value of an option,
 
338
            # respecting the scope rules (That is, once we implement fallback
 
339
            # configs, getting the option value should restart from the top
 
340
            # config, not the current one) -- vila 20101222
 
341
            value = self.get_user_option(name, expand=False)
 
342
            if isinstance(value, list):
 
343
                value = self._expand_options_in_list(value, env, _ref_stack)
 
344
            else:
 
345
                value = self._expand_options_in_string(value, env, _ref_stack)
 
346
        return value
 
347
 
 
348
    def _get_user_option(self, option_name):
 
349
        """Template method to provide a user option."""
 
350
        return None
 
351
 
 
352
    def get_user_option(self, option_name, expand=None):
 
353
        """Get a generic option - no special process, no default.
 
354
 
 
355
        :param option_name: The queried option.
 
356
 
 
357
        :param expand: Whether options references should be expanded.
 
358
 
 
359
        :returns: The value of the option.
 
360
        """
 
361
        if expand is None:
 
362
            expand = _get_expand_default_value()
 
363
        value = self._get_user_option(option_name)
 
364
        if expand:
 
365
            if isinstance(value, list):
 
366
                value = self._expand_options_in_list(value)
 
367
            elif isinstance(value, dict):
 
368
                trace.warning('Cannot expand "%s":'
 
369
                              ' Dicts do not support option expansion'
 
370
                              % (option_name,))
 
371
            else:
 
372
                value = self._expand_options_in_string(value)
 
373
        return value
 
374
 
 
375
    def get_user_option_as_bool(self, option_name, expand=None):
 
376
        """Get a generic option as a boolean - no special process, no default.
 
377
 
 
378
        :return None if the option doesn't exist or its value can't be
 
379
            interpreted as a boolean. Returns True or False otherwise.
 
380
        """
 
381
        s = self.get_user_option(option_name, expand=expand)
 
382
        if s is None:
 
383
            # The option doesn't exist
 
384
            return None
 
385
        val = ui.bool_from_string(s)
 
386
        if val is None:
 
387
            # The value can't be interpreted as a boolean
 
388
            trace.warning('Value "%s" is not a boolean for "%s"',
 
389
                          s, option_name)
 
390
        return val
 
391
 
 
392
    def get_user_option_as_list(self, option_name, expand=None):
 
393
        """Get a generic option as a list - no special process, no default.
 
394
 
 
395
        :return None if the option doesn't exist. Returns the value as a list
 
396
            otherwise.
 
397
        """
 
398
        l = self.get_user_option(option_name, expand=expand)
 
399
        if isinstance(l, (str, unicode)):
 
400
            # A single value, most probably the user forgot (or didn't care to
 
401
            # add) the final ','
 
402
            l = [l]
 
403
        return l
 
404
 
 
405
    def gpg_signing_command(self):
 
406
        """What program should be used to sign signatures?"""
 
407
        result = self._gpg_signing_command()
 
408
        if result is None:
 
409
            result = "gpg"
 
410
        return result
 
411
 
 
412
    def _gpg_signing_command(self):
 
413
        """See gpg_signing_command()."""
 
414
        return None
 
415
 
 
416
    def log_format(self):
 
417
        """What log format should be used"""
 
418
        result = self._log_format()
 
419
        if result is None:
 
420
            result = "long"
 
421
        return result
 
422
 
 
423
    def _log_format(self):
 
424
        """See log_format()."""
 
425
        return None
 
426
 
 
427
    def post_commit(self):
 
428
        """An ordered list of python functions to call.
 
429
 
 
430
        Each function takes branch, rev_id as parameters.
 
431
        """
 
432
        return self._post_commit()
 
433
 
 
434
    def _post_commit(self):
 
435
        """See Config.post_commit."""
 
436
        return None
 
437
 
 
438
    def user_email(self):
 
439
        """Return just the email component of a username."""
 
440
        return extract_email_address(self.username())
 
441
 
 
442
    def username(self):
 
443
        """Return email-style username.
 
444
 
 
445
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
 
446
 
 
447
        $BZR_EMAIL can be set to override this, then
 
448
        the concrete policy type is checked, and finally
 
449
        $EMAIL is examined.
 
450
        If no username can be found, errors.NoWhoami exception is raised.
 
451
        """
 
452
        v = os.environ.get('BZR_EMAIL')
 
453
        if v:
 
454
            return v.decode(osutils.get_user_encoding())
 
455
        v = self._get_user_id()
 
456
        if v:
 
457
            return v
 
458
        v = os.environ.get('EMAIL')
 
459
        if v:
 
460
            return v.decode(osutils.get_user_encoding())
 
461
        name, email = _auto_user_id()
 
462
        if name and email:
 
463
            return '%s <%s>' % (name, email)
 
464
        elif email:
 
465
            return email
 
466
        raise errors.NoWhoami()
 
467
 
 
468
    def ensure_username(self):
 
469
        """Raise errors.NoWhoami if username is not set.
 
470
 
 
471
        This method relies on the username() function raising the error.
 
472
        """
 
473
        self.username()
 
474
 
 
475
    def signature_checking(self):
 
476
        """What is the current policy for signature checking?."""
 
477
        policy = self._get_signature_checking()
 
478
        if policy is not None:
 
479
            return policy
 
480
        return CHECK_IF_POSSIBLE
 
481
 
 
482
    def signing_policy(self):
 
483
        """What is the current policy for signature checking?."""
 
484
        policy = self._get_signing_policy()
 
485
        if policy is not None:
 
486
            return policy
 
487
        return SIGN_WHEN_REQUIRED
 
488
 
 
489
    def signature_needed(self):
 
490
        """Is a signature needed when committing ?."""
 
491
        policy = self._get_signing_policy()
 
492
        if policy is None:
 
493
            policy = self._get_signature_checking()
 
494
            if policy is not None:
 
495
                trace.warning("Please use create_signatures,"
 
496
                              " not check_signatures to set signing policy.")
 
497
            if policy == CHECK_ALWAYS:
 
498
                return True
 
499
        elif policy == SIGN_ALWAYS:
 
500
            return True
 
501
        return False
 
502
 
 
503
    def get_alias(self, value):
 
504
        return self._get_alias(value)
 
505
 
 
506
    def _get_alias(self, value):
 
507
        pass
 
508
 
 
509
    def get_nickname(self):
 
510
        return self._get_nickname()
 
511
 
 
512
    def _get_nickname(self):
 
513
        return None
 
514
 
 
515
    def get_bzr_remote_path(self):
 
516
        try:
 
517
            return os.environ['BZR_REMOTE_PATH']
 
518
        except KeyError:
 
519
            path = self.get_user_option("bzr_remote_path")
 
520
            if path is None:
 
521
                path = 'bzr'
 
522
            return path
 
523
 
 
524
    def suppress_warning(self, warning):
 
525
        """Should the warning be suppressed or emitted.
 
526
 
 
527
        :param warning: The name of the warning being tested.
 
528
 
 
529
        :returns: True if the warning should be suppressed, False otherwise.
 
530
        """
 
531
        warnings = self.get_user_option_as_list('suppress_warnings')
 
532
        if warnings is None or warning not in warnings:
 
533
            return False
 
534
        else:
 
535
            return True
 
536
 
 
537
    def get_merge_tools(self):
 
538
        tools = {}
 
539
        for (oname, value, section, conf_id, parser) in self._get_options():
 
540
            if oname.startswith('bzr.mergetool.'):
 
541
                tool_name = oname[len('bzr.mergetool.'):]
 
542
                tools[tool_name] = value
 
543
        trace.mutter('loaded merge tools: %r' % tools)
 
544
        return tools
 
545
 
 
546
    def find_merge_tool(self, name):
 
547
        # We fake a defaults mechanism here by checking if the given name can 
 
548
        # be found in the known_merge_tools if it's not found in the config.
 
549
        # This should be done through the proposed config defaults mechanism
 
550
        # when it becomes available in the future.
 
551
        command_line = (self.get_user_option('bzr.mergetool.%s' % name,
 
552
                                             expand=False)
 
553
                        or mergetools.known_merge_tools.get(name, None))
 
554
        return command_line
 
555
 
 
556
 
 
557
class IniBasedConfig(Config):
 
558
    """A configuration policy that draws from ini files."""
 
559
 
 
560
    def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
 
561
                 file_name=None):
 
562
        """Base class for configuration files using an ini-like syntax.
 
563
 
 
564
        :param file_name: The configuration file path.
 
565
        """
 
566
        super(IniBasedConfig, self).__init__()
 
567
        self.file_name = file_name
 
568
        if symbol_versioning.deprecated_passed(get_filename):
 
569
            symbol_versioning.warn(
 
570
                'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
 
571
                ' Use file_name instead.',
 
572
                DeprecationWarning,
 
573
                stacklevel=2)
 
574
            if get_filename is not None:
 
575
                self.file_name = get_filename()
 
576
        else:
 
577
            self.file_name = file_name
 
578
        self._content = None
 
579
        self._parser = None
 
580
 
 
581
    @classmethod
 
582
    def from_string(cls, str_or_unicode, file_name=None, save=False):
 
583
        """Create a config object from a string.
 
584
 
 
585
        :param str_or_unicode: A string representing the file content. This will
 
586
            be utf-8 encoded.
 
587
 
 
588
        :param file_name: The configuration file path.
 
589
 
 
590
        :param _save: Whether the file should be saved upon creation.
 
591
        """
 
592
        conf = cls(file_name=file_name)
 
593
        conf._create_from_string(str_or_unicode, save)
 
594
        return conf
 
595
 
 
596
    def _create_from_string(self, str_or_unicode, save):
 
597
        self._content = StringIO(str_or_unicode.encode('utf-8'))
 
598
        # Some tests use in-memory configs, some other always need the config
 
599
        # file to exist on disk.
 
600
        if save:
 
601
            self._write_config_file()
 
602
 
 
603
    def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
 
604
        if self._parser is not None:
 
605
            return self._parser
 
606
        if symbol_versioning.deprecated_passed(file):
 
607
            symbol_versioning.warn(
 
608
                'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
 
609
                ' Use IniBasedConfig(_content=xxx) instead.',
 
610
                DeprecationWarning,
 
611
                stacklevel=2)
 
612
        if self._content is not None:
 
613
            co_input = self._content
 
614
        elif self.file_name is None:
 
615
            raise AssertionError('We have no content to create the config')
 
616
        else:
 
617
            co_input = self.file_name
 
618
        try:
 
619
            self._parser = ConfigObj(co_input, encoding='utf-8')
 
620
        except configobj.ConfigObjError, e:
 
621
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
622
        # Make sure self.reload() will use the right file name
 
623
        self._parser.filename = self.file_name
 
624
        return self._parser
 
625
 
 
626
    def reload(self):
 
627
        """Reload the config file from disk."""
 
628
        if self.file_name is None:
 
629
            raise AssertionError('We need a file name to reload the config')
 
630
        if self._parser is not None:
 
631
            self._parser.reload()
 
632
 
 
633
    def _get_matching_sections(self):
 
634
        """Return an ordered list of (section_name, extra_path) pairs.
 
635
 
 
636
        If the section contains inherited configuration, extra_path is
 
637
        a string containing the additional path components.
 
638
        """
 
639
        section = self._get_section()
 
640
        if section is not None:
 
641
            return [(section, '')]
 
642
        else:
 
643
            return []
 
644
 
 
645
    def _get_section(self):
 
646
        """Override this to define the section used by the config."""
 
647
        return "DEFAULT"
 
648
 
 
649
    def _get_sections(self, name=None):
 
650
        """Returns an iterator of the sections specified by ``name``.
 
651
 
 
652
        :param name: The section name. If None is supplied, the default
 
653
            configurations are yielded.
 
654
 
 
655
        :return: A tuple (name, section, config_id) for all sections that will
 
656
            be walked by user_get_option() in the 'right' order. The first one
 
657
            is where set_user_option() will update the value.
 
658
        """
 
659
        parser = self._get_parser()
 
660
        if name is not None:
 
661
            yield (name, parser[name], self.config_id())
 
662
        else:
 
663
            # No section name has been given so we fallback to the configobj
 
664
            # itself which holds the variables defined outside of any section.
 
665
            yield (None, parser, self.config_id())
 
666
 
 
667
    def _get_options(self, sections=None):
 
668
        """Return an ordered list of (name, value, section, config_id) tuples.
 
669
 
 
670
        All options are returned with their associated value and the section
 
671
        they appeared in. ``config_id`` is a unique identifier for the
 
672
        configuration file the option is defined in.
 
673
 
 
674
        :param sections: Default to ``_get_matching_sections`` if not
 
675
            specified. This gives a better control to daughter classes about
 
676
            which sections should be searched. This is a list of (name,
 
677
            configobj) tuples.
 
678
        """
 
679
        opts = []
 
680
        if sections is None:
 
681
            parser = self._get_parser()
 
682
            sections = []
 
683
            for (section_name, _) in self._get_matching_sections():
 
684
                try:
 
685
                    section = parser[section_name]
 
686
                except KeyError:
 
687
                    # This could happen for an empty file for which we define a
 
688
                    # DEFAULT section. FIXME: Force callers to provide sections
 
689
                    # instead ? -- vila 20100930
 
690
                    continue
 
691
                sections.append((section_name, section))
 
692
        config_id = self.config_id()
 
693
        for (section_name, section) in sections:
 
694
            for (name, value) in section.iteritems():
 
695
                yield (name, parser._quote(value), section_name,
 
696
                       config_id, parser)
 
697
 
 
698
    def _get_option_policy(self, section, option_name):
 
699
        """Return the policy for the given (section, option_name) pair."""
 
700
        return POLICY_NONE
 
701
 
 
702
    def _get_change_editor(self):
 
703
        return self.get_user_option('change_editor')
 
704
 
 
705
    def _get_signature_checking(self):
 
706
        """See Config._get_signature_checking."""
 
707
        policy = self._get_user_option('check_signatures')
 
708
        if policy:
 
709
            return self._string_to_signature_policy(policy)
 
710
 
 
711
    def _get_signing_policy(self):
 
712
        """See Config._get_signing_policy"""
 
713
        policy = self._get_user_option('create_signatures')
 
714
        if policy:
 
715
            return self._string_to_signing_policy(policy)
 
716
 
 
717
    def _get_user_id(self):
 
718
        """Get the user id from the 'email' key in the current section."""
 
719
        return self._get_user_option('email')
 
720
 
 
721
    def _get_user_option(self, option_name):
 
722
        """See Config._get_user_option."""
 
723
        for (section, extra_path) in self._get_matching_sections():
 
724
            try:
 
725
                value = self._get_parser().get_value(section, option_name)
 
726
            except KeyError:
 
727
                continue
 
728
            policy = self._get_option_policy(section, option_name)
 
729
            if policy == POLICY_NONE:
 
730
                return value
 
731
            elif policy == POLICY_NORECURSE:
 
732
                # norecurse items only apply to the exact path
 
733
                if extra_path:
 
734
                    continue
 
735
                else:
 
736
                    return value
 
737
            elif policy == POLICY_APPENDPATH:
 
738
                if extra_path:
 
739
                    value = urlutils.join(value, extra_path)
 
740
                return value
 
741
            else:
 
742
                raise AssertionError('Unexpected config policy %r' % policy)
 
743
        else:
 
744
            return None
 
745
 
 
746
    def _gpg_signing_command(self):
 
747
        """See Config.gpg_signing_command."""
 
748
        return self._get_user_option('gpg_signing_command')
 
749
 
 
750
    def _log_format(self):
 
751
        """See Config.log_format."""
 
752
        return self._get_user_option('log_format')
 
753
 
 
754
    def _post_commit(self):
 
755
        """See Config.post_commit."""
 
756
        return self._get_user_option('post_commit')
 
757
 
 
758
    def _string_to_signature_policy(self, signature_string):
 
759
        """Convert a string to a signing policy."""
 
760
        if signature_string.lower() == 'check-available':
 
761
            return CHECK_IF_POSSIBLE
 
762
        if signature_string.lower() == 'ignore':
 
763
            return CHECK_NEVER
 
764
        if signature_string.lower() == 'require':
 
765
            return CHECK_ALWAYS
 
766
        raise errors.BzrError("Invalid signatures policy '%s'"
 
767
                              % signature_string)
 
768
 
 
769
    def _string_to_signing_policy(self, signature_string):
 
770
        """Convert a string to a signing policy."""
 
771
        if signature_string.lower() == 'when-required':
 
772
            return SIGN_WHEN_REQUIRED
 
773
        if signature_string.lower() == 'never':
 
774
            return SIGN_NEVER
 
775
        if signature_string.lower() == 'always':
 
776
            return SIGN_ALWAYS
 
777
        raise errors.BzrError("Invalid signing policy '%s'"
 
778
                              % signature_string)
 
779
 
 
780
    def _get_alias(self, value):
 
781
        try:
 
782
            return self._get_parser().get_value("ALIASES",
 
783
                                                value)
 
784
        except KeyError:
 
785
            pass
 
786
 
 
787
    def _get_nickname(self):
 
788
        return self.get_user_option('nickname')
 
789
 
 
790
    def remove_user_option(self, option_name, section_name=None):
 
791
        """Remove a user option and save the configuration file.
 
792
 
 
793
        :param option_name: The option to be removed.
 
794
 
 
795
        :param section_name: The section the option is defined in, default to
 
796
            the default section.
 
797
        """
 
798
        self.reload()
 
799
        parser = self._get_parser()
 
800
        if section_name is None:
 
801
            section = parser
 
802
        else:
 
803
            section = parser[section_name]
 
804
        try:
 
805
            del section[option_name]
 
806
        except KeyError:
 
807
            raise errors.NoSuchConfigOption(option_name)
 
808
        self._write_config_file()
 
809
 
 
810
    def _write_config_file(self):
 
811
        if self.file_name is None:
 
812
            raise AssertionError('We cannot save, self.file_name is None')
 
813
        conf_dir = os.path.dirname(self.file_name)
 
814
        ensure_config_dir_exists(conf_dir)
 
815
        atomic_file = atomicfile.AtomicFile(self.file_name)
 
816
        self._get_parser().write(atomic_file)
 
817
        atomic_file.commit()
 
818
        atomic_file.close()
 
819
        osutils.copy_ownership_from_path(self.file_name)
 
820
 
 
821
 
 
822
class LockableConfig(IniBasedConfig):
 
823
    """A configuration needing explicit locking for access.
 
824
 
 
825
    If several processes try to write the config file, the accesses need to be
 
826
    serialized.
 
827
 
 
828
    Daughter classes should decorate all methods that update a config with the
 
829
    ``@needs_write_lock`` decorator (they call, directly or indirectly, the
 
830
    ``_write_config_file()`` method. These methods (typically ``set_option()``
 
831
    and variants must reload the config file from disk before calling
 
832
    ``_write_config_file()``), this can be achieved by calling the
 
833
    ``self.reload()`` method. Note that the lock scope should cover both the
 
834
    reading and the writing of the config file which is why the decorator can't
 
835
    be applied to ``_write_config_file()`` only.
 
836
 
 
837
    This should be enough to implement the following logic:
 
838
    - lock for exclusive write access,
 
839
    - reload the config file from disk,
 
840
    - set the new value
 
841
    - unlock
 
842
 
 
843
    This logic guarantees that a writer can update a value without erasing an
 
844
    update made by another writer.
 
845
    """
 
846
 
 
847
    lock_name = 'lock'
 
848
 
 
849
    def __init__(self, file_name):
 
850
        super(LockableConfig, self).__init__(file_name=file_name)
 
851
        self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
 
852
        # FIXME: It doesn't matter that we don't provide possible_transports
 
853
        # below since this is currently used only for local config files ;
 
854
        # local transports are not shared. But if/when we start using
 
855
        # LockableConfig for other kind of transports, we will need to reuse
 
856
        # whatever connection is already established -- vila 20100929
 
857
        self.transport = transport.get_transport(self.dir)
 
858
        self._lock = lockdir.LockDir(self.transport, self.lock_name)
 
859
 
 
860
    def _create_from_string(self, unicode_bytes, save):
 
861
        super(LockableConfig, self)._create_from_string(unicode_bytes, False)
 
862
        if save:
 
863
            # We need to handle the saving here (as opposed to IniBasedConfig)
 
864
            # to be able to lock
 
865
            self.lock_write()
 
866
            self._write_config_file()
 
867
            self.unlock()
 
868
 
 
869
    def lock_write(self, token=None):
 
870
        """Takes a write lock in the directory containing the config file.
 
871
 
 
872
        If the directory doesn't exist it is created.
 
873
        """
 
874
        ensure_config_dir_exists(self.dir)
 
875
        return self._lock.lock_write(token)
 
876
 
 
877
    def unlock(self):
 
878
        self._lock.unlock()
 
879
 
 
880
    def break_lock(self):
 
881
        self._lock.break_lock()
 
882
 
 
883
    @needs_write_lock
 
884
    def remove_user_option(self, option_name, section_name=None):
 
885
        super(LockableConfig, self).remove_user_option(option_name,
 
886
                                                       section_name)
 
887
 
 
888
    def _write_config_file(self):
 
889
        if self._lock is None or not self._lock.is_held:
 
890
            # NB: if the following exception is raised it probably means a
 
891
            # missing @needs_write_lock decorator on one of the callers.
 
892
            raise errors.ObjectNotLocked(self)
 
893
        super(LockableConfig, self)._write_config_file()
 
894
 
 
895
 
 
896
class GlobalConfig(LockableConfig):
 
897
    """The configuration that should be used for a specific location."""
 
898
 
 
899
    def __init__(self):
 
900
        super(GlobalConfig, self).__init__(file_name=config_filename())
 
901
 
 
902
    def config_id(self):
 
903
        return 'bazaar'
 
904
 
 
905
    @classmethod
 
906
    def from_string(cls, str_or_unicode, save=False):
 
907
        """Create a config object from a string.
 
908
 
 
909
        :param str_or_unicode: A string representing the file content. This
 
910
            will be utf-8 encoded.
 
911
 
 
912
        :param save: Whether the file should be saved upon creation.
 
913
        """
 
914
        conf = cls()
 
915
        conf._create_from_string(str_or_unicode, save)
 
916
        return conf
 
917
 
 
918
    @deprecated_method(deprecated_in((2, 4, 0)))
 
919
    def get_editor(self):
 
920
        return self._get_user_option('editor')
 
921
 
 
922
    @needs_write_lock
 
923
    def set_user_option(self, option, value):
 
924
        """Save option and its value in the configuration."""
 
925
        self._set_option(option, value, 'DEFAULT')
 
926
 
 
927
    def get_aliases(self):
 
928
        """Return the aliases section."""
 
929
        if 'ALIASES' in self._get_parser():
 
930
            return self._get_parser()['ALIASES']
 
931
        else:
 
932
            return {}
 
933
 
 
934
    @needs_write_lock
 
935
    def set_alias(self, alias_name, alias_command):
 
936
        """Save the alias in the configuration."""
 
937
        self._set_option(alias_name, alias_command, 'ALIASES')
 
938
 
 
939
    @needs_write_lock
 
940
    def unset_alias(self, alias_name):
 
941
        """Unset an existing alias."""
 
942
        self.reload()
 
943
        aliases = self._get_parser().get('ALIASES')
 
944
        if not aliases or alias_name not in aliases:
 
945
            raise errors.NoSuchAlias(alias_name)
 
946
        del aliases[alias_name]
 
947
        self._write_config_file()
 
948
 
 
949
    def _set_option(self, option, value, section):
 
950
        self.reload()
 
951
        self._get_parser().setdefault(section, {})[option] = value
 
952
        self._write_config_file()
 
953
 
 
954
 
 
955
    def _get_sections(self, name=None):
 
956
        """See IniBasedConfig._get_sections()."""
 
957
        parser = self._get_parser()
 
958
        # We don't give access to options defined outside of any section, we
 
959
        # used the DEFAULT section by... default.
 
960
        if name in (None, 'DEFAULT'):
 
961
            # This could happen for an empty file where the DEFAULT section
 
962
            # doesn't exist yet. So we force DEFAULT when yielding
 
963
            name = 'DEFAULT'
 
964
            if 'DEFAULT' not in parser:
 
965
               parser['DEFAULT']= {}
 
966
        yield (name, parser[name], self.config_id())
 
967
 
 
968
    @needs_write_lock
 
969
    def remove_user_option(self, option_name, section_name=None):
 
970
        if section_name is None:
 
971
            # We need to force the default section.
 
972
            section_name = 'DEFAULT'
 
973
        # We need to avoid the LockableConfig implementation or we'll lock
 
974
        # twice
 
975
        super(LockableConfig, self).remove_user_option(option_name,
 
976
                                                       section_name)
 
977
 
 
978
def _iter_for_location_by_parts(sections, location):
 
979
    """Keep only the sessions matching the specified location.
 
980
 
 
981
    :param sections: An iterable of section names.
 
982
 
 
983
    :param location: An url or a local path to match against.
 
984
 
 
985
    :returns: An iterator of (section, extra_path, nb_parts) where nb is the
 
986
        number of path components in the section name, section is the section
 
987
        name and extra_path is the difference between location and the section
 
988
        name.
 
989
 
 
990
    ``location`` will always be a local path and never a 'file://' url but the
 
991
    section names themselves can be in either form.
 
992
    """
 
993
    location_parts = location.rstrip('/').split('/')
 
994
 
 
995
    for section in sections:
 
996
        # location is a local path if possible, so we need to convert 'file://'
 
997
        # urls in section names to local paths if necessary.
 
998
 
 
999
        # This also avoids having file:///path be a more exact
 
1000
        # match than '/path'.
 
1001
 
 
1002
        # FIXME: This still raises an issue if a user defines both file:///path
 
1003
        # *and* /path. Should we raise an error in this case -- vila 20110505
 
1004
 
 
1005
        if section.startswith('file://'):
 
1006
            section_path = urlutils.local_path_from_url(section)
 
1007
        else:
 
1008
            section_path = section
 
1009
        section_parts = section_path.rstrip('/').split('/')
 
1010
 
 
1011
        matched = True
 
1012
        if len(section_parts) > len(location_parts):
 
1013
            # More path components in the section, they can't match
 
1014
            matched = False
 
1015
        else:
 
1016
            # Rely on zip truncating in length to the length of the shortest
 
1017
            # argument sequence.
 
1018
            names = zip(location_parts, section_parts)
 
1019
            for name in names:
 
1020
                if not fnmatch.fnmatch(name[0], name[1]):
 
1021
                    matched = False
 
1022
                    break
 
1023
        if not matched:
 
1024
            continue
 
1025
        # build the path difference between the section and the location
 
1026
        extra_path = '/'.join(location_parts[len(section_parts):])
 
1027
        yield section, extra_path, len(section_parts)
 
1028
 
 
1029
 
 
1030
class LocationConfig(LockableConfig):
 
1031
    """A configuration object that gives the policy for a location."""
 
1032
 
 
1033
    def __init__(self, location):
 
1034
        super(LocationConfig, self).__init__(
 
1035
            file_name=locations_config_filename())
 
1036
        # local file locations are looked up by local path, rather than
 
1037
        # by file url. This is because the config file is a user
 
1038
        # file, and we would rather not expose the user to file urls.
 
1039
        if location.startswith('file://'):
 
1040
            location = urlutils.local_path_from_url(location)
 
1041
        self.location = location
 
1042
 
 
1043
    def config_id(self):
 
1044
        return 'locations'
 
1045
 
 
1046
    @classmethod
 
1047
    def from_string(cls, str_or_unicode, location, save=False):
 
1048
        """Create a config object from a string.
 
1049
 
 
1050
        :param str_or_unicode: A string representing the file content. This will
 
1051
            be utf-8 encoded.
 
1052
 
 
1053
        :param location: The location url to filter the configuration.
 
1054
 
 
1055
        :param save: Whether the file should be saved upon creation.
 
1056
        """
 
1057
        conf = cls(location)
 
1058
        conf._create_from_string(str_or_unicode, save)
 
1059
        return conf
 
1060
 
 
1061
    def _get_matching_sections(self):
 
1062
        """Return an ordered list of section names matching this location."""
 
1063
        matches = list(_iter_for_location_by_parts(self._get_parser(),
 
1064
                                                   self.location))
 
1065
        # put the longest (aka more specific) locations first
 
1066
        matches.sort(
 
1067
            key=lambda (section, extra_path, length): (length, section),
 
1068
            reverse=True)
 
1069
        for (section, extra_path, length) in matches:
 
1070
            yield section, extra_path
 
1071
            # should we stop looking for parent configs here?
 
1072
            try:
 
1073
                if self._get_parser()[section].as_bool('ignore_parents'):
 
1074
                    break
 
1075
            except KeyError:
 
1076
                pass
 
1077
 
 
1078
    def _get_sections(self, name=None):
 
1079
        """See IniBasedConfig._get_sections()."""
 
1080
        # We ignore the name here as the only sections handled are named with
 
1081
        # the location path and we don't expose embedded sections either.
 
1082
        parser = self._get_parser()
 
1083
        for name, extra_path in self._get_matching_sections():
 
1084
            yield (name, parser[name], self.config_id())
 
1085
 
 
1086
    def _get_option_policy(self, section, option_name):
 
1087
        """Return the policy for the given (section, option_name) pair."""
 
1088
        # check for the old 'recurse=False' flag
 
1089
        try:
 
1090
            recurse = self._get_parser()[section].as_bool('recurse')
 
1091
        except KeyError:
 
1092
            recurse = True
 
1093
        if not recurse:
 
1094
            return POLICY_NORECURSE
 
1095
 
 
1096
        policy_key = option_name + ':policy'
 
1097
        try:
 
1098
            policy_name = self._get_parser()[section][policy_key]
 
1099
        except KeyError:
 
1100
            policy_name = None
 
1101
 
 
1102
        return _policy_value[policy_name]
 
1103
 
 
1104
    def _set_option_policy(self, section, option_name, option_policy):
 
1105
        """Set the policy for the given option name in the given section."""
 
1106
        # The old recurse=False option affects all options in the
 
1107
        # section.  To handle multiple policies in the section, we
 
1108
        # need to convert it to a policy_norecurse key.
 
1109
        try:
 
1110
            recurse = self._get_parser()[section].as_bool('recurse')
 
1111
        except KeyError:
 
1112
            pass
 
1113
        else:
 
1114
            symbol_versioning.warn(
 
1115
                'The recurse option is deprecated as of 0.14.  '
 
1116
                'The section "%s" has been converted to use policies.'
 
1117
                % section,
 
1118
                DeprecationWarning)
 
1119
            del self._get_parser()[section]['recurse']
 
1120
            if not recurse:
 
1121
                for key in self._get_parser()[section].keys():
 
1122
                    if not key.endswith(':policy'):
 
1123
                        self._get_parser()[section][key +
 
1124
                                                    ':policy'] = 'norecurse'
 
1125
 
 
1126
        policy_key = option_name + ':policy'
 
1127
        policy_name = _policy_name[option_policy]
 
1128
        if policy_name is not None:
 
1129
            self._get_parser()[section][policy_key] = policy_name
 
1130
        else:
 
1131
            if policy_key in self._get_parser()[section]:
 
1132
                del self._get_parser()[section][policy_key]
 
1133
 
 
1134
    @needs_write_lock
 
1135
    def set_user_option(self, option, value, store=STORE_LOCATION):
 
1136
        """Save option and its value in the configuration."""
 
1137
        if store not in [STORE_LOCATION,
 
1138
                         STORE_LOCATION_NORECURSE,
 
1139
                         STORE_LOCATION_APPENDPATH]:
 
1140
            raise ValueError('bad storage policy %r for %r' %
 
1141
                (store, option))
 
1142
        self.reload()
 
1143
        location = self.location
 
1144
        if location.endswith('/'):
 
1145
            location = location[:-1]
 
1146
        parser = self._get_parser()
 
1147
        if not location in parser and not location + '/' in parser:
 
1148
            parser[location] = {}
 
1149
        elif location + '/' in parser:
 
1150
            location = location + '/'
 
1151
        parser[location][option]=value
 
1152
        # the allowed values of store match the config policies
 
1153
        self._set_option_policy(location, option, store)
 
1154
        self._write_config_file()
 
1155
 
 
1156
 
 
1157
class BranchConfig(Config):
 
1158
    """A configuration object giving the policy for a branch."""
 
1159
 
 
1160
    def __init__(self, branch):
 
1161
        super(BranchConfig, self).__init__()
 
1162
        self._location_config = None
 
1163
        self._branch_data_config = None
 
1164
        self._global_config = None
 
1165
        self.branch = branch
 
1166
        self.option_sources = (self._get_location_config,
 
1167
                               self._get_branch_data_config,
 
1168
                               self._get_global_config)
 
1169
 
 
1170
    def config_id(self):
 
1171
        return 'branch'
 
1172
 
 
1173
    def _get_branch_data_config(self):
 
1174
        if self._branch_data_config is None:
 
1175
            self._branch_data_config = TreeConfig(self.branch)
 
1176
            self._branch_data_config.config_id = self.config_id
 
1177
        return self._branch_data_config
 
1178
 
 
1179
    def _get_location_config(self):
 
1180
        if self._location_config is None:
 
1181
            self._location_config = LocationConfig(self.branch.base)
 
1182
        return self._location_config
 
1183
 
 
1184
    def _get_global_config(self):
 
1185
        if self._global_config is None:
 
1186
            self._global_config = GlobalConfig()
 
1187
        return self._global_config
 
1188
 
 
1189
    def _get_best_value(self, option_name):
 
1190
        """This returns a user option from local, tree or global config.
 
1191
 
 
1192
        They are tried in that order.  Use get_safe_value if trusted values
 
1193
        are necessary.
 
1194
        """
 
1195
        for source in self.option_sources:
 
1196
            value = getattr(source(), option_name)()
 
1197
            if value is not None:
 
1198
                return value
 
1199
        return None
 
1200
 
 
1201
    def _get_safe_value(self, option_name):
 
1202
        """This variant of get_best_value never returns untrusted values.
 
1203
 
 
1204
        It does not return values from the branch data, because the branch may
 
1205
        not be controlled by the user.
 
1206
 
 
1207
        We may wish to allow locations.conf to control whether branches are
 
1208
        trusted in the future.
 
1209
        """
 
1210
        for source in (self._get_location_config, self._get_global_config):
 
1211
            value = getattr(source(), option_name)()
 
1212
            if value is not None:
 
1213
                return value
 
1214
        return None
 
1215
 
 
1216
    def _get_user_id(self):
 
1217
        """Return the full user id for the branch.
 
1218
 
 
1219
        e.g. "John Hacker <jhacker@example.com>"
 
1220
        This is looked up in the email controlfile for the branch.
 
1221
        """
 
1222
        try:
 
1223
            return (self.branch._transport.get_bytes("email")
 
1224
                    .decode(osutils.get_user_encoding())
 
1225
                    .rstrip("\r\n"))
 
1226
        except errors.NoSuchFile, e:
 
1227
            pass
 
1228
 
 
1229
        return self._get_best_value('_get_user_id')
 
1230
 
 
1231
    def _get_change_editor(self):
 
1232
        return self._get_best_value('_get_change_editor')
 
1233
 
 
1234
    def _get_signature_checking(self):
 
1235
        """See Config._get_signature_checking."""
 
1236
        return self._get_best_value('_get_signature_checking')
 
1237
 
 
1238
    def _get_signing_policy(self):
 
1239
        """See Config._get_signing_policy."""
 
1240
        return self._get_best_value('_get_signing_policy')
 
1241
 
 
1242
    def _get_user_option(self, option_name):
 
1243
        """See Config._get_user_option."""
 
1244
        for source in self.option_sources:
 
1245
            value = source()._get_user_option(option_name)
 
1246
            if value is not None:
 
1247
                return value
 
1248
        return None
 
1249
 
 
1250
    def _get_sections(self, name=None):
 
1251
        """See IniBasedConfig.get_sections()."""
 
1252
        for source in self.option_sources:
 
1253
            for section in source()._get_sections(name):
 
1254
                yield section
 
1255
 
 
1256
    def _get_options(self, sections=None):
 
1257
        opts = []
 
1258
        # First the locations options
 
1259
        for option in self._get_location_config()._get_options():
 
1260
            yield option
 
1261
        # Then the branch options
 
1262
        branch_config = self._get_branch_data_config()
 
1263
        if sections is None:
 
1264
            sections = [('DEFAULT', branch_config._get_parser())]
 
1265
        # FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
 
1266
        # Config itself has no notion of sections :( -- vila 20101001
 
1267
        config_id = self.config_id()
 
1268
        for (section_name, section) in sections:
 
1269
            for (name, value) in section.iteritems():
 
1270
                yield (name, value, section_name,
 
1271
                       config_id, branch_config._get_parser())
 
1272
        # Then the global options
 
1273
        for option in self._get_global_config()._get_options():
 
1274
            yield option
 
1275
 
 
1276
    def set_user_option(self, name, value, store=STORE_BRANCH,
 
1277
        warn_masked=False):
 
1278
        if store == STORE_BRANCH:
 
1279
            self._get_branch_data_config().set_option(value, name)
 
1280
        elif store == STORE_GLOBAL:
 
1281
            self._get_global_config().set_user_option(name, value)
 
1282
        else:
 
1283
            self._get_location_config().set_user_option(name, value, store)
 
1284
        if not warn_masked:
 
1285
            return
 
1286
        if store in (STORE_GLOBAL, STORE_BRANCH):
 
1287
            mask_value = self._get_location_config().get_user_option(name)
 
1288
            if mask_value is not None:
 
1289
                trace.warning('Value "%s" is masked by "%s" from'
 
1290
                              ' locations.conf', value, mask_value)
 
1291
            else:
 
1292
                if store == STORE_GLOBAL:
 
1293
                    branch_config = self._get_branch_data_config()
 
1294
                    mask_value = branch_config.get_user_option(name)
 
1295
                    if mask_value is not None:
 
1296
                        trace.warning('Value "%s" is masked by "%s" from'
 
1297
                                      ' branch.conf', value, mask_value)
 
1298
 
 
1299
    def remove_user_option(self, option_name, section_name=None):
 
1300
        self._get_branch_data_config().remove_option(option_name, section_name)
 
1301
 
 
1302
    def _gpg_signing_command(self):
 
1303
        """See Config.gpg_signing_command."""
 
1304
        return self._get_safe_value('_gpg_signing_command')
 
1305
 
 
1306
    def _post_commit(self):
 
1307
        """See Config.post_commit."""
 
1308
        return self._get_safe_value('_post_commit')
 
1309
 
 
1310
    def _get_nickname(self):
 
1311
        value = self._get_explicit_nickname()
 
1312
        if value is not None:
 
1313
            return value
 
1314
        return urlutils.unescape(self.branch.base.split('/')[-2])
 
1315
 
 
1316
    def has_explicit_nickname(self):
 
1317
        """Return true if a nickname has been explicitly assigned."""
 
1318
        return self._get_explicit_nickname() is not None
 
1319
 
 
1320
    def _get_explicit_nickname(self):
 
1321
        return self._get_best_value('_get_nickname')
 
1322
 
 
1323
    def _log_format(self):
 
1324
        """See Config.log_format."""
 
1325
        return self._get_best_value('_log_format')
 
1326
 
 
1327
 
 
1328
def ensure_config_dir_exists(path=None):
 
1329
    """Make sure a configuration directory exists.
 
1330
    This makes sure that the directory exists.
 
1331
    On windows, since configuration directories are 2 levels deep,
 
1332
    it makes sure both the directory and the parent directory exists.
 
1333
    """
 
1334
    if path is None:
 
1335
        path = config_dir()
 
1336
    if not os.path.isdir(path):
 
1337
        if sys.platform == 'win32':
 
1338
            parent_dir = os.path.dirname(path)
 
1339
            if not os.path.isdir(parent_dir):
 
1340
                trace.mutter('creating config parent directory: %r', parent_dir)
 
1341
                os.mkdir(parent_dir)
 
1342
        trace.mutter('creating config directory: %r', path)
 
1343
        os.mkdir(path)
 
1344
        osutils.copy_ownership_from_path(path)
 
1345
 
 
1346
 
 
1347
def config_dir():
 
1348
    """Return per-user configuration directory.
 
1349
 
 
1350
    By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
 
1351
    and Linux.  On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
 
1352
    that will be used instead.
 
1353
 
 
1354
    TODO: Global option --config-dir to override this.
 
1355
    """
 
1356
    base = os.environ.get('BZR_HOME', None)
 
1357
    if sys.platform == 'win32':
 
1358
        # environ variables on Windows are in user encoding/mbcs. So decode
 
1359
        # before using one
 
1360
        if base is not None:
 
1361
            base = base.decode('mbcs')
 
1362
        if base is None:
 
1363
            base = win32utils.get_appdata_location_unicode()
 
1364
        if base is None:
 
1365
            base = os.environ.get('HOME', None)
 
1366
            if base is not None:
 
1367
                base = base.decode('mbcs')
 
1368
        if base is None:
 
1369
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
 
1370
                                  ' or HOME set')
 
1371
        return osutils.pathjoin(base, 'bazaar', '2.0')
 
1372
    elif sys.platform == 'darwin':
 
1373
        if base is None:
 
1374
            # this takes into account $HOME
 
1375
            base = os.path.expanduser("~")
 
1376
        return osutils.pathjoin(base, '.bazaar')
 
1377
    else:
 
1378
        if base is None:
 
1379
 
 
1380
            xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
 
1381
            if xdg_dir is None:
 
1382
                xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
 
1383
            xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
 
1384
            if osutils.isdir(xdg_dir):
 
1385
                trace.mutter(
 
1386
                    "Using configuration in XDG directory %s." % xdg_dir)
 
1387
                return xdg_dir
 
1388
 
 
1389
            base = os.path.expanduser("~")
 
1390
        return osutils.pathjoin(base, ".bazaar")
 
1391
 
 
1392
 
 
1393
def config_filename():
 
1394
    """Return per-user configuration ini file filename."""
 
1395
    return osutils.pathjoin(config_dir(), 'bazaar.conf')
 
1396
 
 
1397
 
 
1398
def locations_config_filename():
 
1399
    """Return per-user configuration ini file filename."""
 
1400
    return osutils.pathjoin(config_dir(), 'locations.conf')
 
1401
 
 
1402
 
 
1403
def authentication_config_filename():
 
1404
    """Return per-user authentication ini file filename."""
 
1405
    return osutils.pathjoin(config_dir(), 'authentication.conf')
 
1406
 
 
1407
 
 
1408
def user_ignore_config_filename():
 
1409
    """Return the user default ignore filename"""
 
1410
    return osutils.pathjoin(config_dir(), 'ignore')
 
1411
 
 
1412
 
 
1413
def crash_dir():
 
1414
    """Return the directory name to store crash files.
 
1415
 
 
1416
    This doesn't implicitly create it.
 
1417
 
 
1418
    On Windows it's in the config directory; elsewhere it's /var/crash
 
1419
    which may be monitored by apport.  It can be overridden by
 
1420
    $APPORT_CRASH_DIR.
 
1421
    """
 
1422
    if sys.platform == 'win32':
 
1423
        return osutils.pathjoin(config_dir(), 'Crash')
 
1424
    else:
 
1425
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
 
1426
        # 2010-01-31
 
1427
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
 
1428
 
 
1429
 
 
1430
def xdg_cache_dir():
 
1431
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
 
1432
    # Possibly this should be different on Windows?
 
1433
    e = os.environ.get('XDG_CACHE_DIR', None)
 
1434
    if e:
 
1435
        return e
 
1436
    else:
 
1437
        return os.path.expanduser('~/.cache')
 
1438
 
 
1439
 
 
1440
def _get_default_mail_domain():
 
1441
    """If possible, return the assumed default email domain.
 
1442
 
 
1443
    :returns: string mail domain, or None.
 
1444
    """
 
1445
    if sys.platform == 'win32':
 
1446
        # No implementation yet; patches welcome
 
1447
        return None
 
1448
    try:
 
1449
        f = open('/etc/mailname')
 
1450
    except (IOError, OSError), e:
 
1451
        return None
 
1452
    try:
 
1453
        domain = f.read().strip()
 
1454
        return domain
 
1455
    finally:
 
1456
        f.close()
 
1457
 
 
1458
 
 
1459
def _auto_user_id():
 
1460
    """Calculate automatic user identification.
 
1461
 
 
1462
    :returns: (realname, email), either of which may be None if they can't be
 
1463
    determined.
 
1464
 
 
1465
    Only used when none is set in the environment or the id file.
 
1466
 
 
1467
    This only returns an email address if we can be fairly sure the 
 
1468
    address is reasonable, ie if /etc/mailname is set on unix.
 
1469
 
 
1470
    This doesn't use the FQDN as the default domain because that may be 
 
1471
    slow, and it doesn't use the hostname alone because that's not normally 
 
1472
    a reasonable address.
 
1473
    """
 
1474
    if sys.platform == 'win32':
 
1475
        # No implementation to reliably determine Windows default mail
 
1476
        # address; please add one.
 
1477
        return None, None
 
1478
 
 
1479
    default_mail_domain = _get_default_mail_domain()
 
1480
    if not default_mail_domain:
 
1481
        return None, None
 
1482
 
 
1483
    import pwd
 
1484
    uid = os.getuid()
 
1485
    try:
 
1486
        w = pwd.getpwuid(uid)
 
1487
    except KeyError:
 
1488
        trace.mutter('no passwd entry for uid %d?' % uid)
 
1489
        return None, None
 
1490
 
 
1491
    # we try utf-8 first, because on many variants (like Linux),
 
1492
    # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
1493
    # false positives.  (many users will have their user encoding set to
 
1494
    # latin-1, which cannot raise UnicodeError.)
 
1495
    try:
 
1496
        gecos = w.pw_gecos.decode('utf-8')
 
1497
        encoding = 'utf-8'
 
1498
    except UnicodeError:
 
1499
        try:
 
1500
            encoding = osutils.get_user_encoding()
 
1501
            gecos = w.pw_gecos.decode(encoding)
 
1502
        except UnicodeError, e:
 
1503
            trace.mutter("cannot decode passwd entry %s" % w)
 
1504
            return None, None
 
1505
    try:
 
1506
        username = w.pw_name.decode(encoding)
 
1507
    except UnicodeError, e:
 
1508
        trace.mutter("cannot decode passwd entry %s" % w)
 
1509
        return None, None
 
1510
 
 
1511
    comma = gecos.find(',')
 
1512
    if comma == -1:
 
1513
        realname = gecos
 
1514
    else:
 
1515
        realname = gecos[:comma]
 
1516
 
 
1517
    return realname, (username + '@' + default_mail_domain)
 
1518
 
 
1519
 
 
1520
def parse_username(username):
 
1521
    """Parse e-mail username and return a (name, address) tuple."""
 
1522
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
 
1523
    if match is None:
 
1524
        return (username, '')
 
1525
    else:
 
1526
        return (match.group(1), match.group(2))
 
1527
 
 
1528
 
 
1529
def extract_email_address(e):
 
1530
    """Return just the address part of an email string.
 
1531
 
 
1532
    That is just the user@domain part, nothing else.
 
1533
    This part is required to contain only ascii characters.
 
1534
    If it can't be extracted, raises an error.
 
1535
 
 
1536
    >>> extract_email_address('Jane Tester <jane@test.com>')
 
1537
    "jane@test.com"
 
1538
    """
 
1539
    name, email = parse_username(e)
 
1540
    if not email:
 
1541
        raise errors.NoEmailInUsername(e)
 
1542
    return email
 
1543
 
 
1544
 
 
1545
class TreeConfig(IniBasedConfig):
 
1546
    """Branch configuration data associated with its contents, not location"""
 
1547
 
 
1548
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
 
1549
 
 
1550
    def __init__(self, branch):
 
1551
        self._config = branch._get_config()
 
1552
        self.branch = branch
 
1553
 
 
1554
    def _get_parser(self, file=None):
 
1555
        if file is not None:
 
1556
            return IniBasedConfig._get_parser(file)
 
1557
        return self._config._get_configobj()
 
1558
 
 
1559
    def get_option(self, name, section=None, default=None):
 
1560
        self.branch.lock_read()
 
1561
        try:
 
1562
            return self._config.get_option(name, section, default)
 
1563
        finally:
 
1564
            self.branch.unlock()
 
1565
 
 
1566
    def set_option(self, value, name, section=None):
 
1567
        """Set a per-branch configuration option"""
 
1568
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1569
        # higher levels providing the right lock -- vila 20101004
 
1570
        self.branch.lock_write()
 
1571
        try:
 
1572
            self._config.set_option(value, name, section)
 
1573
        finally:
 
1574
            self.branch.unlock()
 
1575
 
 
1576
    def remove_option(self, option_name, section_name=None):
 
1577
        # FIXME: We shouldn't need to lock explicitly here but rather rely on
 
1578
        # higher levels providing the right lock -- vila 20101004
 
1579
        self.branch.lock_write()
 
1580
        try:
 
1581
            self._config.remove_option(option_name, section_name)
 
1582
        finally:
 
1583
            self.branch.unlock()
 
1584
 
 
1585
 
 
1586
class AuthenticationConfig(object):
 
1587
    """The authentication configuration file based on a ini file.
 
1588
 
 
1589
    Implements the authentication.conf file described in
 
1590
    doc/developers/authentication-ring.txt.
 
1591
    """
 
1592
 
 
1593
    def __init__(self, _file=None):
 
1594
        self._config = None # The ConfigObj
 
1595
        if _file is None:
 
1596
            self._filename = authentication_config_filename()
 
1597
            self._input = self._filename = authentication_config_filename()
 
1598
        else:
 
1599
            # Tests can provide a string as _file
 
1600
            self._filename = None
 
1601
            self._input = _file
 
1602
 
 
1603
    def _get_config(self):
 
1604
        if self._config is not None:
 
1605
            return self._config
 
1606
        try:
 
1607
            # FIXME: Should we validate something here ? Includes: empty
 
1608
            # sections are useless, at least one of
 
1609
            # user/password/password_encoding should be defined, etc.
 
1610
 
 
1611
            # Note: the encoding below declares that the file itself is utf-8
 
1612
            # encoded, but the values in the ConfigObj are always Unicode.
 
1613
            self._config = ConfigObj(self._input, encoding='utf-8')
 
1614
        except configobj.ConfigObjError, e:
 
1615
            raise errors.ParseConfigError(e.errors, e.config.filename)
 
1616
        return self._config
 
1617
 
 
1618
    def _save(self):
 
1619
        """Save the config file, only tests should use it for now."""
 
1620
        conf_dir = os.path.dirname(self._filename)
 
1621
        ensure_config_dir_exists(conf_dir)
 
1622
        f = file(self._filename, 'wb')
 
1623
        try:
 
1624
            self._get_config().write(f)
 
1625
        finally:
 
1626
            f.close()
 
1627
 
 
1628
    def _set_option(self, section_name, option_name, value):
 
1629
        """Set an authentication configuration option"""
 
1630
        conf = self._get_config()
 
1631
        section = conf.get(section_name)
 
1632
        if section is None:
 
1633
            conf[section] = {}
 
1634
            section = conf[section]
 
1635
        section[option_name] = value
 
1636
        self._save()
 
1637
 
 
1638
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
 
1639
                        realm=None):
 
1640
        """Returns the matching credentials from authentication.conf file.
 
1641
 
 
1642
        :param scheme: protocol
 
1643
 
 
1644
        :param host: the server address
 
1645
 
 
1646
        :param port: the associated port (optional)
 
1647
 
 
1648
        :param user: login (optional)
 
1649
 
 
1650
        :param path: the absolute path on the server (optional)
 
1651
        
 
1652
        :param realm: the http authentication realm (optional)
 
1653
 
 
1654
        :return: A dict containing the matching credentials or None.
 
1655
           This includes:
 
1656
           - name: the section name of the credentials in the
 
1657
             authentication.conf file,
 
1658
           - user: can't be different from the provided user if any,
 
1659
           - scheme: the server protocol,
 
1660
           - host: the server address,
 
1661
           - port: the server port (can be None),
 
1662
           - path: the absolute server path (can be None),
 
1663
           - realm: the http specific authentication realm (can be None),
 
1664
           - password: the decoded password, could be None if the credential
 
1665
             defines only the user
 
1666
           - verify_certificates: https specific, True if the server
 
1667
             certificate should be verified, False otherwise.
 
1668
        """
 
1669
        credentials = None
 
1670
        for auth_def_name, auth_def in self._get_config().items():
 
1671
            if type(auth_def) is not configobj.Section:
 
1672
                raise ValueError("%s defined outside a section" % auth_def_name)
 
1673
 
 
1674
            a_scheme, a_host, a_user, a_path = map(
 
1675
                auth_def.get, ['scheme', 'host', 'user', 'path'])
 
1676
 
 
1677
            try:
 
1678
                a_port = auth_def.as_int('port')
 
1679
            except KeyError:
 
1680
                a_port = None
 
1681
            except ValueError:
 
1682
                raise ValueError("'port' not numeric in %s" % auth_def_name)
 
1683
            try:
 
1684
                a_verify_certificates = auth_def.as_bool('verify_certificates')
 
1685
            except KeyError:
 
1686
                a_verify_certificates = True
 
1687
            except ValueError:
 
1688
                raise ValueError(
 
1689
                    "'verify_certificates' not boolean in %s" % auth_def_name)
 
1690
 
 
1691
            # Attempt matching
 
1692
            if a_scheme is not None and scheme != a_scheme:
 
1693
                continue
 
1694
            if a_host is not None:
 
1695
                if not (host == a_host
 
1696
                        or (a_host.startswith('.') and host.endswith(a_host))):
 
1697
                    continue
 
1698
            if a_port is not None and port != a_port:
 
1699
                continue
 
1700
            if (a_path is not None and path is not None
 
1701
                and not path.startswith(a_path)):
 
1702
                continue
 
1703
            if (a_user is not None and user is not None
 
1704
                and a_user != user):
 
1705
                # Never contradict the caller about the user to be used
 
1706
                continue
 
1707
            if a_user is None:
 
1708
                # Can't find a user
 
1709
                continue
 
1710
            # Prepare a credentials dictionary with additional keys
 
1711
            # for the credential providers
 
1712
            credentials = dict(name=auth_def_name,
 
1713
                               user=a_user,
 
1714
                               scheme=a_scheme,
 
1715
                               host=host,
 
1716
                               port=port,
 
1717
                               path=path,
 
1718
                               realm=realm,
 
1719
                               password=auth_def.get('password', None),
 
1720
                               verify_certificates=a_verify_certificates)
 
1721
            # Decode the password in the credentials (or get one)
 
1722
            self.decode_password(credentials,
 
1723
                                 auth_def.get('password_encoding', None))
 
1724
            if 'auth' in debug.debug_flags:
 
1725
                trace.mutter("Using authentication section: %r", auth_def_name)
 
1726
            break
 
1727
 
 
1728
        if credentials is None:
 
1729
            # No credentials were found in authentication.conf, try the fallback
 
1730
            # credentials stores.
 
1731
            credentials = credential_store_registry.get_fallback_credentials(
 
1732
                scheme, host, port, user, path, realm)
 
1733
 
 
1734
        return credentials
 
1735
 
 
1736
    def set_credentials(self, name, host, user, scheme=None, password=None,
 
1737
                        port=None, path=None, verify_certificates=None,
 
1738
                        realm=None):
 
1739
        """Set authentication credentials for a host.
 
1740
 
 
1741
        Any existing credentials with matching scheme, host, port and path
 
1742
        will be deleted, regardless of name.
 
1743
 
 
1744
        :param name: An arbitrary name to describe this set of credentials.
 
1745
        :param host: Name of the host that accepts these credentials.
 
1746
        :param user: The username portion of these credentials.
 
1747
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
 
1748
            to.
 
1749
        :param password: Password portion of these credentials.
 
1750
        :param port: The IP port on the host that these credentials apply to.
 
1751
        :param path: A filesystem path on the host that these credentials
 
1752
            apply to.
 
1753
        :param verify_certificates: On https, verify server certificates if
 
1754
            True.
 
1755
        :param realm: The http authentication realm (optional).
 
1756
        """
 
1757
        values = {'host': host, 'user': user}
 
1758
        if password is not None:
 
1759
            values['password'] = password
 
1760
        if scheme is not None:
 
1761
            values['scheme'] = scheme
 
1762
        if port is not None:
 
1763
            values['port'] = '%d' % port
 
1764
        if path is not None:
 
1765
            values['path'] = path
 
1766
        if verify_certificates is not None:
 
1767
            values['verify_certificates'] = str(verify_certificates)
 
1768
        if realm is not None:
 
1769
            values['realm'] = realm
 
1770
        config = self._get_config()
 
1771
        for_deletion = []
 
1772
        for section, existing_values in config.items():
 
1773
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
 
1774
                if existing_values.get(key) != values.get(key):
 
1775
                    break
 
1776
            else:
 
1777
                del config[section]
 
1778
        config.update({name: values})
 
1779
        self._save()
 
1780
 
 
1781
    def get_user(self, scheme, host, port=None, realm=None, path=None,
 
1782
                 prompt=None, ask=False, default=None):
 
1783
        """Get a user from authentication file.
 
1784
 
 
1785
        :param scheme: protocol
 
1786
 
 
1787
        :param host: the server address
 
1788
 
 
1789
        :param port: the associated port (optional)
 
1790
 
 
1791
        :param realm: the realm sent by the server (optional)
 
1792
 
 
1793
        :param path: the absolute path on the server (optional)
 
1794
 
 
1795
        :param ask: Ask the user if there is no explicitly configured username 
 
1796
                    (optional)
 
1797
 
 
1798
        :param default: The username returned if none is defined (optional).
 
1799
 
 
1800
        :return: The found user.
 
1801
        """
 
1802
        credentials = self.get_credentials(scheme, host, port, user=None,
 
1803
                                           path=path, realm=realm)
 
1804
        if credentials is not None:
 
1805
            user = credentials['user']
 
1806
        else:
 
1807
            user = None
 
1808
        if user is None:
 
1809
            if ask:
 
1810
                if prompt is None:
 
1811
                    # Create a default prompt suitable for most cases
 
1812
                    prompt = u'%s' % (scheme.upper(),) + u' %(host)s username'
 
1813
                # Special handling for optional fields in the prompt
 
1814
                if port is not None:
 
1815
                    prompt_host = '%s:%d' % (host, port)
 
1816
                else:
 
1817
                    prompt_host = host
 
1818
                user = ui.ui_factory.get_username(prompt, host=prompt_host)
 
1819
            else:
 
1820
                user = default
 
1821
        return user
 
1822
 
 
1823
    def get_password(self, scheme, host, user, port=None,
 
1824
                     realm=None, path=None, prompt=None):
 
1825
        """Get a password from authentication file or prompt the user for one.
 
1826
 
 
1827
        :param scheme: protocol
 
1828
 
 
1829
        :param host: the server address
 
1830
 
 
1831
        :param port: the associated port (optional)
 
1832
 
 
1833
        :param user: login
 
1834
 
 
1835
        :param realm: the realm sent by the server (optional)
 
1836
 
 
1837
        :param path: the absolute path on the server (optional)
 
1838
 
 
1839
        :return: The found password or the one entered by the user.
 
1840
        """
 
1841
        credentials = self.get_credentials(scheme, host, port, user, path,
 
1842
                                           realm)
 
1843
        if credentials is not None:
 
1844
            password = credentials['password']
 
1845
            if password is not None and scheme is 'ssh':
 
1846
                trace.warning('password ignored in section [%s],'
 
1847
                              ' use an ssh agent instead'
 
1848
                              % credentials['name'])
 
1849
                password = None
 
1850
        else:
 
1851
            password = None
 
1852
        # Prompt user only if we could't find a password
 
1853
        if password is None:
 
1854
            if prompt is None:
 
1855
                # Create a default prompt suitable for most cases
 
1856
                prompt = u'%s' % scheme.upper() + u' %(user)s@%(host)s password'
 
1857
            # Special handling for optional fields in the prompt
 
1858
            if port is not None:
 
1859
                prompt_host = '%s:%d' % (host, port)
 
1860
            else:
 
1861
                prompt_host = host
 
1862
            password = ui.ui_factory.get_password(prompt,
 
1863
                                                  host=prompt_host, user=user)
 
1864
        return password
 
1865
 
 
1866
    def decode_password(self, credentials, encoding):
 
1867
        try:
 
1868
            cs = credential_store_registry.get_credential_store(encoding)
 
1869
        except KeyError:
 
1870
            raise ValueError('%r is not a known password_encoding' % encoding)
 
1871
        credentials['password'] = cs.decode_password(credentials)
 
1872
        return credentials
 
1873
 
 
1874
 
 
1875
class CredentialStoreRegistry(registry.Registry):
 
1876
    """A class that registers credential stores.
 
1877
 
 
1878
    A credential store provides access to credentials via the password_encoding
 
1879
    field in authentication.conf sections.
 
1880
 
 
1881
    Except for stores provided by bzr itself, most stores are expected to be
 
1882
    provided by plugins that will therefore use
 
1883
    register_lazy(password_encoding, module_name, member_name, help=help,
 
1884
    fallback=fallback) to install themselves.
 
1885
 
 
1886
    A fallback credential store is one that is queried if no credentials can be
 
1887
    found via authentication.conf.
 
1888
    """
 
1889
 
 
1890
    def get_credential_store(self, encoding=None):
 
1891
        cs = self.get(encoding)
 
1892
        if callable(cs):
 
1893
            cs = cs()
 
1894
        return cs
 
1895
 
 
1896
    def is_fallback(self, name):
 
1897
        """Check if the named credentials store should be used as fallback."""
 
1898
        return self.get_info(name)
 
1899
 
 
1900
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
 
1901
                                 path=None, realm=None):
 
1902
        """Request credentials from all fallback credentials stores.
 
1903
 
 
1904
        The first credentials store that can provide credentials wins.
 
1905
        """
 
1906
        credentials = None
 
1907
        for name in self.keys():
 
1908
            if not self.is_fallback(name):
 
1909
                continue
 
1910
            cs = self.get_credential_store(name)
 
1911
            credentials = cs.get_credentials(scheme, host, port, user,
 
1912
                                             path, realm)
 
1913
            if credentials is not None:
 
1914
                # We found some credentials
 
1915
                break
 
1916
        return credentials
 
1917
 
 
1918
    def register(self, key, obj, help=None, override_existing=False,
 
1919
                 fallback=False):
 
1920
        """Register a new object to a name.
 
1921
 
 
1922
        :param key: This is the key to use to request the object later.
 
1923
        :param obj: The object to register.
 
1924
        :param help: Help text for this entry. This may be a string or
 
1925
                a callable. If it is a callable, it should take two
 
1926
                parameters (registry, key): this registry and the key that
 
1927
                the help was registered under.
 
1928
        :param override_existing: Raise KeyErorr if False and something has
 
1929
                already been registered for that key. If True, ignore if there
 
1930
                is an existing key (always register the new value).
 
1931
        :param fallback: Whether this credential store should be 
 
1932
                used as fallback.
 
1933
        """
 
1934
        return super(CredentialStoreRegistry,
 
1935
                     self).register(key, obj, help, info=fallback,
 
1936
                                    override_existing=override_existing)
 
1937
 
 
1938
    def register_lazy(self, key, module_name, member_name,
 
1939
                      help=None, override_existing=False,
 
1940
                      fallback=False):
 
1941
        """Register a new credential store to be loaded on request.
 
1942
 
 
1943
        :param module_name: The python path to the module. Such as 'os.path'.
 
1944
        :param member_name: The member of the module to return.  If empty or
 
1945
                None, get() will return the module itself.
 
1946
        :param help: Help text for this entry. This may be a string or
 
1947
                a callable.
 
1948
        :param override_existing: If True, replace the existing object
 
1949
                with the new one. If False, if there is already something
 
1950
                registered with the same key, raise a KeyError
 
1951
        :param fallback: Whether this credential store should be 
 
1952
                used as fallback.
 
1953
        """
 
1954
        return super(CredentialStoreRegistry, self).register_lazy(
 
1955
            key, module_name, member_name, help,
 
1956
            info=fallback, override_existing=override_existing)
 
1957
 
 
1958
 
 
1959
credential_store_registry = CredentialStoreRegistry()
 
1960
 
 
1961
 
 
1962
class CredentialStore(object):
 
1963
    """An abstract class to implement storage for credentials"""
 
1964
 
 
1965
    def decode_password(self, credentials):
 
1966
        """Returns a clear text password for the provided credentials."""
 
1967
        raise NotImplementedError(self.decode_password)
 
1968
 
 
1969
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
 
1970
                        realm=None):
 
1971
        """Return the matching credentials from this credential store.
 
1972
 
 
1973
        This method is only called on fallback credential stores.
 
1974
        """
 
1975
        raise NotImplementedError(self.get_credentials)
 
1976
 
 
1977
 
 
1978
 
 
1979
class PlainTextCredentialStore(CredentialStore):
 
1980
    __doc__ = """Plain text credential store for the authentication.conf file"""
 
1981
 
 
1982
    def decode_password(self, credentials):
 
1983
        """See CredentialStore.decode_password."""
 
1984
        return credentials['password']
 
1985
 
 
1986
 
 
1987
credential_store_registry.register('plain', PlainTextCredentialStore,
 
1988
                                   help=PlainTextCredentialStore.__doc__)
 
1989
credential_store_registry.default_key = 'plain'
 
1990
 
 
1991
 
 
1992
class BzrDirConfig(object):
 
1993
 
 
1994
    def __init__(self, bzrdir):
 
1995
        self._bzrdir = bzrdir
 
1996
        self._config = bzrdir._get_config()
 
1997
 
 
1998
    def set_default_stack_on(self, value):
 
1999
        """Set the default stacking location.
 
2000
 
 
2001
        It may be set to a location, or None.
 
2002
 
 
2003
        This policy affects all branches contained by this bzrdir, except for
 
2004
        those under repositories.
 
2005
        """
 
2006
        if self._config is None:
 
2007
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
 
2008
        if value is None:
 
2009
            self._config.set_option('', 'default_stack_on')
 
2010
        else:
 
2011
            self._config.set_option(value, 'default_stack_on')
 
2012
 
 
2013
    def get_default_stack_on(self):
 
2014
        """Return the default stacking location.
 
2015
 
 
2016
        This will either be a location, or None.
 
2017
 
 
2018
        This policy affects all branches contained by this bzrdir, except for
 
2019
        those under repositories.
 
2020
        """
 
2021
        if self._config is None:
 
2022
            return None
 
2023
        value = self._config.get_option('default_stack_on')
 
2024
        if value == '':
 
2025
            value = None
 
2026
        return value
 
2027
 
 
2028
 
 
2029
class TransportConfig(object):
 
2030
    """A Config that reads/writes a config file on a Transport.
 
2031
 
 
2032
    It is a low-level object that considers config data to be name/value pairs
 
2033
    that may be associated with a section.  Assigning meaning to these values
 
2034
    is done at higher levels like TreeConfig.
 
2035
    """
 
2036
 
 
2037
    def __init__(self, transport, filename):
 
2038
        self._transport = transport
 
2039
        self._filename = filename
 
2040
 
 
2041
    def get_option(self, name, section=None, default=None):
 
2042
        """Return the value associated with a named option.
 
2043
 
 
2044
        :param name: The name of the value
 
2045
        :param section: The section the option is in (if any)
 
2046
        :param default: The value to return if the value is not set
 
2047
        :return: The value or default value
 
2048
        """
 
2049
        configobj = self._get_configobj()
 
2050
        if section is None:
 
2051
            section_obj = configobj
 
2052
        else:
 
2053
            try:
 
2054
                section_obj = configobj[section]
 
2055
            except KeyError:
 
2056
                return default
 
2057
        return section_obj.get(name, default)
 
2058
 
 
2059
    def set_option(self, value, name, section=None):
 
2060
        """Set the value associated with a named option.
 
2061
 
 
2062
        :param value: The value to set
 
2063
        :param name: The name of the value to set
 
2064
        :param section: The section the option is in (if any)
 
2065
        """
 
2066
        configobj = self._get_configobj()
 
2067
        if section is None:
 
2068
            configobj[name] = value
 
2069
        else:
 
2070
            configobj.setdefault(section, {})[name] = value
 
2071
        self._set_configobj(configobj)
 
2072
 
 
2073
    def remove_option(self, option_name, section_name=None):
 
2074
        configobj = self._get_configobj()
 
2075
        if section_name is None:
 
2076
            del configobj[option_name]
 
2077
        else:
 
2078
            del configobj[section_name][option_name]
 
2079
        self._set_configobj(configobj)
 
2080
 
 
2081
    def _get_config_file(self):
 
2082
        try:
 
2083
            return StringIO(self._transport.get_bytes(self._filename))
 
2084
        except errors.NoSuchFile:
 
2085
            return StringIO()
 
2086
 
 
2087
    def _get_configobj(self):
 
2088
        f = self._get_config_file()
 
2089
        try:
 
2090
            return ConfigObj(f, encoding='utf-8')
 
2091
        finally:
 
2092
            f.close()
 
2093
 
 
2094
    def _set_configobj(self, configobj):
 
2095
        out_file = StringIO()
 
2096
        configobj.write(out_file)
 
2097
        out_file.seek(0)
 
2098
        self._transport.put_file(self._filename, out_file)
 
2099
 
 
2100
 
 
2101
class Option(object):
 
2102
    """An option definition.
 
2103
 
 
2104
    The option *values* are stored in config files and found in sections.
 
2105
 
 
2106
    Here we define various properties about the option itself, its default
 
2107
    value, in which config files it can be stored, etc (TBC).
 
2108
    """
 
2109
 
 
2110
    def __init__(self, name, default=None):
 
2111
        self.name = name
 
2112
        self.default = default
 
2113
 
 
2114
    def get_default(self):
 
2115
        return self.default
 
2116
 
 
2117
 
 
2118
# Options registry
 
2119
 
 
2120
option_registry = registry.Registry()
 
2121
 
 
2122
 
 
2123
option_registry.register(
 
2124
    'editor', Option('editor'),
 
2125
    help='The command called to launch an editor to enter a message.')
 
2126
 
 
2127
 
 
2128
class Section(object):
 
2129
    """A section defines a dict of option name => value.
 
2130
 
 
2131
    This is merely a read-only dict which can add some knowledge about the
 
2132
    options. It is *not* a python dict object though and doesn't try to mimic
 
2133
    its API.
 
2134
    """
 
2135
 
 
2136
    def __init__(self, section_id, options):
 
2137
        self.id = section_id
 
2138
        # We re-use the dict-like object received
 
2139
        self.options = options
 
2140
 
 
2141
    def get(self, name, default=None):
 
2142
        return self.options.get(name, default)
 
2143
 
 
2144
    def __repr__(self):
 
2145
        # Mostly for debugging use
 
2146
        return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
 
2147
 
 
2148
 
 
2149
_NewlyCreatedOption = object()
 
2150
"""Was the option created during the MutableSection lifetime"""
 
2151
 
 
2152
 
 
2153
class MutableSection(Section):
 
2154
    """A section allowing changes and keeping track of the original values."""
 
2155
 
 
2156
    def __init__(self, section_id, options):
 
2157
        super(MutableSection, self).__init__(section_id, options)
 
2158
        self.orig = {}
 
2159
 
 
2160
    def set(self, name, value):
 
2161
        if name not in self.options:
 
2162
            # This is a new option
 
2163
            self.orig[name] = _NewlyCreatedOption
 
2164
        elif name not in self.orig:
 
2165
            self.orig[name] = self.get(name, None)
 
2166
        self.options[name] = value
 
2167
 
 
2168
    def remove(self, name):
 
2169
        if name not in self.orig:
 
2170
            self.orig[name] = self.get(name, None)
 
2171
        del self.options[name]
 
2172
 
 
2173
 
 
2174
class Store(object):
 
2175
    """Abstract interface to persistent storage for configuration options."""
 
2176
 
 
2177
    readonly_section_class = Section
 
2178
    mutable_section_class = MutableSection
 
2179
 
 
2180
    def is_loaded(self):
 
2181
        """Returns True if the Store has been loaded.
 
2182
 
 
2183
        This is used to implement lazy loading and ensure the persistent
 
2184
        storage is queried only when needed.
 
2185
        """
 
2186
        raise NotImplementedError(self.is_loaded)
 
2187
 
 
2188
    def load(self):
 
2189
        """Loads the Store from persistent storage."""
 
2190
        raise NotImplementedError(self.load)
 
2191
 
 
2192
    def _load_from_string(self, str_or_unicode):
 
2193
        """Create a store from a string in configobj syntax.
 
2194
 
 
2195
        :param str_or_unicode: A string representing the file content. This will
 
2196
            be encoded to suit store needs internally.
 
2197
 
 
2198
        This is for tests and should not be used in production unless a
 
2199
        convincing use case can be demonstrated :)
 
2200
        """
 
2201
        raise NotImplementedError(self._load_from_string)
 
2202
 
 
2203
    def unload(self):
 
2204
        """Unloads the Store.
 
2205
 
 
2206
        This should make is_loaded() return False. This is used when the caller
 
2207
        knows that the persistent storage has changed or may have change since
 
2208
        the last load.
 
2209
        """
 
2210
        raise NotImplementedError(self.unload)
 
2211
 
 
2212
    def save(self):
 
2213
        """Saves the Store to persistent storage."""
 
2214
        raise NotImplementedError(self.save)
 
2215
 
 
2216
    def external_url(self):
 
2217
        raise NotImplementedError(self.external_url)
 
2218
 
 
2219
    def get_sections(self):
 
2220
        """Returns an ordered iterable of existing sections.
 
2221
 
 
2222
        :returns: An iterable of (name, dict).
 
2223
        """
 
2224
        raise NotImplementedError(self.get_sections)
 
2225
 
 
2226
    def get_mutable_section(self, section_name=None):
 
2227
        """Returns the specified mutable section.
 
2228
 
 
2229
        :param section_name: The section identifier
 
2230
        """
 
2231
        raise NotImplementedError(self.get_mutable_section)
 
2232
 
 
2233
    def __repr__(self):
 
2234
        # Mostly for debugging use
 
2235
        return "<config.%s(%s)>" % (self.__class__.__name__,
 
2236
                                    self.external_url())
 
2237
 
 
2238
 
 
2239
class IniFileStore(Store):
 
2240
    """A config Store using ConfigObj for storage.
 
2241
 
 
2242
    :ivar transport: The transport object where the config file is located.
 
2243
 
 
2244
    :ivar file_name: The config file basename in the transport directory.
 
2245
 
 
2246
    :ivar _config_obj: Private member to hold the ConfigObj instance used to
 
2247
        serialize/deserialize the config file.
 
2248
    """
 
2249
 
 
2250
    def __init__(self, transport, file_name):
 
2251
        """A config Store using ConfigObj for storage.
 
2252
 
 
2253
        :param transport: The transport object where the config file is located.
 
2254
 
 
2255
        :param file_name: The config file basename in the transport directory.
 
2256
        """
 
2257
        super(IniFileStore, self).__init__()
 
2258
        self.transport = transport
 
2259
        self.file_name = file_name
 
2260
        self._config_obj = None
 
2261
 
 
2262
    def is_loaded(self):
 
2263
        return self._config_obj != None
 
2264
 
 
2265
    def unload(self):
 
2266
        self._config_obj = None
 
2267
 
 
2268
    def load(self):
 
2269
        """Load the store from the associated file."""
 
2270
        if self.is_loaded():
 
2271
            return
 
2272
        content = self.transport.get_bytes(self.file_name)
 
2273
        self._load_from_string(content)
 
2274
 
 
2275
    def _load_from_string(self, str_or_unicode):
 
2276
        """Create a config store from a string.
 
2277
 
 
2278
        :param str_or_unicode: A string representing the file content. This will
 
2279
            be utf-8 encoded internally.
 
2280
 
 
2281
        This is for tests and should not be used in production unless a
 
2282
        convincing use case can be demonstrated :)
 
2283
        """
 
2284
        if self.is_loaded():
 
2285
            raise AssertionError('Already loaded: %r' % (self._config_obj,))
 
2286
        co_input = StringIO(str_or_unicode.encode('utf-8'))
 
2287
        try:
 
2288
            # The config files are always stored utf8-encoded
 
2289
            self._config_obj = ConfigObj(co_input, encoding='utf-8')
 
2290
        except configobj.ConfigObjError, e:
 
2291
            self._config_obj = None
 
2292
            raise errors.ParseConfigError(e.errors, self.external_url())
 
2293
 
 
2294
    def save(self):
 
2295
        if not self.is_loaded():
 
2296
            # Nothing to save
 
2297
            return
 
2298
        out = StringIO()
 
2299
        self._config_obj.write(out)
 
2300
        self.transport.put_bytes(self.file_name, out.getvalue())
 
2301
 
 
2302
    def external_url(self):
 
2303
        # FIXME: external_url should really accepts an optional relpath
 
2304
        # parameter (bug #750169) :-/ -- vila 2011-04-04
 
2305
        # The following will do in the interim but maybe we don't want to
 
2306
        # expose a path here but rather a config ID and its associated
 
2307
        # object </hand wawe>.
 
2308
        return urlutils.join(self.transport.external_url(), self.file_name)
 
2309
 
 
2310
    def get_sections(self):
 
2311
        """Get the configobj section in the file order.
 
2312
 
 
2313
        :returns: An iterable of (name, dict).
 
2314
        """
 
2315
        # We need a loaded store
 
2316
        try:
 
2317
            self.load()
 
2318
        except errors.NoSuchFile:
 
2319
            # If the file doesn't exist, there is no sections
 
2320
            return
 
2321
        cobj = self._config_obj
 
2322
        if cobj.scalars:
 
2323
            yield self.readonly_section_class(None, cobj)
 
2324
        for section_name in cobj.sections:
 
2325
            yield self.readonly_section_class(section_name, cobj[section_name])
 
2326
 
 
2327
    def get_mutable_section(self, section_name=None):
 
2328
        # We need a loaded store
 
2329
        try:
 
2330
            self.load()
 
2331
        except errors.NoSuchFile:
 
2332
            # The file doesn't exist, let's pretend it was empty
 
2333
            self._load_from_string('')
 
2334
        if section_name is None:
 
2335
            section = self._config_obj
 
2336
        else:
 
2337
            section = self._config_obj.setdefault(section_name, {})
 
2338
        return self.mutable_section_class(section_name, section)
 
2339
 
 
2340
 
 
2341
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
 
2342
# unlockable stores for use with objects that can already ensure the locking
 
2343
# (think branches). If different stores (not based on ConfigObj) are created,
 
2344
# they may face the same issue.
 
2345
 
 
2346
 
 
2347
class LockableIniFileStore(IniFileStore):
 
2348
    """A ConfigObjStore using locks on save to ensure store integrity."""
 
2349
 
 
2350
    def __init__(self, transport, file_name, lock_dir_name=None):
 
2351
        """A config Store using ConfigObj for storage.
 
2352
 
 
2353
        :param transport: The transport object where the config file is located.
 
2354
 
 
2355
        :param file_name: The config file basename in the transport directory.
 
2356
        """
 
2357
        if lock_dir_name is None:
 
2358
            lock_dir_name = 'lock'
 
2359
        self.lock_dir_name = lock_dir_name
 
2360
        super(LockableIniFileStore, self).__init__(transport, file_name)
 
2361
        self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
 
2362
 
 
2363
    def lock_write(self, token=None):
 
2364
        """Takes a write lock in the directory containing the config file.
 
2365
 
 
2366
        If the directory doesn't exist it is created.
 
2367
        """
 
2368
        # FIXME: This doesn't check the ownership of the created directories as
 
2369
        # ensure_config_dir_exists does. It should if the transport is local
 
2370
        # -- vila 2011-04-06
 
2371
        self.transport.create_prefix()
 
2372
        return self._lock.lock_write(token)
 
2373
 
 
2374
    def unlock(self):
 
2375
        self._lock.unlock()
 
2376
 
 
2377
    def break_lock(self):
 
2378
        self._lock.break_lock()
 
2379
 
 
2380
    @needs_write_lock
 
2381
    def save(self):
 
2382
        # We need to be able to override the undecorated implementation
 
2383
        self.save_without_locking()
 
2384
 
 
2385
    def save_without_locking(self):
 
2386
        super(LockableIniFileStore, self).save()
 
2387
 
 
2388
 
 
2389
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
 
2390
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
 
2391
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
 
2392
 
 
2393
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
 
2394
# functions or a registry will make it easier and clearer for tests, focusing
 
2395
# on the relevant parts of the API that needs testing -- vila 20110503 (based
 
2396
# on a poolie's remark)
 
2397
class GlobalStore(LockableIniFileStore):
 
2398
 
 
2399
    def __init__(self, possible_transports=None):
 
2400
        t = transport.get_transport(config_dir(),
 
2401
                                    possible_transports=possible_transports)
 
2402
        super(GlobalStore, self).__init__(t, 'bazaar.conf')
 
2403
 
 
2404
 
 
2405
class LocationStore(LockableIniFileStore):
 
2406
 
 
2407
    def __init__(self, possible_transports=None):
 
2408
        t = transport.get_transport(config_dir(),
 
2409
                                    possible_transports=possible_transports)
 
2410
        super(LocationStore, self).__init__(t, 'locations.conf')
 
2411
 
 
2412
 
 
2413
class BranchStore(IniFileStore):
 
2414
 
 
2415
    def __init__(self, branch):
 
2416
        super(BranchStore, self).__init__(branch.control_transport,
 
2417
                                          'branch.conf')
 
2418
        self.branch = branch
 
2419
 
 
2420
    def lock_write(self, token=None):
 
2421
        return self.branch.lock_write(token)
 
2422
 
 
2423
    def unlock(self):
 
2424
        return self.branch.unlock()
 
2425
 
 
2426
    @needs_write_lock
 
2427
    def save(self):
 
2428
        # We need to be able to override the undecorated implementation
 
2429
        self.save_without_locking()
 
2430
 
 
2431
    def save_without_locking(self):
 
2432
        super(BranchStore, self).save()
 
2433
 
 
2434
 
 
2435
class SectionMatcher(object):
 
2436
    """Select sections into a given Store.
 
2437
 
 
2438
    This intended to be used to postpone getting an iterable of sections from a
 
2439
    store.
 
2440
    """
 
2441
 
 
2442
    def __init__(self, store):
 
2443
        self.store = store
 
2444
 
 
2445
    def get_sections(self):
 
2446
        # This is where we require loading the store so we can see all defined
 
2447
        # sections.
 
2448
        sections = self.store.get_sections()
 
2449
        # Walk the revisions in the order provided
 
2450
        for s in sections:
 
2451
            if self.match(s):
 
2452
                yield s
 
2453
 
 
2454
    def match(self, secion):
 
2455
        raise NotImplementedError(self.match)
 
2456
 
 
2457
 
 
2458
class LocationSection(Section):
 
2459
 
 
2460
    def __init__(self, section, length, extra_path):
 
2461
        super(LocationSection, self).__init__(section.id, section.options)
 
2462
        self.length = length
 
2463
        self.extra_path = extra_path
 
2464
 
 
2465
    def get(self, name, default=None):
 
2466
        value = super(LocationSection, self).get(name, default)
 
2467
        if value is not None:
 
2468
            policy_name = self.get(name + ':policy', None)
 
2469
            policy = _policy_value.get(policy_name, POLICY_NONE)
 
2470
            if policy == POLICY_APPENDPATH:
 
2471
                value = urlutils.join(value, self.extra_path)
 
2472
        return value
 
2473
 
 
2474
 
 
2475
class LocationMatcher(SectionMatcher):
 
2476
 
 
2477
    def __init__(self, store, location):
 
2478
        super(LocationMatcher, self).__init__(store)
 
2479
        if location.startswith('file://'):
 
2480
            location = urlutils.local_path_from_url(location)
 
2481
        self.location = location
 
2482
 
 
2483
    def _get_matching_sections(self):
 
2484
        """Get all sections matching ``location``."""
 
2485
        # We slightly diverge from LocalConfig here by allowing the no-name
 
2486
        # section as the most generic one and the lower priority.
 
2487
        no_name_section = None
 
2488
        sections = []
 
2489
        # Filter out the no_name_section so _iter_for_location_by_parts can be
 
2490
        # used (it assumes all sections have a name).
 
2491
        for section in self.store.get_sections():
 
2492
            if section.id is None:
 
2493
                no_name_section = section
 
2494
            else:
 
2495
                sections.append(section)
 
2496
        # Unfortunately _iter_for_location_by_parts deals with section names so
 
2497
        # we have to resync.
 
2498
        filtered_sections = _iter_for_location_by_parts(
 
2499
            [s.id for s in sections], self.location)
 
2500
        iter_sections = iter(sections)
 
2501
        matching_sections = []
 
2502
        if no_name_section is not None:
 
2503
            matching_sections.append(
 
2504
                LocationSection(no_name_section, 0, self.location))
 
2505
        for section_id, extra_path, length in filtered_sections:
 
2506
            # a section id is unique for a given store so it's safe to iterate
 
2507
            # again
 
2508
            section = iter_sections.next()
 
2509
            if section_id == section.id:
 
2510
                matching_sections.append(
 
2511
                    LocationSection(section, length, extra_path))
 
2512
        return matching_sections
 
2513
 
 
2514
    def get_sections(self):
 
2515
        # Override the default implementation as we want to change the order
 
2516
        matching_sections = self._get_matching_sections()
 
2517
        # We want the longest (aka more specific) locations first
 
2518
        sections = sorted(matching_sections,
 
2519
                          key=lambda section: (section.length, section.id),
 
2520
                          reverse=True)
 
2521
        # Sections mentioning 'ignore_parents' restrict the selection
 
2522
        for section in sections:
 
2523
            # FIXME: We really want to use as_bool below -- vila 2011-04-07
 
2524
            ignore = section.get('ignore_parents', None)
 
2525
            if ignore is not None:
 
2526
                ignore = ui.bool_from_string(ignore)
 
2527
            if ignore:
 
2528
                break
 
2529
            # Finally, we have a valid section
 
2530
            yield section
 
2531
 
 
2532
 
 
2533
class Stack(object):
 
2534
    """A stack of configurations where an option can be defined"""
 
2535
 
 
2536
    def __init__(self, sections_def, store=None, mutable_section_name=None):
 
2537
        """Creates a stack of sections with an optional store for changes.
 
2538
 
 
2539
        :param sections_def: A list of Section or callables that returns an
 
2540
            iterable of Section. This defines the Sections for the Stack and
 
2541
            can be called repeatedly if needed.
 
2542
 
 
2543
        :param store: The optional Store where modifications will be
 
2544
            recorded. If none is specified, no modifications can be done.
 
2545
 
 
2546
        :param mutable_section_name: The name of the MutableSection where
 
2547
            changes are recorded. This requires the ``store`` parameter to be
 
2548
            specified.
 
2549
        """
 
2550
        self.sections_def = sections_def
 
2551
        self.store = store
 
2552
        self.mutable_section_name = mutable_section_name
 
2553
 
 
2554
    def get(self, name):
 
2555
        """Return the *first* option value found in the sections.
 
2556
 
 
2557
        This is where we guarantee that sections coming from Store are loaded
 
2558
        lazily: the loading is delayed until we need to either check that an
 
2559
        option exists or get its value, which in turn may require to discover
 
2560
        in which sections it can be defined. Both of these (section and option
 
2561
        existence) require loading the store (even partially).
 
2562
        """
 
2563
        # FIXME: No caching of options nor sections yet -- vila 20110503
 
2564
        value = None
 
2565
        # Ensuring lazy loading is achieved by delaying section matching (which
 
2566
        # implies querying the persistent storage) until it can't be avoided
 
2567
        # anymore by using callables to describe (possibly empty) section
 
2568
        # lists.
 
2569
        for section_or_callable in self.sections_def:
 
2570
            # Each section can expand to multiple ones when a callable is used
 
2571
            if callable(section_or_callable):
 
2572
                sections = section_or_callable()
 
2573
            else:
 
2574
                sections = [section_or_callable]
 
2575
            for section in sections:
 
2576
                value = section.get(name)
 
2577
                if value is not None:
 
2578
                    break
 
2579
            if value is not None:
 
2580
                break
 
2581
        if value is None:
 
2582
            # If the option is registered, it may provide a default value
 
2583
            try:
 
2584
                opt = option_registry.get(name)
 
2585
            except KeyError:
 
2586
                # Not registered
 
2587
                opt = None
 
2588
            if opt is not None:
 
2589
                value = opt.get_default()
 
2590
        return value
 
2591
 
 
2592
    def _get_mutable_section(self):
 
2593
        """Get the MutableSection for the Stack.
 
2594
 
 
2595
        This is where we guarantee that the mutable section is lazily loaded:
 
2596
        this means we won't load the corresponding store before setting a value
 
2597
        or deleting an option. In practice the store will often be loaded but
 
2598
        this allows helps catching some programming errors.
 
2599
        """
 
2600
        section = self.store.get_mutable_section(self.mutable_section_name)
 
2601
        return section
 
2602
 
 
2603
    def set(self, name, value):
 
2604
        """Set a new value for the option."""
 
2605
        section = self._get_mutable_section()
 
2606
        section.set(name, value)
 
2607
 
 
2608
    def remove(self, name):
 
2609
        """Remove an existing option."""
 
2610
        section = self._get_mutable_section()
 
2611
        section.remove(name)
 
2612
 
 
2613
    def __repr__(self):
 
2614
        # Mostly for debugging use
 
2615
        return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
 
2616
 
 
2617
 
 
2618
class _CompatibleStack(Stack):
 
2619
    """Place holder for compatibility with previous design.
 
2620
 
 
2621
    This is intended to ease the transition from the Config-based design to the
 
2622
    Stack-based design and should not be used nor relied upon by plugins.
 
2623
 
 
2624
    One assumption made here is that the daughter classes will all use Stores
 
2625
    derived from LockableIniFileStore).
 
2626
 
 
2627
    It implements set() by re-loading the store before applying the
 
2628
    modification and saving it.
 
2629
 
 
2630
    The long term plan being to implement a single write by store to save
 
2631
    all modifications, this class should not be used in the interim.
 
2632
    """
 
2633
 
 
2634
    def set(self, name, value):
 
2635
        # Force a reload
 
2636
        self.store.unload()
 
2637
        super(_CompatibleStack, self).set(name, value)
 
2638
        # Force a write to persistent storage
 
2639
        self.store.save()
 
2640
 
 
2641
 
 
2642
class GlobalStack(_CompatibleStack):
 
2643
 
 
2644
    def __init__(self):
 
2645
        # Get a GlobalStore
 
2646
        gstore = GlobalStore()
 
2647
        super(GlobalStack, self).__init__([gstore.get_sections], gstore)
 
2648
 
 
2649
 
 
2650
class LocationStack(_CompatibleStack):
 
2651
 
 
2652
    def __init__(self, location):
 
2653
        lstore = LocationStore()
 
2654
        matcher = LocationMatcher(lstore, location)
 
2655
        gstore = GlobalStore()
 
2656
        super(LocationStack, self).__init__(
 
2657
            [matcher.get_sections, gstore.get_sections], lstore)
 
2658
 
 
2659
class BranchStack(_CompatibleStack):
 
2660
 
 
2661
    def __init__(self, branch):
 
2662
        bstore = BranchStore(branch)
 
2663
        lstore = LocationStore()
 
2664
        matcher = LocationMatcher(lstore, branch.base)
 
2665
        gstore = GlobalStore()
 
2666
        super(BranchStack, self).__init__(
 
2667
            [matcher.get_sections, bstore.get_sections, gstore.get_sections],
 
2668
            bstore)
 
2669
        self.branch = branch
 
2670
 
 
2671
 
 
2672
class cmd_config(commands.Command):
 
2673
    __doc__ = """Display, set or remove a configuration option.
 
2674
 
 
2675
    Display the active value for a given option.
 
2676
 
 
2677
    If --all is specified, NAME is interpreted as a regular expression and all
 
2678
    matching options are displayed mentioning their scope. The active value
 
2679
    that bzr will take into account is the first one displayed for each option.
 
2680
 
 
2681
    If no NAME is given, --all .* is implied.
 
2682
 
 
2683
    Setting a value is achieved by using name=value without spaces. The value
 
2684
    is set in the most relevant scope and can be checked by displaying the
 
2685
    option again.
 
2686
    """
 
2687
 
 
2688
    takes_args = ['name?']
 
2689
 
 
2690
    takes_options = [
 
2691
        'directory',
 
2692
        # FIXME: This should be a registry option so that plugins can register
 
2693
        # their own config files (or not) -- vila 20101002
 
2694
        commands.Option('scope', help='Reduce the scope to the specified'
 
2695
                        ' configuration file',
 
2696
                        type=unicode),
 
2697
        commands.Option('all',
 
2698
            help='Display all the defined values for the matching options.',
 
2699
            ),
 
2700
        commands.Option('remove', help='Remove the option from'
 
2701
                        ' the configuration file'),
 
2702
        ]
 
2703
 
 
2704
    @commands.display_command
 
2705
    def run(self, name=None, all=False, directory=None, scope=None,
 
2706
            remove=False):
 
2707
        if directory is None:
 
2708
            directory = '.'
 
2709
        directory = urlutils.normalize_url(directory)
 
2710
        if remove and all:
 
2711
            raise errors.BzrError(
 
2712
                '--all and --remove are mutually exclusive.')
 
2713
        elif remove:
 
2714
            # Delete the option in the given scope
 
2715
            self._remove_config_option(name, directory, scope)
 
2716
        elif name is None:
 
2717
            # Defaults to all options
 
2718
            self._show_matching_options('.*', directory, scope)
 
2719
        else:
 
2720
            try:
 
2721
                name, value = name.split('=', 1)
 
2722
            except ValueError:
 
2723
                # Display the option(s) value(s)
 
2724
                if all:
 
2725
                    self._show_matching_options(name, directory, scope)
 
2726
                else:
 
2727
                    self._show_value(name, directory, scope)
 
2728
            else:
 
2729
                if all:
 
2730
                    raise errors.BzrError(
 
2731
                        'Only one option can be set.')
 
2732
                # Set the option value
 
2733
                self._set_config_option(name, value, directory, scope)
 
2734
 
 
2735
    def _get_configs(self, directory, scope=None):
 
2736
        """Iterate the configurations specified by ``directory`` and ``scope``.
 
2737
 
 
2738
        :param directory: Where the configurations are derived from.
 
2739
 
 
2740
        :param scope: A specific config to start from.
 
2741
        """
 
2742
        if scope is not None:
 
2743
            if scope == 'bazaar':
 
2744
                yield GlobalConfig()
 
2745
            elif scope == 'locations':
 
2746
                yield LocationConfig(directory)
 
2747
            elif scope == 'branch':
 
2748
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2749
                    directory)
 
2750
                yield br.get_config()
 
2751
        else:
 
2752
            try:
 
2753
                (_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
 
2754
                    directory)
 
2755
                yield br.get_config()
 
2756
            except errors.NotBranchError:
 
2757
                yield LocationConfig(directory)
 
2758
                yield GlobalConfig()
 
2759
 
 
2760
    def _show_value(self, name, directory, scope):
 
2761
        displayed = False
 
2762
        for c in self._get_configs(directory, scope):
 
2763
            if displayed:
 
2764
                break
 
2765
            for (oname, value, section, conf_id, parser) in c._get_options():
 
2766
                if name == oname:
 
2767
                    # Display only the first value and exit
 
2768
 
 
2769
                    # FIXME: We need to use get_user_option to take policies
 
2770
                    # into account and we need to make sure the option exists
 
2771
                    # too (hence the two for loops), this needs a better API
 
2772
                    # -- vila 20101117
 
2773
                    value = c.get_user_option(name)
 
2774
                    # Quote the value appropriately
 
2775
                    value = parser._quote(value)
 
2776
                    self.outf.write('%s\n' % (value,))
 
2777
                    displayed = True
 
2778
                    break
 
2779
        if not displayed:
 
2780
            raise errors.NoSuchConfigOption(name)
 
2781
 
 
2782
    def _show_matching_options(self, name, directory, scope):
 
2783
        name = re.compile(name)
 
2784
        # We want any error in the regexp to be raised *now* so we need to
 
2785
        # avoid the delay introduced by the lazy regexp.
 
2786
        name._compile_and_collapse()
 
2787
        cur_conf_id = None
 
2788
        cur_section = None
 
2789
        for c in self._get_configs(directory, scope):
 
2790
            for (oname, value, section, conf_id, parser) in c._get_options():
 
2791
                if name.search(oname):
 
2792
                    if cur_conf_id != conf_id:
 
2793
                        # Explain where the options are defined
 
2794
                        self.outf.write('%s:\n' % (conf_id,))
 
2795
                        cur_conf_id = conf_id
 
2796
                        cur_section = None
 
2797
                    if (section not in (None, 'DEFAULT')
 
2798
                        and cur_section != section):
 
2799
                        # Display the section if it's not the default (or only)
 
2800
                        # one.
 
2801
                        self.outf.write('  [%s]\n' % (section,))
 
2802
                        cur_section = section
 
2803
                    self.outf.write('  %s = %s\n' % (oname, value))
 
2804
 
 
2805
    def _set_config_option(self, name, value, directory, scope):
 
2806
        for conf in self._get_configs(directory, scope):
 
2807
            conf.set_user_option(name, value)
 
2808
            break
 
2809
        else:
 
2810
            raise errors.NoSuchConfig(scope)
 
2811
 
 
2812
    def _remove_config_option(self, name, directory, scope):
 
2813
        if name is None:
 
2814
            raise errors.BzrCommandError(
 
2815
                '--remove expects an option to remove.')
 
2816
        removed = False
 
2817
        for conf in self._get_configs(directory, scope):
 
2818
            for (section_name, section, conf_id) in conf._get_sections():
 
2819
                if scope is not None and conf_id != scope:
 
2820
                    # Not the right configuration file
 
2821
                    continue
 
2822
                if name in section:
 
2823
                    if conf_id != conf.config_id():
 
2824
                        conf = self._get_configs(directory, conf_id).next()
 
2825
                    # We use the first section in the first config where the
 
2826
                    # option is defined to remove it
 
2827
                    conf.remove_user_option(name, section_name)
 
2828
                    removed = True
 
2829
                    break
 
2830
            break
 
2831
        else:
 
2832
            raise errors.NoSuchConfig(scope)
 
2833
        if not removed:
 
2834
            raise errors.NoSuchConfigOption(name)
 
2835
 
 
2836
# Test registries
 
2837
#
 
2838
# We need adapters that can build a Store or a Stack in a test context. Test
 
2839
# classes, based on TestCaseWithTransport, can use the registry to parametrize
 
2840
# themselves. The builder will receive a test instance and should return a
 
2841
# ready-to-use store or stack.  Plugins that define new store/stacks can also
 
2842
# register themselves here to be tested against the tests defined in
 
2843
# bzrlib.tests.test_config. Note that the builder can be called multiple times
 
2844
# for the same tests.
 
2845
 
 
2846
# The registered object should be a callable receiving a test instance
 
2847
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
 
2848
# object.
 
2849
test_store_builder_registry = registry.Registry()
 
2850
 
 
2851
# The registered object should be a callable receiving a test instance
 
2852
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
 
2853
# object.
 
2854
test_stack_builder_registry = registry.Registry()