~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Jelmer Vernooij
  • Date: 2012-01-27 19:05:43 UTC
  • mto: This revision was merged to the branch mainline in revision 6450.
  • Revision ID: jelmer@samba.org-20120127190543-vk350mv4a0c7aug2
Fix weave test.

Show diffs side-by-side

added added

removed removed

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