169
228
def _get_signing_policy(self):
170
229
"""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)
172
355
def _get_user_option(self, option_name):
173
356
"""Template method to provide a user option."""
176
def get_user_option(self, option_name):
177
"""Get a generic option - no special process, no default."""
178
return self._get_user_option(option_name)
180
def get_user_option_as_bool(self, option_name):
181
"""Get a generic option as a boolean - no special process, no default.
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
183
389
:return None if the option doesn't exist or its value can't be
184
interpreted as a boolean. Returns True or False ortherwise.
186
s = self._get_user_option(option_name)
187
return ui.bool_from_string(s)
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
189
416
def gpg_signing_command(self):
190
417
"""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()
308
661
class IniBasedConfig(Config):
309
662
"""A configuration policy that draws from ini files."""
311
def __init__(self, get_filename):
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.
312
670
super(IniBasedConfig, self).__init__()
313
self._get_filename = get_filename
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
314
683
self._parser = None
316
def _get_parser(self, file=None):
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):
317
708
if self._parser is not None:
318
709
return self._parser
320
input = self._get_filename()
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')
721
co_input = self.file_name
324
self._parser = ConfigObj(input, encoding='utf-8')
723
self._parser = ConfigObj(co_input, encoding='utf-8')
325
724
except configobj.ConfigObjError, e:
326
725
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']:
327
732
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']:
329
743
def _get_matching_sections(self):
330
744
"""Return an ordered list of (section_name, extra_path) pairs.
1430
2207
configobj[name] = value
1432
2209
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)
1433
2222
self._set_configobj(configobj)
1435
2224
def _get_config_file(self):
1437
return self._transport.get(self._filename)
2226
f = StringIO(self._transport.get_bytes(self._filename))
2227
for hook in OldConfigHooks['load']:
1438
2230
except errors.NoSuchFile:
1439
2231
return StringIO()
2233
def _external_url(self):
2234
return urlutils.join(self._transport.external_url(), self._filename)
1441
2236
def _get_configobj(self):
1442
return ConfigObj(self._get_config_file(), encoding='utf-8')
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())
1444
2249
def _set_configobj(self, configobj):
1445
2250
out_file = StringIO()
1446
2251
configobj.write(out_file)
1447
2252
out_file.seek(0)
1448
2253
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, from_unicode=None):
2269
self.default = default
2270
self.from_unicode = from_unicode
2272
def get_default(self):
2276
# Predefined converters to get proper values from store
2278
def bool_from_store(unicode_str):
2279
return ui.bool_from_string(unicode_str)
2284
option_registry = registry.Registry()
2287
option_registry.register(
2288
'editor', Option('editor'),
2289
help='The command called to launch an editor to enter a message.')
2291
option_registry.register(
2292
'dirstate.fdatasync', Option('dirstate.fdatasync', default=True,
2293
from_unicode=bool_from_store),
2294
help='Flush dirstate changes onto physical disk?')
2296
option_registry.register(
2297
'repository.fdatasync',
2298
Option('repository.fdatasync', default=True, from_unicode=bool_from_store),
2299
help='Flush repository changes onto physical disk?')
2302
class Section(object):
2303
"""A section defines a dict of option name => value.
2305
This is merely a read-only dict which can add some knowledge about the
2306
options. It is *not* a python dict object though and doesn't try to mimic
2310
def __init__(self, section_id, options):
2311
self.id = section_id
2312
# We re-use the dict-like object received
2313
self.options = options
2315
def get(self, name, default=None):
2316
return self.options.get(name, default)
2319
# Mostly for debugging use
2320
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2323
_NewlyCreatedOption = object()
2324
"""Was the option created during the MutableSection lifetime"""
2327
class MutableSection(Section):
2328
"""A section allowing changes and keeping track of the original values."""
2330
def __init__(self, section_id, options):
2331
super(MutableSection, self).__init__(section_id, options)
2334
def set(self, name, value):
2335
if name not in self.options:
2336
# This is a new option
2337
self.orig[name] = _NewlyCreatedOption
2338
elif name not in self.orig:
2339
self.orig[name] = self.get(name, None)
2340
self.options[name] = value
2342
def remove(self, name):
2343
if name not in self.orig:
2344
self.orig[name] = self.get(name, None)
2345
del self.options[name]
2348
class Store(object):
2349
"""Abstract interface to persistent storage for configuration options."""
2351
readonly_section_class = Section
2352
mutable_section_class = MutableSection
2354
def is_loaded(self):
2355
"""Returns True if the Store has been loaded.
2357
This is used to implement lazy loading and ensure the persistent
2358
storage is queried only when needed.
2360
raise NotImplementedError(self.is_loaded)
2363
"""Loads the Store from persistent storage."""
2364
raise NotImplementedError(self.load)
2366
def _load_from_string(self, bytes):
2367
"""Create a store from a string in configobj syntax.
2369
:param bytes: A string representing the file content.
2371
raise NotImplementedError(self._load_from_string)
2374
"""Unloads the Store.
2376
This should make is_loaded() return False. This is used when the caller
2377
knows that the persistent storage has changed or may have change since
2380
raise NotImplementedError(self.unload)
2383
"""Saves the Store to persistent storage."""
2384
raise NotImplementedError(self.save)
2386
def external_url(self):
2387
raise NotImplementedError(self.external_url)
2389
def get_sections(self):
2390
"""Returns an ordered iterable of existing sections.
2392
:returns: An iterable of (name, dict).
2394
raise NotImplementedError(self.get_sections)
2396
def get_mutable_section(self, section_name=None):
2397
"""Returns the specified mutable section.
2399
:param section_name: The section identifier
2401
raise NotImplementedError(self.get_mutable_section)
2404
# Mostly for debugging use
2405
return "<config.%s(%s)>" % (self.__class__.__name__,
2406
self.external_url())
2409
class IniFileStore(Store):
2410
"""A config Store using ConfigObj for storage.
2412
:ivar transport: The transport object where the config file is located.
2414
:ivar file_name: The config file basename in the transport directory.
2416
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2417
serialize/deserialize the config file.
2420
def __init__(self, transport, file_name):
2421
"""A config Store using ConfigObj for storage.
2423
:param transport: The transport object where the config file is located.
2425
:param file_name: The config file basename in the transport directory.
2427
super(IniFileStore, self).__init__()
2428
self.transport = transport
2429
self.file_name = file_name
2430
self._config_obj = None
2432
def is_loaded(self):
2433
return self._config_obj != None
2436
self._config_obj = None
2439
"""Load the store from the associated file."""
2440
if self.is_loaded():
2442
content = self.transport.get_bytes(self.file_name)
2443
self._load_from_string(content)
2444
for hook in ConfigHooks['load']:
2447
def _load_from_string(self, bytes):
2448
"""Create a config store from a string.
2450
:param bytes: A string representing the file content.
2452
if self.is_loaded():
2453
raise AssertionError('Already loaded: %r' % (self._config_obj,))
2454
co_input = StringIO(bytes)
2456
# The config files are always stored utf8-encoded
2457
self._config_obj = ConfigObj(co_input, encoding='utf-8')
2458
except configobj.ConfigObjError, e:
2459
self._config_obj = None
2460
raise errors.ParseConfigError(e.errors, self.external_url())
2461
except UnicodeDecodeError:
2462
raise errors.ConfigContentError(self.external_url())
2465
if not self.is_loaded():
2469
self._config_obj.write(out)
2470
self.transport.put_bytes(self.file_name, out.getvalue())
2471
for hook in ConfigHooks['save']:
2474
def external_url(self):
2475
# FIXME: external_url should really accepts an optional relpath
2476
# parameter (bug #750169) :-/ -- vila 2011-04-04
2477
# The following will do in the interim but maybe we don't want to
2478
# expose a path here but rather a config ID and its associated
2479
# object </hand wawe>.
2480
return urlutils.join(self.transport.external_url(), self.file_name)
2482
def get_sections(self):
2483
"""Get the configobj section in the file order.
2485
:returns: An iterable of (name, dict).
2487
# We need a loaded store
2490
except errors.NoSuchFile:
2491
# If the file doesn't exist, there is no sections
2493
cobj = self._config_obj
2495
yield self.readonly_section_class(None, cobj)
2496
for section_name in cobj.sections:
2497
yield self.readonly_section_class(section_name, cobj[section_name])
2499
def get_mutable_section(self, section_name=None):
2500
# We need a loaded store
2503
except errors.NoSuchFile:
2504
# The file doesn't exist, let's pretend it was empty
2505
self._load_from_string('')
2506
if section_name is None:
2507
section = self._config_obj
2509
section = self._config_obj.setdefault(section_name, {})
2510
return self.mutable_section_class(section_name, section)
2513
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2514
# unlockable stores for use with objects that can already ensure the locking
2515
# (think branches). If different stores (not based on ConfigObj) are created,
2516
# they may face the same issue.
2519
class LockableIniFileStore(IniFileStore):
2520
"""A ConfigObjStore using locks on save to ensure store integrity."""
2522
def __init__(self, transport, file_name, lock_dir_name=None):
2523
"""A config Store using ConfigObj for storage.
2525
:param transport: The transport object where the config file is located.
2527
:param file_name: The config file basename in the transport directory.
2529
if lock_dir_name is None:
2530
lock_dir_name = 'lock'
2531
self.lock_dir_name = lock_dir_name
2532
super(LockableIniFileStore, self).__init__(transport, file_name)
2533
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2535
def lock_write(self, token=None):
2536
"""Takes a write lock in the directory containing the config file.
2538
If the directory doesn't exist it is created.
2540
# FIXME: This doesn't check the ownership of the created directories as
2541
# ensure_config_dir_exists does. It should if the transport is local
2542
# -- vila 2011-04-06
2543
self.transport.create_prefix()
2544
return self._lock.lock_write(token)
2549
def break_lock(self):
2550
self._lock.break_lock()
2554
# We need to be able to override the undecorated implementation
2555
self.save_without_locking()
2557
def save_without_locking(self):
2558
super(LockableIniFileStore, self).save()
2561
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2562
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2563
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
2565
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2566
# functions or a registry will make it easier and clearer for tests, focusing
2567
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2568
# on a poolie's remark)
2569
class GlobalStore(LockableIniFileStore):
2571
def __init__(self, possible_transports=None):
2572
t = transport.get_transport(config_dir(),
2573
possible_transports=possible_transports)
2574
super(GlobalStore, self).__init__(t, 'bazaar.conf')
2577
class LocationStore(LockableIniFileStore):
2579
def __init__(self, possible_transports=None):
2580
t = transport.get_transport(config_dir(),
2581
possible_transports=possible_transports)
2582
super(LocationStore, self).__init__(t, 'locations.conf')
2585
class BranchStore(IniFileStore):
2587
def __init__(self, branch):
2588
super(BranchStore, self).__init__(branch.control_transport,
2590
self.branch = branch
2592
def lock_write(self, token=None):
2593
return self.branch.lock_write(token)
2596
return self.branch.unlock()
2600
# We need to be able to override the undecorated implementation
2601
self.save_without_locking()
2603
def save_without_locking(self):
2604
super(BranchStore, self).save()
2607
class SectionMatcher(object):
2608
"""Select sections into a given Store.
2610
This intended to be used to postpone getting an iterable of sections from a
2614
def __init__(self, store):
2617
def get_sections(self):
2618
# This is where we require loading the store so we can see all defined
2620
sections = self.store.get_sections()
2621
# Walk the revisions in the order provided
2626
def match(self, secion):
2627
raise NotImplementedError(self.match)
2630
class LocationSection(Section):
2632
def __init__(self, section, length, extra_path):
2633
super(LocationSection, self).__init__(section.id, section.options)
2634
self.length = length
2635
self.extra_path = extra_path
2637
def get(self, name, default=None):
2638
value = super(LocationSection, self).get(name, default)
2639
if value is not None:
2640
policy_name = self.get(name + ':policy', None)
2641
policy = _policy_value.get(policy_name, POLICY_NONE)
2642
if policy == POLICY_APPENDPATH:
2643
value = urlutils.join(value, self.extra_path)
2647
class LocationMatcher(SectionMatcher):
2649
def __init__(self, store, location):
2650
super(LocationMatcher, self).__init__(store)
2651
if location.startswith('file://'):
2652
location = urlutils.local_path_from_url(location)
2653
self.location = location
2655
def _get_matching_sections(self):
2656
"""Get all sections matching ``location``."""
2657
# We slightly diverge from LocalConfig here by allowing the no-name
2658
# section as the most generic one and the lower priority.
2659
no_name_section = None
2661
# Filter out the no_name_section so _iter_for_location_by_parts can be
2662
# used (it assumes all sections have a name).
2663
for section in self.store.get_sections():
2664
if section.id is None:
2665
no_name_section = section
2667
all_sections.append(section)
2668
# Unfortunately _iter_for_location_by_parts deals with section names so
2669
# we have to resync.
2670
filtered_sections = _iter_for_location_by_parts(
2671
[s.id for s in all_sections], self.location)
2672
iter_all_sections = iter(all_sections)
2673
matching_sections = []
2674
if no_name_section is not None:
2675
matching_sections.append(
2676
LocationSection(no_name_section, 0, self.location))
2677
for section_id, extra_path, length in filtered_sections:
2678
# a section id is unique for a given store so it's safe to take the
2679
# first matching section while iterating. Also, all filtered
2680
# sections are part of 'all_sections' and will always be found
2683
section = iter_all_sections.next()
2684
if section_id == section.id:
2685
matching_sections.append(
2686
LocationSection(section, length, extra_path))
2688
return matching_sections
2690
def get_sections(self):
2691
# Override the default implementation as we want to change the order
2692
matching_sections = self._get_matching_sections()
2693
# We want the longest (aka more specific) locations first
2694
sections = sorted(matching_sections,
2695
key=lambda section: (section.length, section.id),
2697
# Sections mentioning 'ignore_parents' restrict the selection
2698
for section in sections:
2699
# FIXME: We really want to use as_bool below -- vila 2011-04-07
2700
ignore = section.get('ignore_parents', None)
2701
if ignore is not None:
2702
ignore = ui.bool_from_string(ignore)
2705
# Finally, we have a valid section
2709
class Stack(object):
2710
"""A stack of configurations where an option can be defined"""
2712
def __init__(self, sections_def, store=None, mutable_section_name=None):
2713
"""Creates a stack of sections with an optional store for changes.
2715
:param sections_def: A list of Section or callables that returns an
2716
iterable of Section. This defines the Sections for the Stack and
2717
can be called repeatedly if needed.
2719
:param store: The optional Store where modifications will be
2720
recorded. If none is specified, no modifications can be done.
2722
:param mutable_section_name: The name of the MutableSection where
2723
changes are recorded. This requires the ``store`` parameter to be
2726
self.sections_def = sections_def
2728
self.mutable_section_name = mutable_section_name
2730
def get(self, name):
2731
"""Return the *first* option value found in the sections.
2733
This is where we guarantee that sections coming from Store are loaded
2734
lazily: the loading is delayed until we need to either check that an
2735
option exists or get its value, which in turn may require to discover
2736
in which sections it can be defined. Both of these (section and option
2737
existence) require loading the store (even partially).
2739
# FIXME: No caching of options nor sections yet -- vila 20110503
2741
# Ensuring lazy loading is achieved by delaying section matching (which
2742
# implies querying the persistent storage) until it can't be avoided
2743
# anymore by using callables to describe (possibly empty) section
2745
for section_or_callable in self.sections_def:
2746
# Each section can expand to multiple ones when a callable is used
2747
if callable(section_or_callable):
2748
sections = section_or_callable()
2750
sections = [section_or_callable]
2751
for section in sections:
2752
value = section.get(name)
2753
if value is not None:
2755
if value is not None:
2757
# If the option is registered, it may provide additional info about
2760
opt = option_registry.get(name)
2764
if (opt is not None and opt.from_unicode is not None
2765
and value is not None):
2766
# If a value exists and the option provides a converter, use it
2768
converted = opt.from_unicode(value)
2769
except (ValueError, TypeError):
2770
# Invalid values are ignored
2774
# If the option is registered, it may provide a default value
2776
value = opt.get_default()
2777
if opt is not None and value is None:
2778
value = opt.get_default()
2779
for hook in ConfigHooks['get']:
2780
hook(self, name, value)
2783
def _get_mutable_section(self):
2784
"""Get the MutableSection for the Stack.
2786
This is where we guarantee that the mutable section is lazily loaded:
2787
this means we won't load the corresponding store before setting a value
2788
or deleting an option. In practice the store will often be loaded but
2789
this allows helps catching some programming errors.
2791
section = self.store.get_mutable_section(self.mutable_section_name)
2794
def set(self, name, value):
2795
"""Set a new value for the option."""
2796
section = self._get_mutable_section()
2797
section.set(name, value)
2798
for hook in ConfigHooks['set']:
2799
hook(self, name, value)
2801
def remove(self, name):
2802
"""Remove an existing option."""
2803
section = self._get_mutable_section()
2804
section.remove(name)
2805
for hook in ConfigHooks['remove']:
2809
# Mostly for debugging use
2810
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2813
class _CompatibleStack(Stack):
2814
"""Place holder for compatibility with previous design.
2816
This is intended to ease the transition from the Config-based design to the
2817
Stack-based design and should not be used nor relied upon by plugins.
2819
One assumption made here is that the daughter classes will all use Stores
2820
derived from LockableIniFileStore).
2822
It implements set() by re-loading the store before applying the
2823
modification and saving it.
2825
The long term plan being to implement a single write by store to save
2826
all modifications, this class should not be used in the interim.
2829
def set(self, name, value):
2832
super(_CompatibleStack, self).set(name, value)
2833
# Force a write to persistent storage
2837
class GlobalStack(_CompatibleStack):
2841
gstore = GlobalStore()
2842
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
2845
class LocationStack(_CompatibleStack):
2847
def __init__(self, location):
2848
"""Make a new stack for a location and global configuration.
2850
:param location: A URL prefix to """
2851
lstore = LocationStore()
2852
matcher = LocationMatcher(lstore, location)
2853
gstore = GlobalStore()
2854
super(LocationStack, self).__init__(
2855
[matcher.get_sections, gstore.get_sections], lstore)
2857
class BranchStack(_CompatibleStack):
2859
def __init__(self, branch):
2860
bstore = BranchStore(branch)
2861
lstore = LocationStore()
2862
matcher = LocationMatcher(lstore, branch.base)
2863
gstore = GlobalStore()
2864
super(BranchStack, self).__init__(
2865
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
2867
self.branch = branch
2870
class cmd_config(commands.Command):
2871
__doc__ = """Display, set or remove a configuration option.
2873
Display the active value for a given option.
2875
If --all is specified, NAME is interpreted as a regular expression and all
2876
matching options are displayed mentioning their scope. The active value
2877
that bzr will take into account is the first one displayed for each option.
2879
If no NAME is given, --all .* is implied.
2881
Setting a value is achieved by using name=value without spaces. The value
2882
is set in the most relevant scope and can be checked by displaying the
2886
takes_args = ['name?']
2890
# FIXME: This should be a registry option so that plugins can register
2891
# their own config files (or not) -- vila 20101002
2892
commands.Option('scope', help='Reduce the scope to the specified'
2893
' configuration file',
2895
commands.Option('all',
2896
help='Display all the defined values for the matching options.',
2898
commands.Option('remove', help='Remove the option from'
2899
' the configuration file'),
2902
_see_also = ['configuration']
2904
@commands.display_command
2905
def run(self, name=None, all=False, directory=None, scope=None,
2907
if directory is None:
2909
directory = urlutils.normalize_url(directory)
2911
raise errors.BzrError(
2912
'--all and --remove are mutually exclusive.')
2914
# Delete the option in the given scope
2915
self._remove_config_option(name, directory, scope)
2917
# Defaults to all options
2918
self._show_matching_options('.*', directory, scope)
2921
name, value = name.split('=', 1)
2923
# Display the option(s) value(s)
2925
self._show_matching_options(name, directory, scope)
2927
self._show_value(name, directory, scope)
2930
raise errors.BzrError(
2931
'Only one option can be set.')
2932
# Set the option value
2933
self._set_config_option(name, value, directory, scope)
2935
def _get_configs(self, directory, scope=None):
2936
"""Iterate the configurations specified by ``directory`` and ``scope``.
2938
:param directory: Where the configurations are derived from.
2940
:param scope: A specific config to start from.
2942
if scope is not None:
2943
if scope == 'bazaar':
2944
yield GlobalConfig()
2945
elif scope == 'locations':
2946
yield LocationConfig(directory)
2947
elif scope == 'branch':
2948
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2950
yield br.get_config()
2953
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
2955
yield br.get_config()
2956
except errors.NotBranchError:
2957
yield LocationConfig(directory)
2958
yield GlobalConfig()
2960
def _show_value(self, name, directory, scope):
2962
for c in self._get_configs(directory, scope):
2965
for (oname, value, section, conf_id, parser) in c._get_options():
2967
# Display only the first value and exit
2969
# FIXME: We need to use get_user_option to take policies
2970
# into account and we need to make sure the option exists
2971
# too (hence the two for loops), this needs a better API
2973
value = c.get_user_option(name)
2974
# Quote the value appropriately
2975
value = parser._quote(value)
2976
self.outf.write('%s\n' % (value,))
2980
raise errors.NoSuchConfigOption(name)
2982
def _show_matching_options(self, name, directory, scope):
2983
name = lazy_regex.lazy_compile(name)
2984
# We want any error in the regexp to be raised *now* so we need to
2985
# avoid the delay introduced by the lazy regexp. But, we still do
2986
# want the nicer errors raised by lazy_regex.
2987
name._compile_and_collapse()
2990
for c in self._get_configs(directory, scope):
2991
for (oname, value, section, conf_id, parser) in c._get_options():
2992
if name.search(oname):
2993
if cur_conf_id != conf_id:
2994
# Explain where the options are defined
2995
self.outf.write('%s:\n' % (conf_id,))
2996
cur_conf_id = conf_id
2998
if (section not in (None, 'DEFAULT')
2999
and cur_section != section):
3000
# Display the section if it's not the default (or only)
3002
self.outf.write(' [%s]\n' % (section,))
3003
cur_section = section
3004
self.outf.write(' %s = %s\n' % (oname, value))
3006
def _set_config_option(self, name, value, directory, scope):
3007
for conf in self._get_configs(directory, scope):
3008
conf.set_user_option(name, value)
3011
raise errors.NoSuchConfig(scope)
3013
def _remove_config_option(self, name, directory, scope):
3015
raise errors.BzrCommandError(
3016
'--remove expects an option to remove.')
3018
for conf in self._get_configs(directory, scope):
3019
for (section_name, section, conf_id) in conf._get_sections():
3020
if scope is not None and conf_id != scope:
3021
# Not the right configuration file
3024
if conf_id != conf.config_id():
3025
conf = self._get_configs(directory, conf_id).next()
3026
# We use the first section in the first config where the
3027
# option is defined to remove it
3028
conf.remove_user_option(name, section_name)
3033
raise errors.NoSuchConfig(scope)
3035
raise errors.NoSuchConfigOption(name)
3039
# We need adapters that can build a Store or a Stack in a test context. Test
3040
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3041
# themselves. The builder will receive a test instance and should return a
3042
# ready-to-use store or stack. Plugins that define new store/stacks can also
3043
# register themselves here to be tested against the tests defined in
3044
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3045
# for the same tests.
3047
# The registered object should be a callable receiving a test instance
3048
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3050
test_store_builder_registry = registry.Registry()
3052
# The registered object should be a callable receiving a test instance
3053
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3055
test_stack_builder_registry = registry.Registry()