1508
2218
configobj[name] = value
1510
2220
configobj.setdefault(section, {})[name] = value
2221
for hook in OldConfigHooks['set']:
2222
hook(self, name, value)
2223
self._set_configobj(configobj)
2225
def remove_option(self, option_name, section_name=None):
2226
configobj = self._get_configobj()
2227
if section_name is None:
2228
del configobj[option_name]
2230
del configobj[section_name][option_name]
2231
for hook in OldConfigHooks['remove']:
2232
hook(self, option_name)
1511
2233
self._set_configobj(configobj)
1513
2235
def _get_config_file(self):
1515
return StringIO(self._transport.get_bytes(self._filename))
2237
f = StringIO(self._transport.get_bytes(self._filename))
2238
for hook in OldConfigHooks['load']:
1516
2241
except errors.NoSuchFile:
1517
2242
return StringIO()
2244
def _external_url(self):
2245
return urlutils.join(self._transport.external_url(), self._filename)
1519
2247
def _get_configobj(self):
1520
return ConfigObj(self._get_config_file(), encoding='utf-8')
2248
f = self._get_config_file()
2251
conf = ConfigObj(f, encoding='utf-8')
2252
except configobj.ConfigObjError, e:
2253
raise errors.ParseConfigError(e.errors, self._external_url())
2254
except UnicodeDecodeError:
2255
raise errors.ConfigContentError(self._external_url())
1522
2260
def _set_configobj(self, configobj):
1523
2261
out_file = StringIO()
1524
2262
configobj.write(out_file)
1525
2263
out_file.seek(0)
1526
2264
self._transport.put_file(self._filename, out_file)
2265
for hook in OldConfigHooks['save']:
2269
class Option(object):
2270
"""An option definition.
2272
The option *values* are stored in config files and found in sections.
2274
Here we define various properties about the option itself, its default
2275
value, how to convert it from stores, what to do when invalid values are
2276
encoutered, in which config files it can be stored.
2279
def __init__(self, name, default=None, help=None, from_unicode=None,
2281
"""Build an option definition.
2283
:param name: the name used to refer to the option.
2285
:param default: the default value to use when none exist in the config
2288
:param help: a doc string to explain the option to the user.
2290
:param from_unicode: a callable to convert the unicode string
2291
representing the option value in a store. This is not called for
2294
:param invalid: the action to be taken when an invalid value is
2295
encountered in a store. This is called only when from_unicode is
2296
invoked to convert a string and returns None or raise ValueError or
2297
TypeError. Accepted values are: None (ignore invalid values),
2298
'warning' (emit a warning), 'error' (emit an error message and
2302
self.default = default
2304
self.from_unicode = from_unicode
2305
if invalid and invalid not in ('warning', 'error'):
2306
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2307
self.invalid = invalid
2309
def get_default(self):
2312
# Predefined converters to get proper values from store
2314
def bool_from_store(unicode_str):
2315
return ui.bool_from_string(unicode_str)
2318
def int_from_store(unicode_str):
2319
return int(unicode_str)
2322
def list_from_store(unicode_str):
2323
# ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
2324
if isinstance(unicode_str, (str, unicode)):
2326
# A single value, most probably the user forgot (or didn't care to
2327
# add) the final ','
2330
# The empty string, convert to empty list
2333
# We rely on ConfigObj providing us with a list already
2338
class OptionRegistry(registry.Registry):
2339
"""Register config options by their name.
2341
This overrides ``registry.Registry`` to simplify registration by acquiring
2342
some information from the option object itself.
2345
def register(self, option):
2346
"""Register a new option to its name.
2348
:param option: The option to register. Its name is used as the key.
2350
super(OptionRegistry, self).register(option.name, option,
2353
def register_lazy(self, key, module_name, member_name):
2354
"""Register a new option to be loaded on request.
2356
:param key: This is the key to use to request the option later. Since
2357
the registration is lazy, it should be provided and match the
2360
:param module_name: The python path to the module. Such as 'os.path'.
2362
:param member_name: The member of the module to return. If empty or
2363
None, get() will return the module itself.
2365
super(OptionRegistry, self).register_lazy(key,
2366
module_name, member_name)
2368
def get_help(self, key=None):
2369
"""Get the help text associated with the given key"""
2370
option = self.get(key)
2371
the_help = option.help
2372
if callable(the_help):
2373
return the_help(self, key)
2377
option_registry = OptionRegistry()
2380
# Registered options in lexicographical order
2382
option_registry.register(
2383
Option('bzr.workingtree.worth_saving_limit', default=10,
2384
from_unicode=int_from_store, invalid='warning',
2386
How many changes before saving the dirstate.
2388
-1 means never save.
2390
option_registry.register(
2391
Option('dirstate.fdatasync', default=True,
2392
from_unicode=bool_from_store,
2394
Flush dirstate changes onto physical disk?
2396
If true (default), working tree metadata changes are flushed through the
2397
OS buffers to physical disk. This is somewhat slower, but means data
2398
should not be lost if the machine crashes. See also repository.fdatasync.
2400
option_registry.register(
2401
Option('default_format', default='2a',
2402
help='Format used when creating branches.'))
2403
option_registry.register(
2405
help='The command called to launch an editor to enter a message.'))
2406
option_registry.register(
2407
Option('ignore_missing_extensions', default=False,
2408
from_unicode=bool_from_store,
2410
Control the missing extensions warning display.
2412
The warning will not be emitted if set to True.
2414
option_registry.register(
2416
help='Language to translate messages into.'))
2417
option_registry.register(
2418
Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2420
Steal locks that appears to be dead.
2422
If set to true, bzr will automatically break locks held by processes from
2423
the same machine and user that are no longer alive. Otherwise, it will
2424
print a message and you can break the lock manually, if you are satisfied
2425
the object is no longer in use.
2427
option_registry.register(
2428
Option('output_encoding',
2429
help= 'Unicode encoding for output'
2430
' (terminal encoding if not specified).'))
2431
option_registry.register(
2432
Option('repository.fdatasync', default=True, from_unicode=bool_from_store,
2434
Flush repository changes onto physical disk?
2436
If true (default), repository changes are flushed through the OS buffers
2437
to physical disk. This is somewhat slower, but means data should not be
2438
lost if the machine crashes. See also dirstate.fdatasync.
2442
class Section(object):
2443
"""A section defines a dict of option name => value.
2445
This is merely a read-only dict which can add some knowledge about the
2446
options. It is *not* a python dict object though and doesn't try to mimic
2450
def __init__(self, section_id, options):
2451
self.id = section_id
2452
# We re-use the dict-like object received
2453
self.options = options
2455
def get(self, name, default=None):
2456
return self.options.get(name, default)
2459
# Mostly for debugging use
2460
return "<config.%s id=%s>" % (self.__class__.__name__, self.id)
2463
_NewlyCreatedOption = object()
2464
"""Was the option created during the MutableSection lifetime"""
2467
class MutableSection(Section):
2468
"""A section allowing changes and keeping track of the original values."""
2470
def __init__(self, section_id, options):
2471
super(MutableSection, self).__init__(section_id, options)
2474
def set(self, name, value):
2475
if name not in self.options:
2476
# This is a new option
2477
self.orig[name] = _NewlyCreatedOption
2478
elif name not in self.orig:
2479
self.orig[name] = self.get(name, None)
2480
self.options[name] = value
2482
def remove(self, name):
2483
if name not in self.orig:
2484
self.orig[name] = self.get(name, None)
2485
del self.options[name]
2488
class Store(object):
2489
"""Abstract interface to persistent storage for configuration options."""
2491
readonly_section_class = Section
2492
mutable_section_class = MutableSection
2494
def is_loaded(self):
2495
"""Returns True if the Store has been loaded.
2497
This is used to implement lazy loading and ensure the persistent
2498
storage is queried only when needed.
2500
raise NotImplementedError(self.is_loaded)
2503
"""Loads the Store from persistent storage."""
2504
raise NotImplementedError(self.load)
2506
def _load_from_string(self, bytes):
2507
"""Create a store from a string in configobj syntax.
2509
:param bytes: A string representing the file content.
2511
raise NotImplementedError(self._load_from_string)
2514
"""Unloads the Store.
2516
This should make is_loaded() return False. This is used when the caller
2517
knows that the persistent storage has changed or may have change since
2520
raise NotImplementedError(self.unload)
2523
"""Saves the Store to persistent storage."""
2524
raise NotImplementedError(self.save)
2526
def external_url(self):
2527
raise NotImplementedError(self.external_url)
2529
def get_sections(self):
2530
"""Returns an ordered iterable of existing sections.
2532
:returns: An iterable of (name, dict).
2534
raise NotImplementedError(self.get_sections)
2536
def get_mutable_section(self, section_name=None):
2537
"""Returns the specified mutable section.
2539
:param section_name: The section identifier
2541
raise NotImplementedError(self.get_mutable_section)
2544
# Mostly for debugging use
2545
return "<config.%s(%s)>" % (self.__class__.__name__,
2546
self.external_url())
2549
class IniFileStore(Store):
2550
"""A config Store using ConfigObj for storage.
2552
:ivar transport: The transport object where the config file is located.
2554
:ivar file_name: The config file basename in the transport directory.
2556
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2557
serialize/deserialize the config file.
2560
def __init__(self, transport, file_name):
2561
"""A config Store using ConfigObj for storage.
2563
:param transport: The transport object where the config file is located.
2565
:param file_name: The config file basename in the transport directory.
2567
super(IniFileStore, self).__init__()
2568
self.transport = transport
2569
self.file_name = file_name
2570
self._config_obj = None
2572
def is_loaded(self):
2573
return self._config_obj != None
2576
self._config_obj = None
2579
"""Load the store from the associated file."""
2580
if self.is_loaded():
2582
content = self.transport.get_bytes(self.file_name)
2583
self._load_from_string(content)
2584
for hook in ConfigHooks['load']:
2587
def _load_from_string(self, bytes):
2588
"""Create a config store from a string.
2590
:param bytes: A string representing the file content.
2592
if self.is_loaded():
2593
raise AssertionError('Already loaded: %r' % (self._config_obj,))
2594
co_input = StringIO(bytes)
2596
# The config files are always stored utf8-encoded
2597
self._config_obj = ConfigObj(co_input, encoding='utf-8')
2598
except configobj.ConfigObjError, e:
2599
self._config_obj = None
2600
raise errors.ParseConfigError(e.errors, self.external_url())
2601
except UnicodeDecodeError:
2602
raise errors.ConfigContentError(self.external_url())
2605
if not self.is_loaded():
2609
self._config_obj.write(out)
2610
self.transport.put_bytes(self.file_name, out.getvalue())
2611
for hook in ConfigHooks['save']:
2614
def external_url(self):
2615
# FIXME: external_url should really accepts an optional relpath
2616
# parameter (bug #750169) :-/ -- vila 2011-04-04
2617
# The following will do in the interim but maybe we don't want to
2618
# expose a path here but rather a config ID and its associated
2619
# object </hand wawe>.
2620
return urlutils.join(self.transport.external_url(), self.file_name)
2622
def get_sections(self):
2623
"""Get the configobj section in the file order.
2625
:returns: An iterable of (name, dict).
2627
# We need a loaded store
2630
except errors.NoSuchFile:
2631
# If the file doesn't exist, there is no sections
2633
cobj = self._config_obj
2635
yield self.readonly_section_class(None, cobj)
2636
for section_name in cobj.sections:
2637
yield self.readonly_section_class(section_name, cobj[section_name])
2639
def get_mutable_section(self, section_name=None):
2640
# We need a loaded store
2643
except errors.NoSuchFile:
2644
# The file doesn't exist, let's pretend it was empty
2645
self._load_from_string('')
2646
if section_name is None:
2647
section = self._config_obj
2649
section = self._config_obj.setdefault(section_name, {})
2650
return self.mutable_section_class(section_name, section)
2653
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2654
# unlockable stores for use with objects that can already ensure the locking
2655
# (think branches). If different stores (not based on ConfigObj) are created,
2656
# they may face the same issue.
2659
class LockableIniFileStore(IniFileStore):
2660
"""A ConfigObjStore using locks on save to ensure store integrity."""
2662
def __init__(self, transport, file_name, lock_dir_name=None):
2663
"""A config Store using ConfigObj for storage.
2665
:param transport: The transport object where the config file is located.
2667
:param file_name: The config file basename in the transport directory.
2669
if lock_dir_name is None:
2670
lock_dir_name = 'lock'
2671
self.lock_dir_name = lock_dir_name
2672
super(LockableIniFileStore, self).__init__(transport, file_name)
2673
self._lock = lockdir.LockDir(self.transport, self.lock_dir_name)
2675
def lock_write(self, token=None):
2676
"""Takes a write lock in the directory containing the config file.
2678
If the directory doesn't exist it is created.
2680
# FIXME: This doesn't check the ownership of the created directories as
2681
# ensure_config_dir_exists does. It should if the transport is local
2682
# -- vila 2011-04-06
2683
self.transport.create_prefix()
2684
return self._lock.lock_write(token)
2689
def break_lock(self):
2690
self._lock.break_lock()
2694
# We need to be able to override the undecorated implementation
2695
self.save_without_locking()
2697
def save_without_locking(self):
2698
super(LockableIniFileStore, self).save()
2701
# FIXME: global, bazaar, shouldn't that be 'user' instead or even
2702
# 'user_defaults' as opposed to 'user_overrides', 'system_defaults'
2703
# (/etc/bzr/bazaar.conf) and 'system_overrides' ? -- vila 2011-04-05
2705
# FIXME: Moreover, we shouldn't need classes for these stores either, factory
2706
# functions or a registry will make it easier and clearer for tests, focusing
2707
# on the relevant parts of the API that needs testing -- vila 20110503 (based
2708
# on a poolie's remark)
2709
class GlobalStore(LockableIniFileStore):
2711
def __init__(self, possible_transports=None):
2712
t = transport.get_transport_from_path(
2713
config_dir(), possible_transports=possible_transports)
2714
super(GlobalStore, self).__init__(t, 'bazaar.conf')
2717
class LocationStore(LockableIniFileStore):
2719
def __init__(self, possible_transports=None):
2720
t = transport.get_transport_from_path(
2721
config_dir(), possible_transports=possible_transports)
2722
super(LocationStore, self).__init__(t, 'locations.conf')
2725
class BranchStore(IniFileStore):
2727
def __init__(self, branch):
2728
super(BranchStore, self).__init__(branch.control_transport,
2730
self.branch = branch
2732
def lock_write(self, token=None):
2733
return self.branch.lock_write(token)
2736
return self.branch.unlock()
2740
# We need to be able to override the undecorated implementation
2741
self.save_without_locking()
2743
def save_without_locking(self):
2744
super(BranchStore, self).save()
2747
class SectionMatcher(object):
2748
"""Select sections into a given Store.
2750
This intended to be used to postpone getting an iterable of sections from a
2754
def __init__(self, store):
2757
def get_sections(self):
2758
# This is where we require loading the store so we can see all defined
2760
sections = self.store.get_sections()
2761
# Walk the revisions in the order provided
2766
def match(self, secion):
2767
raise NotImplementedError(self.match)
2770
class LocationSection(Section):
2772
def __init__(self, section, length, extra_path):
2773
super(LocationSection, self).__init__(section.id, section.options)
2774
self.length = length
2775
self.extra_path = extra_path
2777
def get(self, name, default=None):
2778
value = super(LocationSection, self).get(name, default)
2779
if value is not None:
2780
policy_name = self.get(name + ':policy', None)
2781
policy = _policy_value.get(policy_name, POLICY_NONE)
2782
if policy == POLICY_APPENDPATH:
2783
value = urlutils.join(value, self.extra_path)
2787
class LocationMatcher(SectionMatcher):
2789
def __init__(self, store, location):
2790
super(LocationMatcher, self).__init__(store)
2791
if location.startswith('file://'):
2792
location = urlutils.local_path_from_url(location)
2793
self.location = location
2795
def _get_matching_sections(self):
2796
"""Get all sections matching ``location``."""
2797
# We slightly diverge from LocalConfig here by allowing the no-name
2798
# section as the most generic one and the lower priority.
2799
no_name_section = None
2801
# Filter out the no_name_section so _iter_for_location_by_parts can be
2802
# used (it assumes all sections have a name).
2803
for section in self.store.get_sections():
2804
if section.id is None:
2805
no_name_section = section
2807
sections.append(section)
2808
# Unfortunately _iter_for_location_by_parts deals with section names so
2809
# we have to resync.
2810
filtered_sections = _iter_for_location_by_parts(
2811
[s.id for s in sections], self.location)
2812
iter_sections = iter(sections)
2813
matching_sections = []
2814
if no_name_section is not None:
2815
matching_sections.append(
2816
LocationSection(no_name_section, 0, self.location))
2817
for section_id, extra_path, length in filtered_sections:
2818
# a section id is unique for a given store so it's safe to iterate
2820
section = iter_sections.next()
2821
if section_id == section.id:
2822
matching_sections.append(
2823
LocationSection(section, length, extra_path))
2824
return matching_sections
2826
def get_sections(self):
2827
# Override the default implementation as we want to change the order
2828
matching_sections = self._get_matching_sections()
2829
# We want the longest (aka more specific) locations first
2830
sections = sorted(matching_sections,
2831
key=lambda section: (section.length, section.id),
2833
# Sections mentioning 'ignore_parents' restrict the selection
2834
for section in sections:
2835
# FIXME: We really want to use as_bool below -- vila 2011-04-07
2836
ignore = section.get('ignore_parents', None)
2837
if ignore is not None:
2838
ignore = ui.bool_from_string(ignore)
2841
# Finally, we have a valid section
2845
class Stack(object):
2846
"""A stack of configurations where an option can be defined"""
2848
def __init__(self, sections_def, store=None, mutable_section_name=None):
2849
"""Creates a stack of sections with an optional store for changes.
2851
:param sections_def: A list of Section or callables that returns an
2852
iterable of Section. This defines the Sections for the Stack and
2853
can be called repeatedly if needed.
2855
:param store: The optional Store where modifications will be
2856
recorded. If none is specified, no modifications can be done.
2858
:param mutable_section_name: The name of the MutableSection where
2859
changes are recorded. This requires the ``store`` parameter to be
2862
self.sections_def = sections_def
2864
self.mutable_section_name = mutable_section_name
2866
def get(self, name):
2867
"""Return the *first* option value found in the sections.
2869
This is where we guarantee that sections coming from Store are loaded
2870
lazily: the loading is delayed until we need to either check that an
2871
option exists or get its value, which in turn may require to discover
2872
in which sections it can be defined. Both of these (section and option
2873
existence) require loading the store (even partially).
2875
# FIXME: No caching of options nor sections yet -- vila 20110503
2877
# Ensuring lazy loading is achieved by delaying section matching (which
2878
# implies querying the persistent storage) until it can't be avoided
2879
# anymore by using callables to describe (possibly empty) section
2881
for section_or_callable in self.sections_def:
2882
# Each section can expand to multiple ones when a callable is used
2883
if callable(section_or_callable):
2884
sections = section_or_callable()
2886
sections = [section_or_callable]
2887
for section in sections:
2888
value = section.get(name)
2889
if value is not None:
2891
if value is not None:
2893
# If the option is registered, it may provide additional info about
2896
opt = option_registry.get(name)
2900
if (opt is not None and opt.from_unicode is not None
2901
and value is not None):
2902
# If a value exists and the option provides a converter, use it
2904
converted = opt.from_unicode(value)
2905
except (ValueError, TypeError):
2906
# Invalid values are ignored
2908
if converted is None and opt.invalid is not None:
2909
# The conversion failed
2910
if opt.invalid == 'warning':
2911
trace.warning('Value "%s" is not valid for "%s"',
2913
elif opt.invalid == 'error':
2914
raise errors.ConfigOptionValueError(name, value)
2917
# If the option is registered, it may provide a default value
2919
value = opt.get_default()
2920
for hook in ConfigHooks['get']:
2921
hook(self, name, value)
2924
def _get_mutable_section(self):
2925
"""Get the MutableSection for the Stack.
2927
This is where we guarantee that the mutable section is lazily loaded:
2928
this means we won't load the corresponding store before setting a value
2929
or deleting an option. In practice the store will often be loaded but
2930
this allows helps catching some programming errors.
2932
section = self.store.get_mutable_section(self.mutable_section_name)
2935
def set(self, name, value):
2936
"""Set a new value for the option."""
2937
section = self._get_mutable_section()
2938
section.set(name, value)
2939
for hook in ConfigHooks['set']:
2940
hook(self, name, value)
2942
def remove(self, name):
2943
"""Remove an existing option."""
2944
section = self._get_mutable_section()
2945
section.remove(name)
2946
for hook in ConfigHooks['remove']:
2950
# Mostly for debugging use
2951
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
2954
class _CompatibleStack(Stack):
2955
"""Place holder for compatibility with previous design.
2957
This is intended to ease the transition from the Config-based design to the
2958
Stack-based design and should not be used nor relied upon by plugins.
2960
One assumption made here is that the daughter classes will all use Stores
2961
derived from LockableIniFileStore).
2963
It implements set() by re-loading the store before applying the
2964
modification and saving it.
2966
The long term plan being to implement a single write by store to save
2967
all modifications, this class should not be used in the interim.
2970
def set(self, name, value):
2973
super(_CompatibleStack, self).set(name, value)
2974
# Force a write to persistent storage
2978
class GlobalStack(_CompatibleStack):
2982
gstore = GlobalStore()
2983
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
2986
class LocationStack(_CompatibleStack):
2988
def __init__(self, location):
2989
"""Make a new stack for a location and global configuration.
2991
:param location: A URL prefix to """
2992
lstore = LocationStore()
2993
matcher = LocationMatcher(lstore, location)
2994
gstore = GlobalStore()
2995
super(LocationStack, self).__init__(
2996
[matcher.get_sections, gstore.get_sections], lstore)
2998
class BranchStack(_CompatibleStack):
3000
def __init__(self, branch):
3001
bstore = BranchStore(branch)
3002
lstore = LocationStore()
3003
matcher = LocationMatcher(lstore, branch.base)
3004
gstore = GlobalStore()
3005
super(BranchStack, self).__init__(
3006
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
3008
self.branch = branch
3011
class cmd_config(commands.Command):
3012
__doc__ = """Display, set or remove a configuration option.
3014
Display the active value for a given option.
3016
If --all is specified, NAME is interpreted as a regular expression and all
3017
matching options are displayed mentioning their scope. The active value
3018
that bzr will take into account is the first one displayed for each option.
3020
If no NAME is given, --all .* is implied.
3022
Setting a value is achieved by using name=value without spaces. The value
3023
is set in the most relevant scope and can be checked by displaying the
3027
takes_args = ['name?']
3031
# FIXME: This should be a registry option so that plugins can register
3032
# their own config files (or not) -- vila 20101002
3033
commands.Option('scope', help='Reduce the scope to the specified'
3034
' configuration file',
3036
commands.Option('all',
3037
help='Display all the defined values for the matching options.',
3039
commands.Option('remove', help='Remove the option from'
3040
' the configuration file'),
3043
_see_also = ['configuration']
3045
@commands.display_command
3046
def run(self, name=None, all=False, directory=None, scope=None,
3048
if directory is None:
3050
directory = urlutils.normalize_url(directory)
3052
raise errors.BzrError(
3053
'--all and --remove are mutually exclusive.')
3055
# Delete the option in the given scope
3056
self._remove_config_option(name, directory, scope)
3058
# Defaults to all options
3059
self._show_matching_options('.*', directory, scope)
3062
name, value = name.split('=', 1)
3064
# Display the option(s) value(s)
3066
self._show_matching_options(name, directory, scope)
3068
self._show_value(name, directory, scope)
3071
raise errors.BzrError(
3072
'Only one option can be set.')
3073
# Set the option value
3074
self._set_config_option(name, value, directory, scope)
3076
def _get_configs(self, directory, scope=None):
3077
"""Iterate the configurations specified by ``directory`` and ``scope``.
3079
:param directory: Where the configurations are derived from.
3081
:param scope: A specific config to start from.
3083
if scope is not None:
3084
if scope == 'bazaar':
3085
yield GlobalConfig()
3086
elif scope == 'locations':
3087
yield LocationConfig(directory)
3088
elif scope == 'branch':
3089
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3091
yield br.get_config()
3094
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3096
yield br.get_config()
3097
except errors.NotBranchError:
3098
yield LocationConfig(directory)
3099
yield GlobalConfig()
3101
def _show_value(self, name, directory, scope):
3103
for c in self._get_configs(directory, scope):
3106
for (oname, value, section, conf_id, parser) in c._get_options():
3108
# Display only the first value and exit
3110
# FIXME: We need to use get_user_option to take policies
3111
# into account and we need to make sure the option exists
3112
# too (hence the two for loops), this needs a better API
3114
value = c.get_user_option(name)
3115
# Quote the value appropriately
3116
value = parser._quote(value)
3117
self.outf.write('%s\n' % (value,))
3121
raise errors.NoSuchConfigOption(name)
3123
def _show_matching_options(self, name, directory, scope):
3124
name = lazy_regex.lazy_compile(name)
3125
# We want any error in the regexp to be raised *now* so we need to
3126
# avoid the delay introduced by the lazy regexp. But, we still do
3127
# want the nicer errors raised by lazy_regex.
3128
name._compile_and_collapse()
3131
for c in self._get_configs(directory, scope):
3132
for (oname, value, section, conf_id, parser) in c._get_options():
3133
if name.search(oname):
3134
if cur_conf_id != conf_id:
3135
# Explain where the options are defined
3136
self.outf.write('%s:\n' % (conf_id,))
3137
cur_conf_id = conf_id
3139
if (section not in (None, 'DEFAULT')
3140
and cur_section != section):
3141
# Display the section if it's not the default (or only)
3143
self.outf.write(' [%s]\n' % (section,))
3144
cur_section = section
3145
self.outf.write(' %s = %s\n' % (oname, value))
3147
def _set_config_option(self, name, value, directory, scope):
3148
for conf in self._get_configs(directory, scope):
3149
conf.set_user_option(name, value)
3152
raise errors.NoSuchConfig(scope)
3154
def _remove_config_option(self, name, directory, scope):
3156
raise errors.BzrCommandError(
3157
'--remove expects an option to remove.')
3159
for conf in self._get_configs(directory, scope):
3160
for (section_name, section, conf_id) in conf._get_sections():
3161
if scope is not None and conf_id != scope:
3162
# Not the right configuration file
3165
if conf_id != conf.config_id():
3166
conf = self._get_configs(directory, conf_id).next()
3167
# We use the first section in the first config where the
3168
# option is defined to remove it
3169
conf.remove_user_option(name, section_name)
3174
raise errors.NoSuchConfig(scope)
3176
raise errors.NoSuchConfigOption(name)
3180
# We need adapters that can build a Store or a Stack in a test context. Test
3181
# classes, based on TestCaseWithTransport, can use the registry to parametrize
3182
# themselves. The builder will receive a test instance and should return a
3183
# ready-to-use store or stack. Plugins that define new store/stacks can also
3184
# register themselves here to be tested against the tests defined in
3185
# bzrlib.tests.test_config. Note that the builder can be called multiple times
3186
# for the same tests.
3188
# The registered object should be a callable receiving a test instance
3189
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Store
3191
test_store_builder_registry = registry.Registry()
3193
# The registered object should be a callable receiving a test instance
3194
# parameter (inheriting from tests.TestCaseWithTransport) and returning a Stack
3196
test_stack_builder_registry = registry.Registry()