1508
2003
configobj[name] = value
1510
2005
configobj.setdefault(section, {})[name] = value
2006
for hook in OldConfigHooks['set']:
2007
hook(self, name, value)
2008
self._set_configobj(configobj)
2010
def remove_option(self, option_name, section_name=None):
2011
configobj = self._get_configobj()
2012
if section_name is None:
2013
del configobj[option_name]
2015
del configobj[section_name][option_name]
2016
for hook in OldConfigHooks['remove']:
2017
hook(self, option_name)
1511
2018
self._set_configobj(configobj)
1513
2020
def _get_config_file(self):
1515
return StringIO(self._transport.get_bytes(self._filename))
2022
f = BytesIO(self._transport.get_bytes(self._filename))
2023
for hook in OldConfigHooks['load']:
1516
2026
except errors.NoSuchFile:
2028
except errors.PermissionDenied:
2030
"Permission denied while trying to open "
2031
"configuration file %s.",
2032
urlutils.unescape_for_display(
2033
urlutils.join(self._transport.base, self._filename),
2037
def _external_url(self):
2038
return urlutils.join(self._transport.external_url(), self._filename)
1519
2040
def _get_configobj(self):
1520
return ConfigObj(self._get_config_file(), encoding='utf-8')
2041
f = self._get_config_file()
2044
conf = ConfigObj(f, encoding='utf-8')
2045
except configobj.ConfigObjError as e:
2046
raise ParseConfigError(e.errors, self._external_url())
2047
except UnicodeDecodeError:
2048
raise ConfigContentError(self._external_url())
1522
2053
def _set_configobj(self, configobj):
1523
out_file = StringIO()
2054
out_file = BytesIO()
1524
2055
configobj.write(out_file)
1525
2056
out_file.seek(0)
1526
2057
self._transport.put_file(self._filename, out_file)
2058
for hook in OldConfigHooks['save']:
2062
class Option(object):
2063
"""An option definition.
2065
The option *values* are stored in config files and found in sections.
2067
Here we define various properties about the option itself, its default
2068
value, how to convert it from stores, what to do when invalid values are
2069
encoutered, in which config files it can be stored.
2072
def __init__(self, name, override_from_env=None,
2073
default=None, default_from_env=None,
2074
help=None, from_unicode=None, invalid=None, unquote=True):
2075
"""Build an option definition.
2077
:param name: the name used to refer to the option.
2079
:param override_from_env: A list of environment variables which can
2080
provide override any configuration setting.
2082
:param default: the default value to use when none exist in the config
2083
stores. This is either a string that ``from_unicode`` will convert
2084
into the proper type, a callable returning a unicode string so that
2085
``from_unicode`` can be used on the return value, or a python
2086
object that can be stringified (so only the empty list is supported
2089
:param default_from_env: A list of environment variables which can
2090
provide a default value. 'default' will be used only if none of the
2091
variables specified here are set in the environment.
2093
:param help: a doc string to explain the option to the user.
2095
:param from_unicode: a callable to convert the unicode string
2096
representing the option value in a store or its default value.
2098
:param invalid: the action to be taken when an invalid value is
2099
encountered in a store. This is called only when from_unicode is
2100
invoked to convert a string and returns None or raise ValueError or
2101
TypeError. Accepted values are: None (ignore invalid values),
2102
'warning' (emit a warning), 'error' (emit an error message and
2105
:param unquote: should the unicode value be unquoted before conversion.
2106
This should be used only when the store providing the values cannot
2107
safely unquote them (see http://pad.lv/906897). It is provided so
2108
daughter classes can handle the quoting themselves.
2110
if override_from_env is None:
2111
override_from_env = []
2112
if default_from_env is None:
2113
default_from_env = []
2115
self.override_from_env = override_from_env
2116
# Convert the default value to a unicode string so all values are
2117
# strings internally before conversion (via from_unicode) is attempted.
2120
elif isinstance(default, list):
2121
# Only the empty list is supported
2123
raise AssertionError(
2124
'Only empty lists are supported as default values')
2126
elif isinstance(default, (binary_type, text_type, bool, int, float)):
2127
# Rely on python to convert strings, booleans and integers
2128
self.default = u'%s' % (default,)
2129
elif callable(default):
2130
self.default = default
2132
# other python objects are not expected
2133
raise AssertionError('%r is not supported as a default value'
2135
self.default_from_env = default_from_env
2137
self.from_unicode = from_unicode
2138
self.unquote = unquote
2139
if invalid and invalid not in ('warning', 'error'):
2140
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2141
self.invalid = invalid
2147
def convert_from_unicode(self, store, unicode_value):
2148
if self.unquote and store is not None and unicode_value is not None:
2149
unicode_value = store.unquote(unicode_value)
2150
if self.from_unicode is None or unicode_value is None:
2151
# Don't convert or nothing to convert
2152
return unicode_value
2154
converted = self.from_unicode(unicode_value)
2155
except (ValueError, TypeError):
2156
# Invalid values are ignored
2158
if converted is None and self.invalid is not None:
2159
# The conversion failed
2160
if self.invalid == 'warning':
2161
trace.warning('Value "%s" is not valid for "%s"',
2162
unicode_value, self.name)
2163
elif self.invalid == 'error':
2164
raise ConfigOptionValueError(self.name, unicode_value)
2167
def get_override(self):
2169
for var in self.override_from_env:
2171
# If the env variable is defined, its value takes precedence
2172
value = os.environ[var]
2174
value = value.decode(osutils.get_user_encoding())
2180
def get_default(self):
2182
for var in self.default_from_env:
2184
# If the env variable is defined, its value is the default one
2185
value = os.environ[var]
2187
value = value.decode(osutils.get_user_encoding())
2192
# Otherwise, fallback to the value defined at registration
2193
if callable(self.default):
2194
value = self.default()
2195
if not isinstance(value, text_type):
2196
raise AssertionError(
2197
"Callable default value for '%s' should be unicode"
2200
value = self.default
2203
def get_help_topic(self):
2206
def get_help_text(self, additional_see_also=None, plain=True):
2208
from breezy import help_topics
2209
result += help_topics._format_see_also(additional_see_also)
2211
result = help_topics.help_as_plain_text(result)
2215
# Predefined converters to get proper values from store
2217
def bool_from_store(unicode_str):
2218
return ui.bool_from_string(unicode_str)
2221
def int_from_store(unicode_str):
2222
return int(unicode_str)
2225
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
2228
def int_SI_from_store(unicode_str):
2229
"""Convert a human readable size in SI units, e.g 10MB into an integer.
2231
Accepted suffixes are K,M,G. It is case-insensitive and may be followed
2232
by a trailing b (i.e. Kb, MB). This is intended to be practical and not
2235
:return Integer, expanded to its base-10 value if a proper SI unit is
2236
found, None otherwise.
2238
regexp = "^(\\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
2239
p = re.compile(regexp, re.IGNORECASE)
2240
m = p.match(unicode_str)
2243
val, _, unit = m.groups()
2247
coeff = _unit_suffixes[unit.upper()]
2250
gettext('{0} is not an SI unit.').format(unit))
2255
def float_from_store(unicode_str):
2256
return float(unicode_str)
2259
# Use an empty dict to initialize an empty configobj avoiding all parsing and
2261
_list_converter_config = configobj.ConfigObj(
2262
{}, encoding='utf-8', list_values=True, interpolation=False)
2265
class ListOption(Option):
2267
def __init__(self, name, default=None, default_from_env=None,
2268
help=None, invalid=None):
2269
"""A list Option definition.
2271
This overrides the base class so the conversion from a unicode string
2272
can take quoting into account.
2274
super(ListOption, self).__init__(
2275
name, default=default, default_from_env=default_from_env,
2276
from_unicode=self.from_unicode, help=help,
2277
invalid=invalid, unquote=False)
2279
def from_unicode(self, unicode_str):
2280
if not isinstance(unicode_str, string_types):
2282
# Now inject our string directly as unicode. All callers got their
2283
# value from configobj, so values that need to be quoted are already
2285
_list_converter_config.reset()
2286
_list_converter_config._parse([u"list=%s" % (unicode_str,)])
2287
maybe_list = _list_converter_config['list']
2288
if isinstance(maybe_list, string_types):
2290
# A single value, most probably the user forgot (or didn't care
2291
# to add) the final ','
2294
# The empty string, convert to empty list
2297
# We rely on ConfigObj providing us with a list already
2302
class RegistryOption(Option):
2303
"""Option for a choice from a registry."""
2305
def __init__(self, name, registry, default_from_env=None,
2306
help=None, invalid=None):
2307
"""A registry based Option definition.
2309
This overrides the base class so the conversion from a unicode string
2310
can take quoting into account.
2312
super(RegistryOption, self).__init__(
2313
name, default=lambda: registry.default_key,
2314
default_from_env=default_from_env,
2315
from_unicode=self.from_unicode, help=help,
2316
invalid=invalid, unquote=False)
2317
self.registry = registry
2319
def from_unicode(self, unicode_str):
2320
if not isinstance(unicode_str, string_types):
2323
return self.registry.get(unicode_str)
2326
"Invalid value %s for %s."
2327
"See help for a list of possible values." % (unicode_str,
2332
ret = [self._help, "\n\nThe following values are supported:\n"]
2333
for key in self.registry.keys():
2334
ret.append(" %s - %s\n" % (key, self.registry.get_help(key)))
2338
_option_ref_re = lazy_regex.lazy_compile('({[^\\d\\W](?:\\.\\w|-\\w|\\w)*})')
2339
"""Describes an expandable option reference.
2341
We want to match the most embedded reference first.
2343
I.e. for '{{foo}}' we will get '{foo}',
2344
for '{bar{baz}}' we will get '{baz}'
2348
def iter_option_refs(string):
2349
# Split isolate refs so every other chunk is a ref
2351
for chunk in _option_ref_re.split(string):
2356
class OptionRegistry(registry.Registry):
2357
"""Register config options by their name.
2359
This overrides ``registry.Registry`` to simplify registration by acquiring
2360
some information from the option object itself.
2363
def _check_option_name(self, option_name):
2364
"""Ensures an option name is valid.
2366
:param option_name: The name to validate.
2368
if _option_ref_re.match('{%s}' % option_name) is None:
2369
raise IllegalOptionName(option_name)
2371
def register(self, option):
2372
"""Register a new option to its name.
2374
:param option: The option to register. Its name is used as the key.
2376
self._check_option_name(option.name)
2377
super(OptionRegistry, self).register(option.name, option,
2380
def register_lazy(self, key, module_name, member_name):
2381
"""Register a new option to be loaded on request.
2383
:param key: the key to request the option later. Since the registration
2384
is lazy, it should be provided and match the option name.
2386
:param module_name: the python path to the module. Such as 'os.path'.
2388
:param member_name: the member of the module to return. If empty or
2389
None, get() will return the module itself.
2391
self._check_option_name(key)
2392
super(OptionRegistry, self).register_lazy(key,
2393
module_name, member_name)
2395
def get_help(self, key=None):
2396
"""Get the help text associated with the given key"""
2397
option = self.get(key)
2398
the_help = option.help
2399
if callable(the_help):
2400
return the_help(self, key)
2404
option_registry = OptionRegistry()
2407
# Registered options in lexicographical order
2409
option_registry.register(
2410
Option('append_revisions_only',
2411
default=None, from_unicode=bool_from_store, invalid='warning',
2413
Whether to only append revisions to the mainline.
2415
If this is set to true, then it is not possible to change the
2416
existing mainline of the branch.
2418
option_registry.register(
2419
ListOption('acceptable_keys',
2422
List of GPG key patterns which are acceptable for verification.
2424
option_registry.register(
2425
Option('add.maximum_file_size',
2426
default=u'20MB', from_unicode=int_SI_from_store,
2428
Size above which files should be added manually.
2430
Files below this size are added automatically when using ``bzr add`` without
2433
A negative value means disable the size check.
2435
option_registry.register(
2437
default=None, from_unicode=bool_from_store,
2439
Is the branch bound to ``bound_location``.
2441
If set to "True", the branch should act as a checkout, and push each commit to
2442
the bound_location. This option is normally set by ``bind``/``unbind``.
2444
See also: bound_location.
2446
option_registry.register(
2447
Option('bound_location',
2450
The location that commits should go to when acting as a checkout.
2452
This option is normally set by ``bind``.
2456
option_registry.register(
2457
Option('branch.fetch_tags', default=False, from_unicode=bool_from_store,
2459
Whether revisions associated with tags should be fetched.
2461
option_registry.register_lazy(
2462
'transform.orphan_policy', 'breezy.transform', 'opt_transform_orphan')
2463
option_registry.register(
2464
Option('bzr.workingtree.worth_saving_limit', default=10,
2465
from_unicode=int_from_store, invalid='warning',
2467
How many changes before saving the dirstate.
2469
-1 means that we will never rewrite the dirstate file for only
2470
stat-cache changes. Regardless of this setting, we will always rewrite
2471
the dirstate file if a file is added/removed/renamed/etc. This flag only
2472
affects the behavior of updating the dirstate file after we notice that
2473
a file has been touched.
2475
option_registry.register(
2476
Option('bugtracker', default=None,
2478
Default bug tracker to use.
2480
This bug tracker will be used for example when marking bugs
2481
as fixed using ``bzr commit --fixes``, if no explicit
2482
bug tracker was specified.
2484
option_registry.register(
2485
Option('check_signatures', default=CHECK_IF_POSSIBLE,
2486
from_unicode=signature_policy_from_unicode,
2488
GPG checking policy.
2490
Possible values: require, ignore, check-available (default)
2492
this option will control whether bzr will require good gpg
2493
signatures, ignore them, or check them if they are
2496
option_registry.register(
2497
Option('child_submit_format',
2498
help='''The preferred format of submissions to this branch.'''))
2499
option_registry.register(
2500
Option('child_submit_to',
2501
help='''Where submissions to this branch are mailed to.'''))
2502
option_registry.register(
2503
Option('create_signatures', default=SIGN_WHEN_REQUIRED,
2504
from_unicode=signing_policy_from_unicode,
2508
Possible values: always, never, when-required (default)
2510
This option controls whether bzr will always create
2511
gpg signatures or not on commits.
2513
option_registry.register(
2514
Option('dirstate.fdatasync', default=True,
2515
from_unicode=bool_from_store,
2517
Flush dirstate changes onto physical disk?
2519
If true (default), working tree metadata changes are flushed through the
2520
OS buffers to physical disk. This is somewhat slower, but means data
2521
should not be lost if the machine crashes. See also repository.fdatasync.
2523
option_registry.register(
2524
ListOption('debug_flags', default=[],
2525
help='Debug flags to activate.'))
2526
option_registry.register(
2527
Option('default_format', default='2a',
2528
help='Format used when creating branches.'))
2529
option_registry.register(
2531
help='The command called to launch an editor to enter a message.'))
2532
option_registry.register(
2533
Option('email', override_from_env=['BRZ_EMAIL'],
2534
default=bedding.default_email, help='The users identity'))
2535
option_registry.register(
2536
Option('gpg_signing_key',
2539
GPG key to use for signing.
2541
This defaults to the first key associated with the users email.
2543
option_registry.register(
2545
help='Language to translate messages into.'))
2546
option_registry.register(
2547
Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2549
Steal locks that appears to be dead.
2551
If set to True, bzr will check if a lock is supposed to be held by an
2552
active process from the same user on the same machine. If the user and
2553
machine match, but no process with the given PID is active, then bzr
2554
will automatically break the stale lock, and create a new lock for
2556
Otherwise, bzr will prompt as normal to break the lock.
2558
option_registry.register(
2559
Option('log_format', default='long',
2561
Log format to use when displaying revisions.
2563
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
2564
may be provided by plugins.
2566
option_registry.register_lazy('mail_client', 'breezy.mail_client',
2568
option_registry.register(
2569
Option('output_encoding',
2570
help='Unicode encoding for output'
2571
' (terminal encoding if not specified).'))
2572
option_registry.register(
2573
Option('parent_location',
2576
The location of the default branch for pull or merge.
2578
This option is normally set when creating a branch, the first ``pull`` or by
2579
``pull --remember``.
2581
option_registry.register(
2582
Option('post_commit', default=None,
2584
Post commit functions.
2586
An ordered list of python functions to call, separated by spaces.
2588
Each function takes branch, rev_id as parameters.
2590
option_registry.register_lazy('progress_bar', 'breezy.ui.text',
2592
option_registry.register(
2593
Option('public_branch',
2596
A publically-accessible version of this branch.
2598
This implies that the branch setting this option is not publically-accessible.
2599
Used and set by ``bzr send``.
2601
option_registry.register(
2602
Option('push_location',
2605
The location of the default branch for push.
2607
This option is normally set by the first ``push`` or ``push --remember``.
2609
option_registry.register(
2610
Option('push_strict', default=None,
2611
from_unicode=bool_from_store,
2613
The default value for ``push --strict``.
2615
If present, defines the ``--strict`` option default value for checking
2616
uncommitted changes before sending a merge directive.
2618
option_registry.register(
2619
Option('repository.fdatasync', default=True,
2620
from_unicode=bool_from_store,
2622
Flush repository changes onto physical disk?
2624
If true (default), repository changes are flushed through the OS buffers
2625
to physical disk. This is somewhat slower, but means data should not be
2626
lost if the machine crashes. See also dirstate.fdatasync.
2628
option_registry.register_lazy('smtp_server',
2629
'breezy.smtp_connection', 'smtp_server')
2630
option_registry.register_lazy('smtp_password',
2631
'breezy.smtp_connection', 'smtp_password')
2632
option_registry.register_lazy('smtp_username',
2633
'breezy.smtp_connection', 'smtp_username')
2634
option_registry.register(
2635
Option('selftest.timeout',
2637
from_unicode=int_from_store,
2638
help='Abort selftest if one test takes longer than this many seconds',
2641
option_registry.register(
2642
Option('send_strict', default=None,
2643
from_unicode=bool_from_store,
2645
The default value for ``send --strict``.
2647
If present, defines the ``--strict`` option default value for checking
2648
uncommitted changes before sending a bundle.
2651
option_registry.register(
2652
Option('serve.client_timeout',
2653
default=300.0, from_unicode=float_from_store,
2654
help="If we wait for a new request from a client for more than"
2655
" X seconds, consider the client idle, and hangup."))
2656
option_registry.register(
2657
Option('stacked_on_location',
2659
help="""The location where this branch is stacked on."""))
2660
option_registry.register(
2661
Option('submit_branch',
2664
The branch you intend to submit your current work to.
2666
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
2667
by the ``submit:`` revision spec.
2669
option_registry.register(
2671
help='''Where submissions from this branch are mailed to.'''))
2672
option_registry.register(
2673
ListOption('suppress_warnings',
2675
help="List of warning classes to suppress."))
2676
option_registry.register(
2677
Option('validate_signatures_in_log', default=False,
2678
from_unicode=bool_from_store, invalid='warning',
2679
help='''Whether to validate signatures in brz log.'''))
2680
option_registry.register_lazy('ssl.ca_certs',
2681
'breezy.transport.http', 'opt_ssl_ca_certs')
2683
option_registry.register_lazy('ssl.cert_reqs',
2684
'breezy.transport.http', 'opt_ssl_cert_reqs')
2687
class Section(object):
2688
"""A section defines a dict of option name => value.
2690
This is merely a read-only dict which can add some knowledge about the
2691
options. It is *not* a python dict object though and doesn't try to mimic
2695
def __init__(self, section_id, options):
2696
self.id = section_id
2697
# We re-use the dict-like object received
2698
self.options = options
2700
def get(self, name, default=None, expand=True):
2701
return self.options.get(name, default)
2703
def iter_option_names(self):
2704
for k in self.options.keys():
2708
# Mostly for debugging use
2709
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2712
_NewlyCreatedOption = object()
2713
"""Was the option created during the MutableSection lifetime"""
2714
_DeletedOption = object()
2715
"""Was the option deleted during the MutableSection lifetime"""
2718
class MutableSection(Section):
2719
"""A section allowing changes and keeping track of the original values."""
2721
def __init__(self, section_id, options):
2722
super(MutableSection, self).__init__(section_id, options)
2723
self.reset_changes()
2725
def set(self, name, value):
2726
if name not in self.options:
2727
# This is a new option
2728
self.orig[name] = _NewlyCreatedOption
2729
elif name not in self.orig:
2730
self.orig[name] = self.get(name, None)
2731
self.options[name] = value
2733
def remove(self, name):
2734
if name not in self.orig and name in self.options:
2735
self.orig[name] = self.get(name, None)
2736
del self.options[name]
2738
def reset_changes(self):
2741
def apply_changes(self, dirty, store):
2742
"""Apply option value changes.
2744
``self`` has been reloaded from the persistent storage. ``dirty``
2745
contains the changes made since the previous loading.
2747
:param dirty: the mutable section containing the changes.
2749
:param store: the store containing the section
2751
for k, expected in dirty.orig.items():
2752
actual = dirty.get(k, _DeletedOption)
2753
reloaded = self.get(k, _NewlyCreatedOption)
2754
if actual is _DeletedOption:
2755
if k in self.options:
2759
# Report concurrent updates in an ad-hoc way. This should only
2760
# occurs when different processes try to update the same option
2761
# which is not supported (as in: the config framework is not meant
2762
# to be used as a sharing mechanism).
2763
if expected != reloaded:
2764
if actual is _DeletedOption:
2765
actual = '<DELETED>'
2766
if reloaded is _NewlyCreatedOption:
2767
reloaded = '<CREATED>'
2768
if expected is _NewlyCreatedOption:
2769
expected = '<CREATED>'
2770
# Someone changed the value since we get it from the persistent
2772
trace.warning(gettext(
2773
"Option {0} in section {1} of {2} was changed"
2774
" from {3} to {4}. The {5} value will be saved.".format(
2775
k, self.id, store.external_url(), expected,
2777
# No need to keep track of these changes
2778
self.reset_changes()
2781
class Store(object):
2782
"""Abstract interface to persistent storage for configuration options."""
2784
readonly_section_class = Section
2785
mutable_section_class = MutableSection
2788
# Which sections need to be saved (by section id). We use a dict here
2789
# so the dirty sections can be shared by multiple callers.
2790
self.dirty_sections = {}
2792
def is_loaded(self):
2793
"""Returns True if the Store has been loaded.
2795
This is used to implement lazy loading and ensure the persistent
2796
storage is queried only when needed.
2798
raise NotImplementedError(self.is_loaded)
2801
"""Loads the Store from persistent storage."""
2802
raise NotImplementedError(self.load)
2804
def _load_from_string(self, bytes):
2805
"""Create a store from a string in configobj syntax.
2807
:param bytes: A string representing the file content.
2809
raise NotImplementedError(self._load_from_string)
2812
"""Unloads the Store.
2814
This should make is_loaded() return False. This is used when the caller
2815
knows that the persistent storage has changed or may have change since
2818
raise NotImplementedError(self.unload)
2820
def quote(self, value):
2821
"""Quote a configuration option value for storing purposes.
2823
This allows Stacks to present values as they will be stored.
2827
def unquote(self, value):
2828
"""Unquote a configuration option value into unicode.
2830
The received value is quoted as stored.
2835
"""Saves the Store to persistent storage."""
2836
raise NotImplementedError(self.save)
2838
def _need_saving(self):
2839
for s in self.dirty_sections.values():
2841
# At least one dirty section contains a modification
2845
def apply_changes(self, dirty_sections):
2846
"""Apply changes from dirty sections while checking for coherency.
2848
The Store content is discarded and reloaded from persistent storage to
2849
acquire up-to-date values.
2851
Dirty sections are MutableSection which kept track of the value they
2852
are expected to update.
2854
# We need an up-to-date version from the persistent storage, unload the
2855
# store. The reload will occur when needed (triggered by the first
2856
# get_mutable_section() call below.
2858
# Apply the changes from the preserved dirty sections
2859
for section_id, dirty in dirty_sections.items():
2860
clean = self.get_mutable_section(section_id)
2861
clean.apply_changes(dirty, self)
2862
# Everything is clean now
2863
self.dirty_sections = {}
2865
def save_changes(self):
2866
"""Saves the Store to persistent storage if changes occurred.
2868
Apply the changes recorded in the mutable sections to a store content
2869
refreshed from persistent storage.
2871
raise NotImplementedError(self.save_changes)
2873
def external_url(self):
2874
raise NotImplementedError(self.external_url)
2876
def get_sections(self):
2877
"""Returns an ordered iterable of existing sections.
2879
:returns: An iterable of (store, section).
2881
raise NotImplementedError(self.get_sections)
2883
def get_mutable_section(self, section_id=None):
2884
"""Returns the specified mutable section.
2886
:param section_id: The section identifier
2888
raise NotImplementedError(self.get_mutable_section)
2891
# Mostly for debugging use
2892
return "<config.%s(%s)>" % (self.__class__.__name__,
2893
self.external_url())
2896
class CommandLineStore(Store):
2897
"A store to carry command line overrides for the config options."""
2899
def __init__(self, opts=None):
2900
super(CommandLineStore, self).__init__()
2907
# The dict should be cleared but not replaced so it can be shared.
2908
self.options.clear()
2910
def _from_cmdline(self, overrides):
2911
# Reset before accepting new definitions
2913
for over in overrides:
2915
name, value = over.split('=', 1)
2917
raise errors.BzrCommandError(
2918
gettext("Invalid '%s', should be of the form 'name=value'")
2920
self.options[name] = value
2922
def external_url(self):
2923
# Not an url but it makes debugging easier and is never needed
2927
def get_sections(self):
2928
yield self, self.readonly_section_class(None, self.options)
2931
class IniFileStore(Store):
2932
"""A config Store using ConfigObj for storage.
2934
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2935
serialize/deserialize the config file.
2939
"""A config Store using ConfigObj for storage.
2941
super(IniFileStore, self).__init__()
2942
self._config_obj = None
2944
def is_loaded(self):
2945
return self._config_obj is not None
2948
self._config_obj = None
2949
self.dirty_sections = {}
2951
def _load_content(self):
2952
"""Load the config file bytes.
2954
This should be provided by subclasses
2956
:return: Byte string
2958
raise NotImplementedError(self._load_content)
2960
def _save_content(self, content):
2961
"""Save the config file bytes.
2963
This should be provided by subclasses
2965
:param content: Config file bytes to write
2967
raise NotImplementedError(self._save_content)
2970
"""Load the store from the associated file."""
2971
if self.is_loaded():
2973
content = self._load_content()
2974
self._load_from_string(content)
2975
for hook in ConfigHooks['load']:
2978
def _load_from_string(self, bytes):
2979
"""Create a config store from a string.
2981
:param bytes: A string representing the file content.
2983
if self.is_loaded():
2984
raise AssertionError('Already loaded: %r' % (self._config_obj,))
2985
co_input = BytesIO(bytes)
2987
# The config files are always stored utf8-encoded
2988
self._config_obj = ConfigObj(co_input, encoding='utf-8',
2990
except configobj.ConfigObjError as e:
2991
self._config_obj = None
2992
raise ParseConfigError(e.errors, self.external_url())
2993
except UnicodeDecodeError:
2994
raise ConfigContentError(self.external_url())
2996
def save_changes(self):
2997
if not self.is_loaded():
3000
if not self._need_saving():
3002
# Preserve the current version
3003
dirty_sections = self.dirty_sections.copy()
3004
self.apply_changes(dirty_sections)
3005
# Save to the persistent storage
3009
if not self.is_loaded():
3013
self._config_obj.write(out)
3014
self._save_content(out.getvalue())
3015
for hook in ConfigHooks['save']:
3018
def get_sections(self):
3019
"""Get the configobj section in the file order.
3021
:returns: An iterable of (store, section).
3023
# We need a loaded store
3026
except (errors.NoSuchFile, errors.PermissionDenied):
3027
# If the file can't be read, there is no sections
3029
cobj = self._config_obj
3031
yield self, self.readonly_section_class(None, cobj)
3032
for section_name in cobj.sections:
3034
self.readonly_section_class(section_name,
3035
cobj[section_name]))
3037
def get_mutable_section(self, section_id=None):
3038
# We need a loaded store
3041
except errors.NoSuchFile:
3042
# The file doesn't exist, let's pretend it was empty
3043
self._load_from_string(b'')
3044
if section_id in self.dirty_sections:
3045
# We already created a mutable section for this id
3046
return self.dirty_sections[section_id]
3047
if section_id is None:
3048
section = self._config_obj
3050
section = self._config_obj.setdefault(section_id, {})
3051
mutable_section = self.mutable_section_class(section_id, section)
3052
# All mutable sections can become dirty
3053
self.dirty_sections[section_id] = mutable_section
3054
return mutable_section
3056
def quote(self, value):
3058
# configobj conflates automagical list values and quoting
3059
self._config_obj.list_values = True
3060
return self._config_obj._quote(value)
3062
self._config_obj.list_values = False
3064
def unquote(self, value):
3065
if value and isinstance(value, string_types):
3066
# _unquote doesn't handle None nor empty strings nor anything that
3067
# is not a string, really.
3068
value = self._config_obj._unquote(value)
3071
def external_url(self):
3072
# Since an IniFileStore can be used without a file (at least in tests),
3073
# it's better to provide something than raising a NotImplementedError.
3074
# All daughter classes are supposed to provide an implementation
3076
return 'In-Process Store, no URL'
3079
class TransportIniFileStore(IniFileStore):
3080
"""IniFileStore that loads files from a transport.
3082
:ivar transport: The transport object where the config file is located.
3084
:ivar file_name: The config file basename in the transport directory.
3087
def __init__(self, transport, file_name):
3088
"""A Store using a ini file on a Transport
3090
:param transport: The transport object where the config file is located.
3091
:param file_name: The config file basename in the transport directory.
3093
super(TransportIniFileStore, self).__init__()
3094
self.transport = transport
3095
self.file_name = file_name
3097
def _load_content(self):
3099
return self.transport.get_bytes(self.file_name)
3100
except errors.PermissionDenied:
3101
trace.warning("Permission denied while trying to load "
3102
"configuration store %s.", self.external_url())
3105
def _save_content(self, content):
3106
self.transport.put_bytes(self.file_name, content)
3108
def external_url(self):
3109
# FIXME: external_url should really accepts an optional relpath
3110
# parameter (bug #750169) :-/ -- vila 2011-04-04
3111
# The following will do in the interim but maybe we don't want to
3112
# expose a path here but rather a config ID and its associated
3113
# object </hand wawe>.
3114
return urlutils.join(
3115
self.transport.external_url(), urlutils.escape(self.file_name))
3118
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
3119
# unlockable stores for use with objects that can already ensure the locking
3120
# (think branches). If different stores (not based on ConfigObj) are created,
3121
# they may face the same issue.
3124
class LockableIniFileStore(TransportIniFileStore):
3125
"""A ConfigObjStore using locks on save to ensure store integrity."""
3127
def __init__(self, transport, file_name, lock_dir_name=None):
3128
"""A config Store using ConfigObj for storage.
3130
:param transport: The transport object where the config file is located.
3132
:param file_name: The config file basename in the transport directory.
3134
if lock_dir_name is None:
3135
lock_dir_name = 'lock'
3136
self.lock_dir_name = lock_dir_name
3137
super(LockableIniFileStore, self).__init__(transport, file_name)
3138
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
3140
def lock_write(self, token=None):
3141
"""Takes a write lock in the directory containing the config file.
3143
If the directory doesn't exist it is created.
3145
# FIXME: This doesn't check the ownership of the created directories as
3146
# ensure_config_dir_exists does. It should if the transport is local
3147
# -- vila 2011-04-06
3148
self.transport.create_prefix()
3149
token = self._lock.lock_write(token)
3150
return lock.LogicalLockResult(self.unlock, token)
3155
def break_lock(self):
3156
self._lock.break_lock()
3159
with self.lock_write():
3160
# We need to be able to override the undecorated implementation
3161
self.save_without_locking()
3163
def save_without_locking(self):
3164
super(LockableIniFileStore, self).save()
3167
# FIXME: global, breezy, shouldn't that be 'user' instead or even
3168
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
3169
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
3171
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
3172
# functions or a registry will make it easier and clearer for tests, focusing
3173
# on the relevant parts of the API that needs testing -- vila 20110503 (based
3174
# on a poolie's remark)
3175
class GlobalStore(LockableIniFileStore):
3176
"""A config store for global options.
3178
There is a single GlobalStore for a given process.
3181
def __init__(self, possible_transports=None):
3182
path, kind = bedding._config_dir()
3183
t = transport.get_transport_from_path(
3184
path, possible_transports=possible_transports)
3185
super(GlobalStore, self).__init__(t, kind + '.conf')
3189
class LocationStore(LockableIniFileStore):
3190
"""A config store for options specific to a location.
3192
There is a single LocationStore for a given process.
3195
def __init__(self, possible_transports=None):
3196
t = transport.get_transport_from_path(
3197
bedding.config_dir(), possible_transports=possible_transports)
3198
super(LocationStore, self).__init__(t, 'locations.conf')
3199
self.id = 'locations'
3202
class BranchStore(TransportIniFileStore):
3203
"""A config store for branch options.
3205
There is a single BranchStore for a given branch.
3208
def __init__(self, branch):
3209
super(BranchStore, self).__init__(branch.control_transport,
3211
self.branch = branch
3215
class ControlStore(LockableIniFileStore):
3217
def __init__(self, bzrdir):
3218
super(ControlStore, self).__init__(bzrdir.transport,
3220
lock_dir_name='branch_lock')
3224
class SectionMatcher(object):
3225
"""Select sections into a given Store.
3227
This is intended to be used to postpone getting an iterable of sections
3231
def __init__(self, store):
3234
def get_sections(self):
3235
# This is where we require loading the store so we can see all defined
3237
sections = self.store.get_sections()
3238
# Walk the revisions in the order provided
3239
for store, s in sections:
3243
def match(self, section):
3244
"""Does the proposed section match.
3246
:param section: A Section object.
3248
:returns: True if the section matches, False otherwise.
3250
raise NotImplementedError(self.match)
3253
class NameMatcher(SectionMatcher):
3255
def __init__(self, store, section_id):
3256
super(NameMatcher, self).__init__(store)
3257
self.section_id = section_id
3259
def match(self, section):
3260
return section.id == self.section_id
3263
class LocationSection(Section):
3265
def __init__(self, section, extra_path, branch_name=None):
3266
super(LocationSection, self).__init__(section.id, section.options)
3267
self.extra_path = extra_path
3268
if branch_name is None:
3270
self.locals = {'relpath': extra_path,
3271
'basename': urlutils.basename(extra_path),
3272
'branchname': branch_name}
3274
def get(self, name, default=None, expand=True):
3275
value = super(LocationSection, self).get(name, default)
3276
if value is not None and expand:
3277
policy_name = self.get(name + ':policy', None)
3278
policy = _policy_value.get(policy_name, POLICY_NONE)
3279
if policy == POLICY_APPENDPATH:
3280
value = urlutils.join(value, self.extra_path)
3281
# expand section local options right now (since POLICY_APPENDPATH
3282
# will never add options references, it's ok to expand after it).
3284
for is_ref, chunk in iter_option_refs(value):
3286
chunks.append(chunk)
3289
if ref in self.locals:
3290
chunks.append(self.locals[ref])
3292
chunks.append(chunk)
3293
value = ''.join(chunks)
3297
class StartingPathMatcher(SectionMatcher):
3298
"""Select sections for a given location respecting the Store order."""
3300
# FIXME: Both local paths and urls can be used for section names as well as
3301
# ``location`` to stay consistent with ``LocationMatcher`` which itself
3302
# inherited the fuzziness from the previous ``LocationConfig``
3303
# implementation. We probably need to revisit which encoding is allowed for
3304
# both ``location`` and section names and how we normalize
3305
# them. http://pad.lv/85479, http://pad.lv/437009 and http://359320 are
3306
# related too. -- vila 2012-01-04
3308
def __init__(self, store, location):
3309
super(StartingPathMatcher, self).__init__(store)
3310
if location.startswith('file://'):
3311
location = urlutils.local_path_from_url(location)
3312
self.location = location
3314
def get_sections(self):
3315
"""Get all sections matching ``location`` in the store.
3317
The most generic sections are described first in the store, then more
3318
specific ones can be provided for reduced scopes.
3320
The returned section are therefore returned in the reversed order so
3321
the most specific ones can be found first.
3323
location_parts = self.location.rstrip('/').split('/')
3325
# Later sections are more specific, they should be returned first
3326
for _, section in reversed(list(store.get_sections())):
3327
if section.id is None:
3328
# The no-name section is always included if present
3329
yield store, LocationSection(section, self.location)
3331
section_path = section.id
3332
if section_path.startswith('file://'):
3333
# the location is already a local path or URL, convert the
3334
# section id to the same format
3335
section_path = urlutils.local_path_from_url(section_path)
3336
if (self.location.startswith(section_path) or
3337
fnmatch.fnmatch(self.location, section_path)):
3338
section_parts = section_path.rstrip('/').split('/')
3339
extra_path = '/'.join(location_parts[len(section_parts):])
3340
yield store, LocationSection(section, extra_path)
3343
class LocationMatcher(SectionMatcher):
3345
def __init__(self, store, location):
3346
super(LocationMatcher, self).__init__(store)
3347
url, params = urlutils.split_segment_parameters(location)
3348
if location.startswith('file://'):
3349
location = urlutils.local_path_from_url(location)
3350
self.location = location
3351
branch_name = params.get('branch')
3352
if branch_name is None:
3353
self.branch_name = urlutils.basename(self.location)
3355
self.branch_name = urlutils.unescape(branch_name)
3357
def _get_matching_sections(self):
3358
"""Get all sections matching ``location``."""
3359
# We slightly diverge from LocalConfig here by allowing the no-name
3360
# section as the most generic one and the lower priority.
3361
no_name_section = None
3363
# Filter out the no_name_section so _iter_for_location_by_parts can be
3364
# used (it assumes all sections have a name).
3365
for _, section in self.store.get_sections():
3366
if section.id is None:
3367
no_name_section = section
3369
all_sections.append(section)
3370
# Unfortunately _iter_for_location_by_parts deals with section names so
3371
# we have to resync.
3372
filtered_sections = _iter_for_location_by_parts(
3373
[s.id for s in all_sections], self.location)
3374
iter_all_sections = iter(all_sections)
3375
matching_sections = []
3376
if no_name_section is not None:
3377
matching_sections.append(
3378
(0, LocationSection(no_name_section, self.location)))
3379
for section_id, extra_path, length in filtered_sections:
3380
# a section id is unique for a given store so it's safe to take the
3381
# first matching section while iterating. Also, all filtered
3382
# sections are part of 'all_sections' and will always be found
3385
section = next(iter_all_sections)
3386
if section_id == section.id:
3387
section = LocationSection(section, extra_path,
3389
matching_sections.append((length, section))
3391
return matching_sections
3393
def get_sections(self):
3394
# Override the default implementation as we want to change the order
3395
# We want the longest (aka more specific) locations first
3396
sections = sorted(self._get_matching_sections(),
3397
key=lambda match: (match[0], match[1].id),
3399
# Sections mentioning 'ignore_parents' restrict the selection
3400
for _, section in sections:
3401
# FIXME: We really want to use as_bool below -- vila 2011-04-07
3402
ignore = section.get('ignore_parents', None)
3403
if ignore is not None:
3404
ignore = ui.bool_from_string(ignore)
3407
# Finally, we have a valid section
3408
yield self.store, section
3411
# FIXME: _shared_stores should be an attribute of a library state once a
3412
# library_state object is always available.
3414
_shared_stores_at_exit_installed = False
3417
class Stack(object):
3418
"""A stack of configurations where an option can be defined"""
3420
def __init__(self, sections_def, store=None, mutable_section_id=None):
3421
"""Creates a stack of sections with an optional store for changes.
3423
:param sections_def: A list of Section or callables that returns an
3424
iterable of Section. This defines the Sections for the Stack and
3425
can be called repeatedly if needed.
3427
:param store: The optional Store where modifications will be
3428
recorded. If none is specified, no modifications can be done.
3430
:param mutable_section_id: The id of the MutableSection where changes
3431
are recorded. This requires the ``store`` parameter to be
3434
self.sections_def = sections_def
3436
self.mutable_section_id = mutable_section_id
3438
def iter_sections(self):
3439
"""Iterate all the defined sections."""
3440
# Ensuring lazy loading is achieved by delaying section matching (which
3441
# implies querying the persistent storage) until it can't be avoided
3442
# anymore by using callables to describe (possibly empty) section
3444
for sections in self.sections_def:
3445
for store, section in sections():
3446
yield store, section
3448
def get(self, name, expand=True, convert=True):
3449
"""Return the *first* option value found in the sections.
3451
This is where we guarantee that sections coming from Store are loaded
3452
lazily: the loading is delayed until we need to either check that an
3453
option exists or get its value, which in turn may require to discover
3454
in which sections it can be defined. Both of these (section and option
3455
existence) require loading the store (even partially).
3457
:param name: The queried option.
3459
:param expand: Whether options references should be expanded.
3461
:param convert: Whether the option value should be converted from
3462
unicode (do nothing for non-registered options).
3464
:returns: The value of the option.
3466
# FIXME: No caching of options nor sections yet -- vila 20110503
3468
found_store = None # Where the option value has been found
3469
# If the option is registered, it may provide additional info about
3472
opt = option_registry.get(name)
3477
def expand_and_convert(val):
3478
# This may need to be called in different contexts if the value is
3479
# None or ends up being None during expansion or conversion.
3482
if isinstance(val, string_types):
3483
val = self._expand_options_in_string(val)
3485
trace.warning('Cannot expand "%s":'
3486
' %s does not support option expansion'
3487
% (name, type(val)))
3489
val = found_store.unquote(val)
3491
val = opt.convert_from_unicode(found_store, val)
3494
# First of all, check if the environment can override the configuration
3496
if opt is not None and opt.override_from_env:
3497
value = opt.get_override()
3498
value = expand_and_convert(value)
3500
for store, section in self.iter_sections():
3501
value = section.get(name)
3502
if value is not None:
3505
value = expand_and_convert(value)
3506
if opt is not None and value is None:
3507
# If the option is registered, it may provide a default value
3508
value = opt.get_default()
3509
value = expand_and_convert(value)
3510
for hook in ConfigHooks['get']:
3511
hook(self, name, value)
3514
def expand_options(self, string, env=None):
3515
"""Expand option references in the string in the configuration context.
3517
:param string: The string containing option(s) to expand.
3519
:param env: An option dict defining additional configuration options or
3520
overriding existing ones.
3522
:returns: The expanded string.
3524
return self._expand_options_in_string(string, env)
3526
def _expand_options_in_string(self, string, env=None, _refs=None):
3527
"""Expand options in the string in the configuration context.
3529
:param string: The string to be expanded.
3531
:param env: An option dict defining additional configuration options or
3532
overriding existing ones.
3534
:param _refs: Private list (FIFO) containing the options being expanded
3537
:returns: The expanded string.
3540
# Not much to expand there
3543
# What references are currently resolved (to detect loops)
3546
# We need to iterate until no more refs appear ({{foo}} will need two
3547
# iterations for example).
3552
for is_ref, chunk in iter_option_refs(result):
3554
chunks.append(chunk)
3559
raise OptionExpansionLoop(string, _refs)
3561
value = self._expand_option(name, env, _refs)
3563
raise ExpandingUnknownOption(name, string)
3564
chunks.append(value)
3566
result = ''.join(chunks)
3569
def _expand_option(self, name, env, _refs):
3570
if env is not None and name in env:
3571
# Special case, values provided in env takes precedence over
3575
value = self.get(name, expand=False, convert=False)
3576
value = self._expand_options_in_string(value, env, _refs)
3579
def _get_mutable_section(self):
3580
"""Get the MutableSection for the Stack.
3582
This is where we guarantee that the mutable section is lazily loaded:
3583
this means we won't load the corresponding store before setting a value
3584
or deleting an option. In practice the store will often be loaded but
3585
this helps catching some programming errors.
3588
section = store.get_mutable_section(self.mutable_section_id)
3589
return store, section
3591
def set(self, name, value):
3592
"""Set a new value for the option."""
3593
store, section = self._get_mutable_section()
3594
section.set(name, store.quote(value))
3595
for hook in ConfigHooks['set']:
3596
hook(self, name, value)
3598
def remove(self, name):
3599
"""Remove an existing option."""
3600
_, section = self._get_mutable_section()
3601
section.remove(name)
3602
for hook in ConfigHooks['remove']:
3606
# Mostly for debugging use
3607
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
3609
def _get_overrides(self):
3610
if breezy._global_state is not None:
3611
# TODO(jelmer): Urgh, this is circular so we can't call breezy.get_global_state()
3612
return breezy._global_state.cmdline_overrides.get_sections()
3615
def get_shared_store(self, store, state=None):
3616
"""Get a known shared store.
3618
Store urls uniquely identify them and are used to ensure a single copy
3619
is shared across all users.
3621
:param store: The store known to the caller.
3623
:param state: The library state where the known stores are kept.
3625
:returns: The store received if it's not a known one, an already known
3629
# TODO(jelmer): Urgh, this is circular so we can't call breezy.get_global_state()
3630
state = breezy._global_state
3632
global _shared_stores_at_exit_installed
3633
stores = _shared_stores
3635
def save_config_changes():
3636
for k, store in stores.items():
3637
store.save_changes()
3638
if not _shared_stores_at_exit_installed:
3639
# FIXME: Ugly hack waiting for library_state to always be
3640
# available. -- vila 20120731
3642
atexit.register(save_config_changes)
3643
_shared_stores_at_exit_installed = True
3645
stores = state.config_stores
3646
url = store.external_url()
3654
class MemoryStack(Stack):
3655
"""A configuration stack defined from a string.
3657
This is mainly intended for tests and requires no disk resources.
3660
def __init__(self, content=None):
3661
"""Create an in-memory stack from a given content.
3663
It uses a single store based on configobj and support reading and
3666
:param content: The initial content of the store. If None, the store is
3667
not loaded and ``_load_from_string`` can and should be used if
3670
store = IniFileStore()
3671
if content is not None:
3672
store._load_from_string(content)
3673
super(MemoryStack, self).__init__(
3674
[store.get_sections], store)
3677
class _CompatibleStack(Stack):
3678
"""Place holder for compatibility with previous design.
3680
This is intended to ease the transition from the Config-based design to the
3681
Stack-based design and should not be used nor relied upon by plugins.
3683
One assumption made here is that the daughter classes will all use Stores
3684
derived from LockableIniFileStore).
3686
It implements set() and remove () by re-loading the store before applying
3687
the modification and saving it.
3689
The long term plan being to implement a single write by store to save
3690
all modifications, this class should not be used in the interim.
3693
def set(self, name, value):
3696
super(_CompatibleStack, self).set(name, value)
3697
# Force a write to persistent storage
3700
def remove(self, name):
3703
super(_CompatibleStack, self).remove(name)
3704
# Force a write to persistent storage
3708
class GlobalStack(Stack):
3709
"""Global options only stack.
3711
The following sections are queried:
3713
* command-line overrides,
3715
* the 'DEFAULT' section in bazaar.conf
3717
This stack will use the ``DEFAULT`` section in bazaar.conf as its
3722
gstore = self.get_shared_store(GlobalStore())
3723
super(GlobalStack, self).__init__(
3724
[self._get_overrides,
3725
NameMatcher(gstore, 'DEFAULT').get_sections],
3726
gstore, mutable_section_id='DEFAULT')
3729
class LocationStack(Stack):
3730
"""Per-location options falling back to global options stack.
3733
The following sections are queried:
3735
* command-line overrides,
3737
* the sections matching ``location`` in ``locations.conf``, the order being
3738
defined by the number of path components in the section glob, higher
3739
numbers first (from most specific section to most generic).
3741
* the 'DEFAULT' section in bazaar.conf
3743
This stack will use the ``location`` section in locations.conf as its
3747
def __init__(self, location):
3748
"""Make a new stack for a location and global configuration.
3750
:param location: A URL prefix to """
3751
lstore = self.get_shared_store(LocationStore())
3752
if location.startswith('file://'):
3753
location = urlutils.local_path_from_url(location)
3754
gstore = self.get_shared_store(GlobalStore())
3755
super(LocationStack, self).__init__(
3756
[self._get_overrides,
3757
LocationMatcher(lstore, location).get_sections,
3758
NameMatcher(gstore, 'DEFAULT').get_sections],
3759
lstore, mutable_section_id=location)
3762
class BranchStack(Stack):
3763
"""Per-location options falling back to branch then global options stack.
3765
The following sections are queried:
3767
* command-line overrides,
3769
* the sections matching ``location`` in ``locations.conf``, the order being
3770
defined by the number of path components in the section glob, higher
3771
numbers first (from most specific section to most generic),
3773
* the no-name section in branch.conf,
3775
* the ``DEFAULT`` section in ``bazaar.conf``.
3777
This stack will use the no-name section in ``branch.conf`` as its
3781
def __init__(self, branch):
3782
lstore = self.get_shared_store(LocationStore())
3783
bstore = branch._get_config_store()
3784
gstore = self.get_shared_store(GlobalStore())
3785
super(BranchStack, self).__init__(
3786
[self._get_overrides,
3787
LocationMatcher(lstore, branch.base).get_sections,
3788
NameMatcher(bstore, None).get_sections,
3789
NameMatcher(gstore, 'DEFAULT').get_sections],
3791
self.branch = branch
3793
def lock_write(self, token=None):
3794
return self.branch.lock_write(token)
3797
return self.branch.unlock()
3799
def set(self, name, value):
3800
with self.lock_write():
3801
super(BranchStack, self).set(name, value)
3802
# Unlocking the branch will trigger a store.save_changes() so the
3803
# last unlock saves all the changes.
3805
def remove(self, name):
3806
with self.lock_write():
3807
super(BranchStack, self).remove(name)
3808
# Unlocking the branch will trigger a store.save_changes() so the
3809
# last unlock saves all the changes.
3812
class RemoteControlStack(Stack):
3813
"""Remote control-only options stack."""
3815
# FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
3816
# with the stack used for remote bzr dirs. RemoteControlStack only uses
3817
# control.conf and is used only for stack options.
3819
def __init__(self, bzrdir):
3820
cstore = bzrdir._get_config_store()
3821
super(RemoteControlStack, self).__init__(
3822
[NameMatcher(cstore, None).get_sections],
3824
self.controldir = bzrdir
3827
class BranchOnlyStack(Stack):
3828
"""Branch-only options stack."""
3830
# FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
3831
# stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
3832
# -- vila 2011-12-16
3834
def __init__(self, branch):
3835
bstore = branch._get_config_store()
3836
super(BranchOnlyStack, self).__init__(
3837
[NameMatcher(bstore, None).get_sections],
3839
self.branch = branch
3841
def lock_write(self, token=None):
3842
return self.branch.lock_write(token)
3845
return self.branch.unlock()
3847
def set(self, name, value):
3848
with self.lock_write():
3849
super(BranchOnlyStack, self).set(name, value)
3850
# Force a write to persistent storage
3851
self.store.save_changes()
3853
def remove(self, name):
3854
with self.lock_write():
3855
super(BranchOnlyStack, self).remove(name)
3856
# Force a write to persistent storage
3857
self.store.save_changes()
3860
class cmd_config(commands.Command):
3861
__doc__ = """Display, set or remove a configuration option.
3863
Display the active value for option NAME.
3865
If --all is specified, NAME is interpreted as a regular expression and all
3866
matching options are displayed mentioning their scope and without resolving
3867
option references in the value). The active value that bzr will take into
3868
account is the first one displayed for each option.
3870
If NAME is not given, --all .* is implied (all options are displayed for the
3873
Setting a value is achieved by using NAME=value without spaces. The value
3874
is set in the most relevant scope and can be checked by displaying the
3877
Removing a value is achieved by using --remove NAME.
3880
takes_args = ['name?']
3884
# FIXME: This should be a registry option so that plugins can register
3885
# their own config files (or not) and will also address
3886
# http://pad.lv/788991 -- vila 20101115
3887
commands.Option('scope', help='Reduce the scope to the specified'
3888
' configuration file.',
3890
commands.Option('all',
3891
help='Display all the defined values for the matching options.',
3893
commands.Option('remove', help='Remove the option from'
3894
' the configuration file.'),
3897
_see_also = ['configuration']
3899
@commands.display_command
3900
def run(self, name=None, all=False, directory=None, scope=None,
3902
if directory is None:
3904
directory = directory_service.directories.dereference(directory)
3905
directory = urlutils.normalize_url(directory)
3907
raise errors.BzrError(
3908
'--all and --remove are mutually exclusive.')
3910
# Delete the option in the given scope
3911
self._remove_config_option(name, directory, scope)
3913
# Defaults to all options
3914
self._show_matching_options('.*', directory, scope)
3917
name, value = name.split('=', 1)
3919
# Display the option(s) value(s)
3921
self._show_matching_options(name, directory, scope)
3923
self._show_value(name, directory, scope)
3926
raise errors.BzrError(
3927
'Only one option can be set.')
3928
# Set the option value
3929
self._set_config_option(name, value, directory, scope)
3931
def _get_stack(self, directory, scope=None, write_access=False):
3932
"""Get the configuration stack specified by ``directory`` and ``scope``.
3934
:param directory: Where the configurations are derived from.
3936
:param scope: A specific config to start from.
3938
:param write_access: Whether a write access to the stack will be
3941
# FIXME: scope should allow access to plugin-specific stacks (even
3942
# reduced to the plugin-specific store), related to
3943
# http://pad.lv/788991 -- vila 2011-11-15
3944
if scope is not None:
3945
if scope == 'breezy':
3946
return GlobalStack()
3947
elif scope == 'locations':
3948
return LocationStack(directory)
3949
elif scope == 'branch':
3951
controldir.ControlDir.open_containing_tree_or_branch(
3954
self.add_cleanup(br.lock_write().unlock)
3955
return br.get_config_stack()
3956
raise NoSuchConfig(scope)
3960
controldir.ControlDir.open_containing_tree_or_branch(
3963
self.add_cleanup(br.lock_write().unlock)
3964
return br.get_config_stack()
3965
except errors.NotBranchError:
3966
return LocationStack(directory)
3968
def _quote_multiline(self, value):
3970
value = '"""' + value + '"""'
3973
def _show_value(self, name, directory, scope):
3974
conf = self._get_stack(directory, scope)
3975
value = conf.get(name, expand=True, convert=False)
3976
if value is not None:
3977
# Quote the value appropriately
3978
value = self._quote_multiline(value)
3979
self.outf.write('%s\n' % (value,))
3981
raise NoSuchConfigOption(name)
3983
def _show_matching_options(self, name, directory, scope):
3984
name = lazy_regex.lazy_compile(name)
3985
# We want any error in the regexp to be raised *now* so we need to
3986
# avoid the delay introduced by the lazy regexp. But, we still do
3987
# want the nicer errors raised by lazy_regex.
3988
name._compile_and_collapse()
3991
conf = self._get_stack(directory, scope)
3992
for store, section in conf.iter_sections():
3993
for oname in section.iter_option_names():
3994
if name.search(oname):
3995
if cur_store_id != store.id:
3996
# Explain where the options are defined
3997
self.outf.write('%s:\n' % (store.id,))
3998
cur_store_id = store.id
4000
if (section.id is not None and cur_section != section.id):
4001
# Display the section id as it appears in the store
4002
# (None doesn't appear by definition)
4003
self.outf.write(' [%s]\n' % (section.id,))
4004
cur_section = section.id
4005
value = section.get(oname, expand=False)
4006
# Quote the value appropriately
4007
value = self._quote_multiline(value)
4008
self.outf.write(' %s = %s\n' % (oname, value))
4010
def _set_config_option(self, name, value, directory, scope):
4011
conf = self._get_stack(directory, scope, write_access=True)
4012
conf.set(name, value)
4013
# Explicitly save the changes
4014
conf.store.save_changes()
4016
def _remove_config_option(self, name, directory, scope):
4018
raise errors.BzrCommandError(
4019
'--remove expects an option to remove.')
4020
conf = self._get_stack(directory, scope, write_access=True)
4023
# Explicitly save the changes
4024
conf.store.save_changes()
4026
raise NoSuchConfigOption(name)
4031
# We need adapters that can build a Store or a Stack in a test context. Test
4032
# classes, based on TestCaseWithTransport, can use the registry to parametrize
4033
# themselves. The builder will receive a test instance and should return a
4034
# ready-to-use store or stack. Plugins that define new store/stacks can also
4035
# register themselves here to be tested against the tests defined in
4036
# breezy.tests.test_config. Note that the builder can be called multiple times
4037
# for the same test.
4039
# The registered object should be a callable receiving a test instance
4040
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
4042
test_store_builder_registry = registry.Registry()
4044
# The registered object should be a callable receiving a test instance
4045
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
4047
test_stack_builder_registry = registry.Registry()