228
166
def _get_signing_policy(self):
229
167
"""Template method to override signature creation policy."""
233
def expand_options(self, string, env=None):
234
"""Expand option references in the string in the configuration context.
236
:param string: The string containing option to expand.
238
:param env: An option dict defining additional configuration options or
239
overriding existing ones.
241
:returns: The expanded string.
243
return self._expand_options_in_string(string, env)
245
def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
246
"""Expand options in a list of strings in the configuration context.
248
:param slist: A list of strings.
250
:param env: An option dict defining additional configuration options or
251
overriding existing ones.
253
:param _ref_stack: Private list containing the options being
254
expanded to detect loops.
256
:returns: The flatten list of expanded strings.
258
# expand options in each value separately flattening lists
261
value = self._expand_options_in_string(s, env, _ref_stack)
262
if isinstance(value, list):
268
def _expand_options_in_string(self, string, env=None, _ref_stack=None):
269
"""Expand options in the string in the configuration context.
271
:param string: The string to be expanded.
273
:param env: An option dict defining additional configuration options or
274
overriding existing ones.
276
:param _ref_stack: Private list containing the options being
277
expanded to detect loops.
279
:returns: The expanded string.
282
# Not much to expand there
284
if _ref_stack is None:
285
# What references are currently resolved (to detect loops)
287
if self.option_ref_re is None:
288
# We want to match the most embedded reference first (i.e. for
289
# '{{foo}}' we will get '{foo}',
290
# for '{bar{baz}}' we will get '{baz}'
291
self.option_ref_re = re.compile('({[^{}]+})')
293
# We need to iterate until no more refs appear ({{foo}} will need two
294
# iterations for example).
296
raw_chunks = self.option_ref_re.split(result)
297
if len(raw_chunks) == 1:
298
# Shorcut the trivial case: no refs
302
# Split will isolate refs so that every other chunk is a ref
304
for chunk in raw_chunks:
307
# Keep only non-empty strings (or we get bogus empty
308
# slots when a list value is involved).
313
if name in _ref_stack:
314
raise errors.OptionExpansionLoop(string, _ref_stack)
315
_ref_stack.append(name)
316
value = self._expand_option(name, env, _ref_stack)
318
raise errors.ExpandingUnknownOption(name, string)
319
if isinstance(value, list):
327
# Once a list appears as the result of an expansion, all
328
# callers will get a list result. This allows a consistent
329
# behavior even when some options in the expansion chain
330
# defined as strings (no comma in their value) but their
331
# expanded value is a list.
332
return self._expand_options_in_list(chunks, env, _ref_stack)
334
result = ''.join(chunks)
337
def _expand_option(self, name, env, _ref_stack):
338
if env is not None and name in env:
339
# Special case, values provided in env takes precedence over
343
# FIXME: This is a limited implementation, what we really need is a
344
# way to query the bzr config for the value of an option,
345
# respecting the scope rules (That is, once we implement fallback
346
# configs, getting the option value should restart from the top
347
# config, not the current one) -- vila 20101222
348
value = self.get_user_option(name, expand=False)
349
if isinstance(value, list):
350
value = self._expand_options_in_list(value, env, _ref_stack)
352
value = self._expand_options_in_string(value, env, _ref_stack)
355
169
def _get_user_option(self, option_name):
356
170
"""Template method to provide a user option."""
359
def get_user_option(self, option_name, expand=None):
360
"""Get a generic option - no special process, no default.
362
:param option_name: The queried option.
364
:param expand: Whether options references should be expanded.
366
:returns: The value of the option.
369
expand = _get_expand_default_value()
370
value = self._get_user_option(option_name)
372
if isinstance(value, list):
373
value = self._expand_options_in_list(value)
374
elif isinstance(value, dict):
375
trace.warning('Cannot expand "%s":'
376
' Dicts do not support option expansion'
379
value = self._expand_options_in_string(value)
380
for hook in OldConfigHooks['get']:
381
hook(self, option_name, value)
384
def get_user_option_as_bool(self, option_name, expand=None, default=None):
385
"""Get a generic option as a boolean.
387
:param expand: Allow expanding references to other config values.
388
:param default: Default value if nothing is configured
389
:return None if the option doesn't exist or its value can't be
390
interpreted as a boolean. Returns True or False otherwise.
392
s = self.get_user_option(option_name, expand=expand)
394
# The option doesn't exist
396
val = ui.bool_from_string(s)
398
# The value can't be interpreted as a boolean
399
trace.warning('Value "%s" is not a boolean for "%s"',
403
def get_user_option_as_list(self, option_name, expand=None):
404
"""Get a generic option as a list - no special process, no default.
406
:return None if the option doesn't exist. Returns the value as a list
409
l = self.get_user_option(option_name, expand=expand)
410
if isinstance(l, (str, unicode)):
411
# A single value, most probably the user forgot (or didn't care to
173
def get_user_option(self, option_name):
174
"""Get a generic option - no special process, no default."""
175
return self._get_user_option(option_name)
416
177
def gpg_signing_command(self):
417
178
"""What program should be used to sign signatures?"""
558
def suppress_warning(self, warning):
559
"""Should the warning be suppressed or emitted.
561
:param warning: The name of the warning being tested.
563
:returns: True if the warning should be suppressed, False otherwise.
565
warnings = self.get_user_option_as_list('suppress_warnings')
566
if warnings is None or warning not in warnings:
571
def get_merge_tools(self):
573
for (oname, value, section, conf_id, parser) in self._get_options():
574
if oname.startswith('bzr.mergetool.'):
575
tool_name = oname[len('bzr.mergetool.'):]
576
tools[tool_name] = value
577
trace.mutter('loaded merge tools: %r' % tools)
580
def find_merge_tool(self, name):
581
# We fake a defaults mechanism here by checking if the given name can
582
# be found in the known_merge_tools if it's not found in the config.
583
# This should be done through the proposed config defaults mechanism
584
# when it becomes available in the future.
585
command_line = (self.get_user_option('bzr.mergetool.%s' % name,
587
or mergetools.known_merge_tools.get(name, None))
591
class _ConfigHooks(hooks.Hooks):
592
"""A dict mapping hook names and a list of callables for configs.
596
"""Create the default hooks.
598
These are all empty initially, because by default nothing should get
601
super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
602
self.add_hook('load',
603
'Invoked when a config store is loaded.'
604
' The signature is (store).',
606
self.add_hook('save',
607
'Invoked when a config store is saved.'
608
' The signature is (store).',
610
# The hooks for config options
612
'Invoked when a config option is read.'
613
' The signature is (stack, name, value).',
616
'Invoked when a config option is set.'
617
' The signature is (stack, name, value).',
619
self.add_hook('remove',
620
'Invoked when a config option is removed.'
621
' The signature is (stack, name).',
623
ConfigHooks = _ConfigHooks()
626
class _OldConfigHooks(hooks.Hooks):
627
"""A dict mapping hook names and a list of callables for configs.
631
"""Create the default hooks.
633
These are all empty initially, because by default nothing should get
636
super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
637
self.add_hook('load',
638
'Invoked when a config store is loaded.'
639
' The signature is (config).',
641
self.add_hook('save',
642
'Invoked when a config store is saved.'
643
' The signature is (config).',
645
# The hooks for config options
647
'Invoked when a config option is read.'
648
' The signature is (config, name, value).',
651
'Invoked when a config option is set.'
652
' The signature is (config, name, value).',
654
self.add_hook('remove',
655
'Invoked when a config option is removed.'
656
' The signature is (config, name).',
658
OldConfigHooks = _OldConfigHooks()
661
299
class IniBasedConfig(Config):
662
300
"""A configuration policy that draws from ini files."""
664
def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
666
"""Base class for configuration files using an ini-like syntax.
668
:param file_name: The configuration file path.
670
super(IniBasedConfig, self).__init__()
671
self.file_name = file_name
672
if symbol_versioning.deprecated_passed(get_filename):
673
symbol_versioning.warn(
674
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
675
' Use file_name instead.',
678
if get_filename is not None:
679
self.file_name = get_filename()
681
self.file_name = file_name
686
def from_string(cls, str_or_unicode, file_name=None, save=False):
687
"""Create a config object from a string.
689
:param str_or_unicode: A string representing the file content. This will
692
:param file_name: The configuration file path.
694
:param _save: Whether the file should be saved upon creation.
696
conf = cls(file_name=file_name)
697
conf._create_from_string(str_or_unicode, save)
700
def _create_from_string(self, str_or_unicode, save):
701
self._content = StringIO(str_or_unicode.encode('utf-8'))
702
# Some tests use in-memory configs, some other always need the config
703
# file to exist on disk.
705
self._write_config_file()
707
def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
302
def _get_parser(self, file=None):
708
303
if self._parser is not None:
709
304
return self._parser
710
if symbol_versioning.deprecated_passed(file):
711
symbol_versioning.warn(
712
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
713
' Use IniBasedConfig(_content=xxx) instead.',
716
if self._content is not None:
717
co_input = self._content
718
elif self.file_name is None:
719
raise AssertionError('We have no content to create the config')
306
input = self._get_filename()
721
co_input = self.file_name
723
self._parser = ConfigObj(co_input, encoding='utf-8')
310
self._parser = ConfigObj(input, encoding='utf-8')
724
311
except configobj.ConfigObjError, e:
725
312
raise errors.ParseConfigError(e.errors, e.config.filename)
726
except UnicodeDecodeError:
727
raise errors.ConfigContentError(self.file_name)
728
# Make sure self.reload() will use the right file name
729
self._parser.filename = self.file_name
730
for hook in OldConfigHooks['load']:
732
313
return self._parser
735
"""Reload the config file from disk."""
736
if self.file_name is None:
737
raise AssertionError('We need a file name to reload the config')
738
if self._parser is not None:
739
self._parser.reload()
740
for hook in ConfigHooks['load']:
743
315
def _get_matching_sections(self):
744
316
"""Return an ordered list of (section_name, extra_path) pairs.
2207
1421
configobj[name] = value
2209
1423
configobj.setdefault(section, {})[name] = value
2210
for hook in OldConfigHooks['set']:
2211
hook(self, name, value)
2212
self._set_configobj(configobj)
2214
def remove_option(self, option_name, section_name=None):
2215
configobj = self._get_configobj()
2216
if section_name is None:
2217
del configobj[option_name]
2219
del configobj[section_name][option_name]
2220
for hook in OldConfigHooks['remove']:
2221
hook(self, option_name)
2222
1424
self._set_configobj(configobj)
2224
1426
def _get_config_file(self):
2226
f = StringIO(self._transport.get_bytes(self._filename))
2227
for hook in OldConfigHooks['load']:
1428
return self._transport.get(self._filename)
2230
1429
except errors.NoSuchFile:
2231
1430
return StringIO()
2233
def _external_url(self):
2234
return urlutils.join(self._transport.external_url(), self._filename)
2236
1432
def _get_configobj(self):
2237
f = self._get_config_file()
2240
conf = ConfigObj(f, encoding='utf-8')
2241
except configobj.ConfigObjError, e:
2242
raise errors.ParseConfigError(e.errors, self._external_url())
2243
except UnicodeDecodeError:
2244
raise errors.ConfigContentError(self._external_url())
1433
return ConfigObj(self._get_config_file(), encoding='utf-8')
2249
1435
def _set_configobj(self, configobj):
2250
1436
out_file = StringIO()
2251
1437
configobj.write(out_file)
2252
1438
out_file.seek(0)
2253
1439
self._transport.put_file(self._filename, out_file)
2254
for hook in OldConfigHooks['save']:
2258
class Option(object):
2259
"""An option definition.
2261
The option *values* are stored in config files and found in sections.
2263
Here we define various properties about the option itself, its default
2264
value, in which config files it can be stored, etc (TBC).
2267
def __init__(self, name, default=None):
2269
self.default = default
2271
def get_default(self):
2277
option_registry = registry.Registry()
2280
option_registry.register(
2281
'editor', Option('editor'),
2282
help='The command called to launch an editor to enter a message.')
2284
option_registry.register(
2285
'dirstate.fdatasync', Option('dirstate.fdatasync', default=True),
2286
help='Flush dirstate changes onto physical disk?')
2288
option_registry.register(
2289
'repository.fdatasync',
2290
Option('repository.fdatasync', default=True),
2291
help='Flush repository changes onto physical disk?')
2294
class Section(object):
2295
"""A section defines a dict of option name => value.
2297
This is merely a read-only dict which can add some knowledge about the
2298
options. It is *not* a python dict object though and doesn't try to mimic
2302
def __init__(self, section_id, options):
2303
self.id = section_id
2304
# We re-use the dict-like object received
2305
self.options = options
2307
def get(self, name, default=None):
2308
return self.options.get(name, default)
2311
# Mostly for debugging use
2312
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2315
_NewlyCreatedOption = object()
2316
"""Was the option created during the MutableSection lifetime"""
2319
class MutableSection(Section):
2320
"""A section allowing changes and keeping track of the original values."""
2322
def __init__(self, section_id, options):
2323
super(MutableSection, self).__init__(section_id, options)
2326
def set(self, name, value):
2327
if name not in self.options:
2328
# This is a new option
2329
self.orig[name] = _NewlyCreatedOption
2330
elif name not in self.orig:
2331
self.orig[name] = self.get(name, None)
2332
self.options[name] = value
2334
def remove(self, name):
2335
if name not in self.orig:
2336
self.orig[name] = self.get(name, None)
2337
del self.options[name]
2340
class Store(object):
2341
"""Abstract interface to persistent storage for configuration options."""
2343
readonly_section_class = Section
2344
mutable_section_class = MutableSection
2346
def is_loaded(self):
2347
"""Returns True if the Store has been loaded.
2349
This is used to implement lazy loading and ensure the persistent
2350
storage is queried only when needed.
2352
raise NotImplementedError(self.is_loaded)
2355
"""Loads the Store from persistent storage."""
2356
raise NotImplementedError(self.load)
2358
def _load_from_string(self, bytes):
2359
"""Create a store from a string in configobj syntax.
2361
:param bytes: A string representing the file content.
2363
raise NotImplementedError(self._load_from_string)
2366
"""Unloads the Store.
2368
This should make is_loaded() return False. This is used when the caller
2369
knows that the persistent storage has changed or may have change since
2372
raise NotImplementedError(self.unload)
2375
"""Saves the Store to persistent storage."""
2376
raise NotImplementedError(self.save)
2378
def external_url(self):
2379
raise NotImplementedError(self.external_url)
2381
def get_sections(self):
2382
"""Returns an ordered iterable of existing sections.
2384
:returns: An iterable of (name, dict).
2386
raise NotImplementedError(self.get_sections)
2388
def get_mutable_section(self, section_name=None):
2389
"""Returns the specified mutable section.
2391
:param section_name: The section identifier
2393
raise NotImplementedError(self.get_mutable_section)
2396
# Mostly for debugging use
2397
return "<config.%s(%s)>" % (self.__class__.__name__,
2398
self.external_url())
2401
class IniFileStore(Store):
2402
"""A config Store using ConfigObj for storage.
2404
:ivar transport: The transport object where the config file is located.
2406
:ivar file_name: The config file basename in the transport directory.
2408
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2409
serialize/deserialize the config file.
2412
def __init__(self, transport, file_name):
2413
"""A config Store using ConfigObj for storage.
2415
:param transport: The transport object where the config file is located.
2417
:param file_name: The config file basename in the transport directory.
2419
super(IniFileStore, self).__init__()
2420
self.transport = transport
2421
self.file_name = file_name
2422
self._config_obj = None
2424
def is_loaded(self):
2425
return self._config_obj != None
2428
self._config_obj = None
2431
"""Load the store from the associated file."""
2432
if self.is_loaded():
2434
content = self.transport.get_bytes(self.file_name)
2435
self._load_from_string(content)
2436
for hook in ConfigHooks['load']:
2439
def _load_from_string(self, bytes):
2440
"""Create a config store from a string.
2442
:param bytes: A string representing the file content.
2444
if self.is_loaded():
2445
raise AssertionError('Already loaded: %r' % (self._config_obj,))
2446
co_input = StringIO(bytes)
2448
# The config files are always stored utf8-encoded
2449
self._config_obj = ConfigObj(co_input, encoding='utf-8')
2450
except configobj.ConfigObjError, e:
2451
self._config_obj = None
2452
raise errors.ParseConfigError(e.errors, self.external_url())
2453
except UnicodeDecodeError:
2454
raise errors.ConfigContentError(self.external_url())
2457
if not self.is_loaded():
2461
self._config_obj.write(out)
2462
self.transport.put_bytes(self.file_name, out.getvalue())
2463
for hook in ConfigHooks['save']:
2466
def external_url(self):
2467
# FIXME: external_url should really accepts an optional relpath
2468
# parameter (bug #750169) :-/ -- vila 2011-04-04
2469
# The following will do in the interim but maybe we don't want to
2470
# expose a path here but rather a config ID and its associated
2471
# object </hand wawe>.
2472
return urlutils.join(self.transport.external_url(), self.file_name)
2474
def get_sections(self):
2475
"""Get the configobj section in the file order.
2477
:returns: An iterable of (name, dict).
2479
# We need a loaded store
2482
except errors.NoSuchFile:
2483
# If the file doesn't exist, there is no sections
2485
cobj = self._config_obj
2487
yield self.readonly_section_class(None, cobj)
2488
for section_name in cobj.sections:
2489
yield self.readonly_section_class(section_name, cobj[section_name])
2491
def get_mutable_section(self, section_name=None):
2492
# We need a loaded store
2495
except errors.NoSuchFile:
2496
# The file doesn't exist, let's pretend it was empty
2497
self._load_from_string('')
2498
if section_name is None:
2499
section = self._config_obj
2501
section = self._config_obj.setdefault(section_name, {})
2502
return self.mutable_section_class(section_name, section)
2505
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2506
# unlockable stores for use with objects that can already ensure the locking
2507
# (think branches). If different stores (not based on ConfigObj) are created,
2508
# they may face the same issue.
2511
class LockableIniFileStore(IniFileStore):
2512
"""A ConfigObjStore using locks on save to ensure store integrity."""
2514
def __init__(self, transport, file_name, lock_dir_name=None):
2515
"""A config Store using ConfigObj for storage.
2517
:param transport: The transport object where the config file is located.
2519
:param file_name: The config file basename in the transport directory.
2521
if lock_dir_name is None:
2522
lock_dir_name = 'lock'
2523
self.lock_dir_name = lock_dir_name
2524
super(LockableIniFileStore, self).__init__(transport, file_name)
2525
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2527
def lock_write(self, token=None):
2528
"""Takes a write lock in the directory containing the config file.
2530
If the directory doesn't exist it is created.
2532
# FIXME: This doesn't check the ownership of the created directories as
2533
# ensure_config_dir_exists does. It should if the transport is local
2534
# -- vila 2011-04-06
2535
self.transport.create_prefix()
2536
return self._lock.lock_write(token)
2541
def break_lock(self):
2542
self._lock.break_lock()
2546
# We need to be able to override the undecorated implementation
2547
self.save_without_locking()
2549
def save_without_locking(self):
2550
super(LockableIniFileStore, self).save()
2553
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2554
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2555
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
2557
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2558
# functions or a registry will make it easier and clearer for tests, focusing
2559
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2560
# on a poolie's remark)
2561
class GlobalStore(LockableIniFileStore):
2563
def __init__(self, possible_transports=None):
2564
t = transport.get_transport(config_dir(),
2565
possible_transports=possible_transports)
2566
super(GlobalStore, self).__init__(t, 'bazaar.conf')
2569
class LocationStore(LockableIniFileStore):
2571
def __init__(self, possible_transports=None):
2572
t = transport.get_transport(config_dir(),
2573
possible_transports=possible_transports)
2574
super(LocationStore, self).__init__(t, 'locations.conf')
2577
class BranchStore(IniFileStore):
2579
def __init__(self, branch):
2580
super(BranchStore, self).__init__(branch.control_transport,
2582
self.branch = branch
2584
def lock_write(self, token=None):
2585
return self.branch.lock_write(token)
2588
return self.branch.unlock()
2592
# We need to be able to override the undecorated implementation
2593
self.save_without_locking()
2595
def save_without_locking(self):
2596
super(BranchStore, self).save()
2599
class SectionMatcher(object):
2600
"""Select sections into a given Store.
2602
This intended to be used to postpone getting an iterable of sections from a
2606
def __init__(self, store):
2609
def get_sections(self):
2610
# This is where we require loading the store so we can see all defined
2612
sections = self.store.get_sections()
2613
# Walk the revisions in the order provided
2618
def match(self, secion):
2619
raise NotImplementedError(self.match)
2622
class LocationSection(Section):
2624
def __init__(self, section, length, extra_path):
2625
super(LocationSection, self).__init__(section.id, section.options)
2626
self.length = length
2627
self.extra_path = extra_path
2629
def get(self, name, default=None):
2630
value = super(LocationSection, self).get(name, default)
2631
if value is not None:
2632
policy_name = self.get(name + ':policy', None)
2633
policy = _policy_value.get(policy_name, POLICY_NONE)
2634
if policy == POLICY_APPENDPATH:
2635
value = urlutils.join(value, self.extra_path)
2639
class LocationMatcher(SectionMatcher):
2641
def __init__(self, store, location):
2642
super(LocationMatcher, self).__init__(store)
2643
if location.startswith('file://'):
2644
location = urlutils.local_path_from_url(location)
2645
self.location = location
2647
def _get_matching_sections(self):
2648
"""Get all sections matching ``location``."""
2649
# We slightly diverge from LocalConfig here by allowing the no-name
2650
# section as the most generic one and the lower priority.
2651
no_name_section = None
2653
# Filter out the no_name_section so _iter_for_location_by_parts can be
2654
# used (it assumes all sections have a name).
2655
for section in self.store.get_sections():
2656
if section.id is None:
2657
no_name_section = section
2659
sections.append(section)
2660
# Unfortunately _iter_for_location_by_parts deals with section names so
2661
# we have to resync.
2662
filtered_sections = _iter_for_location_by_parts(
2663
[s.id for s in sections], self.location)
2664
iter_sections = iter(sections)
2665
matching_sections = []
2666
if no_name_section is not None:
2667
matching_sections.append(
2668
LocationSection(no_name_section, 0, self.location))
2669
for section_id, extra_path, length in filtered_sections:
2670
# a section id is unique for a given store so it's safe to iterate
2672
section = iter_sections.next()
2673
if section_id == section.id:
2674
matching_sections.append(
2675
LocationSection(section, length, extra_path))
2676
return matching_sections
2678
def get_sections(self):
2679
# Override the default implementation as we want to change the order
2680
matching_sections = self._get_matching_sections()
2681
# We want the longest (aka more specific) locations first
2682
sections = sorted(matching_sections,
2683
key=lambda section: (section.length, section.id),
2685
# Sections mentioning 'ignore_parents' restrict the selection
2686
for section in sections:
2687
# FIXME: We really want to use as_bool below -- vila 2011-04-07
2688
ignore = section.get('ignore_parents', None)
2689
if ignore is not None:
2690
ignore = ui.bool_from_string(ignore)
2693
# Finally, we have a valid section
2697
class Stack(object):
2698
"""A stack of configurations where an option can be defined"""
2700
def __init__(self, sections_def, store=None, mutable_section_name=None):
2701
"""Creates a stack of sections with an optional store for changes.
2703
:param sections_def: A list of Section or callables that returns an
2704
iterable of Section. This defines the Sections for the Stack and
2705
can be called repeatedly if needed.
2707
:param store: The optional Store where modifications will be
2708
recorded. If none is specified, no modifications can be done.
2710
:param mutable_section_name: The name of the MutableSection where
2711
changes are recorded. This requires the ``store`` parameter to be
2714
self.sections_def = sections_def
2716
self.mutable_section_name = mutable_section_name
2718
def get(self, name):
2719
"""Return the *first* option value found in the sections.
2721
This is where we guarantee that sections coming from Store are loaded
2722
lazily: the loading is delayed until we need to either check that an
2723
option exists or get its value, which in turn may require to discover
2724
in which sections it can be defined. Both of these (section and option
2725
existence) require loading the store (even partially).
2727
# FIXME: No caching of options nor sections yet -- vila 20110503
2729
# Ensuring lazy loading is achieved by delaying section matching (which
2730
# implies querying the persistent storage) until it can't be avoided
2731
# anymore by using callables to describe (possibly empty) section
2733
for section_or_callable in self.sections_def:
2734
# Each section can expand to multiple ones when a callable is used
2735
if callable(section_or_callable):
2736
sections = section_or_callable()
2738
sections = [section_or_callable]
2739
for section in sections:
2740
value = section.get(name)
2741
if value is not None:
2743
if value is not None:
2746
# If the option is registered, it may provide a default value
2748
opt = option_registry.get(name)
2753
value = opt.get_default()
2754
for hook in ConfigHooks['get']:
2755
hook(self, name, value)
2758
def _get_mutable_section(self):
2759
"""Get the MutableSection for the Stack.
2761
This is where we guarantee that the mutable section is lazily loaded:
2762
this means we won't load the corresponding store before setting a value
2763
or deleting an option. In practice the store will often be loaded but
2764
this allows helps catching some programming errors.
2766
section = self.store.get_mutable_section(self.mutable_section_name)
2769
def set(self, name, value):
2770
"""Set a new value for the option."""
2771
section = self._get_mutable_section()
2772
section.set(name, value)
2773
for hook in ConfigHooks['set']:
2774
hook(self, name, value)
2776
def remove(self, name):
2777
"""Remove an existing option."""
2778
section = self._get_mutable_section()
2779
section.remove(name)
2780
for hook in ConfigHooks['remove']:
2784
# Mostly for debugging use
2785
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2788
class _CompatibleStack(Stack):
2789
"""Place holder for compatibility with previous design.
2791
This is intended to ease the transition from the Config-based design to the
2792
Stack-based design and should not be used nor relied upon by plugins.
2794
One assumption made here is that the daughter classes will all use Stores
2795
derived from LockableIniFileStore).
2797
It implements set() by re-loading the store before applying the
2798
modification and saving it.
2800
The long term plan being to implement a single write by store to save
2801
all modifications, this class should not be used in the interim.
2804
def set(self, name, value):
2807
super(_CompatibleStack, self).set(name, value)
2808
# Force a write to persistent storage
2812
class GlobalStack(_CompatibleStack):
2816
gstore = GlobalStore()
2817
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
2820
class LocationStack(_CompatibleStack):
2822
def __init__(self, location):
2823
"""Make a new stack for a location and global configuration.
2825
:param location: A URL prefix to """
2826
lstore = LocationStore()
2827
matcher = LocationMatcher(lstore, location)
2828
gstore = GlobalStore()
2829
super(LocationStack, self).__init__(
2830
[matcher.get_sections, gstore.get_sections], lstore)
2832
class BranchStack(_CompatibleStack):
2834
def __init__(self, branch):
2835
bstore = BranchStore(branch)
2836
lstore = LocationStore()
2837
matcher = LocationMatcher(lstore, branch.base)
2838
gstore = GlobalStore()
2839
super(BranchStack, self).__init__(
2840
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
2842
self.branch = branch
2845
class cmd_config(commands.Command):
2846
__doc__ = """Display, set or remove a configuration option.
2848
Display the active value for a given option.
2850
If --all is specified, NAME is interpreted as a regular expression and all
2851
matching options are displayed mentioning their scope. The active value
2852
that bzr will take into account is the first one displayed for each option.
2854
If no NAME is given, --all .* is implied.
2856
Setting a value is achieved by using name=value without spaces. The value
2857
is set in the most relevant scope and can be checked by displaying the
2861
takes_args = ['name?']
2865
# FIXME: This should be a registry option so that plugins can register
2866
# their own config files (or not) -- vila 20101002
2867
commands.Option('scope', help='Reduce the scope to the specified'
2868
' configuration file',
2870
commands.Option('all',
2871
help='Display all the defined values for the matching options.',
2873
commands.Option('remove', help='Remove the option from'
2874
' the configuration file'),
2877
_see_also = ['configuration']
2879
@commands.display_command
2880
def run(self, name=None, all=False, directory=None, scope=None,
2882
if directory is None:
2884
directory = urlutils.normalize_url(directory)
2886
raise errors.BzrError(
2887
'--all and --remove are mutually exclusive.')
2889
# Delete the option in the given scope
2890
self._remove_config_option(name, directory, scope)
2892
# Defaults to all options
2893
self._show_matching_options('.*', directory, scope)
2896
name, value = name.split('=', 1)
2898
# Display the option(s) value(s)
2900
self._show_matching_options(name, directory, scope)
2902
self._show_value(name, directory, scope)
2905
raise errors.BzrError(
2906
'Only one option can be set.')
2907
# Set the option value
2908
self._set_config_option(name, value, directory, scope)
2910
def _get_configs(self, directory, scope=None):
2911
"""Iterate the configurations specified by ``directory`` and ``scope``.
2913
:param directory: Where the configurations are derived from.
2915
:param scope: A specific config to start from.
2917
if scope is not None:
2918
if scope == 'bazaar':
2919
yield GlobalConfig()
2920
elif scope == 'locations':
2921
yield LocationConfig(directory)
2922
elif scope == 'branch':
2923
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2925
yield br.get_config()
2928
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2930
yield br.get_config()
2931
except errors.NotBranchError:
2932
yield LocationConfig(directory)
2933
yield GlobalConfig()
2935
def _show_value(self, name, directory, scope):
2937
for c in self._get_configs(directory, scope):
2940
for (oname, value, section, conf_id, parser) in c._get_options():
2942
# Display only the first value and exit
2944
# FIXME: We need to use get_user_option to take policies
2945
# into account and we need to make sure the option exists
2946
# too (hence the two for loops), this needs a better API
2948
value = c.get_user_option(name)
2949
# Quote the value appropriately
2950
value = parser._quote(value)
2951
self.outf.write('%s\n' % (value,))
2955
raise errors.NoSuchConfigOption(name)
2957
def _show_matching_options(self, name, directory, scope):
2958
name = lazy_regex.lazy_compile(name)
2959
# We want any error in the regexp to be raised *now* so we need to
2960
# avoid the delay introduced by the lazy regexp. But, we still do
2961
# want the nicer errors raised by lazy_regex.
2962
name._compile_and_collapse()
2965
for c in self._get_configs(directory, scope):
2966
for (oname, value, section, conf_id, parser) in c._get_options():
2967
if name.search(oname):
2968
if cur_conf_id != conf_id:
2969
# Explain where the options are defined
2970
self.outf.write('%s:\n' % (conf_id,))
2971
cur_conf_id = conf_id
2973
if (section not in (None, 'DEFAULT')
2974
and cur_section != section):
2975
# Display the section if it's not the default (or only)
2977
self.outf.write(' [%s]\n' % (section,))
2978
cur_section = section
2979
self.outf.write(' %s = %s\n' % (oname, value))
2981
def _set_config_option(self, name, value, directory, scope):
2982
for conf in self._get_configs(directory, scope):
2983
conf.set_user_option(name, value)
2986
raise errors.NoSuchConfig(scope)
2988
def _remove_config_option(self, name, directory, scope):
2990
raise errors.BzrCommandError(
2991
'--remove expects an option to remove.')
2993
for conf in self._get_configs(directory, scope):
2994
for (section_name, section, conf_id) in conf._get_sections():
2995
if scope is not None and conf_id != scope:
2996
# Not the right configuration file
2999
if conf_id != conf.config_id():
3000
conf = self._get_configs(directory, conf_id).next()
3001
# We use the first section in the first config where the
3002
# option is defined to remove it
3003
conf.remove_user_option(name, section_name)
3008
raise errors.NoSuchConfig(scope)
3010
raise errors.NoSuchConfigOption(name)
3014
# We need adapters that can build a Store or a Stack in a test context. Test
3015
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3016
# themselves. The builder will receive a test instance and should return a
3017
# ready-to-use store or stack. Plugins that define new store/stacks can also
3018
# register themselves here to be tested against the tests defined in
3019
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3020
# for the same tests.
3022
# The registered object should be a callable receiving a test instance
3023
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3025
test_store_builder_registry = registry.Registry()
3027
# The registered object should be a callable receiving a test instance
3028
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3030
test_stack_builder_registry = registry.Registry()