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
2218
configobj[name] = value
1510
2220
configobj.setdefault(section, {})[name] = value
2221
for hook in OldConfigHooks['set']:
2222
hook(self, name, value)
2223
self._set_configobj(configobj)
2225
def remove_option(self, option_name, section_name=None):
2226
configobj = self._get_configobj()
2227
if section_name is None:
2228
del configobj[option_name]
2230
del configobj[section_name][option_name]
2231
for hook in OldConfigHooks['remove']:
2232
hook(self, option_name)
1511
2233
self._set_configobj(configobj)
1513
2235
def _get_config_file(self):
1515
return StringIO(self._transport.get_bytes(self._filename))
2237
f = StringIO(self._transport.get_bytes(self._filename))
2238
for hook in OldConfigHooks['load']:
1516
2241
except errors.NoSuchFile:
1517
2242
return StringIO()
2244
def _external_url(self):
2245
return urlutils.join(self._transport.external_url(), self._filename)
1519
2247
def _get_configobj(self):
1520
return ConfigObj(self._get_config_file(), encoding='utf-8')
2248
f = self._get_config_file()
2251
conf = ConfigObj(f, encoding='utf-8')
2252
except configobj.ConfigObjError, e:
2253
raise errors.ParseConfigError(e.errors, self._external_url())
2254
except UnicodeDecodeError:
2255
raise errors.ConfigContentError(self._external_url())
1522
2260
def _set_configobj(self, configobj):
1523
2261
out_file = StringIO()
1524
2262
configobj.write(out_file)
1525
2263
out_file.seek(0)
1526
2264
self._transport.put_file(self._filename, out_file)
2265
for hook in OldConfigHooks['save']:
2269
class Option(object):
2270
"""An option definition.
2272
The option *values* are stored in config files and found in sections.
2274
Here we define various properties about the option itself, its default
2275
value, in which config files it can be stored, etc (TBC).
2278
def __init__(self, name, default=None, help=None):
2280
self.default = default
2283
def get_default(self):
2287
class OptionRegistry(registry.Registry):
2288
"""Register config options by their name.
2290
This overrides ``registry.Registry`` to simplify registration by acquiring
2291
some information from the option object itself.
2294
def register(self, option):
2295
"""Register a new option to its name.
2297
:param option: The option to register. Its name is used as the key.
2299
super(OptionRegistry, self).register(option.name, option,
2302
def register_lazy(self, key, module_name, member_name):
2303
"""Register a new option to be loaded on request.
2305
:param key: This is the key to use to request the option later. Since
2306
the registration is lazy, it should be provided and match the
2309
:param module_name: The python path to the module. Such as 'os.path'.
2311
:param member_name: The member of the module to return. If empty or
2312
None, get() will return the module itself.
2314
super(OptionRegistry, self).register_lazy(key,
2315
module_name, member_name)
2317
def get_help(self, key=None):
2318
"""Get the help text associated with the given key"""
2319
option = self.get(key)
2320
the_help = option.help
2321
if callable(the_help):
2322
return the_help(self, key)
2326
option_registry = OptionRegistry()
2329
# Registered options in lexicographical order
2331
option_registry.register(
2332
Option('dirstate.fdatasync', default=True,
2334
Flush dirstate changes onto physical disk?
2336
If true (default), working tree metadata changes are flushed through the
2337
OS buffers to physical disk. This is somewhat slower, but means data
2338
should not be lost if the machine crashes. See also repository.fdatasync.
2340
option_registry.register(
2341
Option('default_format', default='2a',
2342
help='Format used when creating branches.'))
2343
option_registry.register(
2345
help='The command called to launch an editor to enter a message.'))
2346
option_registry.register(
2348
help='Language to translate messages into.'))
2349
option_registry.register(
2350
Option('output_encoding',
2351
help= 'Unicode encoding for output'
2352
' (terminal encoding if not specified).'))
2353
option_registry.register(
2354
Option('repository.fdatasync', default=True,
2356
Flush repository changes onto physical disk?
2358
If true (default), repository changes are flushed through the OS buffers
2359
to physical disk. This is somewhat slower, but means data should not be
2360
lost if the machine crashes. See also dirstate.fdatasync.
2364
class Section(object):
2365
"""A section defines a dict of option name => value.
2367
This is merely a read-only dict which can add some knowledge about the
2368
options. It is *not* a python dict object though and doesn't try to mimic
2372
def __init__(self, section_id, options):
2373
self.id = section_id
2374
# We re-use the dict-like object received
2375
self.options = options
2377
def get(self, name, default=None):
2378
return self.options.get(name, default)
2381
# Mostly for debugging use
2382
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2385
_NewlyCreatedOption = object()
2386
"""Was the option created during the MutableSection lifetime"""
2389
class MutableSection(Section):
2390
"""A section allowing changes and keeping track of the original values."""
2392
def __init__(self, section_id, options):
2393
super(MutableSection, self).__init__(section_id, options)
2396
def set(self, name, value):
2397
if name not in self.options:
2398
# This is a new option
2399
self.orig[name] = _NewlyCreatedOption
2400
elif name not in self.orig:
2401
self.orig[name] = self.get(name, None)
2402
self.options[name] = value
2404
def remove(self, name):
2405
if name not in self.orig:
2406
self.orig[name] = self.get(name, None)
2407
del self.options[name]
2410
class Store(object):
2411
"""Abstract interface to persistent storage for configuration options."""
2413
readonly_section_class = Section
2414
mutable_section_class = MutableSection
2416
def is_loaded(self):
2417
"""Returns True if the Store has been loaded.
2419
This is used to implement lazy loading and ensure the persistent
2420
storage is queried only when needed.
2422
raise NotImplementedError(self.is_loaded)
2425
"""Loads the Store from persistent storage."""
2426
raise NotImplementedError(self.load)
2428
def _load_from_string(self, bytes):
2429
"""Create a store from a string in configobj syntax.
2431
:param bytes: A string representing the file content.
2433
raise NotImplementedError(self._load_from_string)
2436
"""Unloads the Store.
2438
This should make is_loaded() return False. This is used when the caller
2439
knows that the persistent storage has changed or may have change since
2442
raise NotImplementedError(self.unload)
2445
"""Saves the Store to persistent storage."""
2446
raise NotImplementedError(self.save)
2448
def external_url(self):
2449
raise NotImplementedError(self.external_url)
2451
def get_sections(self):
2452
"""Returns an ordered iterable of existing sections.
2454
:returns: An iterable of (name, dict).
2456
raise NotImplementedError(self.get_sections)
2458
def get_mutable_section(self, section_name=None):
2459
"""Returns the specified mutable section.
2461
:param section_name: The section identifier
2463
raise NotImplementedError(self.get_mutable_section)
2466
# Mostly for debugging use
2467
return "<config.%s(%s)>" % (self.__class__.__name__,
2468
self.external_url())
2471
class IniFileStore(Store):
2472
"""A config Store using ConfigObj for storage.
2474
:ivar transport: The transport object where the config file is located.
2476
:ivar file_name: The config file basename in the transport directory.
2478
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2479
serialize/deserialize the config file.
2482
def __init__(self, transport, file_name):
2483
"""A config Store using ConfigObj for storage.
2485
:param transport: The transport object where the config file is located.
2487
:param file_name: The config file basename in the transport directory.
2489
super(IniFileStore, self).__init__()
2490
self.transport = transport
2491
self.file_name = file_name
2492
self._config_obj = None
2494
def is_loaded(self):
2495
return self._config_obj != None
2498
self._config_obj = None
2501
"""Load the store from the associated file."""
2502
if self.is_loaded():
2504
content = self.transport.get_bytes(self.file_name)
2505
self._load_from_string(content)
2506
for hook in ConfigHooks['load']:
2509
def _load_from_string(self, bytes):
2510
"""Create a config store from a string.
2512
:param bytes: A string representing the file content.
2514
if self.is_loaded():
2515
raise AssertionError('Already loaded: %r' % (self._config_obj,))
2516
co_input = StringIO(bytes)
2518
# The config files are always stored utf8-encoded
2519
self._config_obj = ConfigObj(co_input, encoding='utf-8')
2520
except configobj.ConfigObjError, e:
2521
self._config_obj = None
2522
raise errors.ParseConfigError(e.errors, self.external_url())
2523
except UnicodeDecodeError:
2524
raise errors.ConfigContentError(self.external_url())
2527
if not self.is_loaded():
2531
self._config_obj.write(out)
2532
self.transport.put_bytes(self.file_name, out.getvalue())
2533
for hook in ConfigHooks['save']:
2536
def external_url(self):
2537
# FIXME: external_url should really accepts an optional relpath
2538
# parameter (bug #750169) :-/ -- vila 2011-04-04
2539
# The following will do in the interim but maybe we don't want to
2540
# expose a path here but rather a config ID and its associated
2541
# object </hand wawe>.
2542
return urlutils.join(self.transport.external_url(), self.file_name)
2544
def get_sections(self):
2545
"""Get the configobj section in the file order.
2547
:returns: An iterable of (name, dict).
2549
# We need a loaded store
2552
except errors.NoSuchFile:
2553
# If the file doesn't exist, there is no sections
2555
cobj = self._config_obj
2557
yield self.readonly_section_class(None, cobj)
2558
for section_name in cobj.sections:
2559
yield self.readonly_section_class(section_name, cobj[section_name])
2561
def get_mutable_section(self, section_name=None):
2562
# We need a loaded store
2565
except errors.NoSuchFile:
2566
# The file doesn't exist, let's pretend it was empty
2567
self._load_from_string('')
2568
if section_name is None:
2569
section = self._config_obj
2571
section = self._config_obj.setdefault(section_name, {})
2572
return self.mutable_section_class(section_name, section)
2575
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2576
# unlockable stores for use with objects that can already ensure the locking
2577
# (think branches). If different stores (not based on ConfigObj) are created,
2578
# they may face the same issue.
2581
class LockableIniFileStore(IniFileStore):
2582
"""A ConfigObjStore using locks on save to ensure store integrity."""
2584
def __init__(self, transport, file_name, lock_dir_name=None):
2585
"""A config Store using ConfigObj for storage.
2587
:param transport: The transport object where the config file is located.
2589
:param file_name: The config file basename in the transport directory.
2591
if lock_dir_name is None:
2592
lock_dir_name = 'lock'
2593
self.lock_dir_name = lock_dir_name
2594
super(LockableIniFileStore, self).__init__(transport, file_name)
2595
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2597
def lock_write(self, token=None):
2598
"""Takes a write lock in the directory containing the config file.
2600
If the directory doesn't exist it is created.
2602
# FIXME: This doesn't check the ownership of the created directories as
2603
# ensure_config_dir_exists does. It should if the transport is local
2604
# -- vila 2011-04-06
2605
self.transport.create_prefix()
2606
return self._lock.lock_write(token)
2611
def break_lock(self):
2612
self._lock.break_lock()
2616
# We need to be able to override the undecorated implementation
2617
self.save_without_locking()
2619
def save_without_locking(self):
2620
super(LockableIniFileStore, self).save()
2623
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2624
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2625
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
2627
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2628
# functions or a registry will make it easier and clearer for tests, focusing
2629
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2630
# on a poolie's remark)
2631
class GlobalStore(LockableIniFileStore):
2633
def __init__(self, possible_transports=None):
2634
t = transport.get_transport_from_path(
2635
config_dir(), possible_transports=possible_transports)
2636
super(GlobalStore, self).__init__(t, 'bazaar.conf')
2639
class LocationStore(LockableIniFileStore):
2641
def __init__(self, possible_transports=None):
2642
t = transport.get_transport_from_path(
2643
config_dir(), possible_transports=possible_transports)
2644
super(LocationStore, self).__init__(t, 'locations.conf')
2647
class BranchStore(IniFileStore):
2649
def __init__(self, branch):
2650
super(BranchStore, self).__init__(branch.control_transport,
2652
self.branch = branch
2654
def lock_write(self, token=None):
2655
return self.branch.lock_write(token)
2658
return self.branch.unlock()
2662
# We need to be able to override the undecorated implementation
2663
self.save_without_locking()
2665
def save_without_locking(self):
2666
super(BranchStore, self).save()
2669
class SectionMatcher(object):
2670
"""Select sections into a given Store.
2672
This intended to be used to postpone getting an iterable of sections from a
2676
def __init__(self, store):
2679
def get_sections(self):
2680
# This is where we require loading the store so we can see all defined
2682
sections = self.store.get_sections()
2683
# Walk the revisions in the order provided
2688
def match(self, secion):
2689
raise NotImplementedError(self.match)
2692
class LocationSection(Section):
2694
def __init__(self, section, length, extra_path):
2695
super(LocationSection, self).__init__(section.id, section.options)
2696
self.length = length
2697
self.extra_path = extra_path
2699
def get(self, name, default=None):
2700
value = super(LocationSection, self).get(name, default)
2701
if value is not None:
2702
policy_name = self.get(name + ':policy', None)
2703
policy = _policy_value.get(policy_name, POLICY_NONE)
2704
if policy == POLICY_APPENDPATH:
2705
value = urlutils.join(value, self.extra_path)
2709
class LocationMatcher(SectionMatcher):
2711
def __init__(self, store, location):
2712
super(LocationMatcher, self).__init__(store)
2713
if location.startswith('file://'):
2714
location = urlutils.local_path_from_url(location)
2715
self.location = location
2717
def _get_matching_sections(self):
2718
"""Get all sections matching ``location``."""
2719
# We slightly diverge from LocalConfig here by allowing the no-name
2720
# section as the most generic one and the lower priority.
2721
no_name_section = None
2723
# Filter out the no_name_section so _iter_for_location_by_parts can be
2724
# used (it assumes all sections have a name).
2725
for section in self.store.get_sections():
2726
if section.id is None:
2727
no_name_section = section
2729
sections.append(section)
2730
# Unfortunately _iter_for_location_by_parts deals with section names so
2731
# we have to resync.
2732
filtered_sections = _iter_for_location_by_parts(
2733
[s.id for s in sections], self.location)
2734
iter_sections = iter(sections)
2735
matching_sections = []
2736
if no_name_section is not None:
2737
matching_sections.append(
2738
LocationSection(no_name_section, 0, self.location))
2739
for section_id, extra_path, length in filtered_sections:
2740
# a section id is unique for a given store so it's safe to iterate
2742
section = iter_sections.next()
2743
if section_id == section.id:
2744
matching_sections.append(
2745
LocationSection(section, length, extra_path))
2746
return matching_sections
2748
def get_sections(self):
2749
# Override the default implementation as we want to change the order
2750
matching_sections = self._get_matching_sections()
2751
# We want the longest (aka more specific) locations first
2752
sections = sorted(matching_sections,
2753
key=lambda section: (section.length, section.id),
2755
# Sections mentioning 'ignore_parents' restrict the selection
2756
for section in sections:
2757
# FIXME: We really want to use as_bool below -- vila 2011-04-07
2758
ignore = section.get('ignore_parents', None)
2759
if ignore is not None:
2760
ignore = ui.bool_from_string(ignore)
2763
# Finally, we have a valid section
2767
class Stack(object):
2768
"""A stack of configurations where an option can be defined"""
2770
def __init__(self, sections_def, store=None, mutable_section_name=None):
2771
"""Creates a stack of sections with an optional store for changes.
2773
:param sections_def: A list of Section or callables that returns an
2774
iterable of Section. This defines the Sections for the Stack and
2775
can be called repeatedly if needed.
2777
:param store: The optional Store where modifications will be
2778
recorded. If none is specified, no modifications can be done.
2780
:param mutable_section_name: The name of the MutableSection where
2781
changes are recorded. This requires the ``store`` parameter to be
2784
self.sections_def = sections_def
2786
self.mutable_section_name = mutable_section_name
2788
def get(self, name):
2789
"""Return the *first* option value found in the sections.
2791
This is where we guarantee that sections coming from Store are loaded
2792
lazily: the loading is delayed until we need to either check that an
2793
option exists or get its value, which in turn may require to discover
2794
in which sections it can be defined. Both of these (section and option
2795
existence) require loading the store (even partially).
2797
# FIXME: No caching of options nor sections yet -- vila 20110503
2799
# Ensuring lazy loading is achieved by delaying section matching (which
2800
# implies querying the persistent storage) until it can't be avoided
2801
# anymore by using callables to describe (possibly empty) section
2803
for section_or_callable in self.sections_def:
2804
# Each section can expand to multiple ones when a callable is used
2805
if callable(section_or_callable):
2806
sections = section_or_callable()
2808
sections = [section_or_callable]
2809
for section in sections:
2810
value = section.get(name)
2811
if value is not None:
2813
if value is not None:
2816
# If the option is registered, it may provide a default value
2818
opt = option_registry.get(name)
2823
value = opt.get_default()
2824
for hook in ConfigHooks['get']:
2825
hook(self, name, value)
2828
def _get_mutable_section(self):
2829
"""Get the MutableSection for the Stack.
2831
This is where we guarantee that the mutable section is lazily loaded:
2832
this means we won't load the corresponding store before setting a value
2833
or deleting an option. In practice the store will often be loaded but
2834
this allows helps catching some programming errors.
2836
section = self.store.get_mutable_section(self.mutable_section_name)
2839
def set(self, name, value):
2840
"""Set a new value for the option."""
2841
section = self._get_mutable_section()
2842
section.set(name, value)
2843
for hook in ConfigHooks['set']:
2844
hook(self, name, value)
2846
def remove(self, name):
2847
"""Remove an existing option."""
2848
section = self._get_mutable_section()
2849
section.remove(name)
2850
for hook in ConfigHooks['remove']:
2854
# Mostly for debugging use
2855
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2858
class _CompatibleStack(Stack):
2859
"""Place holder for compatibility with previous design.
2861
This is intended to ease the transition from the Config-based design to the
2862
Stack-based design and should not be used nor relied upon by plugins.
2864
One assumption made here is that the daughter classes will all use Stores
2865
derived from LockableIniFileStore).
2867
It implements set() by re-loading the store before applying the
2868
modification and saving it.
2870
The long term plan being to implement a single write by store to save
2871
all modifications, this class should not be used in the interim.
2874
def set(self, name, value):
2877
super(_CompatibleStack, self).set(name, value)
2878
# Force a write to persistent storage
2882
class GlobalStack(_CompatibleStack):
2886
gstore = GlobalStore()
2887
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
2890
class LocationStack(_CompatibleStack):
2892
def __init__(self, location):
2893
"""Make a new stack for a location and global configuration.
2895
:param location: A URL prefix to """
2896
lstore = LocationStore()
2897
matcher = LocationMatcher(lstore, location)
2898
gstore = GlobalStore()
2899
super(LocationStack, self).__init__(
2900
[matcher.get_sections, gstore.get_sections], lstore)
2902
class BranchStack(_CompatibleStack):
2904
def __init__(self, branch):
2905
bstore = BranchStore(branch)
2906
lstore = LocationStore()
2907
matcher = LocationMatcher(lstore, branch.base)
2908
gstore = GlobalStore()
2909
super(BranchStack, self).__init__(
2910
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
2912
self.branch = branch
2915
class cmd_config(commands.Command):
2916
__doc__ = """Display, set or remove a configuration option.
2918
Display the active value for a given option.
2920
If --all is specified, NAME is interpreted as a regular expression and all
2921
matching options are displayed mentioning their scope. The active value
2922
that bzr will take into account is the first one displayed for each option.
2924
If no NAME is given, --all .* is implied.
2926
Setting a value is achieved by using name=value without spaces. The value
2927
is set in the most relevant scope and can be checked by displaying the
2931
takes_args = ['name?']
2935
# FIXME: This should be a registry option so that plugins can register
2936
# their own config files (or not) -- vila 20101002
2937
commands.Option('scope', help='Reduce the scope to the specified'
2938
' configuration file',
2940
commands.Option('all',
2941
help='Display all the defined values for the matching options.',
2943
commands.Option('remove', help='Remove the option from'
2944
' the configuration file'),
2947
_see_also = ['configuration']
2949
@commands.display_command
2950
def run(self, name=None, all=False, directory=None, scope=None,
2952
if directory is None:
2954
directory = urlutils.normalize_url(directory)
2956
raise errors.BzrError(
2957
'--all and --remove are mutually exclusive.')
2959
# Delete the option in the given scope
2960
self._remove_config_option(name, directory, scope)
2962
# Defaults to all options
2963
self._show_matching_options('.*', directory, scope)
2966
name, value = name.split('=', 1)
2968
# Display the option(s) value(s)
2970
self._show_matching_options(name, directory, scope)
2972
self._show_value(name, directory, scope)
2975
raise errors.BzrError(
2976
'Only one option can be set.')
2977
# Set the option value
2978
self._set_config_option(name, value, directory, scope)
2980
def _get_configs(self, directory, scope=None):
2981
"""Iterate the configurations specified by ``directory`` and ``scope``.
2983
:param directory: Where the configurations are derived from.
2985
:param scope: A specific config to start from.
2987
if scope is not None:
2988
if scope == 'bazaar':
2989
yield GlobalConfig()
2990
elif scope == 'locations':
2991
yield LocationConfig(directory)
2992
elif scope == 'branch':
2993
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2995
yield br.get_config()
2998
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3000
yield br.get_config()
3001
except errors.NotBranchError:
3002
yield LocationConfig(directory)
3003
yield GlobalConfig()
3005
def _show_value(self, name, directory, scope):
3007
for c in self._get_configs(directory, scope):
3010
for (oname, value, section, conf_id, parser) in c._get_options():
3012
# Display only the first value and exit
3014
# FIXME: We need to use get_user_option to take policies
3015
# into account and we need to make sure the option exists
3016
# too (hence the two for loops), this needs a better API
3018
value = c.get_user_option(name)
3019
# Quote the value appropriately
3020
value = parser._quote(value)
3021
self.outf.write('%s\n' % (value,))
3025
raise errors.NoSuchConfigOption(name)
3027
def _show_matching_options(self, name, directory, scope):
3028
name = lazy_regex.lazy_compile(name)
3029
# We want any error in the regexp to be raised *now* so we need to
3030
# avoid the delay introduced by the lazy regexp. But, we still do
3031
# want the nicer errors raised by lazy_regex.
3032
name._compile_and_collapse()
3035
for c in self._get_configs(directory, scope):
3036
for (oname, value, section, conf_id, parser) in c._get_options():
3037
if name.search(oname):
3038
if cur_conf_id != conf_id:
3039
# Explain where the options are defined
3040
self.outf.write('%s:\n' % (conf_id,))
3041
cur_conf_id = conf_id
3043
if (section not in (None, 'DEFAULT')
3044
and cur_section != section):
3045
# Display the section if it's not the default (or only)
3047
self.outf.write(' [%s]\n' % (section,))
3048
cur_section = section
3049
self.outf.write(' %s = %s\n' % (oname, value))
3051
def _set_config_option(self, name, value, directory, scope):
3052
for conf in self._get_configs(directory, scope):
3053
conf.set_user_option(name, value)
3056
raise errors.NoSuchConfig(scope)
3058
def _remove_config_option(self, name, directory, scope):
3060
raise errors.BzrCommandError(
3061
'--remove expects an option to remove.')
3063
for conf in self._get_configs(directory, scope):
3064
for (section_name, section, conf_id) in conf._get_sections():
3065
if scope is not None and conf_id != scope:
3066
# Not the right configuration file
3069
if conf_id != conf.config_id():
3070
conf = self._get_configs(directory, conf_id).next()
3071
# We use the first section in the first config where the
3072
# option is defined to remove it
3073
conf.remove_user_option(name, section_name)
3078
raise errors.NoSuchConfig(scope)
3080
raise errors.NoSuchConfigOption(name)
3084
# We need adapters that can build a Store or a Stack in a test context. Test
3085
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3086
# themselves. The builder will receive a test instance and should return a
3087
# ready-to-use store or stack. Plugins that define new store/stacks can also
3088
# register themselves here to be tested against the tests defined in
3089
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3090
# for the same tests.
3092
# The registered object should be a callable receiving a test instance
3093
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3095
test_store_builder_registry = registry.Registry()
3097
# The registered object should be a callable receiving a test instance
3098
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3100
test_stack_builder_registry = registry.Registry()