178
231
def _get_signing_policy(self):
179
232
"""Template method to override signature creation policy."""
236
def expand_options(self, string, env=None):
237
"""Expand option references in the string in the configuration context.
239
:param string: The string containing option to expand.
241
:param env: An option dict defining additional configuration options or
242
overriding existing ones.
244
:returns: The expanded string.
246
return self._expand_options_in_string(string, env)
248
def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
249
"""Expand options in a list of strings in the configuration context.
251
:param slist: A list of strings.
253
:param env: An option dict defining additional configuration options or
254
overriding existing ones.
256
:param _ref_stack: Private list containing the options being
257
expanded to detect loops.
259
:returns: The flatten list of expanded strings.
261
# expand options in each value separately flattening lists
264
value = self._expand_options_in_string(s, env, _ref_stack)
265
if isinstance(value, list):
271
def _expand_options_in_string(self, string, env=None, _ref_stack=None):
272
"""Expand options in the string in the configuration context.
274
:param string: The string to be expanded.
276
:param env: An option dict defining additional configuration options or
277
overriding existing ones.
279
:param _ref_stack: Private list containing the options being
280
expanded to detect loops.
282
:returns: The expanded string.
285
# Not much to expand there
287
if _ref_stack is None:
288
# What references are currently resolved (to detect loops)
290
if self.option_ref_re is None:
291
# We want to match the most embedded reference first (i.e. for
292
# '{{foo}}' we will get '{foo}',
293
# for '{bar{baz}}' we will get '{baz}'
294
self.option_ref_re = re.compile('({[^{}]+})')
296
# We need to iterate until no more refs appear ({{foo}} will need two
297
# iterations for example).
299
raw_chunks = self.option_ref_re.split(result)
300
if len(raw_chunks) == 1:
301
# Shorcut the trivial case: no refs
305
# Split will isolate refs so that every other chunk is a ref
307
for chunk in raw_chunks:
310
# Keep only non-empty strings (or we get bogus empty
311
# slots when a list value is involved).
316
if name in _ref_stack:
317
raise errors.OptionExpansionLoop(string, _ref_stack)
318
_ref_stack.append(name)
319
value = self._expand_option(name, env, _ref_stack)
321
raise errors.ExpandingUnknownOption(name, string)
322
if isinstance(value, list):
330
# Once a list appears as the result of an expansion, all
331
# callers will get a list result. This allows a consistent
332
# behavior even when some options in the expansion chain
333
# defined as strings (no comma in their value) but their
334
# expanded value is a list.
335
return self._expand_options_in_list(chunks, env, _ref_stack)
337
result = ''.join(chunks)
340
def _expand_option(self, name, env, _ref_stack):
341
if env is not None and name in env:
342
# Special case, values provided in env takes precedence over
346
# FIXME: This is a limited implementation, what we really need is a
347
# way to query the bzr config for the value of an option,
348
# respecting the scope rules (That is, once we implement fallback
349
# configs, getting the option value should restart from the top
350
# config, not the current one) -- vila 20101222
351
value = self.get_user_option(name, expand=False)
352
if isinstance(value, list):
353
value = self._expand_options_in_list(value, env, _ref_stack)
355
value = self._expand_options_in_string(value, env, _ref_stack)
181
358
def _get_user_option(self, option_name):
182
359
"""Template method to provide a user option."""
185
def get_user_option(self, option_name):
186
"""Get a generic option - no special process, no default."""
187
return self._get_user_option(option_name)
189
def get_user_option_as_bool(self, option_name):
190
"""Get a generic option as a boolean - no special process, no default.
362
def get_user_option(self, option_name, expand=None):
363
"""Get a generic option - no special process, no default.
365
:param option_name: The queried option.
367
:param expand: Whether options references should be expanded.
369
:returns: The value of the option.
372
expand = _get_expand_default_value()
373
value = self._get_user_option(option_name)
375
if isinstance(value, list):
376
value = self._expand_options_in_list(value)
377
elif isinstance(value, dict):
378
trace.warning('Cannot expand "%s":'
379
' Dicts do not support option expansion'
382
value = self._expand_options_in_string(value)
383
for hook in OldConfigHooks['get']:
384
hook(self, option_name, value)
387
def get_user_option_as_bool(self, option_name, expand=None, default=None):
388
"""Get a generic option as a boolean.
390
:param expand: Allow expanding references to other config values.
391
:param default: Default value if nothing is configured
192
392
:return None if the option doesn't exist or its value can't be
193
393
interpreted as a boolean. Returns True or False otherwise.
195
s = self._get_user_option(option_name)
395
s = self.get_user_option(option_name, expand=expand)
197
397
# The option doesn't exist
199
399
val = ui.bool_from_string(s)
201
401
# The value can't be interpreted as a boolean
582
def get_merge_tools(self):
584
for (oname, value, section, conf_id, parser) in self._get_options():
585
if oname.startswith('bzr.mergetool.'):
586
tool_name = oname[len('bzr.mergetool.'):]
587
tools[tool_name] = value
588
trace.mutter('loaded merge tools: %r' % tools)
591
def find_merge_tool(self, name):
592
# We fake a defaults mechanism here by checking if the given name can
593
# be found in the known_merge_tools if it's not found in the config.
594
# This should be done through the proposed config defaults mechanism
595
# when it becomes available in the future.
596
command_line = (self.get_user_option('bzr.mergetool.%s' % name,
598
or mergetools.known_merge_tools.get(name, None))
602
class _ConfigHooks(hooks.Hooks):
603
"""A dict mapping hook names and a list of callables for configs.
607
"""Create the default hooks.
609
These are all empty initially, because by default nothing should get
612
super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
613
self.add_hook('load',
614
'Invoked when a config store is loaded.'
615
' The signature is (store).',
617
self.add_hook('save',
618
'Invoked when a config store is saved.'
619
' The signature is (store).',
621
# The hooks for config options
623
'Invoked when a config option is read.'
624
' The signature is (stack, name, value).',
627
'Invoked when a config option is set.'
628
' The signature is (stack, name, value).',
630
self.add_hook('remove',
631
'Invoked when a config option is removed.'
632
' The signature is (stack, name).',
634
ConfigHooks = _ConfigHooks()
637
class _OldConfigHooks(hooks.Hooks):
638
"""A dict mapping hook names and a list of callables for configs.
642
"""Create the default hooks.
644
These are all empty initially, because by default nothing should get
647
super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
648
self.add_hook('load',
649
'Invoked when a config store is loaded.'
650
' The signature is (config).',
652
self.add_hook('save',
653
'Invoked when a config store is saved.'
654
' The signature is (config).',
656
# The hooks for config options
658
'Invoked when a config option is read.'
659
' The signature is (config, name, value).',
662
'Invoked when a config option is set.'
663
' The signature is (config, name, value).',
665
self.add_hook('remove',
666
'Invoked when a config option is removed.'
667
' The signature is (config, name).',
669
OldConfigHooks = _OldConfigHooks()
350
672
class IniBasedConfig(Config):
351
673
"""A configuration policy that draws from ini files."""
353
def __init__(self, get_filename):
675
def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
677
"""Base class for configuration files using an ini-like syntax.
679
:param file_name: The configuration file path.
354
681
super(IniBasedConfig, self).__init__()
355
self._get_filename = get_filename
682
self.file_name = file_name
683
if symbol_versioning.deprecated_passed(get_filename):
684
symbol_versioning.warn(
685
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
686
' Use file_name instead.',
689
if get_filename is not None:
690
self.file_name = get_filename()
692
self.file_name = file_name
356
694
self._parser = None
358
def _get_parser(self, file=None):
697
def from_string(cls, str_or_unicode, file_name=None, save=False):
698
"""Create a config object from a string.
700
:param str_or_unicode: A string representing the file content. This will
703
:param file_name: The configuration file path.
705
:param _save: Whether the file should be saved upon creation.
707
conf = cls(file_name=file_name)
708
conf._create_from_string(str_or_unicode, save)
711
def _create_from_string(self, str_or_unicode, save):
712
self._content = StringIO(str_or_unicode.encode('utf-8'))
713
# Some tests use in-memory configs, some other always need the config
714
# file to exist on disk.
716
self._write_config_file()
718
def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
359
719
if self._parser is not None:
360
720
return self._parser
362
input = self._get_filename()
721
if symbol_versioning.deprecated_passed(file):
722
symbol_versioning.warn(
723
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
724
' Use IniBasedConfig(_content=xxx) instead.',
727
if self._content is not None:
728
co_input = self._content
729
elif self.file_name is None:
730
raise AssertionError('We have no content to create the config')
732
co_input = self.file_name
366
self._parser = ConfigObj(input, encoding='utf-8')
734
self._parser = ConfigObj(co_input, encoding='utf-8')
367
735
except configobj.ConfigObjError, e:
368
736
raise errors.ParseConfigError(e.errors, e.config.filename)
737
except UnicodeDecodeError:
738
raise errors.ConfigContentError(self.file_name)
739
# Make sure self.reload() will use the right file name
740
self._parser.filename = self.file_name
741
for hook in OldConfigHooks['load']:
369
743
return self._parser
746
"""Reload the config file from disk."""
747
if self.file_name is None:
748
raise AssertionError('We need a file name to reload the config')
749
if self._parser is not None:
750
self._parser.reload()
751
for hook in ConfigHooks['load']:
371
754
def _get_matching_sections(self):
372
755
"""Return an ordered list of (section_name, extra_path) pairs.
1508
2217
configobj[name] = value
1510
2219
configobj.setdefault(section, {})[name] = value
2220
for hook in OldConfigHooks['set']:
2221
hook(self, name, value)
2222
self._set_configobj(configobj)
2224
def remove_option(self, option_name, section_name=None):
2225
configobj = self._get_configobj()
2226
if section_name is None:
2227
del configobj[option_name]
2229
del configobj[section_name][option_name]
2230
for hook in OldConfigHooks['remove']:
2231
hook(self, option_name)
1511
2232
self._set_configobj(configobj)
1513
2234
def _get_config_file(self):
1515
return StringIO(self._transport.get_bytes(self._filename))
2236
f = StringIO(self._transport.get_bytes(self._filename))
2237
for hook in OldConfigHooks['load']:
1516
2240
except errors.NoSuchFile:
1517
2241
return StringIO()
2243
def _external_url(self):
2244
return urlutils.join(self._transport.external_url(), self._filename)
1519
2246
def _get_configobj(self):
1520
return ConfigObj(self._get_config_file(), encoding='utf-8')
2247
f = self._get_config_file()
2250
conf = ConfigObj(f, encoding='utf-8')
2251
except configobj.ConfigObjError, e:
2252
raise errors.ParseConfigError(e.errors, self._external_url())
2253
except UnicodeDecodeError:
2254
raise errors.ConfigContentError(self._external_url())
1522
2259
def _set_configobj(self, configobj):
1523
2260
out_file = StringIO()
1524
2261
configobj.write(out_file)
1525
2262
out_file.seek(0)
1526
2263
self._transport.put_file(self._filename, out_file)
2264
for hook in OldConfigHooks['save']:
2268
class Option(object):
2269
"""An option definition.
2271
The option *values* are stored in config files and found in sections.
2273
Here we define various properties about the option itself, its default
2274
value, in which config files it can be stored, etc (TBC).
2277
def __init__(self, name, default=None, help=None):
2279
self.default = default
2282
def get_default(self):
2285
def get_help_text(self, additional_see_also=None, plain=True):
2287
from bzrlib import help_topics
2288
result += help_topics._format_see_also(additional_see_also)
2290
result = help_topics.help_as_plain_text(result)
2294
class OptionRegistry(registry.Registry):
2295
"""Register config options by their name.
2297
This overrides ``registry.Registry`` to simplify registration by acquiring
2298
some information from the option object itself.
2301
def register(self, option):
2302
"""Register a new option to its name.
2304
:param option: The option to register. Its name is used as the key.
2306
super(OptionRegistry, self).register(option.name, option,
2309
def register_lazy(self, key, module_name, member_name):
2310
"""Register a new option to be loaded on request.
2312
:param key: the key to request the option later. Since the registration
2313
is lazy, it should be provided and match the option name.
2315
:param module_name: the python path to the module. Such as 'os.path'.
2317
:param member_name: the member of the module to return. If empty or
2318
None, get() will return the module itself.
2320
super(OptionRegistry, self).register_lazy(key,
2321
module_name, member_name)
2323
def get_help(self, key=None):
2324
"""Get the help text associated with the given key"""
2325
option = self.get(key)
2326
the_help = option.help
2327
if callable(the_help):
2328
return the_help(self, key)
2332
option_registry = OptionRegistry()
2335
# Registered options in lexicographical order
2337
option_registry.register(
2338
Option('dirstate.fdatasync', default=True,
2340
Flush dirstate changes onto physical disk?
2342
If true (default), working tree metadata changes are flushed through the
2343
OS buffers to physical disk. This is somewhat slower, but means data
2344
should not be lost if the machine crashes. See also repository.fdatasync.
2346
option_registry.register(
2347
Option('default_format', default='2a',
2348
help='Format used when creating branches.'))
2349
option_registry.register(
2351
help='The command called to launch an editor to enter a message.'))
2352
option_registry.register(
2354
help='Language to translate messages into.'))
2355
option_registry.register(
2356
Option('output_encoding',
2357
help= 'Unicode encoding for output'
2358
' (terminal encoding if not specified).'))
2359
option_registry.register(
2360
Option('repository.fdatasync', default=True,
2362
Flush repository changes onto physical disk?
2364
If true (default), repository changes are flushed through the OS buffers
2365
to physical disk. This is somewhat slower, but means data should not be
2366
lost if the machine crashes. See also dirstate.fdatasync.
2370
class Section(object):
2371
"""A section defines a dict of option name => value.
2373
This is merely a read-only dict which can add some knowledge about the
2374
options. It is *not* a python dict object though and doesn't try to mimic
2378
def __init__(self, section_id, options):
2379
self.id = section_id
2380
# We re-use the dict-like object received
2381
self.options = options
2383
def get(self, name, default=None):
2384
return self.options.get(name, default)
2387
# Mostly for debugging use
2388
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2391
_NewlyCreatedOption = object()
2392
"""Was the option created during the MutableSection lifetime"""
2395
class MutableSection(Section):
2396
"""A section allowing changes and keeping track of the original values."""
2398
def __init__(self, section_id, options):
2399
super(MutableSection, self).__init__(section_id, options)
2402
def set(self, name, value):
2403
if name not in self.options:
2404
# This is a new option
2405
self.orig[name] = _NewlyCreatedOption
2406
elif name not in self.orig:
2407
self.orig[name] = self.get(name, None)
2408
self.options[name] = value
2410
def remove(self, name):
2411
if name not in self.orig:
2412
self.orig[name] = self.get(name, None)
2413
del self.options[name]
2416
class Store(object):
2417
"""Abstract interface to persistent storage for configuration options."""
2419
readonly_section_class = Section
2420
mutable_section_class = MutableSection
2422
def is_loaded(self):
2423
"""Returns True if the Store has been loaded.
2425
This is used to implement lazy loading and ensure the persistent
2426
storage is queried only when needed.
2428
raise NotImplementedError(self.is_loaded)
2431
"""Loads the Store from persistent storage."""
2432
raise NotImplementedError(self.load)
2434
def _load_from_string(self, bytes):
2435
"""Create a store from a string in configobj syntax.
2437
:param bytes: A string representing the file content.
2439
raise NotImplementedError(self._load_from_string)
2442
"""Unloads the Store.
2444
This should make is_loaded() return False. This is used when the caller
2445
knows that the persistent storage has changed or may have change since
2448
raise NotImplementedError(self.unload)
2451
"""Saves the Store to persistent storage."""
2452
raise NotImplementedError(self.save)
2454
def external_url(self):
2455
raise NotImplementedError(self.external_url)
2457
def get_sections(self):
2458
"""Returns an ordered iterable of existing sections.
2460
:returns: An iterable of (name, dict).
2462
raise NotImplementedError(self.get_sections)
2464
def get_mutable_section(self, section_name=None):
2465
"""Returns the specified mutable section.
2467
:param section_name: The section identifier
2469
raise NotImplementedError(self.get_mutable_section)
2472
# Mostly for debugging use
2473
return "<config.%s(%s)>" % (self.__class__.__name__,
2474
self.external_url())
2477
class IniFileStore(Store):
2478
"""A config Store using ConfigObj for storage.
2480
:ivar transport: The transport object where the config file is located.
2482
:ivar file_name: The config file basename in the transport directory.
2484
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2485
serialize/deserialize the config file.
2488
def __init__(self, transport, file_name):
2489
"""A config Store using ConfigObj for storage.
2491
:param transport: The transport object where the config file is located.
2493
:param file_name: The config file basename in the transport directory.
2495
super(IniFileStore, self).__init__()
2496
self.transport = transport
2497
self.file_name = file_name
2498
self._config_obj = None
2500
def is_loaded(self):
2501
return self._config_obj != None
2504
self._config_obj = None
2507
"""Load the store from the associated file."""
2508
if self.is_loaded():
2510
content = self.transport.get_bytes(self.file_name)
2511
self._load_from_string(content)
2512
for hook in ConfigHooks['load']:
2515
def _load_from_string(self, bytes):
2516
"""Create a config store from a string.
2518
:param bytes: A string representing the file content.
2520
if self.is_loaded():
2521
raise AssertionError('Already loaded: %r' % (self._config_obj,))
2522
co_input = StringIO(bytes)
2524
# The config files are always stored utf8-encoded
2525
self._config_obj = ConfigObj(co_input, encoding='utf-8')
2526
except configobj.ConfigObjError, e:
2527
self._config_obj = None
2528
raise errors.ParseConfigError(e.errors, self.external_url())
2529
except UnicodeDecodeError:
2530
raise errors.ConfigContentError(self.external_url())
2533
if not self.is_loaded():
2537
self._config_obj.write(out)
2538
self.transport.put_bytes(self.file_name, out.getvalue())
2539
for hook in ConfigHooks['save']:
2542
def external_url(self):
2543
# FIXME: external_url should really accepts an optional relpath
2544
# parameter (bug #750169) :-/ -- vila 2011-04-04
2545
# The following will do in the interim but maybe we don't want to
2546
# expose a path here but rather a config ID and its associated
2547
# object </hand wawe>.
2548
return urlutils.join(self.transport.external_url(), self.file_name)
2550
def get_sections(self):
2551
"""Get the configobj section in the file order.
2553
:returns: An iterable of (name, dict).
2555
# We need a loaded store
2558
except errors.NoSuchFile:
2559
# If the file doesn't exist, there is no sections
2561
cobj = self._config_obj
2563
yield self.readonly_section_class(None, cobj)
2564
for section_name in cobj.sections:
2565
yield self.readonly_section_class(section_name, cobj[section_name])
2567
def get_mutable_section(self, section_name=None):
2568
# We need a loaded store
2571
except errors.NoSuchFile:
2572
# The file doesn't exist, let's pretend it was empty
2573
self._load_from_string('')
2574
if section_name is None:
2575
section = self._config_obj
2577
section = self._config_obj.setdefault(section_name, {})
2578
return self.mutable_section_class(section_name, section)
2581
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2582
# unlockable stores for use with objects that can already ensure the locking
2583
# (think branches). If different stores (not based on ConfigObj) are created,
2584
# they may face the same issue.
2587
class LockableIniFileStore(IniFileStore):
2588
"""A ConfigObjStore using locks on save to ensure store integrity."""
2590
def __init__(self, transport, file_name, lock_dir_name=None):
2591
"""A config Store using ConfigObj for storage.
2593
:param transport: The transport object where the config file is located.
2595
:param file_name: The config file basename in the transport directory.
2597
if lock_dir_name is None:
2598
lock_dir_name = 'lock'
2599
self.lock_dir_name = lock_dir_name
2600
super(LockableIniFileStore, self).__init__(transport, file_name)
2601
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2603
def lock_write(self, token=None):
2604
"""Takes a write lock in the directory containing the config file.
2606
If the directory doesn't exist it is created.
2608
# FIXME: This doesn't check the ownership of the created directories as
2609
# ensure_config_dir_exists does. It should if the transport is local
2610
# -- vila 2011-04-06
2611
self.transport.create_prefix()
2612
return self._lock.lock_write(token)
2617
def break_lock(self):
2618
self._lock.break_lock()
2622
# We need to be able to override the undecorated implementation
2623
self.save_without_locking()
2625
def save_without_locking(self):
2626
super(LockableIniFileStore, self).save()
2629
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2630
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2631
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
2633
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2634
# functions or a registry will make it easier and clearer for tests, focusing
2635
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2636
# on a poolie's remark)
2637
class GlobalStore(LockableIniFileStore):
2639
def __init__(self, possible_transports=None):
2640
t = transport.get_transport_from_path(config_dir(),
2641
possible_transports=possible_transports)
2642
super(GlobalStore, self).__init__(t, 'bazaar.conf')
2645
class LocationStore(LockableIniFileStore):
2647
def __init__(self, possible_transports=None):
2648
t = transport.get_transport_from_path(config_dir(),
2649
possible_transports=possible_transports)
2650
super(LocationStore, self).__init__(t, 'locations.conf')
2653
class BranchStore(IniFileStore):
2655
def __init__(self, branch):
2656
super(BranchStore, self).__init__(branch.control_transport,
2658
self.branch = branch
2660
def lock_write(self, token=None):
2661
return self.branch.lock_write(token)
2664
return self.branch.unlock()
2668
# We need to be able to override the undecorated implementation
2669
self.save_without_locking()
2671
def save_without_locking(self):
2672
super(BranchStore, self).save()
2675
class SectionMatcher(object):
2676
"""Select sections into a given Store.
2678
This intended to be used to postpone getting an iterable of sections from a
2682
def __init__(self, store):
2685
def get_sections(self):
2686
# This is where we require loading the store so we can see all defined
2688
sections = self.store.get_sections()
2689
# Walk the revisions in the order provided
2694
def match(self, secion):
2695
raise NotImplementedError(self.match)
2698
class LocationSection(Section):
2700
def __init__(self, section, length, extra_path):
2701
super(LocationSection, self).__init__(section.id, section.options)
2702
self.length = length
2703
self.extra_path = extra_path
2705
def get(self, name, default=None):
2706
value = super(LocationSection, self).get(name, default)
2707
if value is not None:
2708
policy_name = self.get(name + ':policy', None)
2709
policy = _policy_value.get(policy_name, POLICY_NONE)
2710
if policy == POLICY_APPENDPATH:
2711
value = urlutils.join(value, self.extra_path)
2715
class LocationMatcher(SectionMatcher):
2717
def __init__(self, store, location):
2718
super(LocationMatcher, self).__init__(store)
2719
if location.startswith('file://'):
2720
location = urlutils.local_path_from_url(location)
2721
self.location = location
2723
def _get_matching_sections(self):
2724
"""Get all sections matching ``location``."""
2725
# We slightly diverge from LocalConfig here by allowing the no-name
2726
# section as the most generic one and the lower priority.
2727
no_name_section = None
2729
# Filter out the no_name_section so _iter_for_location_by_parts can be
2730
# used (it assumes all sections have a name).
2731
for section in self.store.get_sections():
2732
if section.id is None:
2733
no_name_section = section
2735
sections.append(section)
2736
# Unfortunately _iter_for_location_by_parts deals with section names so
2737
# we have to resync.
2738
filtered_sections = _iter_for_location_by_parts(
2739
[s.id for s in sections], self.location)
2740
iter_sections = iter(sections)
2741
matching_sections = []
2742
if no_name_section is not None:
2743
matching_sections.append(
2744
LocationSection(no_name_section, 0, self.location))
2745
for section_id, extra_path, length in filtered_sections:
2746
# a section id is unique for a given store so it's safe to iterate
2748
section = iter_sections.next()
2749
if section_id == section.id:
2750
matching_sections.append(
2751
LocationSection(section, length, extra_path))
2752
return matching_sections
2754
def get_sections(self):
2755
# Override the default implementation as we want to change the order
2756
matching_sections = self._get_matching_sections()
2757
# We want the longest (aka more specific) locations first
2758
sections = sorted(matching_sections,
2759
key=lambda section: (section.length, section.id),
2761
# Sections mentioning 'ignore_parents' restrict the selection
2762
for section in sections:
2763
# FIXME: We really want to use as_bool below -- vila 2011-04-07
2764
ignore = section.get('ignore_parents', None)
2765
if ignore is not None:
2766
ignore = ui.bool_from_string(ignore)
2769
# Finally, we have a valid section
2773
class Stack(object):
2774
"""A stack of configurations where an option can be defined"""
2776
def __init__(self, sections_def, store=None, mutable_section_name=None):
2777
"""Creates a stack of sections with an optional store for changes.
2779
:param sections_def: A list of Section or callables that returns an
2780
iterable of Section. This defines the Sections for the Stack and
2781
can be called repeatedly if needed.
2783
:param store: The optional Store where modifications will be
2784
recorded. If none is specified, no modifications can be done.
2786
:param mutable_section_name: The name of the MutableSection where
2787
changes are recorded. This requires the ``store`` parameter to be
2790
self.sections_def = sections_def
2792
self.mutable_section_name = mutable_section_name
2794
def get(self, name):
2795
"""Return the *first* option value found in the sections.
2797
This is where we guarantee that sections coming from Store are loaded
2798
lazily: the loading is delayed until we need to either check that an
2799
option exists or get its value, which in turn may require to discover
2800
in which sections it can be defined. Both of these (section and option
2801
existence) require loading the store (even partially).
2803
# FIXME: No caching of options nor sections yet -- vila 20110503
2805
# Ensuring lazy loading is achieved by delaying section matching (which
2806
# implies querying the persistent storage) until it can't be avoided
2807
# anymore by using callables to describe (possibly empty) section
2809
for section_or_callable in self.sections_def:
2810
# Each section can expand to multiple ones when a callable is used
2811
if callable(section_or_callable):
2812
sections = section_or_callable()
2814
sections = [section_or_callable]
2815
for section in sections:
2816
value = section.get(name)
2817
if value is not None:
2819
if value is not None:
2822
# If the option is registered, it may provide a default value
2824
opt = option_registry.get(name)
2829
value = opt.get_default()
2830
for hook in ConfigHooks['get']:
2831
hook(self, name, value)
2834
def _get_mutable_section(self):
2835
"""Get the MutableSection for the Stack.
2837
This is where we guarantee that the mutable section is lazily loaded:
2838
this means we won't load the corresponding store before setting a value
2839
or deleting an option. In practice the store will often be loaded but
2840
this allows helps catching some programming errors.
2842
section = self.store.get_mutable_section(self.mutable_section_name)
2845
def set(self, name, value):
2846
"""Set a new value for the option."""
2847
section = self._get_mutable_section()
2848
section.set(name, value)
2849
for hook in ConfigHooks['set']:
2850
hook(self, name, value)
2852
def remove(self, name):
2853
"""Remove an existing option."""
2854
section = self._get_mutable_section()
2855
section.remove(name)
2856
for hook in ConfigHooks['remove']:
2860
# Mostly for debugging use
2861
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2864
class _CompatibleStack(Stack):
2865
"""Place holder for compatibility with previous design.
2867
This is intended to ease the transition from the Config-based design to the
2868
Stack-based design and should not be used nor relied upon by plugins.
2870
One assumption made here is that the daughter classes will all use Stores
2871
derived from LockableIniFileStore).
2873
It implements set() by re-loading the store before applying the
2874
modification and saving it.
2876
The long term plan being to implement a single write by store to save
2877
all modifications, this class should not be used in the interim.
2880
def set(self, name, value):
2883
super(_CompatibleStack, self).set(name, value)
2884
# Force a write to persistent storage
2888
class GlobalStack(_CompatibleStack):
2892
gstore = GlobalStore()
2893
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
2896
class LocationStack(_CompatibleStack):
2898
def __init__(self, location):
2899
"""Make a new stack for a location and global configuration.
2901
:param location: A URL prefix to """
2902
lstore = LocationStore()
2903
matcher = LocationMatcher(lstore, location)
2904
gstore = GlobalStore()
2905
super(LocationStack, self).__init__(
2906
[matcher.get_sections, gstore.get_sections], lstore)
2908
class BranchStack(_CompatibleStack):
2910
def __init__(self, branch):
2911
bstore = BranchStore(branch)
2912
lstore = LocationStore()
2913
matcher = LocationMatcher(lstore, branch.base)
2914
gstore = GlobalStore()
2915
super(BranchStack, self).__init__(
2916
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
2918
self.branch = branch
2921
class cmd_config(commands.Command):
2922
__doc__ = """Display, set or remove a configuration option.
2924
Display the active value for a given option.
2926
If --all is specified, NAME is interpreted as a regular expression and all
2927
matching options are displayed mentioning their scope. The active value
2928
that bzr will take into account is the first one displayed for each option.
2930
If no NAME is given, --all .* is implied.
2932
Setting a value is achieved by using name=value without spaces. The value
2933
is set in the most relevant scope and can be checked by displaying the
2937
takes_args = ['name?']
2941
# FIXME: This should be a registry option so that plugins can register
2942
# their own config files (or not) -- vila 20101002
2943
commands.Option('scope', help='Reduce the scope to the specified'
2944
' configuration file',
2946
commands.Option('all',
2947
help='Display all the defined values for the matching options.',
2949
commands.Option('remove', help='Remove the option from'
2950
' the configuration file'),
2953
_see_also = ['configuration']
2955
@commands.display_command
2956
def run(self, name=None, all=False, directory=None, scope=None,
2958
if directory is None:
2960
directory = urlutils.normalize_url(directory)
2962
raise errors.BzrError(
2963
'--all and --remove are mutually exclusive.')
2965
# Delete the option in the given scope
2966
self._remove_config_option(name, directory, scope)
2968
# Defaults to all options
2969
self._show_matching_options('.*', directory, scope)
2972
name, value = name.split('=', 1)
2974
# Display the option(s) value(s)
2976
self._show_matching_options(name, directory, scope)
2978
self._show_value(name, directory, scope)
2981
raise errors.BzrError(
2982
'Only one option can be set.')
2983
# Set the option value
2984
self._set_config_option(name, value, directory, scope)
2986
def _get_configs(self, directory, scope=None):
2987
"""Iterate the configurations specified by ``directory`` and ``scope``.
2989
:param directory: Where the configurations are derived from.
2991
:param scope: A specific config to start from.
2993
if scope is not None:
2994
if scope == 'bazaar':
2995
yield GlobalConfig()
2996
elif scope == 'locations':
2997
yield LocationConfig(directory)
2998
elif scope == 'branch':
2999
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3001
yield br.get_config()
3004
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3006
yield br.get_config()
3007
except errors.NotBranchError:
3008
yield LocationConfig(directory)
3009
yield GlobalConfig()
3011
def _show_value(self, name, directory, scope):
3013
for c in self._get_configs(directory, scope):
3016
for (oname, value, section, conf_id, parser) in c._get_options():
3018
# Display only the first value and exit
3020
# FIXME: We need to use get_user_option to take policies
3021
# into account and we need to make sure the option exists
3022
# too (hence the two for loops), this needs a better API
3024
value = c.get_user_option(name)
3025
# Quote the value appropriately
3026
value = parser._quote(value)
3027
self.outf.write('%s\n' % (value,))
3031
raise errors.NoSuchConfigOption(name)
3033
def _show_matching_options(self, name, directory, scope):
3034
name = lazy_regex.lazy_compile(name)
3035
# We want any error in the regexp to be raised *now* so we need to
3036
# avoid the delay introduced by the lazy regexp. But, we still do
3037
# want the nicer errors raised by lazy_regex.
3038
name._compile_and_collapse()
3041
for c in self._get_configs(directory, scope):
3042
for (oname, value, section, conf_id, parser) in c._get_options():
3043
if name.search(oname):
3044
if cur_conf_id != conf_id:
3045
# Explain where the options are defined
3046
self.outf.write('%s:\n' % (conf_id,))
3047
cur_conf_id = conf_id
3049
if (section not in (None, 'DEFAULT')
3050
and cur_section != section):
3051
# Display the section if it's not the default (or only)
3053
self.outf.write(' [%s]\n' % (section,))
3054
cur_section = section
3055
self.outf.write(' %s = %s\n' % (oname, value))
3057
def _set_config_option(self, name, value, directory, scope):
3058
for conf in self._get_configs(directory, scope):
3059
conf.set_user_option(name, value)
3062
raise errors.NoSuchConfig(scope)
3064
def _remove_config_option(self, name, directory, scope):
3066
raise errors.BzrCommandError(
3067
'--remove expects an option to remove.')
3069
for conf in self._get_configs(directory, scope):
3070
for (section_name, section, conf_id) in conf._get_sections():
3071
if scope is not None and conf_id != scope:
3072
# Not the right configuration file
3075
if conf_id != conf.config_id():
3076
conf = self._get_configs(directory, conf_id).next()
3077
# We use the first section in the first config where the
3078
# option is defined to remove it
3079
conf.remove_user_option(name, section_name)
3084
raise errors.NoSuchConfig(scope)
3086
raise errors.NoSuchConfigOption(name)
3090
# We need adapters that can build a Store or a Stack in a test context. Test
3091
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3092
# themselves. The builder will receive a test instance and should return a
3093
# ready-to-use store or stack. Plugins that define new store/stacks can also
3094
# register themselves here to be tested against the tests defined in
3095
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3096
# for the same tests.
3098
# The registered object should be a callable receiving a test instance
3099
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3101
test_store_builder_registry = registry.Registry()
3103
# The registered object should be a callable receiving a test instance
3104
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3106
test_stack_builder_registry = registry.Registry()