229
160
def _get_signing_policy(self):
230
161
"""Template method to override signature creation policy."""
234
def expand_options(self, string, env=None):
235
"""Expand option references in the string in the configuration context.
237
:param string: The string containing option to expand.
239
:param env: An option dict defining additional configuration options or
240
overriding existing ones.
242
:returns: The expanded string.
244
return self._expand_options_in_string(string, env)
246
def _expand_options_in_list(self, slist, env=None, _ref_stack=None):
247
"""Expand options in a list of strings in the configuration context.
249
:param slist: A list of strings.
251
:param env: An option dict defining additional configuration options or
252
overriding existing ones.
254
:param _ref_stack: Private list containing the options being
255
expanded to detect loops.
257
:returns: The flatten list of expanded strings.
259
# expand options in each value separately flattening lists
262
value = self._expand_options_in_string(s, env, _ref_stack)
263
if isinstance(value, list):
269
def _expand_options_in_string(self, string, env=None, _ref_stack=None):
270
"""Expand options in the string in the configuration context.
272
:param string: The string to be expanded.
274
:param env: An option dict defining additional configuration options or
275
overriding existing ones.
277
:param _ref_stack: Private list containing the options being
278
expanded to detect loops.
280
:returns: The expanded string.
283
# Not much to expand there
285
if _ref_stack is None:
286
# What references are currently resolved (to detect loops)
288
if self.option_ref_re is None:
289
# We want to match the most embedded reference first (i.e. for
290
# '{{foo}}' we will get '{foo}',
291
# for '{bar{baz}}' we will get '{baz}'
292
self.option_ref_re = re.compile('({[^{}]+})')
294
# We need to iterate until no more refs appear ({{foo}} will need two
295
# iterations for example).
297
raw_chunks = self.option_ref_re.split(result)
298
if len(raw_chunks) == 1:
299
# Shorcut the trivial case: no refs
303
# Split will isolate refs so that every other chunk is a ref
305
for chunk in raw_chunks:
308
# Keep only non-empty strings (or we get bogus empty
309
# slots when a list value is involved).
314
if name in _ref_stack:
315
raise errors.OptionExpansionLoop(string, _ref_stack)
316
_ref_stack.append(name)
317
value = self._expand_option(name, env, _ref_stack)
319
raise errors.ExpandingUnknownOption(name, string)
320
if isinstance(value, list):
328
# Once a list appears as the result of an expansion, all
329
# callers will get a list result. This allows a consistent
330
# behavior even when some options in the expansion chain
331
# defined as strings (no comma in their value) but their
332
# expanded value is a list.
333
return self._expand_options_in_list(chunks, env, _ref_stack)
335
result = ''.join(chunks)
338
def _expand_option(self, name, env, _ref_stack):
339
if env is not None and name in env:
340
# Special case, values provided in env takes precedence over
344
# FIXME: This is a limited implementation, what we really need is a
345
# way to query the bzr config for the value of an option,
346
# respecting the scope rules (That is, once we implement fallback
347
# configs, getting the option value should restart from the top
348
# config, not the current one) -- vila 20101222
349
value = self.get_user_option(name, expand=False)
350
if isinstance(value, list):
351
value = self._expand_options_in_list(value, env, _ref_stack)
353
value = self._expand_options_in_string(value, env, _ref_stack)
356
163
def _get_user_option(self, option_name):
357
164
"""Template method to provide a user option."""
360
def get_user_option(self, option_name, expand=None):
361
"""Get a generic option - no special process, no default.
363
:param option_name: The queried option.
365
:param expand: Whether options references should be expanded.
367
:returns: The value of the option.
370
expand = _get_expand_default_value()
371
value = self._get_user_option(option_name)
373
if isinstance(value, list):
374
value = self._expand_options_in_list(value)
375
elif isinstance(value, dict):
376
trace.warning('Cannot expand "%s":'
377
' Dicts do not support option expansion'
380
value = self._expand_options_in_string(value)
381
for hook in OldConfigHooks['get']:
382
hook(self, option_name, value)
385
def get_user_option_as_bool(self, option_name, expand=None, default=None):
386
"""Get a generic option as a boolean.
388
:param expand: Allow expanding references to other config values.
389
:param default: Default value if nothing is configured
390
:return None if the option doesn't exist or its value can't be
391
interpreted as a boolean. Returns True or False otherwise.
393
s = self.get_user_option(option_name, expand=expand)
395
# The option doesn't exist
397
val = ui.bool_from_string(s)
399
# The value can't be interpreted as a boolean
400
trace.warning('Value "%s" is not a boolean for "%s"',
404
def get_user_option_as_list(self, option_name, expand=None):
405
"""Get a generic option as a list - no special process, no default.
407
:return None if the option doesn't exist. Returns the value as a list
410
l = self.get_user_option(option_name, expand=expand)
411
if isinstance(l, (str, unicode)):
412
# A single value, most probably the user forgot (or didn't care to
167
def get_user_option(self, option_name):
168
"""Get a generic option - no special process, no default."""
169
return self._get_user_option(option_name)
417
171
def gpg_signing_command(self):
418
172
"""What program should be used to sign signatures?"""
567
def suppress_warning(self, warning):
568
"""Should the warning be suppressed or emitted.
570
:param warning: The name of the warning being tested.
572
:returns: True if the warning should be suppressed, False otherwise.
574
warnings = self.get_user_option_as_list('suppress_warnings')
575
if warnings is None or warning not in warnings:
580
def get_merge_tools(self):
582
for (oname, value, section, conf_id, parser) in self._get_options():
583
if oname.startswith('bzr.mergetool.'):
584
tool_name = oname[len('bzr.mergetool.'):]
585
tools[tool_name] = value
586
trace.mutter('loaded merge tools: %r' % tools)
589
def find_merge_tool(self, name):
590
# We fake a defaults mechanism here by checking if the given name can
591
# be found in the known_merge_tools if it's not found in the config.
592
# This should be done through the proposed config defaults mechanism
593
# when it becomes available in the future.
594
command_line = (self.get_user_option('bzr.mergetool.%s' % name,
596
or mergetools.known_merge_tools.get(name, None))
600
class _ConfigHooks(hooks.Hooks):
601
"""A dict mapping hook names and a list of callables for configs.
605
"""Create the default hooks.
607
These are all empty initially, because by default nothing should get
610
super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
611
self.add_hook('load',
612
'Invoked when a config store is loaded.'
613
' The signature is (store).',
615
self.add_hook('save',
616
'Invoked when a config store is saved.'
617
' The signature is (store).',
619
# The hooks for config options
621
'Invoked when a config option is read.'
622
' The signature is (stack, name, value).',
625
'Invoked when a config option is set.'
626
' The signature is (stack, name, value).',
628
self.add_hook('remove',
629
'Invoked when a config option is removed.'
630
' The signature is (stack, name).',
632
ConfigHooks = _ConfigHooks()
635
class _OldConfigHooks(hooks.Hooks):
636
"""A dict mapping hook names and a list of callables for configs.
640
"""Create the default hooks.
642
These are all empty initially, because by default nothing should get
645
super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
646
self.add_hook('load',
647
'Invoked when a config store is loaded.'
648
' The signature is (config).',
650
self.add_hook('save',
651
'Invoked when a config store is saved.'
652
' The signature is (config).',
654
# The hooks for config options
656
'Invoked when a config option is read.'
657
' The signature is (config, name, value).',
660
'Invoked when a config option is set.'
661
' The signature is (config, name, value).',
663
self.add_hook('remove',
664
'Invoked when a config option is removed.'
665
' The signature is (config, name).',
667
OldConfigHooks = _OldConfigHooks()
670
293
class IniBasedConfig(Config):
671
294
"""A configuration policy that draws from ini files."""
673
def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
675
"""Base class for configuration files using an ini-like syntax.
677
:param file_name: The configuration file path.
679
super(IniBasedConfig, self).__init__()
680
self.file_name = file_name
681
if symbol_versioning.deprecated_passed(get_filename):
682
symbol_versioning.warn(
683
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
684
' Use file_name instead.',
687
if get_filename is not None:
688
self.file_name = get_filename()
690
self.file_name = file_name
695
def from_string(cls, str_or_unicode, file_name=None, save=False):
696
"""Create a config object from a string.
698
:param str_or_unicode: A string representing the file content. This will
701
:param file_name: The configuration file path.
703
:param _save: Whether the file should be saved upon creation.
705
conf = cls(file_name=file_name)
706
conf._create_from_string(str_or_unicode, save)
709
def _create_from_string(self, str_or_unicode, save):
710
self._content = StringIO(str_or_unicode.encode('utf-8'))
711
# Some tests use in-memory configs, some other always need the config
712
# file to exist on disk.
714
self._write_config_file()
716
def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
296
def _get_parser(self, file=None):
717
297
if self._parser is not None:
718
298
return self._parser
719
if symbol_versioning.deprecated_passed(file):
720
symbol_versioning.warn(
721
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
722
' Use IniBasedConfig(_content=xxx) instead.',
725
if self._content is not None:
726
co_input = self._content
727
elif self.file_name is None:
728
raise AssertionError('We have no content to create the config')
300
input = self._get_filename()
730
co_input = self.file_name
732
self._parser = ConfigObj(co_input, encoding='utf-8')
304
self._parser = ConfigObj(input, encoding='utf-8')
733
305
except configobj.ConfigObjError, e:
734
306
raise errors.ParseConfigError(e.errors, e.config.filename)
735
except UnicodeDecodeError:
736
raise errors.ConfigContentError(self.file_name)
737
# Make sure self.reload() will use the right file name
738
self._parser.filename = self.file_name
739
for hook in OldConfigHooks['load']:
741
307
return self._parser
744
"""Reload the config file from disk."""
745
if self.file_name is None:
746
raise AssertionError('We need a file name to reload the config')
747
if self._parser is not None:
748
self._parser.reload()
749
for hook in ConfigHooks['load']:
752
309
def _get_matching_sections(self):
753
310
"""Return an ordered list of (section_name, extra_path) pairs.
2216
1202
configobj[name] = value
2218
1204
configobj.setdefault(section, {})[name] = value
2219
for hook in OldConfigHooks['set']:
2220
hook(self, name, value)
2221
self._set_configobj(configobj)
2223
def remove_option(self, option_name, section_name=None):
2224
configobj = self._get_configobj()
2225
if section_name is None:
2226
del configobj[option_name]
2228
del configobj[section_name][option_name]
2229
for hook in OldConfigHooks['remove']:
2230
hook(self, option_name)
2231
self._set_configobj(configobj)
2233
def _get_config_file(self):
2235
f = StringIO(self._transport.get_bytes(self._filename))
2236
for hook in OldConfigHooks['load']:
2239
except errors.NoSuchFile:
2242
def _external_url(self):
2243
return urlutils.join(self._transport.external_url(), self._filename)
1205
self._set_configobj(configobj)
2245
1207
def _get_configobj(self):
2246
f = self._get_config_file()
2249
conf = ConfigObj(f, encoding='utf-8')
2250
except configobj.ConfigObjError, e:
2251
raise errors.ParseConfigError(e.errors, self._external_url())
2252
except UnicodeDecodeError:
2253
raise errors.ConfigContentError(self._external_url())
1209
return ConfigObj(self._transport.get(self._filename),
1211
except errors.NoSuchFile:
1212
return ConfigObj(encoding='utf-8')
2258
1214
def _set_configobj(self, configobj):
2259
1215
out_file = StringIO()
2260
1216
configobj.write(out_file)
2261
1217
out_file.seek(0)
2262
1218
self._transport.put_file(self._filename, out_file)
2263
for hook in OldConfigHooks['save']:
2267
class Option(object):
2268
"""An option definition.
2270
The option *values* are stored in config files and found in sections.
2272
Here we define various properties about the option itself, its default
2273
value, how to convert it from stores, what to do when invalid values are
2274
encoutered, in which config files it can be stored.
2277
def __init__(self, name, default=None, help=None, from_unicode=None,
2279
"""Build an option definition.
2281
:param name: the name used to refer to the option.
2283
:param default: the default value to use when none exist in the config
2286
:param help: a doc string to explain the option to the user.
2288
:param from_unicode: a callable to convert the unicode string
2289
representing the option value in a store. This is not called for
2292
:param invalid: the action to be taken when an invalid value is
2293
encountered in a store. This is called only when from_unicode is
2294
invoked to convert a string and returns None or raise ValueError or
2295
TypeError. Accepted values are: None (ignore invalid values),
2296
'warning' (emit a warning), 'error' (emit an error message and
2300
self.default = default
2302
self.from_unicode = from_unicode
2303
if invalid and invalid not in ('warning', 'error'):
2304
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2305
self.invalid = invalid
2307
def get_default(self):
2310
def get_help_text(self, additional_see_also=None, plain=True):
2312
from bzrlib import help_topics
2313
result += help_topics._format_see_also(additional_see_also)
2315
result = help_topics.help_as_plain_text(result)
2319
# Predefined converters to get proper values from store
2321
def bool_from_store(unicode_str):
2322
return ui.bool_from_string(unicode_str)
2325
def int_from_store(unicode_str):
2326
return int(unicode_str)
2329
def list_from_store(unicode_str):
2330
# ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
2331
if isinstance(unicode_str, (str, unicode)):
2333
# A single value, most probably the user forgot (or didn't care to
2334
# add) the final ','
2337
# The empty string, convert to empty list
2340
# We rely on ConfigObj providing us with a list already
2345
class OptionRegistry(registry.Registry):
2346
"""Register config options by their name.
2348
This overrides ``registry.Registry`` to simplify registration by acquiring
2349
some information from the option object itself.
2352
def register(self, option):
2353
"""Register a new option to its name.
2355
:param option: The option to register. Its name is used as the key.
2357
super(OptionRegistry, self).register(option.name, option,
2360
def register_lazy(self, key, module_name, member_name):
2361
"""Register a new option to be loaded on request.
2363
:param key: the key to request the option later. Since the registration
2364
is lazy, it should be provided and match the option name.
2366
:param module_name: the python path to the module. Such as 'os.path'.
2368
:param member_name: the member of the module to return. If empty or
2369
None, get() will return the module itself.
2371
super(OptionRegistry, self).register_lazy(key,
2372
module_name, member_name)
2374
def get_help(self, key=None):
2375
"""Get the help text associated with the given key"""
2376
option = self.get(key)
2377
the_help = option.help
2378
if callable(the_help):
2379
return the_help(self, key)
2383
option_registry = OptionRegistry()
2386
# Registered options in lexicographical order
2388
option_registry.register(
2389
Option('bzr.workingtree.worth_saving_limit', default=10,
2390
from_unicode=int_from_store, invalid='warning',
2392
How many changes before saving the dirstate.
2394
-1 means that we will never rewrite the dirstate file for only
2395
stat-cache changes. Regardless of this setting, we will always rewrite
2396
the dirstate file if a file is added/removed/renamed/etc. This flag only
2397
affects the behavior of updating the dirstate file after we notice that
2398
a file has been touched.
2400
option_registry.register(
2401
Option('dirstate.fdatasync', default=True,
2402
from_unicode=bool_from_store,
2404
Flush dirstate changes onto physical disk?
2406
If true (default), working tree metadata changes are flushed through the
2407
OS buffers to physical disk. This is somewhat slower, but means data
2408
should not be lost if the machine crashes. See also repository.fdatasync.
2410
option_registry.register(
2411
Option('debug_flags', default=[], from_unicode=list_from_store,
2412
help='Debug flags to activate.'))
2413
option_registry.register(
2414
Option('default_format', default='2a',
2415
help='Format used when creating branches.'))
2416
option_registry.register(
2418
help='The command called to launch an editor to enter a message.'))
2419
option_registry.register(
2420
Option('ignore_missing_extensions', default=False,
2421
from_unicode=bool_from_store,
2423
Control the missing extensions warning display.
2425
The warning will not be emitted if set to True.
2427
option_registry.register(
2429
help='Language to translate messages into.'))
2430
option_registry.register(
2431
Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2433
Steal locks that appears to be dead.
2435
If set to True, bzr will check if a lock is supposed to be held by an
2436
active process from the same user on the same machine. If the user and
2437
machine match, but no process with the given PID is active, then bzr
2438
will automatically break the stale lock, and create a new lock for
2440
Otherwise, bzr will prompt as normal to break the lock.
2442
option_registry.register(
2443
Option('output_encoding',
2444
help= 'Unicode encoding for output'
2445
' (terminal encoding if not specified).'))
2446
option_registry.register(
2447
Option('repository.fdatasync', default=True, from_unicode=bool_from_store,
2449
Flush repository changes onto physical disk?
2451
If true (default), repository changes are flushed through the OS buffers
2452
to physical disk. This is somewhat slower, but means data should not be
2453
lost if the machine crashes. See also dirstate.fdatasync.
2457
class Section(object):
2458
"""A section defines a dict of option name => value.
2460
This is merely a read-only dict which can add some knowledge about the
2461
options. It is *not* a python dict object though and doesn't try to mimic
2465
def __init__(self, section_id, options):
2466
self.id = section_id
2467
# We re-use the dict-like object received
2468
self.options = options
2470
def get(self, name, default=None):
2471
return self.options.get(name, default)
2474
# Mostly for debugging use
2475
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2478
_NewlyCreatedOption = object()
2479
"""Was the option created during the MutableSection lifetime"""
2482
class MutableSection(Section):
2483
"""A section allowing changes and keeping track of the original values."""
2485
def __init__(self, section_id, options):
2486
super(MutableSection, self).__init__(section_id, options)
2489
def set(self, name, value):
2490
if name not in self.options:
2491
# This is a new option
2492
self.orig[name] = _NewlyCreatedOption
2493
elif name not in self.orig:
2494
self.orig[name] = self.get(name, None)
2495
self.options[name] = value
2497
def remove(self, name):
2498
if name not in self.orig:
2499
self.orig[name] = self.get(name, None)
2500
del self.options[name]
2503
class Store(object):
2504
"""Abstract interface to persistent storage for configuration options."""
2506
readonly_section_class = Section
2507
mutable_section_class = MutableSection
2509
def is_loaded(self):
2510
"""Returns True if the Store has been loaded.
2512
This is used to implement lazy loading and ensure the persistent
2513
storage is queried only when needed.
2515
raise NotImplementedError(self.is_loaded)
2518
"""Loads the Store from persistent storage."""
2519
raise NotImplementedError(self.load)
2521
def _load_from_string(self, bytes):
2522
"""Create a store from a string in configobj syntax.
2524
:param bytes: A string representing the file content.
2526
raise NotImplementedError(self._load_from_string)
2529
"""Unloads the Store.
2531
This should make is_loaded() return False. This is used when the caller
2532
knows that the persistent storage has changed or may have change since
2535
raise NotImplementedError(self.unload)
2538
"""Saves the Store to persistent storage."""
2539
raise NotImplementedError(self.save)
2541
def external_url(self):
2542
raise NotImplementedError(self.external_url)
2544
def get_sections(self):
2545
"""Returns an ordered iterable of existing sections.
2547
:returns: An iterable of (name, dict).
2549
raise NotImplementedError(self.get_sections)
2551
def get_mutable_section(self, section_name=None):
2552
"""Returns the specified mutable section.
2554
:param section_name: The section identifier
2556
raise NotImplementedError(self.get_mutable_section)
2559
# Mostly for debugging use
2560
return "<config.%s(%s)>" % (self.__class__.__name__,
2561
self.external_url())
2564
class IniFileStore(Store):
2565
"""A config Store using ConfigObj for storage.
2567
:ivar transport: The transport object where the config file is located.
2569
:ivar file_name: The config file basename in the transport directory.
2571
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2572
serialize/deserialize the config file.
2575
def __init__(self, transport, file_name):
2576
"""A config Store using ConfigObj for storage.
2578
:param transport: The transport object where the config file is located.
2580
:param file_name: The config file basename in the transport directory.
2582
super(IniFileStore, self).__init__()
2583
self.transport = transport
2584
self.file_name = file_name
2585
self._config_obj = None
2587
def is_loaded(self):
2588
return self._config_obj != None
2591
self._config_obj = None
2594
"""Load the store from the associated file."""
2595
if self.is_loaded():
2597
content = self.transport.get_bytes(self.file_name)
2598
self._load_from_string(content)
2599
for hook in ConfigHooks['load']:
2602
def _load_from_string(self, bytes):
2603
"""Create a config store from a string.
2605
:param bytes: A string representing the file content.
2607
if self.is_loaded():
2608
raise AssertionError('Already loaded: %r' % (self._config_obj,))
2609
co_input = StringIO(bytes)
2611
# The config files are always stored utf8-encoded
2612
self._config_obj = ConfigObj(co_input, encoding='utf-8')
2613
except configobj.ConfigObjError, e:
2614
self._config_obj = None
2615
raise errors.ParseConfigError(e.errors, self.external_url())
2616
except UnicodeDecodeError:
2617
raise errors.ConfigContentError(self.external_url())
2620
if not self.is_loaded():
2624
self._config_obj.write(out)
2625
self.transport.put_bytes(self.file_name, out.getvalue())
2626
for hook in ConfigHooks['save']:
2629
def external_url(self):
2630
# FIXME: external_url should really accepts an optional relpath
2631
# parameter (bug #750169) :-/ -- vila 2011-04-04
2632
# The following will do in the interim but maybe we don't want to
2633
# expose a path here but rather a config ID and its associated
2634
# object </hand wawe>.
2635
return urlutils.join(self.transport.external_url(), self.file_name)
2637
def get_sections(self):
2638
"""Get the configobj section in the file order.
2640
:returns: An iterable of (name, dict).
2642
# We need a loaded store
2645
except errors.NoSuchFile:
2646
# If the file doesn't exist, there is no sections
2648
cobj = self._config_obj
2650
yield self.readonly_section_class(None, cobj)
2651
for section_name in cobj.sections:
2652
yield self.readonly_section_class(section_name, cobj[section_name])
2654
def get_mutable_section(self, section_name=None):
2655
# We need a loaded store
2658
except errors.NoSuchFile:
2659
# The file doesn't exist, let's pretend it was empty
2660
self._load_from_string('')
2661
if section_name is None:
2662
section = self._config_obj
2664
section = self._config_obj.setdefault(section_name, {})
2665
return self.mutable_section_class(section_name, section)
2668
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2669
# unlockable stores for use with objects that can already ensure the locking
2670
# (think branches). If different stores (not based on ConfigObj) are created,
2671
# they may face the same issue.
2674
class LockableIniFileStore(IniFileStore):
2675
"""A ConfigObjStore using locks on save to ensure store integrity."""
2677
def __init__(self, transport, file_name, lock_dir_name=None):
2678
"""A config Store using ConfigObj for storage.
2680
:param transport: The transport object where the config file is located.
2682
:param file_name: The config file basename in the transport directory.
2684
if lock_dir_name is None:
2685
lock_dir_name = 'lock'
2686
self.lock_dir_name = lock_dir_name
2687
super(LockableIniFileStore, self).__init__(transport, file_name)
2688
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2690
def lock_write(self, token=None):
2691
"""Takes a write lock in the directory containing the config file.
2693
If the directory doesn't exist it is created.
2695
# FIXME: This doesn't check the ownership of the created directories as
2696
# ensure_config_dir_exists does. It should if the transport is local
2697
# -- vila 2011-04-06
2698
self.transport.create_prefix()
2699
return self._lock.lock_write(token)
2704
def break_lock(self):
2705
self._lock.break_lock()
2709
# We need to be able to override the undecorated implementation
2710
self.save_without_locking()
2712
def save_without_locking(self):
2713
super(LockableIniFileStore, self).save()
2716
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2717
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2718
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
2720
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2721
# functions or a registry will make it easier and clearer for tests, focusing
2722
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2723
# on a poolie's remark)
2724
class GlobalStore(LockableIniFileStore):
2726
def __init__(self, possible_transports=None):
2727
t = transport.get_transport_from_path(
2728
config_dir(), possible_transports=possible_transports)
2729
super(GlobalStore, self).__init__(t, 'bazaar.conf')
2732
class LocationStore(LockableIniFileStore):
2734
def __init__(self, possible_transports=None):
2735
t = transport.get_transport_from_path(
2736
config_dir(), possible_transports=possible_transports)
2737
super(LocationStore, self).__init__(t, 'locations.conf')
2740
class BranchStore(IniFileStore):
2742
def __init__(self, branch):
2743
super(BranchStore, self).__init__(branch.control_transport,
2745
self.branch = branch
2747
def lock_write(self, token=None):
2748
return self.branch.lock_write(token)
2751
return self.branch.unlock()
2755
# We need to be able to override the undecorated implementation
2756
self.save_without_locking()
2758
def save_without_locking(self):
2759
super(BranchStore, self).save()
2762
class SectionMatcher(object):
2763
"""Select sections into a given Store.
2765
This intended to be used to postpone getting an iterable of sections from a
2769
def __init__(self, store):
2772
def get_sections(self):
2773
# This is where we require loading the store so we can see all defined
2775
sections = self.store.get_sections()
2776
# Walk the revisions in the order provided
2781
def match(self, secion):
2782
raise NotImplementedError(self.match)
2785
class LocationSection(Section):
2787
def __init__(self, section, length, extra_path):
2788
super(LocationSection, self).__init__(section.id, section.options)
2789
self.length = length
2790
self.extra_path = extra_path
2792
def get(self, name, default=None):
2793
value = super(LocationSection, self).get(name, default)
2794
if value is not None:
2795
policy_name = self.get(name + ':policy', None)
2796
policy = _policy_value.get(policy_name, POLICY_NONE)
2797
if policy == POLICY_APPENDPATH:
2798
value = urlutils.join(value, self.extra_path)
2802
class LocationMatcher(SectionMatcher):
2804
def __init__(self, store, location):
2805
super(LocationMatcher, self).__init__(store)
2806
if location.startswith('file://'):
2807
location = urlutils.local_path_from_url(location)
2808
self.location = location
2810
def _get_matching_sections(self):
2811
"""Get all sections matching ``location``."""
2812
# We slightly diverge from LocalConfig here by allowing the no-name
2813
# section as the most generic one and the lower priority.
2814
no_name_section = None
2816
# Filter out the no_name_section so _iter_for_location_by_parts can be
2817
# used (it assumes all sections have a name).
2818
for section in self.store.get_sections():
2819
if section.id is None:
2820
no_name_section = section
2822
sections.append(section)
2823
# Unfortunately _iter_for_location_by_parts deals with section names so
2824
# we have to resync.
2825
filtered_sections = _iter_for_location_by_parts(
2826
[s.id for s in sections], self.location)
2827
iter_sections = iter(sections)
2828
matching_sections = []
2829
if no_name_section is not None:
2830
matching_sections.append(
2831
LocationSection(no_name_section, 0, self.location))
2832
for section_id, extra_path, length in filtered_sections:
2833
# a section id is unique for a given store so it's safe to iterate
2835
section = iter_sections.next()
2836
if section_id == section.id:
2837
matching_sections.append(
2838
LocationSection(section, length, extra_path))
2839
return matching_sections
2841
def get_sections(self):
2842
# Override the default implementation as we want to change the order
2843
matching_sections = self._get_matching_sections()
2844
# We want the longest (aka more specific) locations first
2845
sections = sorted(matching_sections,
2846
key=lambda section: (section.length, section.id),
2848
# Sections mentioning 'ignore_parents' restrict the selection
2849
for section in sections:
2850
# FIXME: We really want to use as_bool below -- vila 2011-04-07
2851
ignore = section.get('ignore_parents', None)
2852
if ignore is not None:
2853
ignore = ui.bool_from_string(ignore)
2856
# Finally, we have a valid section
2860
class Stack(object):
2861
"""A stack of configurations where an option can be defined"""
2863
def __init__(self, sections_def, store=None, mutable_section_name=None):
2864
"""Creates a stack of sections with an optional store for changes.
2866
:param sections_def: A list of Section or callables that returns an
2867
iterable of Section. This defines the Sections for the Stack and
2868
can be called repeatedly if needed.
2870
:param store: The optional Store where modifications will be
2871
recorded. If none is specified, no modifications can be done.
2873
:param mutable_section_name: The name of the MutableSection where
2874
changes are recorded. This requires the ``store`` parameter to be
2877
self.sections_def = sections_def
2879
self.mutable_section_name = mutable_section_name
2881
def get(self, name):
2882
"""Return the *first* option value found in the sections.
2884
This is where we guarantee that sections coming from Store are loaded
2885
lazily: the loading is delayed until we need to either check that an
2886
option exists or get its value, which in turn may require to discover
2887
in which sections it can be defined. Both of these (section and option
2888
existence) require loading the store (even partially).
2890
# FIXME: No caching of options nor sections yet -- vila 20110503
2892
# Ensuring lazy loading is achieved by delaying section matching (which
2893
# implies querying the persistent storage) until it can't be avoided
2894
# anymore by using callables to describe (possibly empty) section
2896
for section_or_callable in self.sections_def:
2897
# Each section can expand to multiple ones when a callable is used
2898
if callable(section_or_callable):
2899
sections = section_or_callable()
2901
sections = [section_or_callable]
2902
for section in sections:
2903
value = section.get(name)
2904
if value is not None:
2906
if value is not None:
2908
# If the option is registered, it may provide additional info about
2911
opt = option_registry.get(name)
2915
if (opt is not None and opt.from_unicode is not None
2916
and value is not None):
2917
# If a value exists and the option provides a converter, use it
2919
converted = opt.from_unicode(value)
2920
except (ValueError, TypeError):
2921
# Invalid values are ignored
2923
if converted is None and opt.invalid is not None:
2924
# The conversion failed
2925
if opt.invalid == 'warning':
2926
trace.warning('Value "%s" is not valid for "%s"',
2928
elif opt.invalid == 'error':
2929
raise errors.ConfigOptionValueError(name, value)
2932
# If the option is registered, it may provide a default value
2934
value = opt.get_default()
2935
for hook in ConfigHooks['get']:
2936
hook(self, name, value)
2939
def _get_mutable_section(self):
2940
"""Get the MutableSection for the Stack.
2942
This is where we guarantee that the mutable section is lazily loaded:
2943
this means we won't load the corresponding store before setting a value
2944
or deleting an option. In practice the store will often be loaded but
2945
this allows helps catching some programming errors.
2947
section = self.store.get_mutable_section(self.mutable_section_name)
2950
def set(self, name, value):
2951
"""Set a new value for the option."""
2952
section = self._get_mutable_section()
2953
section.set(name, value)
2954
for hook in ConfigHooks['set']:
2955
hook(self, name, value)
2957
def remove(self, name):
2958
"""Remove an existing option."""
2959
section = self._get_mutable_section()
2960
section.remove(name)
2961
for hook in ConfigHooks['remove']:
2965
# Mostly for debugging use
2966
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2969
class _CompatibleStack(Stack):
2970
"""Place holder for compatibility with previous design.
2972
This is intended to ease the transition from the Config-based design to the
2973
Stack-based design and should not be used nor relied upon by plugins.
2975
One assumption made here is that the daughter classes will all use Stores
2976
derived from LockableIniFileStore).
2978
It implements set() by re-loading the store before applying the
2979
modification and saving it.
2981
The long term plan being to implement a single write by store to save
2982
all modifications, this class should not be used in the interim.
2985
def set(self, name, value):
2988
super(_CompatibleStack, self).set(name, value)
2989
# Force a write to persistent storage
2993
class GlobalStack(_CompatibleStack):
2997
gstore = GlobalStore()
2998
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
3001
class LocationStack(_CompatibleStack):
3003
def __init__(self, location):
3004
"""Make a new stack for a location and global configuration.
3006
:param location: A URL prefix to """
3007
lstore = LocationStore()
3008
matcher = LocationMatcher(lstore, location)
3009
gstore = GlobalStore()
3010
super(LocationStack, self).__init__(
3011
[matcher.get_sections, gstore.get_sections], lstore)
3013
class BranchStack(_CompatibleStack):
3015
def __init__(self, branch):
3016
bstore = BranchStore(branch)
3017
lstore = LocationStore()
3018
matcher = LocationMatcher(lstore, branch.base)
3019
gstore = GlobalStore()
3020
super(BranchStack, self).__init__(
3021
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
3023
self.branch = branch
3026
class cmd_config(commands.Command):
3027
__doc__ = """Display, set or remove a configuration option.
3029
Display the active value for a given option.
3031
If --all is specified, NAME is interpreted as a regular expression and all
3032
matching options are displayed mentioning their scope. The active value
3033
that bzr will take into account is the first one displayed for each option.
3035
If no NAME is given, --all .* is implied.
3037
Setting a value is achieved by using name=value without spaces. The value
3038
is set in the most relevant scope and can be checked by displaying the
3042
takes_args = ['name?']
3046
# FIXME: This should be a registry option so that plugins can register
3047
# their own config files (or not) -- vila 20101002
3048
commands.Option('scope', help='Reduce the scope to the specified'
3049
' configuration file',
3051
commands.Option('all',
3052
help='Display all the defined values for the matching options.',
3054
commands.Option('remove', help='Remove the option from'
3055
' the configuration file'),
3058
_see_also = ['configuration']
3060
@commands.display_command
3061
def run(self, name=None, all=False, directory=None, scope=None,
3063
if directory is None:
3065
directory = urlutils.normalize_url(directory)
3067
raise errors.BzrError(
3068
'--all and --remove are mutually exclusive.')
3070
# Delete the option in the given scope
3071
self._remove_config_option(name, directory, scope)
3073
# Defaults to all options
3074
self._show_matching_options('.*', directory, scope)
3077
name, value = name.split('=', 1)
3079
# Display the option(s) value(s)
3081
self._show_matching_options(name, directory, scope)
3083
self._show_value(name, directory, scope)
3086
raise errors.BzrError(
3087
'Only one option can be set.')
3088
# Set the option value
3089
self._set_config_option(name, value, directory, scope)
3091
def _get_configs(self, directory, scope=None):
3092
"""Iterate the configurations specified by ``directory`` and ``scope``.
3094
:param directory: Where the configurations are derived from.
3096
:param scope: A specific config to start from.
3098
if scope is not None:
3099
if scope == 'bazaar':
3100
yield GlobalConfig()
3101
elif scope == 'locations':
3102
yield LocationConfig(directory)
3103
elif scope == 'branch':
3104
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3106
yield br.get_config()
3109
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3111
yield br.get_config()
3112
except errors.NotBranchError:
3113
yield LocationConfig(directory)
3114
yield GlobalConfig()
3116
def _show_value(self, name, directory, scope):
3118
for c in self._get_configs(directory, scope):
3121
for (oname, value, section, conf_id, parser) in c._get_options():
3123
# Display only the first value and exit
3125
# FIXME: We need to use get_user_option to take policies
3126
# into account and we need to make sure the option exists
3127
# too (hence the two for loops), this needs a better API
3129
value = c.get_user_option(name)
3130
# Quote the value appropriately
3131
value = parser._quote(value)
3132
self.outf.write('%s\n' % (value,))
3136
raise errors.NoSuchConfigOption(name)
3138
def _show_matching_options(self, name, directory, scope):
3139
name = lazy_regex.lazy_compile(name)
3140
# We want any error in the regexp to be raised *now* so we need to
3141
# avoid the delay introduced by the lazy regexp. But, we still do
3142
# want the nicer errors raised by lazy_regex.
3143
name._compile_and_collapse()
3146
for c in self._get_configs(directory, scope):
3147
for (oname, value, section, conf_id, parser) in c._get_options():
3148
if name.search(oname):
3149
if cur_conf_id != conf_id:
3150
# Explain where the options are defined
3151
self.outf.write('%s:\n' % (conf_id,))
3152
cur_conf_id = conf_id
3154
if (section not in (None, 'DEFAULT')
3155
and cur_section != section):
3156
# Display the section if it's not the default (or only)
3158
self.outf.write(' [%s]\n' % (section,))
3159
cur_section = section
3160
self.outf.write(' %s = %s\n' % (oname, value))
3162
def _set_config_option(self, name, value, directory, scope):
3163
for conf in self._get_configs(directory, scope):
3164
conf.set_user_option(name, value)
3167
raise errors.NoSuchConfig(scope)
3169
def _remove_config_option(self, name, directory, scope):
3171
raise errors.BzrCommandError(
3172
'--remove expects an option to remove.')
3174
for conf in self._get_configs(directory, scope):
3175
for (section_name, section, conf_id) in conf._get_sections():
3176
if scope is not None and conf_id != scope:
3177
# Not the right configuration file
3180
if conf_id != conf.config_id():
3181
conf = self._get_configs(directory, conf_id).next()
3182
# We use the first section in the first config where the
3183
# option is defined to remove it
3184
conf.remove_user_option(name, section_name)
3189
raise errors.NoSuchConfig(scope)
3191
raise errors.NoSuchConfigOption(name)
3195
# We need adapters that can build a Store or a Stack in a test context. Test
3196
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3197
# themselves. The builder will receive a test instance and should return a
3198
# ready-to-use store or stack. Plugins that define new store/stacks can also
3199
# register themselves here to be tested against the tests defined in
3200
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3201
# for the same tests.
3203
# The registered object should be a callable receiving a test instance
3204
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3206
test_store_builder_registry = registry.Registry()
3208
# The registered object should be a callable receiving a test instance
3209
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3211
test_stack_builder_registry = registry.Registry()