1508
2248
configobj[name] = value
1510
2250
configobj.setdefault(section, {})[name] = value
2251
for hook in OldConfigHooks['set']:
2252
hook(self, name, value)
2253
self._set_configobj(configobj)
2255
def remove_option(self, option_name, section_name=None):
2256
configobj = self._get_configobj()
2257
if section_name is None:
2258
del configobj[option_name]
2260
del configobj[section_name][option_name]
2261
for hook in OldConfigHooks['remove']:
2262
hook(self, option_name)
1511
2263
self._set_configobj(configobj)
1513
2265
def _get_config_file(self):
1515
return StringIO(self._transport.get_bytes(self._filename))
2267
f = BytesIO(self._transport.get_bytes(self._filename))
2268
for hook in OldConfigHooks['load']:
1516
2271
except errors.NoSuchFile:
2273
except errors.PermissionDenied as e:
2274
trace.warning("Permission denied while trying to open "
2275
"configuration file %s.", urlutils.unescape_for_display(
2276
urlutils.join(self._transport.base, self._filename), "utf-8"))
2279
def _external_url(self):
2280
return urlutils.join(self._transport.external_url(), self._filename)
1519
2282
def _get_configobj(self):
1520
return ConfigObj(self._get_config_file(), encoding='utf-8')
2283
f = self._get_config_file()
2286
conf = ConfigObj(f, encoding='utf-8')
2287
except configobj.ConfigObjError as e:
2288
raise ParseConfigError(e.errors, self._external_url())
2289
except UnicodeDecodeError:
2290
raise ConfigContentError(self._external_url())
1522
2295
def _set_configobj(self, configobj):
1523
out_file = StringIO()
2296
out_file = BytesIO()
1524
2297
configobj.write(out_file)
1525
2298
out_file.seek(0)
1526
2299
self._transport.put_file(self._filename, out_file)
2300
for hook in OldConfigHooks['save']:
2304
class Option(object):
2305
"""An option definition.
2307
The option *values* are stored in config files and found in sections.
2309
Here we define various properties about the option itself, its default
2310
value, how to convert it from stores, what to do when invalid values are
2311
encoutered, in which config files it can be stored.
2314
def __init__(self, name, override_from_env=None,
2315
default=None, default_from_env=None,
2316
help=None, from_unicode=None, invalid=None, unquote=True):
2317
"""Build an option definition.
2319
:param name: the name used to refer to the option.
2321
:param override_from_env: A list of environment variables which can
2322
provide override any configuration setting.
2324
:param default: the default value to use when none exist in the config
2325
stores. This is either a string that ``from_unicode`` will convert
2326
into the proper type, a callable returning a unicode string so that
2327
``from_unicode`` can be used on the return value, or a python
2328
object that can be stringified (so only the empty list is supported
2331
:param default_from_env: A list of environment variables which can
2332
provide a default value. 'default' will be used only if none of the
2333
variables specified here are set in the environment.
2335
:param help: a doc string to explain the option to the user.
2337
:param from_unicode: a callable to convert the unicode string
2338
representing the option value in a store or its default value.
2340
:param invalid: the action to be taken when an invalid value is
2341
encountered in a store. This is called only when from_unicode is
2342
invoked to convert a string and returns None or raise ValueError or
2343
TypeError. Accepted values are: None (ignore invalid values),
2344
'warning' (emit a warning), 'error' (emit an error message and
2347
:param unquote: should the unicode value be unquoted before conversion.
2348
This should be used only when the store providing the values cannot
2349
safely unquote them (see http://pad.lv/906897). It is provided so
2350
daughter classes can handle the quoting themselves.
2352
if override_from_env is None:
2353
override_from_env = []
2354
if default_from_env is None:
2355
default_from_env = []
2357
self.override_from_env = override_from_env
2358
# Convert the default value to a unicode string so all values are
2359
# strings internally before conversion (via from_unicode) is attempted.
2362
elif isinstance(default, list):
2363
# Only the empty list is supported
2365
raise AssertionError(
2366
'Only empty lists are supported as default values')
2368
elif isinstance(default, (binary_type, text_type, bool, int, float)):
2369
# Rely on python to convert strings, booleans and integers
2370
self.default = u'%s' % (default,)
2371
elif callable(default):
2372
self.default = default
2374
# other python objects are not expected
2375
raise AssertionError('%r is not supported as a default value'
2377
self.default_from_env = default_from_env
2379
self.from_unicode = from_unicode
2380
self.unquote = unquote
2381
if invalid and invalid not in ('warning', 'error'):
2382
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2383
self.invalid = invalid
2389
def convert_from_unicode(self, store, unicode_value):
2390
if self.unquote and store is not None and unicode_value is not None:
2391
unicode_value = store.unquote(unicode_value)
2392
if self.from_unicode is None or unicode_value is None:
2393
# Don't convert or nothing to convert
2394
return unicode_value
2396
converted = self.from_unicode(unicode_value)
2397
except (ValueError, TypeError):
2398
# Invalid values are ignored
2400
if converted is None and self.invalid is not None:
2401
# The conversion failed
2402
if self.invalid == 'warning':
2403
trace.warning('Value "%s" is not valid for "%s"',
2404
unicode_value, self.name)
2405
elif self.invalid == 'error':
2406
raise ConfigOptionValueError(self.name, unicode_value)
2409
def get_override(self):
2411
for var in self.override_from_env:
2413
# If the env variable is defined, its value takes precedence
2414
value = os.environ[var].decode(osutils.get_user_encoding())
2420
def get_default(self):
2422
for var in self.default_from_env:
2424
# If the env variable is defined, its value is the default one
2425
value = os.environ[var]
2427
value = value.decode(osutils.get_user_encoding())
2432
# Otherwise, fallback to the value defined at registration
2433
if callable(self.default):
2434
value = self.default()
2435
if not isinstance(value, text_type):
2436
raise AssertionError(
2437
"Callable default value for '%s' should be unicode"
2440
value = self.default
2443
def get_help_topic(self):
2446
def get_help_text(self, additional_see_also=None, plain=True):
2448
from breezy import help_topics
2449
result += help_topics._format_see_also(additional_see_also)
2451
result = help_topics.help_as_plain_text(result)
2455
# Predefined converters to get proper values from store
2457
def bool_from_store(unicode_str):
2458
return ui.bool_from_string(unicode_str)
2461
def int_from_store(unicode_str):
2462
return int(unicode_str)
2465
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
2467
def int_SI_from_store(unicode_str):
2468
"""Convert a human readable size in SI units, e.g 10MB into an integer.
2470
Accepted suffixes are K,M,G. It is case-insensitive and may be followed
2471
by a trailing b (i.e. Kb, MB). This is intended to be practical and not
2474
:return Integer, expanded to its base-10 value if a proper SI unit is
2475
found, None otherwise.
2477
regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
2478
p = re.compile(regexp, re.IGNORECASE)
2479
m = p.match(unicode_str)
2482
val, _, unit = m.groups()
2486
coeff = _unit_suffixes[unit.upper()]
2488
raise ValueError(gettext('{0} is not an SI unit.').format(unit))
2493
def float_from_store(unicode_str):
2494
return float(unicode_str)
2497
# Use an empty dict to initialize an empty configobj avoiding all parsing and
2499
_list_converter_config = configobj.ConfigObj(
2500
{}, encoding='utf-8', list_values=True, interpolation=False)
2503
class ListOption(Option):
2505
def __init__(self, name, default=None, default_from_env=None,
2506
help=None, invalid=None):
2507
"""A list Option definition.
2509
This overrides the base class so the conversion from a unicode string
2510
can take quoting into account.
2512
super(ListOption, self).__init__(
2513
name, default=default, default_from_env=default_from_env,
2514
from_unicode=self.from_unicode, help=help,
2515
invalid=invalid, unquote=False)
2517
def from_unicode(self, unicode_str):
2518
if not isinstance(unicode_str, string_types):
2520
# Now inject our string directly as unicode. All callers got their
2521
# value from configobj, so values that need to be quoted are already
2523
_list_converter_config.reset()
2524
_list_converter_config._parse([u"list=%s" % (unicode_str,)])
2525
maybe_list = _list_converter_config['list']
2526
if isinstance(maybe_list, string_types):
2528
# A single value, most probably the user forgot (or didn't care
2529
# to add) the final ','
2532
# The empty string, convert to empty list
2535
# We rely on ConfigObj providing us with a list already
2540
class RegistryOption(Option):
2541
"""Option for a choice from a registry."""
2543
def __init__(self, name, registry, default_from_env=None,
2544
help=None, invalid=None):
2545
"""A registry based Option definition.
2547
This overrides the base class so the conversion from a unicode string
2548
can take quoting into account.
2550
super(RegistryOption, self).__init__(
2551
name, default=lambda: unicode(registry.default_key),
2552
default_from_env=default_from_env,
2553
from_unicode=self.from_unicode, help=help,
2554
invalid=invalid, unquote=False)
2555
self.registry = registry
2557
def from_unicode(self, unicode_str):
2558
if not isinstance(unicode_str, string_types):
2561
return self.registry.get(unicode_str)
2564
"Invalid value %s for %s."
2565
"See help for a list of possible values." % (unicode_str,
2570
ret = [self._help, "\n\nThe following values are supported:\n"]
2571
for key in self.registry.keys():
2572
ret.append(" %s - %s\n" % (key, self.registry.get_help(key)))
2576
_option_ref_re = lazy_regex.lazy_compile('({[^\d\W](?:\.\w|-\w|\w)*})')
2577
"""Describes an expandable option reference.
2579
We want to match the most embedded reference first.
2581
I.e. for '{{foo}}' we will get '{foo}',
2582
for '{bar{baz}}' we will get '{baz}'
2585
def iter_option_refs(string):
2586
# Split isolate refs so every other chunk is a ref
2588
for chunk in _option_ref_re.split(string):
2593
class OptionRegistry(registry.Registry):
2594
"""Register config options by their name.
2596
This overrides ``registry.Registry`` to simplify registration by acquiring
2597
some information from the option object itself.
2600
def _check_option_name(self, option_name):
2601
"""Ensures an option name is valid.
2603
:param option_name: The name to validate.
2605
if _option_ref_re.match('{%s}' % option_name) is None:
2606
raise IllegalOptionName(option_name)
2608
def register(self, option):
2609
"""Register a new option to its name.
2611
:param option: The option to register. Its name is used as the key.
2613
self._check_option_name(option.name)
2614
super(OptionRegistry, self).register(option.name, option,
2617
def register_lazy(self, key, module_name, member_name):
2618
"""Register a new option to be loaded on request.
2620
:param key: the key to request the option later. Since the registration
2621
is lazy, it should be provided and match the option name.
2623
:param module_name: the python path to the module. Such as 'os.path'.
2625
:param member_name: the member of the module to return. If empty or
2626
None, get() will return the module itself.
2628
self._check_option_name(key)
2629
super(OptionRegistry, self).register_lazy(key,
2630
module_name, member_name)
2632
def get_help(self, key=None):
2633
"""Get the help text associated with the given key"""
2634
option = self.get(key)
2635
the_help = option.help
2636
if callable(the_help):
2637
return the_help(self, key)
2641
option_registry = OptionRegistry()
2644
# Registered options in lexicographical order
2646
option_registry.register(
2647
Option('append_revisions_only',
2648
default=None, from_unicode=bool_from_store, invalid='warning',
2650
Whether to only append revisions to the mainline.
2652
If this is set to true, then it is not possible to change the
2653
existing mainline of the branch.
2655
option_registry.register(
2656
ListOption('acceptable_keys',
2659
List of GPG key patterns which are acceptable for verification.
2661
option_registry.register(
2662
Option('add.maximum_file_size',
2663
default=u'20MB', from_unicode=int_SI_from_store,
2665
Size above which files should be added manually.
2667
Files below this size are added automatically when using ``bzr add`` without
2670
A negative value means disable the size check.
2672
option_registry.register(
2674
default=None, from_unicode=bool_from_store,
2676
Is the branch bound to ``bound_location``.
2678
If set to "True", the branch should act as a checkout, and push each commit to
2679
the bound_location. This option is normally set by ``bind``/``unbind``.
2681
See also: bound_location.
2683
option_registry.register(
2684
Option('bound_location',
2687
The location that commits should go to when acting as a checkout.
2689
This option is normally set by ``bind``.
2693
option_registry.register(
2694
Option('branch.fetch_tags', default=False, from_unicode=bool_from_store,
2696
Whether revisions associated with tags should be fetched.
2698
option_registry.register_lazy(
2699
'bzr.transform.orphan_policy', 'breezy.transform', 'opt_transform_orphan')
2700
option_registry.register(
2701
Option('bzr.workingtree.worth_saving_limit', default=10,
2702
from_unicode=int_from_store, invalid='warning',
2704
How many changes before saving the dirstate.
2706
-1 means that we will never rewrite the dirstate file for only
2707
stat-cache changes. Regardless of this setting, we will always rewrite
2708
the dirstate file if a file is added/removed/renamed/etc. This flag only
2709
affects the behavior of updating the dirstate file after we notice that
2710
a file has been touched.
2712
option_registry.register(
2713
Option('bugtracker', default=None,
2715
Default bug tracker to use.
2717
This bug tracker will be used for example when marking bugs
2718
as fixed using ``bzr commit --fixes``, if no explicit
2719
bug tracker was specified.
2721
option_registry.register(
2722
Option('check_signatures', default=CHECK_IF_POSSIBLE,
2723
from_unicode=signature_policy_from_unicode,
2725
GPG checking policy.
2727
Possible values: require, ignore, check-available (default)
2729
this option will control whether bzr will require good gpg
2730
signatures, ignore them, or check them if they are
2733
option_registry.register(
2734
Option('child_submit_format',
2735
help='''The preferred format of submissions to this branch.'''))
2736
option_registry.register(
2737
Option('child_submit_to',
2738
help='''Where submissions to this branch are mailed to.'''))
2739
option_registry.register(
2740
Option('create_signatures', default=SIGN_WHEN_REQUIRED,
2741
from_unicode=signing_policy_from_unicode,
2745
Possible values: always, never, when-required (default)
2747
This option controls whether bzr will always create
2748
gpg signatures or not on commits.
2750
option_registry.register(
2751
Option('dirstate.fdatasync', default=True,
2752
from_unicode=bool_from_store,
2754
Flush dirstate changes onto physical disk?
2756
If true (default), working tree metadata changes are flushed through the
2757
OS buffers to physical disk. This is somewhat slower, but means data
2758
should not be lost if the machine crashes. See also repository.fdatasync.
2760
option_registry.register(
2761
ListOption('debug_flags', default=[],
2762
help='Debug flags to activate.'))
2763
option_registry.register(
2764
Option('default_format', default='2a',
2765
help='Format used when creating branches.'))
2766
option_registry.register(
2767
Option('dpush_strict', default=None,
2768
from_unicode=bool_from_store,
2770
The default value for ``dpush --strict``.
2772
If present, defines the ``--strict`` option default value for checking
2773
uncommitted changes before pushing into a different VCS without any
2774
custom bzr metadata.
2776
option_registry.register(
2778
help='The command called to launch an editor to enter a message.'))
2779
option_registry.register(
2780
Option('email', override_from_env=['BRZ_EMAIL'], default=default_email,
2781
help='The users identity'))
2782
option_registry.register(
2783
Option('gpg_signing_key',
2786
GPG key to use for signing.
2788
This defaults to the first key associated with the users email.
2790
option_registry.register(
2792
help='Language to translate messages into.'))
2793
option_registry.register(
2794
Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2796
Steal locks that appears to be dead.
2798
If set to True, bzr will check if a lock is supposed to be held by an
2799
active process from the same user on the same machine. If the user and
2800
machine match, but no process with the given PID is active, then bzr
2801
will automatically break the stale lock, and create a new lock for
2803
Otherwise, bzr will prompt as normal to break the lock.
2805
option_registry.register(
2806
Option('log_format', default='long',
2808
Log format to use when displaying revisions.
2810
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
2811
may be provided by plugins.
2813
option_registry.register_lazy('mail_client', 'breezy.mail_client',
2815
option_registry.register(
2816
Option('output_encoding',
2817
help= 'Unicode encoding for output'
2818
' (terminal encoding if not specified).'))
2819
option_registry.register(
2820
Option('parent_location',
2823
The location of the default branch for pull or merge.
2825
This option is normally set when creating a branch, the first ``pull`` or by
2826
``pull --remember``.
2828
option_registry.register(
2829
Option('post_commit', default=None,
2831
Post commit functions.
2833
An ordered list of python functions to call, separated by spaces.
2835
Each function takes branch, rev_id as parameters.
2837
option_registry.register_lazy('progress_bar', 'breezy.ui.text',
2839
option_registry.register(
2840
Option('public_branch',
2843
A publically-accessible version of this branch.
2845
This implies that the branch setting this option is not publically-accessible.
2846
Used and set by ``bzr send``.
2848
option_registry.register(
2849
Option('push_location',
2852
The location of the default branch for push.
2854
This option is normally set by the first ``push`` or ``push --remember``.
2856
option_registry.register(
2857
Option('push_strict', default=None,
2858
from_unicode=bool_from_store,
2860
The default value for ``push --strict``.
2862
If present, defines the ``--strict`` option default value for checking
2863
uncommitted changes before sending a merge directive.
2865
option_registry.register(
2866
Option('repository.fdatasync', default=True,
2867
from_unicode=bool_from_store,
2869
Flush repository changes onto physical disk?
2871
If true (default), repository changes are flushed through the OS buffers
2872
to physical disk. This is somewhat slower, but means data should not be
2873
lost if the machine crashes. See also dirstate.fdatasync.
2875
option_registry.register_lazy('smtp_server',
2876
'breezy.smtp_connection', 'smtp_server')
2877
option_registry.register_lazy('smtp_password',
2878
'breezy.smtp_connection', 'smtp_password')
2879
option_registry.register_lazy('smtp_username',
2880
'breezy.smtp_connection', 'smtp_username')
2881
option_registry.register(
2882
Option('selftest.timeout',
2884
from_unicode=int_from_store,
2885
help='Abort selftest if one test takes longer than this many seconds',
2888
option_registry.register(
2889
Option('send_strict', default=None,
2890
from_unicode=bool_from_store,
2892
The default value for ``send --strict``.
2894
If present, defines the ``--strict`` option default value for checking
2895
uncommitted changes before sending a bundle.
2898
option_registry.register(
2899
Option('serve.client_timeout',
2900
default=300.0, from_unicode=float_from_store,
2901
help="If we wait for a new request from a client for more than"
2902
" X seconds, consider the client idle, and hangup."))
2903
option_registry.register(
2904
Option('stacked_on_location',
2906
help="""The location where this branch is stacked on."""))
2907
option_registry.register(
2908
Option('submit_branch',
2911
The branch you intend to submit your current work to.
2913
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
2914
by the ``submit:`` revision spec.
2916
option_registry.register(
2918
help='''Where submissions from this branch are mailed to.'''))
2919
option_registry.register(
2920
ListOption('suppress_warnings',
2922
help="List of warning classes to suppress."))
2923
option_registry.register(
2924
Option('validate_signatures_in_log', default=False,
2925
from_unicode=bool_from_store, invalid='warning',
2926
help='''Whether to validate signatures in brz log.'''))
2927
option_registry.register_lazy('ssl.ca_certs',
2928
'breezy.transport.http._urllib2_wrappers', 'opt_ssl_ca_certs')
2930
option_registry.register_lazy('ssl.cert_reqs',
2931
'breezy.transport.http._urllib2_wrappers', 'opt_ssl_cert_reqs')
2934
class Section(object):
2935
"""A section defines a dict of option name => value.
2937
This is merely a read-only dict which can add some knowledge about the
2938
options. It is *not* a python dict object though and doesn't try to mimic
2942
def __init__(self, section_id, options):
2943
self.id = section_id
2944
# We re-use the dict-like object received
2945
self.options = options
2947
def get(self, name, default=None, expand=True):
2948
return self.options.get(name, default)
2950
def iter_option_names(self):
2951
for k in self.options.keys():
2955
# Mostly for debugging use
2956
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2959
_NewlyCreatedOption = object()
2960
"""Was the option created during the MutableSection lifetime"""
2961
_DeletedOption = object()
2962
"""Was the option deleted during the MutableSection lifetime"""
2965
class MutableSection(Section):
2966
"""A section allowing changes and keeping track of the original values."""
2968
def __init__(self, section_id, options):
2969
super(MutableSection, self).__init__(section_id, options)
2970
self.reset_changes()
2972
def set(self, name, value):
2973
if name not in self.options:
2974
# This is a new option
2975
self.orig[name] = _NewlyCreatedOption
2976
elif name not in self.orig:
2977
self.orig[name] = self.get(name, None)
2978
self.options[name] = value
2980
def remove(self, name):
2981
if name not in self.orig and name in self.options:
2982
self.orig[name] = self.get(name, None)
2983
del self.options[name]
2985
def reset_changes(self):
2988
def apply_changes(self, dirty, store):
2989
"""Apply option value changes.
2991
``self`` has been reloaded from the persistent storage. ``dirty``
2992
contains the changes made since the previous loading.
2994
:param dirty: the mutable section containing the changes.
2996
:param store: the store containing the section
2998
for k, expected in dirty.orig.items():
2999
actual = dirty.get(k, _DeletedOption)
3000
reloaded = self.get(k, _NewlyCreatedOption)
3001
if actual is _DeletedOption:
3002
if k in self.options:
3006
# Report concurrent updates in an ad-hoc way. This should only
3007
# occurs when different processes try to update the same option
3008
# which is not supported (as in: the config framework is not meant
3009
# to be used as a sharing mechanism).
3010
if expected != reloaded:
3011
if actual is _DeletedOption:
3012
actual = '<DELETED>'
3013
if reloaded is _NewlyCreatedOption:
3014
reloaded = '<CREATED>'
3015
if expected is _NewlyCreatedOption:
3016
expected = '<CREATED>'
3017
# Someone changed the value since we get it from the persistent
3019
trace.warning(gettext(
3020
"Option {0} in section {1} of {2} was changed"
3021
" from {3} to {4}. The {5} value will be saved.".format(
3022
k, self.id, store.external_url(), expected,
3024
# No need to keep track of these changes
3025
self.reset_changes()
3028
class Store(object):
3029
"""Abstract interface to persistent storage for configuration options."""
3031
readonly_section_class = Section
3032
mutable_section_class = MutableSection
3035
# Which sections need to be saved (by section id). We use a dict here
3036
# so the dirty sections can be shared by multiple callers.
3037
self.dirty_sections = {}
3039
def is_loaded(self):
3040
"""Returns True if the Store has been loaded.
3042
This is used to implement lazy loading and ensure the persistent
3043
storage is queried only when needed.
3045
raise NotImplementedError(self.is_loaded)
3048
"""Loads the Store from persistent storage."""
3049
raise NotImplementedError(self.load)
3051
def _load_from_string(self, bytes):
3052
"""Create a store from a string in configobj syntax.
3054
:param bytes: A string representing the file content.
3056
raise NotImplementedError(self._load_from_string)
3059
"""Unloads the Store.
3061
This should make is_loaded() return False. This is used when the caller
3062
knows that the persistent storage has changed or may have change since
3065
raise NotImplementedError(self.unload)
3067
def quote(self, value):
3068
"""Quote a configuration option value for storing purposes.
3070
This allows Stacks to present values as they will be stored.
3074
def unquote(self, value):
3075
"""Unquote a configuration option value into unicode.
3077
The received value is quoted as stored.
3082
"""Saves the Store to persistent storage."""
3083
raise NotImplementedError(self.save)
3085
def _need_saving(self):
3086
for s in self.dirty_sections.values():
3088
# At least one dirty section contains a modification
3092
def apply_changes(self, dirty_sections):
3093
"""Apply changes from dirty sections while checking for coherency.
3095
The Store content is discarded and reloaded from persistent storage to
3096
acquire up-to-date values.
3098
Dirty sections are MutableSection which kept track of the value they
3099
are expected to update.
3101
# We need an up-to-date version from the persistent storage, unload the
3102
# store. The reload will occur when needed (triggered by the first
3103
# get_mutable_section() call below.
3105
# Apply the changes from the preserved dirty sections
3106
for section_id, dirty in dirty_sections.items():
3107
clean = self.get_mutable_section(section_id)
3108
clean.apply_changes(dirty, self)
3109
# Everything is clean now
3110
self.dirty_sections = {}
3112
def save_changes(self):
3113
"""Saves the Store to persistent storage if changes occurred.
3115
Apply the changes recorded in the mutable sections to a store content
3116
refreshed from persistent storage.
3118
raise NotImplementedError(self.save_changes)
3120
def external_url(self):
3121
raise NotImplementedError(self.external_url)
3123
def get_sections(self):
3124
"""Returns an ordered iterable of existing sections.
3126
:returns: An iterable of (store, section).
3128
raise NotImplementedError(self.get_sections)
3130
def get_mutable_section(self, section_id=None):
3131
"""Returns the specified mutable section.
3133
:param section_id: The section identifier
3135
raise NotImplementedError(self.get_mutable_section)
3138
# Mostly for debugging use
3139
return "<config.%s(%s)>" % (self.__class__.__name__,
3140
self.external_url())
3143
class CommandLineStore(Store):
3144
"A store to carry command line overrides for the config options."""
3146
def __init__(self, opts=None):
3147
super(CommandLineStore, self).__init__()
3154
# The dict should be cleared but not replaced so it can be shared.
3155
self.options.clear()
3157
def _from_cmdline(self, overrides):
3158
# Reset before accepting new definitions
3160
for over in overrides:
3162
name, value = over.split('=', 1)
3164
raise errors.BzrCommandError(
3165
gettext("Invalid '%s', should be of the form 'name=value'")
3167
self.options[name] = value
3169
def external_url(self):
3170
# Not an url but it makes debugging easier and is never needed
3174
def get_sections(self):
3175
yield self, self.readonly_section_class(None, self.options)
3178
class IniFileStore(Store):
3179
"""A config Store using ConfigObj for storage.
3181
:ivar _config_obj: Private member to hold the ConfigObj instance used to
3182
serialize/deserialize the config file.
3186
"""A config Store using ConfigObj for storage.
3188
super(IniFileStore, self).__init__()
3189
self._config_obj = None
3191
def is_loaded(self):
3192
return self._config_obj != None
3195
self._config_obj = None
3196
self.dirty_sections = {}
3198
def _load_content(self):
3199
"""Load the config file bytes.
3201
This should be provided by subclasses
3203
:return: Byte string
3205
raise NotImplementedError(self._load_content)
3207
def _save_content(self, content):
3208
"""Save the config file bytes.
3210
This should be provided by subclasses
3212
:param content: Config file bytes to write
3214
raise NotImplementedError(self._save_content)
3217
"""Load the store from the associated file."""
3218
if self.is_loaded():
3220
content = self._load_content()
3221
self._load_from_string(content)
3222
for hook in ConfigHooks['load']:
3225
def _load_from_string(self, bytes):
3226
"""Create a config store from a string.
3228
:param bytes: A string representing the file content.
3230
if self.is_loaded():
3231
raise AssertionError('Already loaded: %r' % (self._config_obj,))
3232
co_input = BytesIO(bytes)
3234
# The config files are always stored utf8-encoded
3235
self._config_obj = ConfigObj(co_input, encoding='utf-8',
3237
except configobj.ConfigObjError as e:
3238
self._config_obj = None
3239
raise ParseConfigError(e.errors, self.external_url())
3240
except UnicodeDecodeError:
3241
raise ConfigContentError(self.external_url())
3243
def save_changes(self):
3244
if not self.is_loaded():
3247
if not self._need_saving():
3249
# Preserve the current version
3250
dirty_sections = self.dirty_sections.copy()
3251
self.apply_changes(dirty_sections)
3252
# Save to the persistent storage
3256
if not self.is_loaded():
3260
self._config_obj.write(out)
3261
self._save_content(out.getvalue())
3262
for hook in ConfigHooks['save']:
3265
def get_sections(self):
3266
"""Get the configobj section in the file order.
3268
:returns: An iterable of (store, section).
3270
# We need a loaded store
3273
except (errors.NoSuchFile, errors.PermissionDenied):
3274
# If the file can't be read, there is no sections
3276
cobj = self._config_obj
3278
yield self, self.readonly_section_class(None, cobj)
3279
for section_name in cobj.sections:
3281
self.readonly_section_class(section_name,
3282
cobj[section_name]))
3284
def get_mutable_section(self, section_id=None):
3285
# We need a loaded store
3288
except errors.NoSuchFile:
3289
# The file doesn't exist, let's pretend it was empty
3290
self._load_from_string(b'')
3291
if section_id in self.dirty_sections:
3292
# We already created a mutable section for this id
3293
return self.dirty_sections[section_id]
3294
if section_id is None:
3295
section = self._config_obj
3297
section = self._config_obj.setdefault(section_id, {})
3298
mutable_section = self.mutable_section_class(section_id, section)
3299
# All mutable sections can become dirty
3300
self.dirty_sections[section_id] = mutable_section
3301
return mutable_section
3303
def quote(self, value):
3305
# configobj conflates automagical list values and quoting
3306
self._config_obj.list_values = True
3307
return self._config_obj._quote(value)
3309
self._config_obj.list_values = False
3311
def unquote(self, value):
3312
if value and isinstance(value, string_types):
3313
# _unquote doesn't handle None nor empty strings nor anything that
3314
# is not a string, really.
3315
value = self._config_obj._unquote(value)
3318
def external_url(self):
3319
# Since an IniFileStore can be used without a file (at least in tests),
3320
# it's better to provide something than raising a NotImplementedError.
3321
# All daughter classes are supposed to provide an implementation
3323
return 'In-Process Store, no URL'
3326
class TransportIniFileStore(IniFileStore):
3327
"""IniFileStore that loads files from a transport.
3329
:ivar transport: The transport object where the config file is located.
3331
:ivar file_name: The config file basename in the transport directory.
3334
def __init__(self, transport, file_name):
3335
"""A Store using a ini file on a Transport
3337
:param transport: The transport object where the config file is located.
3338
:param file_name: The config file basename in the transport directory.
3340
super(TransportIniFileStore, self).__init__()
3341
self.transport = transport
3342
self.file_name = file_name
3344
def _load_content(self):
3346
return self.transport.get_bytes(self.file_name)
3347
except errors.PermissionDenied:
3348
trace.warning("Permission denied while trying to load "
3349
"configuration store %s.", self.external_url())
3352
def _save_content(self, content):
3353
self.transport.put_bytes(self.file_name, content)
3355
def external_url(self):
3356
# FIXME: external_url should really accepts an optional relpath
3357
# parameter (bug #750169) :-/ -- vila 2011-04-04
3358
# The following will do in the interim but maybe we don't want to
3359
# expose a path here but rather a config ID and its associated
3360
# object </hand wawe>.
3361
return urlutils.join(
3362
self.transport.external_url(), urlutils.escape(self.file_name))
3365
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
3366
# unlockable stores for use with objects that can already ensure the locking
3367
# (think branches). If different stores (not based on ConfigObj) are created,
3368
# they may face the same issue.
3371
class LockableIniFileStore(TransportIniFileStore):
3372
"""A ConfigObjStore using locks on save to ensure store integrity."""
3374
def __init__(self, transport, file_name, lock_dir_name=None):
3375
"""A config Store using ConfigObj for storage.
3377
:param transport: The transport object where the config file is located.
3379
:param file_name: The config file basename in the transport directory.
3381
if lock_dir_name is None:
3382
lock_dir_name = 'lock'
3383
self.lock_dir_name = lock_dir_name
3384
super(LockableIniFileStore, self).__init__(transport, file_name)
3385
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
3387
def lock_write(self, token=None):
3388
"""Takes a write lock in the directory containing the config file.
3390
If the directory doesn't exist it is created.
3392
# FIXME: This doesn't check the ownership of the created directories as
3393
# ensure_config_dir_exists does. It should if the transport is local
3394
# -- vila 2011-04-06
3395
self.transport.create_prefix()
3396
return self._lock.lock_write(token)
3401
def break_lock(self):
3402
self._lock.break_lock()
3406
# We need to be able to override the undecorated implementation
3407
self.save_without_locking()
3409
def save_without_locking(self):
3410
super(LockableIniFileStore, self).save()
3413
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
3414
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
3415
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
3417
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
3418
# functions or a registry will make it easier and clearer for tests, focusing
3419
# on the relevant parts of the API that needs testing -- vila 20110503 (based
3420
# on a poolie's remark)
3421
class GlobalStore(LockableIniFileStore):
3422
"""A config store for global options.
3424
There is a single GlobalStore for a given process.
3427
def __init__(self, possible_transports=None):
3428
t = transport.get_transport_from_path(
3429
config_dir(), possible_transports=possible_transports)
3430
super(GlobalStore, self).__init__(t, 'bazaar.conf')
3434
class LocationStore(LockableIniFileStore):
3435
"""A config store for options specific to a location.
3437
There is a single LocationStore for a given process.
3440
def __init__(self, possible_transports=None):
3441
t = transport.get_transport_from_path(
3442
config_dir(), possible_transports=possible_transports)
3443
super(LocationStore, self).__init__(t, 'locations.conf')
3444
self.id = 'locations'
3447
class BranchStore(TransportIniFileStore):
3448
"""A config store for branch options.
3450
There is a single BranchStore for a given branch.
3453
def __init__(self, branch):
3454
super(BranchStore, self).__init__(branch.control_transport,
3456
self.branch = branch
3460
class ControlStore(LockableIniFileStore):
3462
def __init__(self, bzrdir):
3463
super(ControlStore, self).__init__(bzrdir.transport,
3465
lock_dir_name='branch_lock')
3469
class SectionMatcher(object):
3470
"""Select sections into a given Store.
3472
This is intended to be used to postpone getting an iterable of sections
3476
def __init__(self, store):
3479
def get_sections(self):
3480
# This is where we require loading the store so we can see all defined
3482
sections = self.store.get_sections()
3483
# Walk the revisions in the order provided
3484
for store, s in sections:
3488
def match(self, section):
3489
"""Does the proposed section match.
3491
:param section: A Section object.
3493
:returns: True if the section matches, False otherwise.
3495
raise NotImplementedError(self.match)
3498
class NameMatcher(SectionMatcher):
3500
def __init__(self, store, section_id):
3501
super(NameMatcher, self).__init__(store)
3502
self.section_id = section_id
3504
def match(self, section):
3505
return section.id == self.section_id
3508
class LocationSection(Section):
3510
def __init__(self, section, extra_path, branch_name=None):
3511
super(LocationSection, self).__init__(section.id, section.options)
3512
self.extra_path = extra_path
3513
if branch_name is None:
3515
self.locals = {'relpath': extra_path,
3516
'basename': urlutils.basename(extra_path),
3517
'branchname': branch_name}
3519
def get(self, name, default=None, expand=True):
3520
value = super(LocationSection, self).get(name, default)
3521
if value is not None and expand:
3522
policy_name = self.get(name + ':policy', None)
3523
policy = _policy_value.get(policy_name, POLICY_NONE)
3524
if policy == POLICY_APPENDPATH:
3525
value = urlutils.join(value, self.extra_path)
3526
# expand section local options right now (since POLICY_APPENDPATH
3527
# will never add options references, it's ok to expand after it).
3529
for is_ref, chunk in iter_option_refs(value):
3531
chunks.append(chunk)
3534
if ref in self.locals:
3535
chunks.append(self.locals[ref])
3537
chunks.append(chunk)
3538
value = ''.join(chunks)
3542
class StartingPathMatcher(SectionMatcher):
3543
"""Select sections for a given location respecting the Store order."""
3545
# FIXME: Both local paths and urls can be used for section names as well as
3546
# ``location`` to stay consistent with ``LocationMatcher`` which itself
3547
# inherited the fuzziness from the previous ``LocationConfig``
3548
# implementation. We probably need to revisit which encoding is allowed for
3549
# both ``location`` and section names and how we normalize
3550
# them. http://pad.lv/85479, http://pad.lv/437009 and http://359320 are
3551
# related too. -- vila 2012-01-04
3553
def __init__(self, store, location):
3554
super(StartingPathMatcher, self).__init__(store)
3555
if location.startswith('file://'):
3556
location = urlutils.local_path_from_url(location)
3557
self.location = location
3559
def get_sections(self):
3560
"""Get all sections matching ``location`` in the store.
3562
The most generic sections are described first in the store, then more
3563
specific ones can be provided for reduced scopes.
3565
The returned section are therefore returned in the reversed order so
3566
the most specific ones can be found first.
3568
location_parts = self.location.rstrip('/').split('/')
3570
# Later sections are more specific, they should be returned first
3571
for _, section in reversed(list(store.get_sections())):
3572
if section.id is None:
3573
# The no-name section is always included if present
3574
yield store, LocationSection(section, self.location)
3576
section_path = section.id
3577
if section_path.startswith('file://'):
3578
# the location is already a local path or URL, convert the
3579
# section id to the same format
3580
section_path = urlutils.local_path_from_url(section_path)
3581
if (self.location.startswith(section_path)
3582
or fnmatch.fnmatch(self.location, section_path)):
3583
section_parts = section_path.rstrip('/').split('/')
3584
extra_path = '/'.join(location_parts[len(section_parts):])
3585
yield store, LocationSection(section, extra_path)
3588
class LocationMatcher(SectionMatcher):
3590
def __init__(self, store, location):
3591
super(LocationMatcher, self).__init__(store)
3592
url, params = urlutils.split_segment_parameters(location)
3593
if location.startswith('file://'):
3594
location = urlutils.local_path_from_url(location)
3595
self.location = location
3596
branch_name = params.get('branch')
3597
if branch_name is None:
3598
self.branch_name = urlutils.basename(self.location)
3600
self.branch_name = urlutils.unescape(branch_name)
3602
def _get_matching_sections(self):
3603
"""Get all sections matching ``location``."""
3604
# We slightly diverge from LocalConfig here by allowing the no-name
3605
# section as the most generic one and the lower priority.
3606
no_name_section = None
3608
# Filter out the no_name_section so _iter_for_location_by_parts can be
3609
# used (it assumes all sections have a name).
3610
for _, section in self.store.get_sections():
3611
if section.id is None:
3612
no_name_section = section
3614
all_sections.append(section)
3615
# Unfortunately _iter_for_location_by_parts deals with section names so
3616
# we have to resync.
3617
filtered_sections = _iter_for_location_by_parts(
3618
[s.id for s in all_sections], self.location)
3619
iter_all_sections = iter(all_sections)
3620
matching_sections = []
3621
if no_name_section is not None:
3622
matching_sections.append(
3623
(0, LocationSection(no_name_section, self.location)))
3624
for section_id, extra_path, length in filtered_sections:
3625
# a section id is unique for a given store so it's safe to take the
3626
# first matching section while iterating. Also, all filtered
3627
# sections are part of 'all_sections' and will always be found
3630
section = next(iter_all_sections)
3631
if section_id == section.id:
3632
section = LocationSection(section, extra_path,
3634
matching_sections.append((length, section))
3636
return matching_sections
3638
def get_sections(self):
3639
# Override the default implementation as we want to change the order
3640
# We want the longest (aka more specific) locations first
3641
sections = sorted(self._get_matching_sections(),
3642
key=lambda match: (match[0], match[1].id),
3644
# Sections mentioning 'ignore_parents' restrict the selection
3645
for _, section in sections:
3646
# FIXME: We really want to use as_bool below -- vila 2011-04-07
3647
ignore = section.get('ignore_parents', None)
3648
if ignore is not None:
3649
ignore = ui.bool_from_string(ignore)
3652
# Finally, we have a valid section
3653
yield self.store, section
3656
# FIXME: _shared_stores should be an attribute of a library state once a
3657
# library_state object is always available.
3659
_shared_stores_at_exit_installed = False
3661
class Stack(object):
3662
"""A stack of configurations where an option can be defined"""
3664
def __init__(self, sections_def, store=None, mutable_section_id=None):
3665
"""Creates a stack of sections with an optional store for changes.
3667
:param sections_def: A list of Section or callables that returns an
3668
iterable of Section. This defines the Sections for the Stack and
3669
can be called repeatedly if needed.
3671
:param store: The optional Store where modifications will be
3672
recorded. If none is specified, no modifications can be done.
3674
:param mutable_section_id: The id of the MutableSection where changes
3675
are recorded. This requires the ``store`` parameter to be
3678
self.sections_def = sections_def
3680
self.mutable_section_id = mutable_section_id
3682
def iter_sections(self):
3683
"""Iterate all the defined sections."""
3684
# Ensuring lazy loading is achieved by delaying section matching (which
3685
# implies querying the persistent storage) until it can't be avoided
3686
# anymore by using callables to describe (possibly empty) section
3688
for sections in self.sections_def:
3689
for store, section in sections():
3690
yield store, section
3692
def get(self, name, expand=True, convert=True):
3693
"""Return the *first* option value found in the sections.
3695
This is where we guarantee that sections coming from Store are loaded
3696
lazily: the loading is delayed until we need to either check that an
3697
option exists or get its value, which in turn may require to discover
3698
in which sections it can be defined. Both of these (section and option
3699
existence) require loading the store (even partially).
3701
:param name: The queried option.
3703
:param expand: Whether options references should be expanded.
3705
:param convert: Whether the option value should be converted from
3706
unicode (do nothing for non-registered options).
3708
:returns: The value of the option.
3710
# FIXME: No caching of options nor sections yet -- vila 20110503
3712
found_store = None # Where the option value has been found
3713
# If the option is registered, it may provide additional info about
3716
opt = option_registry.get(name)
3721
def expand_and_convert(val):
3722
# This may need to be called in different contexts if the value is
3723
# None or ends up being None during expansion or conversion.
3726
if isinstance(val, string_types):
3727
val = self._expand_options_in_string(val)
3729
trace.warning('Cannot expand "%s":'
3730
' %s does not support option expansion'
3731
% (name, type(val)))
3733
val = found_store.unquote(val)
3735
val = opt.convert_from_unicode(found_store, val)
3738
# First of all, check if the environment can override the configuration
3740
if opt is not None and opt.override_from_env:
3741
value = opt.get_override()
3742
value = expand_and_convert(value)
3744
for store, section in self.iter_sections():
3745
value = section.get(name)
3746
if value is not None:
3749
value = expand_and_convert(value)
3750
if opt is not None and value is None:
3751
# If the option is registered, it may provide a default value
3752
value = opt.get_default()
3753
value = expand_and_convert(value)
3754
for hook in ConfigHooks['get']:
3755
hook(self, name, value)
3758
def expand_options(self, string, env=None):
3759
"""Expand option references in the string in the configuration context.
3761
:param string: The string containing option(s) to expand.
3763
:param env: An option dict defining additional configuration options or
3764
overriding existing ones.
3766
:returns: The expanded string.
3768
return self._expand_options_in_string(string, env)
3770
def _expand_options_in_string(self, string, env=None, _refs=None):
3771
"""Expand options in the string in the configuration context.
3773
:param string: The string to be expanded.
3775
:param env: An option dict defining additional configuration options or
3776
overriding existing ones.
3778
:param _refs: Private list (FIFO) containing the options being expanded
3781
:returns: The expanded string.
3784
# Not much to expand there
3787
# What references are currently resolved (to detect loops)
3790
# We need to iterate until no more refs appear ({{foo}} will need two
3791
# iterations for example).
3796
for is_ref, chunk in iter_option_refs(result):
3798
chunks.append(chunk)
3803
raise OptionExpansionLoop(string, _refs)
3805
value = self._expand_option(name, env, _refs)
3807
raise ExpandingUnknownOption(name, string)
3808
chunks.append(value)
3810
result = ''.join(chunks)
3813
def _expand_option(self, name, env, _refs):
3814
if env is not None and name in env:
3815
# Special case, values provided in env takes precedence over
3819
value = self.get(name, expand=False, convert=False)
3820
value = self._expand_options_in_string(value, env, _refs)
3823
def _get_mutable_section(self):
3824
"""Get the MutableSection for the Stack.
3826
This is where we guarantee that the mutable section is lazily loaded:
3827
this means we won't load the corresponding store before setting a value
3828
or deleting an option. In practice the store will often be loaded but
3829
this helps catching some programming errors.
3832
section = store.get_mutable_section(self.mutable_section_id)
3833
return store, section
3835
def set(self, name, value):
3836
"""Set a new value for the option."""
3837
store, section = self._get_mutable_section()
3838
section.set(name, store.quote(value))
3839
for hook in ConfigHooks['set']:
3840
hook(self, name, value)
3842
def remove(self, name):
3843
"""Remove an existing option."""
3844
_, section = self._get_mutable_section()
3845
section.remove(name)
3846
for hook in ConfigHooks['remove']:
3850
# Mostly for debugging use
3851
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
3853
def _get_overrides(self):
3854
# FIXME: Hack around library_state.initialize never called
3855
if breezy.global_state is not None:
3856
return breezy.global_state.cmdline_overrides.get_sections()
3859
def get_shared_store(self, store, state=None):
3860
"""Get a known shared store.
3862
Store urls uniquely identify them and are used to ensure a single copy
3863
is shared across all users.
3865
:param store: The store known to the caller.
3867
:param state: The library state where the known stores are kept.
3869
:returns: The store received if it's not a known one, an already known
3873
state = breezy.global_state
3875
global _shared_stores_at_exit_installed
3876
stores = _shared_stores
3877
def save_config_changes():
3878
for k, store in stores.items():
3879
store.save_changes()
3880
if not _shared_stores_at_exit_installed:
3881
# FIXME: Ugly hack waiting for library_state to always be
3882
# available. -- vila 20120731
3884
atexit.register(save_config_changes)
3885
_shared_stores_at_exit_installed = True
3887
stores = state.config_stores
3888
url = store.external_url()
3896
class MemoryStack(Stack):
3897
"""A configuration stack defined from a string.
3899
This is mainly intended for tests and requires no disk resources.
3902
def __init__(self, content=None):
3903
"""Create an in-memory stack from a given content.
3905
It uses a single store based on configobj and support reading and
3908
:param content: The initial content of the store. If None, the store is
3909
not loaded and ``_load_from_string`` can and should be used if
3912
store = IniFileStore()
3913
if content is not None:
3914
store._load_from_string(content)
3915
super(MemoryStack, self).__init__(
3916
[store.get_sections], store)
3919
class _CompatibleStack(Stack):
3920
"""Place holder for compatibility with previous design.
3922
This is intended to ease the transition from the Config-based design to the
3923
Stack-based design and should not be used nor relied upon by plugins.
3925
One assumption made here is that the daughter classes will all use Stores
3926
derived from LockableIniFileStore).
3928
It implements set() and remove () by re-loading the store before applying
3929
the modification and saving it.
3931
The long term plan being to implement a single write by store to save
3932
all modifications, this class should not be used in the interim.
3935
def set(self, name, value):
3938
super(_CompatibleStack, self).set(name, value)
3939
# Force a write to persistent storage
3942
def remove(self, name):
3945
super(_CompatibleStack, self).remove(name)
3946
# Force a write to persistent storage
3950
class GlobalStack(Stack):
3951
"""Global options only stack.
3953
The following sections are queried:
3955
* command-line overrides,
3957
* the 'DEFAULT' section in bazaar.conf
3959
This stack will use the ``DEFAULT`` section in bazaar.conf as its
3964
gstore = self.get_shared_store(GlobalStore())
3965
super(GlobalStack, self).__init__(
3966
[self._get_overrides,
3967
NameMatcher(gstore, 'DEFAULT').get_sections],
3968
gstore, mutable_section_id='DEFAULT')
3971
class LocationStack(Stack):
3972
"""Per-location options falling back to global options stack.
3975
The following sections are queried:
3977
* command-line overrides,
3979
* the sections matching ``location`` in ``locations.conf``, the order being
3980
defined by the number of path components in the section glob, higher
3981
numbers first (from most specific section to most generic).
3983
* the 'DEFAULT' section in bazaar.conf
3985
This stack will use the ``location`` section in locations.conf as its
3989
def __init__(self, location):
3990
"""Make a new stack for a location and global configuration.
3992
:param location: A URL prefix to """
3993
lstore = self.get_shared_store(LocationStore())
3994
if location.startswith('file://'):
3995
location = urlutils.local_path_from_url(location)
3996
gstore = self.get_shared_store(GlobalStore())
3997
super(LocationStack, self).__init__(
3998
[self._get_overrides,
3999
LocationMatcher(lstore, location).get_sections,
4000
NameMatcher(gstore, 'DEFAULT').get_sections],
4001
lstore, mutable_section_id=location)
4004
class BranchStack(Stack):
4005
"""Per-location options falling back to branch then global options stack.
4007
The following sections are queried:
4009
* command-line overrides,
4011
* the sections matching ``location`` in ``locations.conf``, the order being
4012
defined by the number of path components in the section glob, higher
4013
numbers first (from most specific section to most generic),
4015
* the no-name section in branch.conf,
4017
* the ``DEFAULT`` section in ``bazaar.conf``.
4019
This stack will use the no-name section in ``branch.conf`` as its
4023
def __init__(self, branch):
4024
lstore = self.get_shared_store(LocationStore())
4025
bstore = branch._get_config_store()
4026
gstore = self.get_shared_store(GlobalStore())
4027
super(BranchStack, self).__init__(
4028
[self._get_overrides,
4029
LocationMatcher(lstore, branch.base).get_sections,
4030
NameMatcher(bstore, None).get_sections,
4031
NameMatcher(gstore, 'DEFAULT').get_sections],
4033
self.branch = branch
4035
def lock_write(self, token=None):
4036
return self.branch.lock_write(token)
4039
return self.branch.unlock()
4042
def set(self, name, value):
4043
super(BranchStack, self).set(name, value)
4044
# Unlocking the branch will trigger a store.save_changes() so the last
4045
# unlock saves all the changes.
4048
def remove(self, name):
4049
super(BranchStack, self).remove(name)
4050
# Unlocking the branch will trigger a store.save_changes() so the last
4051
# unlock saves all the changes.
4054
class RemoteControlStack(Stack):
4055
"""Remote control-only options stack."""
4057
# FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
4058
# with the stack used for remote bzr dirs. RemoteControlStack only uses
4059
# control.conf and is used only for stack options.
4061
def __init__(self, bzrdir):
4062
cstore = bzrdir._get_config_store()
4063
super(RemoteControlStack, self).__init__(
4064
[NameMatcher(cstore, None).get_sections],
4066
self.controldir = bzrdir
4069
class BranchOnlyStack(Stack):
4070
"""Branch-only options stack."""
4072
# FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
4073
# stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
4074
# -- vila 2011-12-16
4076
def __init__(self, branch):
4077
bstore = branch._get_config_store()
4078
super(BranchOnlyStack, self).__init__(
4079
[NameMatcher(bstore, None).get_sections],
4081
self.branch = branch
4083
def lock_write(self, token=None):
4084
return self.branch.lock_write(token)
4087
return self.branch.unlock()
4090
def set(self, name, value):
4091
super(BranchOnlyStack, self).set(name, value)
4092
# Force a write to persistent storage
4093
self.store.save_changes()
4096
def remove(self, name):
4097
super(BranchOnlyStack, self).remove(name)
4098
# Force a write to persistent storage
4099
self.store.save_changes()
4102
class cmd_config(commands.Command):
4103
__doc__ = """Display, set or remove a configuration option.
4105
Display the active value for option NAME.
4107
If --all is specified, NAME is interpreted as a regular expression and all
4108
matching options are displayed mentioning their scope and without resolving
4109
option references in the value). The active value that bzr will take into
4110
account is the first one displayed for each option.
4112
If NAME is not given, --all .* is implied (all options are displayed for the
4115
Setting a value is achieved by using NAME=value without spaces. The value
4116
is set in the most relevant scope and can be checked by displaying the
4119
Removing a value is achieved by using --remove NAME.
4122
takes_args = ['name?']
4126
# FIXME: This should be a registry option so that plugins can register
4127
# their own config files (or not) and will also address
4128
# http://pad.lv/788991 -- vila 20101115
4129
commands.Option('scope', help='Reduce the scope to the specified'
4130
' configuration file.',
4132
commands.Option('all',
4133
help='Display all the defined values for the matching options.',
4135
commands.Option('remove', help='Remove the option from'
4136
' the configuration file.'),
4139
_see_also = ['configuration']
4141
@commands.display_command
4142
def run(self, name=None, all=False, directory=None, scope=None,
4144
if directory is None:
4146
directory = directory_service.directories.dereference(directory)
4147
directory = urlutils.normalize_url(directory)
4149
raise errors.BzrError(
4150
'--all and --remove are mutually exclusive.')
4152
# Delete the option in the given scope
4153
self._remove_config_option(name, directory, scope)
4155
# Defaults to all options
4156
self._show_matching_options('.*', directory, scope)
4159
name, value = name.split('=', 1)
4161
# Display the option(s) value(s)
4163
self._show_matching_options(name, directory, scope)
4165
self._show_value(name, directory, scope)
4168
raise errors.BzrError(
4169
'Only one option can be set.')
4170
# Set the option value
4171
self._set_config_option(name, value, directory, scope)
4173
def _get_stack(self, directory, scope=None, write_access=False):
4174
"""Get the configuration stack specified by ``directory`` and ``scope``.
4176
:param directory: Where the configurations are derived from.
4178
:param scope: A specific config to start from.
4180
:param write_access: Whether a write access to the stack will be
4183
# FIXME: scope should allow access to plugin-specific stacks (even
4184
# reduced to the plugin-specific store), related to
4185
# http://pad.lv/788991 -- vila 2011-11-15
4186
if scope is not None:
4187
if scope == 'bazaar':
4188
return GlobalStack()
4189
elif scope == 'locations':
4190
return LocationStack(directory)
4191
elif scope == 'branch':
4193
controldir.ControlDir.open_containing_tree_or_branch(
4196
self.add_cleanup(br.lock_write().unlock)
4197
return br.get_config_stack()
4198
raise NoSuchConfig(scope)
4202
controldir.ControlDir.open_containing_tree_or_branch(
4205
self.add_cleanup(br.lock_write().unlock)
4206
return br.get_config_stack()
4207
except errors.NotBranchError:
4208
return LocationStack(directory)
4210
def _quote_multiline(self, value):
4212
value = '"""' + value + '"""'
4215
def _show_value(self, name, directory, scope):
4216
conf = self._get_stack(directory, scope)
4217
value = conf.get(name, expand=True, convert=False)
4218
if value is not None:
4219
# Quote the value appropriately
4220
value = self._quote_multiline(value)
4221
self.outf.write('%s\n' % (value,))
4223
raise NoSuchConfigOption(name)
4225
def _show_matching_options(self, name, directory, scope):
4226
name = lazy_regex.lazy_compile(name)
4227
# We want any error in the regexp to be raised *now* so we need to
4228
# avoid the delay introduced by the lazy regexp. But, we still do
4229
# want the nicer errors raised by lazy_regex.
4230
name._compile_and_collapse()
4233
conf = self._get_stack(directory, scope)
4234
for store, section in conf.iter_sections():
4235
for oname in section.iter_option_names():
4236
if name.search(oname):
4237
if cur_store_id != store.id:
4238
# Explain where the options are defined
4239
self.outf.write('%s:\n' % (store.id,))
4240
cur_store_id = store.id
4242
if (section.id is not None and cur_section != section.id):
4243
# Display the section id as it appears in the store
4244
# (None doesn't appear by definition)
4245
self.outf.write(' [%s]\n' % (section.id,))
4246
cur_section = section.id
4247
value = section.get(oname, expand=False)
4248
# Quote the value appropriately
4249
value = self._quote_multiline(value)
4250
self.outf.write(' %s = %s\n' % (oname, value))
4252
def _set_config_option(self, name, value, directory, scope):
4253
conf = self._get_stack(directory, scope, write_access=True)
4254
conf.set(name, value)
4255
# Explicitly save the changes
4256
conf.store.save_changes()
4258
def _remove_config_option(self, name, directory, scope):
4260
raise errors.BzrCommandError(
4261
'--remove expects an option to remove.')
4262
conf = self._get_stack(directory, scope, write_access=True)
4265
# Explicitly save the changes
4266
conf.store.save_changes()
4268
raise NoSuchConfigOption(name)
4273
# We need adapters that can build a Store or a Stack in a test context. Test
4274
# classes, based on TestCaseWithTransport, can use the registry to parametrize
4275
# themselves. The builder will receive a test instance and should return a
4276
# ready-to-use store or stack. Plugins that define new store/stacks can also
4277
# register themselves here to be tested against the tests defined in
4278
# breezy.tests.test_config. Note that the builder can be called multiple times
4279
# for the same test.
4281
# The registered object should be a callable receiving a test instance
4282
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
4284
test_store_builder_registry = registry.Registry()
4286
# The registered object should be a callable receiving a test instance
4287
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
4289
test_stack_builder_registry = registry.Registry()