547
637
return command_line
640
class _ConfigHooks(hooks.Hooks):
641
"""A dict mapping hook names and a list of callables for configs.
645
"""Create the default hooks.
647
These are all empty initially, because by default nothing should get
650
super(_ConfigHooks, self).__init__('bzrlib.config', 'ConfigHooks')
651
self.add_hook('load',
652
'Invoked when a config store is loaded.'
653
' The signature is (store).',
655
self.add_hook('save',
656
'Invoked when a config store is saved.'
657
' The signature is (store).',
659
# The hooks for config options
661
'Invoked when a config option is read.'
662
' The signature is (stack, name, value).',
665
'Invoked when a config option is set.'
666
' The signature is (stack, name, value).',
668
self.add_hook('remove',
669
'Invoked when a config option is removed.'
670
' The signature is (stack, name).',
672
ConfigHooks = _ConfigHooks()
675
class _OldConfigHooks(hooks.Hooks):
676
"""A dict mapping hook names and a list of callables for configs.
680
"""Create the default hooks.
682
These are all empty initially, because by default nothing should get
685
super(_OldConfigHooks, self).__init__('bzrlib.config', 'OldConfigHooks')
686
self.add_hook('load',
687
'Invoked when a config store is loaded.'
688
' The signature is (config).',
690
self.add_hook('save',
691
'Invoked when a config store is saved.'
692
' The signature is (config).',
694
# The hooks for config options
696
'Invoked when a config option is read.'
697
' The signature is (config, name, value).',
700
'Invoked when a config option is set.'
701
' The signature is (config, name, value).',
703
self.add_hook('remove',
704
'Invoked when a config option is removed.'
705
' The signature is (config, name).',
707
OldConfigHooks = _OldConfigHooks()
550
710
class IniBasedConfig(Config):
551
711
"""A configuration policy that draws from ini files."""
2072
2266
del configobj[option_name]
2074
2268
del configobj[section_name][option_name]
2269
for hook in OldConfigHooks['remove']:
2270
hook(self, option_name)
2075
2271
self._set_configobj(configobj)
2077
2273
def _get_config_file(self):
2079
return StringIO(self._transport.get_bytes(self._filename))
2275
f = StringIO(self._transport.get_bytes(self._filename))
2276
for hook in OldConfigHooks['load']:
2080
2279
except errors.NoSuchFile:
2081
2280
return StringIO()
2281
except errors.PermissionDenied, e:
2282
trace.warning("Permission denied while trying to open "
2283
"configuration file %s.", urlutils.unescape_for_display(
2284
urlutils.join(self._transport.base, self._filename), "utf-8"))
2287
def _external_url(self):
2288
return urlutils.join(self._transport.external_url(), self._filename)
2083
2290
def _get_configobj(self):
2084
2291
f = self._get_config_file()
2086
return ConfigObj(f, encoding='utf-8')
2294
conf = ConfigObj(f, encoding='utf-8')
2295
except configobj.ConfigObjError, e:
2296
raise errors.ParseConfigError(e.errors, self._external_url())
2297
except UnicodeDecodeError:
2298
raise errors.ConfigContentError(self._external_url())
2090
2303
def _set_configobj(self, configobj):
2091
2304
out_file = StringIO()
2092
2305
configobj.write(out_file)
2093
2306
out_file.seek(0)
2094
2307
self._transport.put_file(self._filename, out_file)
2308
for hook in OldConfigHooks['save']:
2312
class Option(object):
2313
"""An option definition.
2315
The option *values* are stored in config files and found in sections.
2317
Here we define various properties about the option itself, its default
2318
value, how to convert it from stores, what to do when invalid values are
2319
encoutered, in which config files it can be stored.
2322
def __init__(self, name, default=None, default_from_env=None,
2324
from_unicode=None, invalid=None):
2325
"""Build an option definition.
2327
:param name: the name used to refer to the option.
2329
:param default: the default value to use when none exist in the config
2330
stores. This is either a string that ``from_unicode`` will convert
2331
into the proper type or a python object that can be stringified (so
2332
only the empty list is supported for example).
2334
:param default_from_env: A list of environment variables which can
2335
provide a default value. 'default' will be used only if none of the
2336
variables specified here are set in the environment.
2338
:param help: a doc string to explain the option to the user.
2340
:param from_unicode: a callable to convert the unicode string
2341
representing the option value in a store. This is not called for
2344
:param invalid: the action to be taken when an invalid value is
2345
encountered in a store. This is called only when from_unicode is
2346
invoked to convert a string and returns None or raise ValueError or
2347
TypeError. Accepted values are: None (ignore invalid values),
2348
'warning' (emit a warning), 'error' (emit an error message and
2351
if default_from_env is None:
2352
default_from_env = []
2354
# Convert the default value to a unicode string so all values are
2355
# strings internally before conversion (via from_unicode) is attempted.
2358
elif isinstance(default, list):
2359
# Only the empty list is supported
2361
raise AssertionError(
2362
'Only empty lists are supported as default values')
2364
elif isinstance(default, (str, unicode, bool, int)):
2365
# Rely on python to convert strings, booleans and integers
2366
self.default = u'%s' % (default,)
2368
# other python objects are not expected
2369
raise AssertionError('%r is not supported as a default value'
2371
self.default_from_env = default_from_env
2373
self.from_unicode = from_unicode
2374
if invalid and invalid not in ('warning', 'error'):
2375
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2376
self.invalid = invalid
2378
def convert_from_unicode(self, unicode_value):
2379
if self.from_unicode is None or unicode_value is None:
2380
# Don't convert or nothing to convert
2381
return unicode_value
2383
converted = self.from_unicode(unicode_value)
2384
except (ValueError, TypeError):
2385
# Invalid values are ignored
2387
if converted is None and self.invalid is not None:
2388
# The conversion failed
2389
if self.invalid == 'warning':
2390
trace.warning('Value "%s" is not valid for "%s"',
2391
unicode_value, self.name)
2392
elif self.invalid == 'error':
2393
raise errors.ConfigOptionValueError(self.name, unicode_value)
2396
def get_default(self):
2398
for var in self.default_from_env:
2400
# If the env variable is defined, its value is the default one
2401
value = os.environ[var]
2406
# Otherwise, fallback to the value defined at registration
2407
value = self.default
2410
def get_help_text(self, additional_see_also=None, plain=True):
2412
from bzrlib import help_topics
2413
result += help_topics._format_see_also(additional_see_also)
2415
result = help_topics.help_as_plain_text(result)
2419
# Predefined converters to get proper values from store
2421
def bool_from_store(unicode_str):
2422
return ui.bool_from_string(unicode_str)
2425
def int_from_store(unicode_str):
2426
return int(unicode_str)
2429
# Use a an empty dict to initialize an empty configobj avoiding all
2430
# parsing and encoding checks
2431
_list_converter_config = configobj.ConfigObj(
2432
{}, encoding='utf-8', list_values=True, interpolation=False)
2435
def list_from_store(unicode_str):
2436
if not isinstance(unicode_str, basestring):
2438
# Now inject our string directly as unicode. All callers got their value
2439
# from configobj, so values that need to be quoted are already properly
2441
_list_converter_config.reset()
2442
_list_converter_config._parse([u"list=%s" % (unicode_str,)])
2443
maybe_list = _list_converter_config['list']
2444
# ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
2445
if isinstance(maybe_list, basestring):
2447
# A single value, most probably the user forgot (or didn't care to
2448
# add) the final ','
2451
# The empty string, convert to empty list
2454
# We rely on ConfigObj providing us with a list already
2459
class OptionRegistry(registry.Registry):
2460
"""Register config options by their name.
2462
This overrides ``registry.Registry`` to simplify registration by acquiring
2463
some information from the option object itself.
2466
def register(self, option):
2467
"""Register a new option to its name.
2469
:param option: The option to register. Its name is used as the key.
2471
super(OptionRegistry, self).register(option.name, option,
2474
def register_lazy(self, key, module_name, member_name):
2475
"""Register a new option to be loaded on request.
2477
:param key: the key to request the option later. Since the registration
2478
is lazy, it should be provided and match the option name.
2480
:param module_name: the python path to the module. Such as 'os.path'.
2482
:param member_name: the member of the module to return. If empty or
2483
None, get() will return the module itself.
2485
super(OptionRegistry, self).register_lazy(key,
2486
module_name, member_name)
2488
def get_help(self, key=None):
2489
"""Get the help text associated with the given key"""
2490
option = self.get(key)
2491
the_help = option.help
2492
if callable(the_help):
2493
return the_help(self, key)
2497
option_registry = OptionRegistry()
2500
# Registered options in lexicographical order
2502
option_registry.register(
2503
Option('bzr.workingtree.worth_saving_limit', default=10,
2504
from_unicode=int_from_store, invalid='warning',
2506
How many changes before saving the dirstate.
2508
-1 means that we will never rewrite the dirstate file for only
2509
stat-cache changes. Regardless of this setting, we will always rewrite
2510
the dirstate file if a file is added/removed/renamed/etc. This flag only
2511
affects the behavior of updating the dirstate file after we notice that
2512
a file has been touched.
2514
option_registry.register(
2515
Option('dirstate.fdatasync', default=True,
2516
from_unicode=bool_from_store,
2518
Flush dirstate changes onto physical disk?
2520
If true (default), working tree metadata changes are flushed through the
2521
OS buffers to physical disk. This is somewhat slower, but means data
2522
should not be lost if the machine crashes. See also repository.fdatasync.
2524
option_registry.register(
2525
Option('debug_flags', default=[], from_unicode=list_from_store,
2526
help='Debug flags to activate.'))
2527
option_registry.register(
2528
Option('default_format', default='2a',
2529
help='Format used when creating branches.'))
2530
option_registry.register(
2531
Option('dpush_strict', default=None,
2532
from_unicode=bool_from_store,
2534
The default value for ``dpush --strict``.
2536
If present, defines the ``--strict`` option default value for checking
2537
uncommitted changes before pushing into a different VCS without any
2538
custom bzr metadata.
2540
option_registry.register(
2542
help='The command called to launch an editor to enter a message.'))
2543
option_registry.register(
2544
Option('ignore_missing_extensions', default=False,
2545
from_unicode=bool_from_store,
2547
Control the missing extensions warning display.
2549
The warning will not be emitted if set to True.
2551
option_registry.register(
2553
help='Language to translate messages into.'))
2554
option_registry.register(
2555
Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2557
Steal locks that appears to be dead.
2559
If set to True, bzr will check if a lock is supposed to be held by an
2560
active process from the same user on the same machine. If the user and
2561
machine match, but no process with the given PID is active, then bzr
2562
will automatically break the stale lock, and create a new lock for
2564
Otherwise, bzr will prompt as normal to break the lock.
2566
option_registry.register(
2567
Option('output_encoding',
2568
help= 'Unicode encoding for output'
2569
' (terminal encoding if not specified).'))
2570
option_registry.register(
2571
Option('push_strict', default=None,
2572
from_unicode=bool_from_store,
2574
The default value for ``push --strict``.
2576
If present, defines the ``--strict`` option default value for checking
2577
uncommitted changes before sending a merge directive.
2579
option_registry.register(
2580
Option('repository.fdatasync', default=True,
2581
from_unicode=bool_from_store,
2583
Flush repository changes onto physical disk?
2585
If true (default), repository changes are flushed through the OS buffers
2586
to physical disk. This is somewhat slower, but means data should not be
2587
lost if the machine crashes. See also dirstate.fdatasync.
2589
option_registry.register(
2590
Option('send_strict', default=None,
2591
from_unicode=bool_from_store,
2593
The default value for ``send --strict``.
2595
If present, defines the ``--strict`` option default value for checking
2596
uncommitted changes before pushing.
2097
2600
class Section(object):
2098
"""A section defines a dict of options.
2601
"""A section defines a dict of option name => value.
2100
2603
This is merely a read-only dict which can add some knowledge about the
2101
2604
options. It is *not* a python dict object though and doesn't try to mimic
2410
2977
def __init__(self, store, location):
2411
2978
super(LocationMatcher, self).__init__(store)
2979
if location.startswith('file://'):
2980
location = urlutils.local_path_from_url(location)
2412
2981
self.location = location
2414
def get_sections(self):
2415
# Override the default implementation as we want to change the order
2417
# The following is a bit hackish but ensures compatibility with
2418
# LocationConfig by reusing the same code
2419
sections = list(self.store.get_sections())
2983
def _get_matching_sections(self):
2984
"""Get all sections matching ``location``."""
2985
# We slightly diverge from LocalConfig here by allowing the no-name
2986
# section as the most generic one and the lower priority.
2987
no_name_section = None
2989
# Filter out the no_name_section so _iter_for_location_by_parts can be
2990
# used (it assumes all sections have a name).
2991
for section in self.store.get_sections():
2992
if section.id is None:
2993
no_name_section = section
2995
all_sections.append(section)
2996
# Unfortunately _iter_for_location_by_parts deals with section names so
2997
# we have to resync.
2420
2998
filtered_sections = _iter_for_location_by_parts(
2421
[s.id for s in sections], self.location)
2422
iter_sections = iter(sections)
2999
[s.id for s in all_sections], self.location)
3000
iter_all_sections = iter(all_sections)
2423
3001
matching_sections = []
3002
if no_name_section is not None:
3003
matching_sections.append(
3004
LocationSection(no_name_section, 0, self.location))
2424
3005
for section_id, extra_path, length in filtered_sections:
2425
# a section id is unique for a given store so it's safe to iterate
2427
section = iter_sections.next()
2428
if section_id == section.id:
2429
matching_sections.append(
2430
LocationSection(section, length, extra_path))
3006
# a section id is unique for a given store so it's safe to take the
3007
# first matching section while iterating. Also, all filtered
3008
# sections are part of 'all_sections' and will always be found
3011
section = iter_all_sections.next()
3012
if section_id == section.id:
3013
matching_sections.append(
3014
LocationSection(section, length, extra_path))
3016
return matching_sections
3018
def get_sections(self):
3019
# Override the default implementation as we want to change the order
3020
matching_sections = self._get_matching_sections()
2431
3021
# We want the longest (aka more specific) locations first
2432
3022
sections = sorted(matching_sections,
2433
3023
key=lambda section: (section.length, section.id),
2488
3096
for section in sections:
2489
3097
value = section.get(name)
2490
3098
if value is not None:
2492
# No definition was found
3100
if value is not None:
3102
# If the option is registered, it may provide additional info about
3105
opt = option_registry.get(name)
3109
def expand_and_convert(val):
3110
# This may need to be called twice if the value is None or ends up
3111
# being None during expansion or conversion.
3114
if isinstance(val, basestring):
3115
val = self._expand_options_in_string(val)
3117
trace.warning('Cannot expand "%s":'
3118
' %s does not support option expansion'
3119
% (name, type(val)))
3121
val = opt.convert_from_unicode(val)
3123
value = expand_and_convert(value)
3124
if opt is not None and value is None:
3125
# If the option is registered, it may provide a default value
3126
value = opt.get_default()
3127
value = expand_and_convert(value)
3128
for hook in ConfigHooks['get']:
3129
hook(self, name, value)
3132
def expand_options(self, string, env=None):
3133
"""Expand option references in the string in the configuration context.
3135
:param string: The string containing option(s) to expand.
3137
:param env: An option dict defining additional configuration options or
3138
overriding existing ones.
3140
:returns: The expanded string.
3142
return self._expand_options_in_string(string, env)
3144
def _expand_options_in_string(self, string, env=None, _refs=None):
3145
"""Expand options in the string in the configuration context.
3147
:param string: The string to be expanded.
3149
:param env: An option dict defining additional configuration options or
3150
overriding existing ones.
3152
:param _refs: Private list (FIFO) containing the options being expanded
3155
:returns: The expanded string.
3158
# Not much to expand there
3161
# What references are currently resolved (to detect loops)
3164
# We need to iterate until no more refs appear ({{foo}} will need two
3165
# iterations for example).
3167
raw_chunks = Stack._option_ref_re.split(result)
3168
if len(raw_chunks) == 1:
3169
# Shorcut the trivial case: no refs
3172
# Split will isolate refs so that every other chunk is a ref
3173
chunk_is_ref = False
3174
for chunk in raw_chunks:
3175
if not chunk_is_ref:
3176
chunks.append(chunk)
3181
raise errors.OptionExpansionLoop(string, _refs)
3183
value = self._expand_option(name, env, _refs)
3185
raise errors.ExpandingUnknownOption(name, string)
3186
chunks.append(value)
3188
chunk_is_ref = False
3189
result = ''.join(chunks)
3192
def _expand_option(self, name, env, _refs):
3193
if env is not None and name in env:
3194
# Special case, values provided in env takes precedence over
3198
# FIXME: This is a limited implementation, what we really need is a
3199
# way to query the bzr config for the value of an option,
3200
# respecting the scope rules (That is, once we implement fallback
3201
# configs, getting the option value should restart from the top
3202
# config, not the current one) -- vila 20101222
3203
value = self.get(name, expand=False)
3204
value = self._expand_options_in_string(value, env, _refs)
2495
3207
def _get_mutable_section(self):
2496
3208
"""Get the MutableSection for the Stack.
2507
3219
"""Set a new value for the option."""
2508
3220
section = self._get_mutable_section()
2509
3221
section.set(name, value)
3222
for hook in ConfigHooks['set']:
3223
hook(self, name, value)
2511
3225
def remove(self, name):
2512
3226
"""Remove an existing option."""
2513
3227
section = self._get_mutable_section()
2514
3228
section.remove(name)
3229
for hook in ConfigHooks['remove']:
2516
3232
def __repr__(self):
2517
3233
# Mostly for debugging use
2518
3234
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
3237
class _CompatibleStack(Stack):
3238
"""Place holder for compatibility with previous design.
3240
This is intended to ease the transition from the Config-based design to the
3241
Stack-based design and should not be used nor relied upon by plugins.
3243
One assumption made here is that the daughter classes will all use Stores
3244
derived from LockableIniFileStore).
3246
It implements set() by re-loading the store before applying the
3247
modification and saving it.
3249
The long term plan being to implement a single write by store to save
3250
all modifications, this class should not be used in the interim.
3253
def set(self, name, value):
3256
super(_CompatibleStack, self).set(name, value)
3257
# Force a write to persistent storage
3261
class GlobalStack(_CompatibleStack):
3262
"""Global options only stack."""
3266
gstore = GlobalStore()
3267
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
3270
class LocationStack(_CompatibleStack):
3271
"""Per-location options falling back to global options stack."""
3273
def __init__(self, location):
3274
"""Make a new stack for a location and global configuration.
3276
:param location: A URL prefix to """
3277
lstore = LocationStore()
3278
matcher = LocationMatcher(lstore, location)
3279
gstore = GlobalStore()
3280
super(LocationStack, self).__init__(
3281
[matcher.get_sections, gstore.get_sections], lstore)
3284
class BranchStack(_CompatibleStack):
3285
"""Per-location options falling back to branch then global options stack."""
3287
def __init__(self, branch):
3288
bstore = BranchStore(branch)
3289
lstore = LocationStore()
3290
matcher = LocationMatcher(lstore, branch.base)
3291
gstore = GlobalStore()
3292
super(BranchStack, self).__init__(
3293
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
3295
self.branch = branch
3298
class RemoteControlStack(_CompatibleStack):
3299
"""Remote control-only options stack."""
3301
def __init__(self, bzrdir):
3302
cstore = ControlStore(bzrdir)
3303
super(RemoteControlStack, self).__init__(
3304
[cstore.get_sections],
3306
self.bzrdir = bzrdir
3309
class RemoteBranchStack(_CompatibleStack):
3310
"""Remote branch-only options stack."""
3312
def __init__(self, branch):
3313
bstore = BranchStore(branch)
3314
super(RemoteBranchStack, self).__init__(
3315
[bstore.get_sections],
3317
self.branch = branch
2521
3320
class cmd_config(commands.Command):
2522
3321
__doc__ = """Display, set or remove a configuration option.