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, how to convert it from stores, what to do when invalid values are
2276
encoutered, in which config files it can be stored.
2279
def __init__(self, name, default=None, help=None, from_unicode=None,
2281
"""Build an option definition.
2283
:param name: the name used to refer to the option.
2285
:param default: the default value to use when none exist in the config
2288
:param help: a doc string to explain the option to the user.
2290
:param from_unicode: a callable to convert the unicode string
2291
representing the option value in a store. This is not called for
2294
:param invalid: the action to be taken when an invalid value is
2295
encountered in a store. This is called only when from_unicode is
2296
invoked to convert a string and returns None or raise ValueError or
2297
TypeError. Accepted values are: None (ignore invalid values),
2298
'warning' (emit a warning), 'error' (emit an error message and
2302
self.default = default
2304
self.from_unicode = from_unicode
2305
if invalid and invalid not in ('warning', 'error'):
2306
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2307
self.invalid = invalid
2309
def get_default(self):
2312
# Predefined converters to get proper values from store
2314
def bool_from_store(unicode_str):
2315
return ui.bool_from_string(unicode_str)
2318
def int_from_store(unicode_str):
2319
return int(unicode_str)
2322
class OptionRegistry(registry.Registry):
2323
"""Register config options by their name.
2325
This overrides ``registry.Registry`` to simplify registration by acquiring
2326
some information from the option object itself.
2329
def register(self, option):
2330
"""Register a new option to its name.
2332
:param option: The option to register. Its name is used as the key.
2334
super(OptionRegistry, self).register(option.name, option,
2337
def register_lazy(self, key, module_name, member_name):
2338
"""Register a new option to be loaded on request.
2340
:param key: This is the key to use to request the option later. Since
2341
the registration is lazy, it should be provided and match the
2344
:param module_name: The python path to the module. Such as 'os.path'.
2346
:param member_name: The member of the module to return. If empty or
2347
None, get() will return the module itself.
2349
super(OptionRegistry, self).register_lazy(key,
2350
module_name, member_name)
2352
def get_help(self, key=None):
2353
"""Get the help text associated with the given key"""
2354
option = self.get(key)
2355
the_help = option.help
2356
if callable(the_help):
2357
return the_help(self, key)
2361
option_registry = OptionRegistry()
2364
# Registered options in lexicographical order
2366
option_registry.register(
2367
Option('dirstate.fdatasync', default=True, from_unicode=bool_from_store,
2369
Flush dirstate changes onto physical disk?
2371
If true (default), working tree metadata changes are flushed through the
2372
OS buffers to physical disk. This is somewhat slower, but means data
2373
should not be lost if the machine crashes. See also repository.fdatasync.
2375
option_registry.register(
2376
Option('default_format', default='2a',
2377
help='Format used when creating branches.'))
2378
option_registry.register(
2380
help='The command called to launch an editor to enter a message.'))
2381
option_registry.register(
2383
help='Language to translate messages into.'))
2384
option_registry.register(
2385
Option('output_encoding',
2386
help= 'Unicode encoding for output'
2387
' (terminal encoding if not specified).'))
2388
option_registry.register(
2389
Option('repository.fdatasync', default=True, from_unicode=bool_from_store,
2391
Flush repository changes onto physical disk?
2393
If true (default), repository changes are flushed through the OS buffers
2394
to physical disk. This is somewhat slower, but means data should not be
2395
lost if the machine crashes. See also dirstate.fdatasync.
2399
class Section(object):
2400
"""A section defines a dict of option name => value.
2402
This is merely a read-only dict which can add some knowledge about the
2403
options. It is *not* a python dict object though and doesn't try to mimic
2407
def __init__(self, section_id, options):
2408
self.id = section_id
2409
# We re-use the dict-like object received
2410
self.options = options
2412
def get(self, name, default=None):
2413
return self.options.get(name, default)
2416
# Mostly for debugging use
2417
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2420
_NewlyCreatedOption = object()
2421
"""Was the option created during the MutableSection lifetime"""
2424
class MutableSection(Section):
2425
"""A section allowing changes and keeping track of the original values."""
2427
def __init__(self, section_id, options):
2428
super(MutableSection, self).__init__(section_id, options)
2431
def set(self, name, value):
2432
if name not in self.options:
2433
# This is a new option
2434
self.orig[name] = _NewlyCreatedOption
2435
elif name not in self.orig:
2436
self.orig[name] = self.get(name, None)
2437
self.options[name] = value
2439
def remove(self, name):
2440
if name not in self.orig:
2441
self.orig[name] = self.get(name, None)
2442
del self.options[name]
2445
class Store(object):
2446
"""Abstract interface to persistent storage for configuration options."""
2448
readonly_section_class = Section
2449
mutable_section_class = MutableSection
2451
def is_loaded(self):
2452
"""Returns True if the Store has been loaded.
2454
This is used to implement lazy loading and ensure the persistent
2455
storage is queried only when needed.
2457
raise NotImplementedError(self.is_loaded)
2460
"""Loads the Store from persistent storage."""
2461
raise NotImplementedError(self.load)
2463
def _load_from_string(self, bytes):
2464
"""Create a store from a string in configobj syntax.
2466
:param bytes: A string representing the file content.
2468
raise NotImplementedError(self._load_from_string)
2471
"""Unloads the Store.
2473
This should make is_loaded() return False. This is used when the caller
2474
knows that the persistent storage has changed or may have change since
2477
raise NotImplementedError(self.unload)
2480
"""Saves the Store to persistent storage."""
2481
raise NotImplementedError(self.save)
2483
def external_url(self):
2484
raise NotImplementedError(self.external_url)
2486
def get_sections(self):
2487
"""Returns an ordered iterable of existing sections.
2489
:returns: An iterable of (name, dict).
2491
raise NotImplementedError(self.get_sections)
2493
def get_mutable_section(self, section_name=None):
2494
"""Returns the specified mutable section.
2496
:param section_name: The section identifier
2498
raise NotImplementedError(self.get_mutable_section)
2501
# Mostly for debugging use
2502
return "<config.%s(%s)>" % (self.__class__.__name__,
2503
self.external_url())
2506
class IniFileStore(Store):
2507
"""A config Store using ConfigObj for storage.
2509
:ivar transport: The transport object where the config file is located.
2511
:ivar file_name: The config file basename in the transport directory.
2513
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2514
serialize/deserialize the config file.
2517
def __init__(self, transport, file_name):
2518
"""A config Store using ConfigObj for storage.
2520
:param transport: The transport object where the config file is located.
2522
:param file_name: The config file basename in the transport directory.
2524
super(IniFileStore, self).__init__()
2525
self.transport = transport
2526
self.file_name = file_name
2527
self._config_obj = None
2529
def is_loaded(self):
2530
return self._config_obj != None
2533
self._config_obj = None
2536
"""Load the store from the associated file."""
2537
if self.is_loaded():
2539
content = self.transport.get_bytes(self.file_name)
2540
self._load_from_string(content)
2541
for hook in ConfigHooks['load']:
2544
def _load_from_string(self, bytes):
2545
"""Create a config store from a string.
2547
:param bytes: A string representing the file content.
2549
if self.is_loaded():
2550
raise AssertionError('Already loaded: %r' % (self._config_obj,))
2551
co_input = StringIO(bytes)
2553
# The config files are always stored utf8-encoded
2554
self._config_obj = ConfigObj(co_input, encoding='utf-8')
2555
except configobj.ConfigObjError, e:
2556
self._config_obj = None
2557
raise errors.ParseConfigError(e.errors, self.external_url())
2558
except UnicodeDecodeError:
2559
raise errors.ConfigContentError(self.external_url())
2562
if not self.is_loaded():
2566
self._config_obj.write(out)
2567
self.transport.put_bytes(self.file_name, out.getvalue())
2568
for hook in ConfigHooks['save']:
2571
def external_url(self):
2572
# FIXME: external_url should really accepts an optional relpath
2573
# parameter (bug #750169) :-/ -- vila 2011-04-04
2574
# The following will do in the interim but maybe we don't want to
2575
# expose a path here but rather a config ID and its associated
2576
# object </hand wawe>.
2577
return urlutils.join(self.transport.external_url(), self.file_name)
2579
def get_sections(self):
2580
"""Get the configobj section in the file order.
2582
:returns: An iterable of (name, dict).
2584
# We need a loaded store
2587
except errors.NoSuchFile:
2588
# If the file doesn't exist, there is no sections
2590
cobj = self._config_obj
2592
yield self.readonly_section_class(None, cobj)
2593
for section_name in cobj.sections:
2594
yield self.readonly_section_class(section_name, cobj[section_name])
2596
def get_mutable_section(self, section_name=None):
2597
# We need a loaded store
2600
except errors.NoSuchFile:
2601
# The file doesn't exist, let's pretend it was empty
2602
self._load_from_string('')
2603
if section_name is None:
2604
section = self._config_obj
2606
section = self._config_obj.setdefault(section_name, {})
2607
return self.mutable_section_class(section_name, section)
2610
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2611
# unlockable stores for use with objects that can already ensure the locking
2612
# (think branches). If different stores (not based on ConfigObj) are created,
2613
# they may face the same issue.
2616
class LockableIniFileStore(IniFileStore):
2617
"""A ConfigObjStore using locks on save to ensure store integrity."""
2619
def __init__(self, transport, file_name, lock_dir_name=None):
2620
"""A config Store using ConfigObj for storage.
2622
:param transport: The transport object where the config file is located.
2624
:param file_name: The config file basename in the transport directory.
2626
if lock_dir_name is None:
2627
lock_dir_name = 'lock'
2628
self.lock_dir_name = lock_dir_name
2629
super(LockableIniFileStore, self).__init__(transport, file_name)
2630
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2632
def lock_write(self, token=None):
2633
"""Takes a write lock in the directory containing the config file.
2635
If the directory doesn't exist it is created.
2637
# FIXME: This doesn't check the ownership of the created directories as
2638
# ensure_config_dir_exists does. It should if the transport is local
2639
# -- vila 2011-04-06
2640
self.transport.create_prefix()
2641
return self._lock.lock_write(token)
2646
def break_lock(self):
2647
self._lock.break_lock()
2651
# We need to be able to override the undecorated implementation
2652
self.save_without_locking()
2654
def save_without_locking(self):
2655
super(LockableIniFileStore, self).save()
2658
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2659
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2660
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
2662
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2663
# functions or a registry will make it easier and clearer for tests, focusing
2664
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2665
# on a poolie's remark)
2666
class GlobalStore(LockableIniFileStore):
2668
def __init__(self, possible_transports=None):
2669
t = transport.get_transport_from_path(
2670
config_dir(), possible_transports=possible_transports)
2671
super(GlobalStore, self).__init__(t, 'bazaar.conf')
2674
class LocationStore(LockableIniFileStore):
2676
def __init__(self, possible_transports=None):
2677
t = transport.get_transport_from_path(
2678
config_dir(), possible_transports=possible_transports)
2679
super(LocationStore, self).__init__(t, 'locations.conf')
2682
class BranchStore(IniFileStore):
2684
def __init__(self, branch):
2685
super(BranchStore, self).__init__(branch.control_transport,
2687
self.branch = branch
2689
def lock_write(self, token=None):
2690
return self.branch.lock_write(token)
2693
return self.branch.unlock()
2697
# We need to be able to override the undecorated implementation
2698
self.save_without_locking()
2700
def save_without_locking(self):
2701
super(BranchStore, self).save()
2704
class SectionMatcher(object):
2705
"""Select sections into a given Store.
2707
This intended to be used to postpone getting an iterable of sections from a
2711
def __init__(self, store):
2714
def get_sections(self):
2715
# This is where we require loading the store so we can see all defined
2717
sections = self.store.get_sections()
2718
# Walk the revisions in the order provided
2723
def match(self, secion):
2724
raise NotImplementedError(self.match)
2727
class LocationSection(Section):
2729
def __init__(self, section, length, extra_path):
2730
super(LocationSection, self).__init__(section.id, section.options)
2731
self.length = length
2732
self.extra_path = extra_path
2734
def get(self, name, default=None):
2735
value = super(LocationSection, self).get(name, default)
2736
if value is not None:
2737
policy_name = self.get(name + ':policy', None)
2738
policy = _policy_value.get(policy_name, POLICY_NONE)
2739
if policy == POLICY_APPENDPATH:
2740
value = urlutils.join(value, self.extra_path)
2744
class LocationMatcher(SectionMatcher):
2746
def __init__(self, store, location):
2747
super(LocationMatcher, self).__init__(store)
2748
if location.startswith('file://'):
2749
location = urlutils.local_path_from_url(location)
2750
self.location = location
2752
def _get_matching_sections(self):
2753
"""Get all sections matching ``location``."""
2754
# We slightly diverge from LocalConfig here by allowing the no-name
2755
# section as the most generic one and the lower priority.
2756
no_name_section = None
2758
# Filter out the no_name_section so _iter_for_location_by_parts can be
2759
# used (it assumes all sections have a name).
2760
for section in self.store.get_sections():
2761
if section.id is None:
2762
no_name_section = section
2764
sections.append(section)
2765
# Unfortunately _iter_for_location_by_parts deals with section names so
2766
# we have to resync.
2767
filtered_sections = _iter_for_location_by_parts(
2768
[s.id for s in sections], self.location)
2769
iter_sections = iter(sections)
2770
matching_sections = []
2771
if no_name_section is not None:
2772
matching_sections.append(
2773
LocationSection(no_name_section, 0, self.location))
2774
for section_id, extra_path, length in filtered_sections:
2775
# a section id is unique for a given store so it's safe to iterate
2777
section = iter_sections.next()
2778
if section_id == section.id:
2779
matching_sections.append(
2780
LocationSection(section, length, extra_path))
2781
return matching_sections
2783
def get_sections(self):
2784
# Override the default implementation as we want to change the order
2785
matching_sections = self._get_matching_sections()
2786
# We want the longest (aka more specific) locations first
2787
sections = sorted(matching_sections,
2788
key=lambda section: (section.length, section.id),
2790
# Sections mentioning 'ignore_parents' restrict the selection
2791
for section in sections:
2792
# FIXME: We really want to use as_bool below -- vila 2011-04-07
2793
ignore = section.get('ignore_parents', None)
2794
if ignore is not None:
2795
ignore = ui.bool_from_string(ignore)
2798
# Finally, we have a valid section
2802
class Stack(object):
2803
"""A stack of configurations where an option can be defined"""
2805
def __init__(self, sections_def, store=None, mutable_section_name=None):
2806
"""Creates a stack of sections with an optional store for changes.
2808
:param sections_def: A list of Section or callables that returns an
2809
iterable of Section. This defines the Sections for the Stack and
2810
can be called repeatedly if needed.
2812
:param store: The optional Store where modifications will be
2813
recorded. If none is specified, no modifications can be done.
2815
:param mutable_section_name: The name of the MutableSection where
2816
changes are recorded. This requires the ``store`` parameter to be
2819
self.sections_def = sections_def
2821
self.mutable_section_name = mutable_section_name
2823
def get(self, name):
2824
"""Return the *first* option value found in the sections.
2826
This is where we guarantee that sections coming from Store are loaded
2827
lazily: the loading is delayed until we need to either check that an
2828
option exists or get its value, which in turn may require to discover
2829
in which sections it can be defined. Both of these (section and option
2830
existence) require loading the store (even partially).
2832
# FIXME: No caching of options nor sections yet -- vila 20110503
2834
# Ensuring lazy loading is achieved by delaying section matching (which
2835
# implies querying the persistent storage) until it can't be avoided
2836
# anymore by using callables to describe (possibly empty) section
2838
for section_or_callable in self.sections_def:
2839
# Each section can expand to multiple ones when a callable is used
2840
if callable(section_or_callable):
2841
sections = section_or_callable()
2843
sections = [section_or_callable]
2844
for section in sections:
2845
value = section.get(name)
2846
if value is not None:
2848
if value is not None:
2850
# If the option is registered, it may provide additional info about
2853
opt = option_registry.get(name)
2857
if (opt is not None and opt.from_unicode is not None
2858
and value is not None):
2859
# If a value exists and the option provides a converter, use it
2861
converted = opt.from_unicode(value)
2862
except (ValueError, TypeError):
2863
# Invalid values are ignored
2865
if converted is None and opt.invalid is not None:
2866
# The conversion failed
2867
if opt.invalid == 'warning':
2868
trace.warning('Value "%s" is not valid for "%s"',
2870
elif opt.invalid == 'error':
2871
raise errors.ConfigOptionValueError(name, value)
2874
# If the option is registered, it may provide a default value
2876
value = opt.get_default()
2877
for hook in ConfigHooks['get']:
2878
hook(self, name, value)
2881
def _get_mutable_section(self):
2882
"""Get the MutableSection for the Stack.
2884
This is where we guarantee that the mutable section is lazily loaded:
2885
this means we won't load the corresponding store before setting a value
2886
or deleting an option. In practice the store will often be loaded but
2887
this allows helps catching some programming errors.
2889
section = self.store.get_mutable_section(self.mutable_section_name)
2892
def set(self, name, value):
2893
"""Set a new value for the option."""
2894
section = self._get_mutable_section()
2895
section.set(name, value)
2896
for hook in ConfigHooks['set']:
2897
hook(self, name, value)
2899
def remove(self, name):
2900
"""Remove an existing option."""
2901
section = self._get_mutable_section()
2902
section.remove(name)
2903
for hook in ConfigHooks['remove']:
2907
# Mostly for debugging use
2908
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2911
class _CompatibleStack(Stack):
2912
"""Place holder for compatibility with previous design.
2914
This is intended to ease the transition from the Config-based design to the
2915
Stack-based design and should not be used nor relied upon by plugins.
2917
One assumption made here is that the daughter classes will all use Stores
2918
derived from LockableIniFileStore).
2920
It implements set() by re-loading the store before applying the
2921
modification and saving it.
2923
The long term plan being to implement a single write by store to save
2924
all modifications, this class should not be used in the interim.
2927
def set(self, name, value):
2930
super(_CompatibleStack, self).set(name, value)
2931
# Force a write to persistent storage
2935
class GlobalStack(_CompatibleStack):
2939
gstore = GlobalStore()
2940
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
2943
class LocationStack(_CompatibleStack):
2945
def __init__(self, location):
2946
"""Make a new stack for a location and global configuration.
2948
:param location: A URL prefix to """
2949
lstore = LocationStore()
2950
matcher = LocationMatcher(lstore, location)
2951
gstore = GlobalStore()
2952
super(LocationStack, self).__init__(
2953
[matcher.get_sections, gstore.get_sections], lstore)
2955
class BranchStack(_CompatibleStack):
2957
def __init__(self, branch):
2958
bstore = BranchStore(branch)
2959
lstore = LocationStore()
2960
matcher = LocationMatcher(lstore, branch.base)
2961
gstore = GlobalStore()
2962
super(BranchStack, self).__init__(
2963
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
2965
self.branch = branch
2968
class cmd_config(commands.Command):
2969
__doc__ = """Display, set or remove a configuration option.
2971
Display the active value for a given option.
2973
If --all is specified, NAME is interpreted as a regular expression and all
2974
matching options are displayed mentioning their scope. The active value
2975
that bzr will take into account is the first one displayed for each option.
2977
If no NAME is given, --all .* is implied.
2979
Setting a value is achieved by using name=value without spaces. The value
2980
is set in the most relevant scope and can be checked by displaying the
2984
takes_args = ['name?']
2988
# FIXME: This should be a registry option so that plugins can register
2989
# their own config files (or not) -- vila 20101002
2990
commands.Option('scope', help='Reduce the scope to the specified'
2991
' configuration file',
2993
commands.Option('all',
2994
help='Display all the defined values for the matching options.',
2996
commands.Option('remove', help='Remove the option from'
2997
' the configuration file'),
3000
_see_also = ['configuration']
3002
@commands.display_command
3003
def run(self, name=None, all=False, directory=None, scope=None,
3005
if directory is None:
3007
directory = urlutils.normalize_url(directory)
3009
raise errors.BzrError(
3010
'--all and --remove are mutually exclusive.')
3012
# Delete the option in the given scope
3013
self._remove_config_option(name, directory, scope)
3015
# Defaults to all options
3016
self._show_matching_options('.*', directory, scope)
3019
name, value = name.split('=', 1)
3021
# Display the option(s) value(s)
3023
self._show_matching_options(name, directory, scope)
3025
self._show_value(name, directory, scope)
3028
raise errors.BzrError(
3029
'Only one option can be set.')
3030
# Set the option value
3031
self._set_config_option(name, value, directory, scope)
3033
def _get_configs(self, directory, scope=None):
3034
"""Iterate the configurations specified by ``directory`` and ``scope``.
3036
:param directory: Where the configurations are derived from.
3038
:param scope: A specific config to start from.
3040
if scope is not None:
3041
if scope == 'bazaar':
3042
yield GlobalConfig()
3043
elif scope == 'locations':
3044
yield LocationConfig(directory)
3045
elif scope == 'branch':
3046
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3048
yield br.get_config()
3051
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3053
yield br.get_config()
3054
except errors.NotBranchError:
3055
yield LocationConfig(directory)
3056
yield GlobalConfig()
3058
def _show_value(self, name, directory, scope):
3060
for c in self._get_configs(directory, scope):
3063
for (oname, value, section, conf_id, parser) in c._get_options():
3065
# Display only the first value and exit
3067
# FIXME: We need to use get_user_option to take policies
3068
# into account and we need to make sure the option exists
3069
# too (hence the two for loops), this needs a better API
3071
value = c.get_user_option(name)
3072
# Quote the value appropriately
3073
value = parser._quote(value)
3074
self.outf.write('%s\n' % (value,))
3078
raise errors.NoSuchConfigOption(name)
3080
def _show_matching_options(self, name, directory, scope):
3081
name = lazy_regex.lazy_compile(name)
3082
# We want any error in the regexp to be raised *now* so we need to
3083
# avoid the delay introduced by the lazy regexp. But, we still do
3084
# want the nicer errors raised by lazy_regex.
3085
name._compile_and_collapse()
3088
for c in self._get_configs(directory, scope):
3089
for (oname, value, section, conf_id, parser) in c._get_options():
3090
if name.search(oname):
3091
if cur_conf_id != conf_id:
3092
# Explain where the options are defined
3093
self.outf.write('%s:\n' % (conf_id,))
3094
cur_conf_id = conf_id
3096
if (section not in (None, 'DEFAULT')
3097
and cur_section != section):
3098
# Display the section if it's not the default (or only)
3100
self.outf.write(' [%s]\n' % (section,))
3101
cur_section = section
3102
self.outf.write(' %s = %s\n' % (oname, value))
3104
def _set_config_option(self, name, value, directory, scope):
3105
for conf in self._get_configs(directory, scope):
3106
conf.set_user_option(name, value)
3109
raise errors.NoSuchConfig(scope)
3111
def _remove_config_option(self, name, directory, scope):
3113
raise errors.BzrCommandError(
3114
'--remove expects an option to remove.')
3116
for conf in self._get_configs(directory, scope):
3117
for (section_name, section, conf_id) in conf._get_sections():
3118
if scope is not None and conf_id != scope:
3119
# Not the right configuration file
3122
if conf_id != conf.config_id():
3123
conf = self._get_configs(directory, conf_id).next()
3124
# We use the first section in the first config where the
3125
# option is defined to remove it
3126
conf.remove_user_option(name, section_name)
3131
raise errors.NoSuchConfig(scope)
3133
raise errors.NoSuchConfigOption(name)
3137
# We need adapters that can build a Store or a Stack in a test context. Test
3138
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3139
# themselves. The builder will receive a test instance and should return a
3140
# ready-to-use store or stack. Plugins that define new store/stacks can also
3141
# register themselves here to be tested against the tests defined in
3142
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3143
# for the same tests.
3145
# The registered object should be a callable receiving a test instance
3146
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3148
test_store_builder_registry = registry.Registry()
3150
# The registered object should be a callable receiving a test instance
3151
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3153
test_stack_builder_registry = registry.Registry()