2271
2281
The option *values* are stored in config files and found in sections.
2273
2283
Here we define various properties about the option itself, its default
2274
value, in which config files it can be stored, etc (TBC).
2284
value, how to convert it from stores, what to do when invalid values are
2285
encoutered, in which config files it can be stored.
2277
def __init__(self, name, default=None):
2288
def __init__(self, name, override_from_env=None,
2289
default=None, default_from_env=None,
2290
help=None, from_unicode=None, invalid=None, unquote=True):
2291
"""Build an option definition.
2293
:param name: the name used to refer to the option.
2295
:param override_from_env: A list of environment variables which can
2296
provide override any configuration setting.
2298
:param default: the default value to use when none exist in the config
2299
stores. This is either a string that ``from_unicode`` will convert
2300
into the proper type, a callable returning a unicode string so that
2301
``from_unicode`` can be used on the return value, or a python
2302
object that can be stringified (so only the empty list is supported
2305
:param default_from_env: A list of environment variables which can
2306
provide a default value. 'default' will be used only if none of the
2307
variables specified here are set in the environment.
2309
:param help: a doc string to explain the option to the user.
2311
:param from_unicode: a callable to convert the unicode string
2312
representing the option value in a store. This is not called for
2315
:param invalid: the action to be taken when an invalid value is
2316
encountered in a store. This is called only when from_unicode is
2317
invoked to convert a string and returns None or raise ValueError or
2318
TypeError. Accepted values are: None (ignore invalid values),
2319
'warning' (emit a warning), 'error' (emit an error message and
2322
:param unquote: should the unicode value be unquoted before conversion.
2323
This should be used only when the store providing the values cannot
2324
safely unquote them (see http://pad.lv/906897). It is provided so
2325
daughter classes can handle the quoting themselves.
2327
if override_from_env is None:
2328
override_from_env = []
2329
if default_from_env is None:
2330
default_from_env = []
2278
2331
self.name = name
2279
self.default = default
2332
self.override_from_env = override_from_env
2333
# Convert the default value to a unicode string so all values are
2334
# strings internally before conversion (via from_unicode) is attempted.
2337
elif isinstance(default, list):
2338
# Only the empty list is supported
2340
raise AssertionError(
2341
'Only empty lists are supported as default values')
2343
elif isinstance(default, (str, unicode, bool, int, float)):
2344
# Rely on python to convert strings, booleans and integers
2345
self.default = u'%s' % (default,)
2346
elif callable(default):
2347
self.default = default
2349
# other python objects are not expected
2350
raise AssertionError('%r is not supported as a default value'
2352
self.default_from_env = default_from_env
2354
self.from_unicode = from_unicode
2355
self.unquote = unquote
2356
if invalid and invalid not in ('warning', 'error'):
2357
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2358
self.invalid = invalid
2364
def convert_from_unicode(self, store, unicode_value):
2365
if self.unquote and store is not None and unicode_value is not None:
2366
unicode_value = store.unquote(unicode_value)
2367
if self.from_unicode is None or unicode_value is None:
2368
# Don't convert or nothing to convert
2369
return unicode_value
2371
converted = self.from_unicode(unicode_value)
2372
except (ValueError, TypeError):
2373
# Invalid values are ignored
2375
if converted is None and self.invalid is not None:
2376
# The conversion failed
2377
if self.invalid == 'warning':
2378
trace.warning('Value "%s" is not valid for "%s"',
2379
unicode_value, self.name)
2380
elif self.invalid == 'error':
2381
raise errors.ConfigOptionValueError(self.name, unicode_value)
2384
def get_override(self):
2386
for var in self.override_from_env:
2388
# If the env variable is defined, its value takes precedence
2389
value = os.environ[var].decode(osutils.get_user_encoding())
2281
2395
def get_default(self):
2287
option_registry = registry.Registry()
2290
option_registry.register(
2291
'editor', Option('editor'),
2292
help='The command called to launch an editor to enter a message.')
2397
for var in self.default_from_env:
2399
# If the env variable is defined, its value is the default one
2400
value = os.environ[var].decode(osutils.get_user_encoding())
2405
# Otherwise, fallback to the value defined at registration
2406
if callable(self.default):
2407
value = self.default()
2408
if not isinstance(value, unicode):
2409
raise AssertionError(
2410
'Callable default values should be unicode')
2412
value = self.default
2415
def get_help_topic(self):
2418
def get_help_text(self, additional_see_also=None, plain=True):
2420
from bzrlib import help_topics
2421
result += help_topics._format_see_also(additional_see_also)
2423
result = help_topics.help_as_plain_text(result)
2427
# Predefined converters to get proper values from store
2429
def bool_from_store(unicode_str):
2430
return ui.bool_from_string(unicode_str)
2433
def int_from_store(unicode_str):
2434
return int(unicode_str)
2437
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
2439
def int_SI_from_store(unicode_str):
2440
"""Convert a human readable size in SI units, e.g 10MB into an integer.
2442
Accepted suffixes are K,M,G. It is case-insensitive and may be followed
2443
by a trailing b (i.e. Kb, MB). This is intended to be practical and not
2446
:return Integer, expanded to its base-10 value if a proper SI unit is
2447
found, None otherwise.
2449
regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
2450
p = re.compile(regexp, re.IGNORECASE)
2451
m = p.match(unicode_str)
2454
val, _, unit = m.groups()
2458
coeff = _unit_suffixes[unit.upper()]
2460
raise ValueError(gettext('{0} is not an SI unit.').format(unit))
2465
def float_from_store(unicode_str):
2466
return float(unicode_str)
2469
# Use a an empty dict to initialize an empty configobj avoiding all
2470
# parsing and encoding checks
2471
_list_converter_config = configobj.ConfigObj(
2472
{}, encoding='utf-8', list_values=True, interpolation=False)
2475
class ListOption(Option):
2477
def __init__(self, name, default=None, default_from_env=None,
2478
help=None, invalid=None):
2479
"""A list Option definition.
2481
This overrides the base class so the conversion from a unicode string
2482
can take quoting into account.
2484
super(ListOption, self).__init__(
2485
name, default=default, default_from_env=default_from_env,
2486
from_unicode=self.from_unicode, help=help,
2487
invalid=invalid, unquote=False)
2489
def from_unicode(self, unicode_str):
2490
if not isinstance(unicode_str, basestring):
2492
# Now inject our string directly as unicode. All callers got their
2493
# value from configobj, so values that need to be quoted are already
2495
_list_converter_config.reset()
2496
_list_converter_config._parse([u"list=%s" % (unicode_str,)])
2497
maybe_list = _list_converter_config['list']
2498
if isinstance(maybe_list, basestring):
2500
# A single value, most probably the user forgot (or didn't care
2501
# to add) the final ','
2504
# The empty string, convert to empty list
2507
# We rely on ConfigObj providing us with a list already
2512
class RegistryOption(Option):
2513
"""Option for a choice from a registry."""
2515
def __init__(self, name, registry, default_from_env=None,
2516
help=None, invalid=None):
2517
"""A registry based Option definition.
2519
This overrides the base class so the conversion from a unicode string
2520
can take quoting into account.
2522
super(RegistryOption, self).__init__(
2523
name, default=lambda: unicode(registry.default_key),
2524
default_from_env=default_from_env,
2525
from_unicode=self.from_unicode, help=help,
2526
invalid=invalid, unquote=False)
2527
self.registry = registry
2529
def from_unicode(self, unicode_str):
2530
if not isinstance(unicode_str, basestring):
2533
return self.registry.get(unicode_str)
2536
"Invalid value %s for %s."
2537
"See help for a list of possible values." % (unicode_str,
2542
ret = [self._help, "\n\nThe following values are supported:\n"]
2543
for key in self.registry.keys():
2544
ret.append(" %s - %s\n" % (key, self.registry.get_help(key)))
2548
class OptionRegistry(registry.Registry):
2549
"""Register config options by their name.
2551
This overrides ``registry.Registry`` to simplify registration by acquiring
2552
some information from the option object itself.
2555
def register(self, option):
2556
"""Register a new option to its name.
2558
:param option: The option to register. Its name is used as the key.
2560
super(OptionRegistry, self).register(option.name, option,
2563
def register_lazy(self, key, module_name, member_name):
2564
"""Register a new option to be loaded on request.
2566
:param key: the key to request the option later. Since the registration
2567
is lazy, it should be provided and match the option name.
2569
:param module_name: the python path to the module. Such as 'os.path'.
2571
:param member_name: the member of the module to return. If empty or
2572
None, get() will return the module itself.
2574
super(OptionRegistry, self).register_lazy(key,
2575
module_name, member_name)
2577
def get_help(self, key=None):
2578
"""Get the help text associated with the given key"""
2579
option = self.get(key)
2580
the_help = option.help
2581
if callable(the_help):
2582
return the_help(self, key)
2586
option_registry = OptionRegistry()
2589
# Registered options in lexicographical order
2591
option_registry.register(
2592
Option('append_revisions_only',
2593
default=None, from_unicode=bool_from_store, invalid='warning',
2595
Whether to only append revisions to the mainline.
2597
If this is set to true, then it is not possible to change the
2598
existing mainline of the branch.
2600
option_registry.register(
2601
ListOption('acceptable_keys',
2604
List of GPG key patterns which are acceptable for verification.
2606
option_registry.register(
2607
Option('add.maximum_file_size',
2608
default=u'20MB', from_unicode=int_SI_from_store,
2610
Size above which files should be added manually.
2612
Files below this size are added automatically when using ``bzr add`` without
2615
A negative value means disable the size check.
2617
option_registry.register(
2619
default=None, from_unicode=bool_from_store,
2621
Is the branch bound to ``bound_location``.
2623
If set to "True", the branch should act as a checkout, and push each commit to
2624
the bound_location. This option is normally set by ``bind``/``unbind``.
2626
See also: bound_location.
2628
option_registry.register(
2629
Option('bound_location',
2632
The location that commits should go to when acting as a checkout.
2634
This option is normally set by ``bind``.
2638
option_registry.register(
2639
Option('branch.fetch_tags', default=False, from_unicode=bool_from_store,
2641
Whether revisions associated with tags should be fetched.
2643
option_registry.register_lazy(
2644
'bzr.transform.orphan_policy', 'bzrlib.transform', 'opt_transform_orphan')
2645
option_registry.register(
2646
Option('bzr.workingtree.worth_saving_limit', default=10,
2647
from_unicode=int_from_store, invalid='warning',
2649
How many changes before saving the dirstate.
2651
-1 means that we will never rewrite the dirstate file for only
2652
stat-cache changes. Regardless of this setting, we will always rewrite
2653
the dirstate file if a file is added/removed/renamed/etc. This flag only
2654
affects the behavior of updating the dirstate file after we notice that
2655
a file has been touched.
2657
option_registry.register(
2658
Option('bugtracker', default=None,
2660
Default bug tracker to use.
2662
This bug tracker will be used for example when marking bugs
2663
as fixed using ``bzr commit --fixes``, if no explicit
2664
bug tracker was specified.
2666
option_registry.register(
2667
Option('check_signatures', default=CHECK_IF_POSSIBLE,
2668
from_unicode=signature_policy_from_unicode,
2670
GPG checking policy.
2672
Possible values: require, ignore, check-available (default)
2674
this option will control whether bzr will require good gpg
2675
signatures, ignore them, or check them if they are
2678
option_registry.register(
2679
Option('child_submit_format',
2680
help='''The preferred format of submissions to this branch.'''))
2681
option_registry.register(
2682
Option('child_submit_to',
2683
help='''Where submissions to this branch are mailed to.'''))
2684
option_registry.register(
2685
Option('create_signatures', default=SIGN_WHEN_REQUIRED,
2686
from_unicode=signing_policy_from_unicode,
2690
Possible values: always, never, when-required (default)
2692
This option controls whether bzr will always create
2693
gpg signatures or not on commits.
2695
option_registry.register(
2696
Option('dirstate.fdatasync', default=True,
2697
from_unicode=bool_from_store,
2699
Flush dirstate changes onto physical disk?
2701
If true (default), working tree metadata changes are flushed through the
2702
OS buffers to physical disk. This is somewhat slower, but means data
2703
should not be lost if the machine crashes. See also repository.fdatasync.
2705
option_registry.register(
2706
ListOption('debug_flags', default=[],
2707
help='Debug flags to activate.'))
2708
option_registry.register(
2709
Option('default_format', default='2a',
2710
help='Format used when creating branches.'))
2711
option_registry.register(
2712
Option('dpush_strict', default=None,
2713
from_unicode=bool_from_store,
2715
The default value for ``dpush --strict``.
2717
If present, defines the ``--strict`` option default value for checking
2718
uncommitted changes before pushing into a different VCS without any
2719
custom bzr metadata.
2721
option_registry.register(
2723
help='The command called to launch an editor to enter a message.'))
2724
option_registry.register(
2725
Option('email', override_from_env=['BZR_EMAIL'], default=default_email,
2726
help='The users identity'))
2727
option_registry.register(
2728
Option('gpg_signing_command',
2731
Program to use use for creating signatures.
2733
This should support at least the -u and --clearsign options.
2735
option_registry.register(
2736
Option('gpg_signing_key',
2739
GPG key to use for signing.
2741
This defaults to the first key associated with the users email.
2743
option_registry.register(
2744
Option('ignore_missing_extensions', default=False,
2745
from_unicode=bool_from_store,
2747
Control the missing extensions warning display.
2749
The warning will not be emitted if set to True.
2751
option_registry.register(
2753
help='Language to translate messages into.'))
2754
option_registry.register(
2755
Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2757
Steal locks that appears to be dead.
2759
If set to True, bzr will check if a lock is supposed to be held by an
2760
active process from the same user on the same machine. If the user and
2761
machine match, but no process with the given PID is active, then bzr
2762
will automatically break the stale lock, and create a new lock for
2764
Otherwise, bzr will prompt as normal to break the lock.
2766
option_registry.register(
2767
Option('log_format', default='long',
2769
Log format to use when displaying revisions.
2771
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
2772
may be provided by plugins.
2774
option_registry.register_lazy('mail_client', 'bzrlib.mail_client',
2776
option_registry.register(
2777
Option('output_encoding',
2778
help= 'Unicode encoding for output'
2779
' (terminal encoding if not specified).'))
2780
option_registry.register(
2781
Option('parent_location',
2784
The location of the default branch for pull or merge.
2786
This option is normally set when creating a branch, the first ``pull`` or by
2787
``pull --remember``.
2789
option_registry.register(
2790
Option('post_commit', default=None,
2792
Post commit functions.
2794
An ordered list of python functions to call, separated by spaces.
2796
Each function takes branch, rev_id as parameters.
2798
option_registry.register(
2799
Option('public_branch',
2802
A publically-accessible version of this branch.
2804
This implies that the branch setting this option is not publically-accessible.
2805
Used and set by ``bzr send``.
2807
option_registry.register(
2808
Option('push_location',
2811
The location of the default branch for push.
2813
This option is normally set by the first ``push`` or ``push --remember``.
2815
option_registry.register(
2816
Option('push_strict', default=None,
2817
from_unicode=bool_from_store,
2819
The default value for ``push --strict``.
2821
If present, defines the ``--strict`` option default value for checking
2822
uncommitted changes before sending a merge directive.
2824
option_registry.register(
2825
Option('repository.fdatasync', default=True,
2826
from_unicode=bool_from_store,
2828
Flush repository changes onto physical disk?
2830
If true (default), repository changes are flushed through the OS buffers
2831
to physical disk. This is somewhat slower, but means data should not be
2832
lost if the machine crashes. See also dirstate.fdatasync.
2834
option_registry.register_lazy('smtp_server',
2835
'bzrlib.smtp_connection', 'smtp_server')
2836
option_registry.register_lazy('smtp_password',
2837
'bzrlib.smtp_connection', 'smtp_password')
2838
option_registry.register_lazy('smtp_username',
2839
'bzrlib.smtp_connection', 'smtp_username')
2840
option_registry.register(
2841
Option('selftest.timeout',
2843
from_unicode=int_from_store,
2844
help='Abort selftest if one test takes longer than this many seconds',
2847
option_registry.register(
2848
Option('send_strict', default=None,
2849
from_unicode=bool_from_store,
2851
The default value for ``send --strict``.
2853
If present, defines the ``--strict`` option default value for checking
2854
uncommitted changes before sending a bundle.
2857
option_registry.register(
2858
Option('serve.client_timeout',
2859
default=300.0, from_unicode=float_from_store,
2860
help="If we wait for a new request from a client for more than"
2861
" X seconds, consider the client idle, and hangup."))
2862
option_registry.register(
2863
Option('stacked_on_location',
2865
help="""The location where this branch is stacked on."""))
2866
option_registry.register(
2867
Option('submit_branch',
2870
The branch you intend to submit your current work to.
2872
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
2873
by the ``submit:`` revision spec.
2875
option_registry.register(
2877
help='''Where submissions from this branch are mailed to.'''))
2878
option_registry.register(
2879
ListOption('suppress_warnings',
2881
help="List of warning classes to suppress."))
2882
option_registry.register(
2883
Option('validate_signatures_in_log', default=False,
2884
from_unicode=bool_from_store, invalid='warning',
2885
help='''Whether to validate signatures in bzr log.'''))
2886
option_registry.register_lazy('ssl.ca_certs',
2887
'bzrlib.transport.http._urllib2_wrappers', 'opt_ssl_ca_certs')
2889
option_registry.register_lazy('ssl.cert_reqs',
2890
'bzrlib.transport.http._urllib2_wrappers', 'opt_ssl_cert_reqs')
2295
2893
class Section(object):
2447
3190
co_input = StringIO(bytes)
2449
3192
# The config files are always stored utf8-encoded
2450
self._config_obj = ConfigObj(co_input, encoding='utf-8')
3193
self._config_obj = ConfigObj(co_input, encoding='utf-8',
2451
3195
except configobj.ConfigObjError, e:
2452
3196
self._config_obj = None
2453
3197
raise errors.ParseConfigError(e.errors, self.external_url())
2454
3198
except UnicodeDecodeError:
2455
3199
raise errors.ConfigContentError(self.external_url())
3201
def save_changes(self):
3202
if not self.is_loaded():
3205
if not self._need_saving():
3207
# Preserve the current version
3208
current = self._config_obj
3209
dirty_sections = list(self.dirty_sections)
3210
self.apply_changes(dirty_sections)
3211
# Save to the persistent storage
2457
3214
def save(self):
2458
3215
if not self.is_loaded():
2459
3216
# Nothing to save
2461
3218
out = StringIO()
2462
3219
self._config_obj.write(out)
2463
self.transport.put_bytes(self.file_name, out.getvalue())
3220
self._save_content(out.getvalue())
2464
3221
for hook in ConfigHooks['save']:
2467
def external_url(self):
2468
# FIXME: external_url should really accepts an optional relpath
2469
# parameter (bug #750169) :-/ -- vila 2011-04-04
2470
# The following will do in the interim but maybe we don't want to
2471
# expose a path here but rather a config ID and its associated
2472
# object </hand wawe>.
2473
return urlutils.join(self.transport.external_url(), self.file_name)
2475
3224
def get_sections(self):
2476
3225
"""Get the configobj section in the file order.
2478
:returns: An iterable of (name, dict).
3227
:returns: An iterable of (store, section).
2480
3229
# We need a loaded store
2483
except errors.NoSuchFile:
2484
# If the file doesn't exist, there is no sections
3232
except (errors.NoSuchFile, errors.PermissionDenied):
3233
# If the file can't be read, there is no sections
2486
3235
cobj = self._config_obj
2487
3236
if cobj.scalars:
2488
yield self.readonly_section_class(None, cobj)
3237
yield self, self.readonly_section_class(None, cobj)
2489
3238
for section_name in cobj.sections:
2490
yield self.readonly_section_class(section_name, cobj[section_name])
3240
self.readonly_section_class(section_name,
3241
cobj[section_name]))
2492
def get_mutable_section(self, section_name=None):
3243
def get_mutable_section(self, section_id=None):
2493
3244
# We need a loaded store
2496
3247
except errors.NoSuchFile:
2497
3248
# The file doesn't exist, let's pretend it was empty
2498
3249
self._load_from_string('')
2499
if section_name is None:
3250
if section_id is None:
2500
3251
section = self._config_obj
2502
section = self._config_obj.setdefault(section_name, {})
2503
return self.mutable_section_class(section_name, section)
3253
section = self._config_obj.setdefault(section_id, {})
3254
mutable_section = self.mutable_section_class(section_id, section)
3255
# All mutable sections can become dirty
3256
self.dirty_sections.append(mutable_section)
3257
return mutable_section
3259
def quote(self, value):
3261
# configobj conflates automagical list values and quoting
3262
self._config_obj.list_values = True
3263
return self._config_obj._quote(value)
3265
self._config_obj.list_values = False
3267
def unquote(self, value):
3268
if value and isinstance(value, basestring):
3269
# _unquote doesn't handle None nor empty strings nor anything that
3270
# is not a string, really.
3271
value = self._config_obj._unquote(value)
3274
def external_url(self):
3275
# Since an IniFileStore can be used without a file (at least in tests),
3276
# it's better to provide something than raising a NotImplementedError.
3277
# All daughter classes are supposed to provide an implementation
3279
return 'In-Process Store, no URL'
3281
class TransportIniFileStore(IniFileStore):
3282
"""IniFileStore that loads files from a transport.
3284
:ivar transport: The transport object where the config file is located.
3286
:ivar file_name: The config file basename in the transport directory.
3289
def __init__(self, transport, file_name):
3290
"""A Store using a ini file on a Transport
3292
:param transport: The transport object where the config file is located.
3293
:param file_name: The config file basename in the transport directory.
3295
super(TransportIniFileStore, self).__init__()
3296
self.transport = transport
3297
self.file_name = file_name
3299
def _load_content(self):
3301
return self.transport.get_bytes(self.file_name)
3302
except errors.PermissionDenied:
3303
trace.warning("Permission denied while trying to load "
3304
"configuration store %s.", self.external_url())
3307
def _save_content(self, content):
3308
self.transport.put_bytes(self.file_name, content)
3310
def external_url(self):
3311
# FIXME: external_url should really accepts an optional relpath
3312
# parameter (bug #750169) :-/ -- vila 2011-04-04
3313
# The following will do in the interim but maybe we don't want to
3314
# expose a path here but rather a config ID and its associated
3315
# object </hand wawe>.
3316
return urlutils.join(self.transport.external_url(), self.file_name)
2506
3319
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2724
3643
option exists or get its value, which in turn may require to discover
2725
3644
in which sections it can be defined. Both of these (section and option
2726
3645
existence) require loading the store (even partially).
3647
:param name: The queried option.
3649
:param expand: Whether options references should be expanded.
3651
:param convert: Whether the option value should be converted from
3652
unicode (do nothing for non-registered options).
3654
:returns: The value of the option.
2728
3656
# FIXME: No caching of options nor sections yet -- vila 20110503
2730
# Ensuring lazy loading is achieved by delaying section matching (which
2731
# implies querying the persistent storage) until it can't be avoided
2732
# anymore by using callables to describe (possibly empty) section
2734
for section_or_callable in self.sections_def:
2735
# Each section can expand to multiple ones when a callable is used
2736
if callable(section_or_callable):
2737
sections = section_or_callable()
2739
sections = [section_or_callable]
2740
for section in sections:
3658
found_store = None # Where the option value has been found
3659
# If the option is registered, it may provide additional info about
3662
opt = option_registry.get(name)
3667
def expand_and_convert(val):
3668
# This may need to be called in different contexts if the value is
3669
# None or ends up being None during expansion or conversion.
3672
if isinstance(val, basestring):
3673
val = self._expand_options_in_string(val)
3675
trace.warning('Cannot expand "%s":'
3676
' %s does not support option expansion'
3677
% (name, type(val)))
3679
val = found_store.unquote(val)
3681
val = opt.convert_from_unicode(found_store, val)
3684
# First of all, check if the environment can override the configuration
3686
if opt is not None and opt.override_from_env:
3687
value = opt.get_override()
3688
value = expand_and_convert(value)
3690
for store, section in self.iter_sections():
2741
3691
value = section.get(name)
2742
3692
if value is not None:
2744
if value is not None:
2747
# If the option is registered, it may provide a default value
2749
opt = option_registry.get(name)
3695
value = expand_and_convert(value)
3696
if opt is not None and value is None:
3697
# If the option is registered, it may provide a default value
2754
3698
value = opt.get_default()
3699
value = expand_and_convert(value)
2755
3700
for hook in ConfigHooks['get']:
2756
3701
hook(self, name, value)
3704
def expand_options(self, string, env=None):
3705
"""Expand option references in the string in the configuration context.
3707
:param string: The string containing option(s) to expand.
3709
:param env: An option dict defining additional configuration options or
3710
overriding existing ones.
3712
:returns: The expanded string.
3714
return self._expand_options_in_string(string, env)
3716
def _expand_options_in_string(self, string, env=None, _refs=None):
3717
"""Expand options in the string in the configuration context.
3719
:param string: The string to be expanded.
3721
:param env: An option dict defining additional configuration options or
3722
overriding existing ones.
3724
:param _refs: Private list (FIFO) containing the options being expanded
3727
:returns: The expanded string.
3730
# Not much to expand there
3733
# What references are currently resolved (to detect loops)
3736
# We need to iterate until no more refs appear ({{foo}} will need two
3737
# iterations for example).
3742
for is_ref, chunk in iter_option_refs(result):
3744
chunks.append(chunk)
3749
raise errors.OptionExpansionLoop(string, _refs)
3751
value = self._expand_option(name, env, _refs)
3753
raise errors.ExpandingUnknownOption(name, string)
3754
chunks.append(value)
3756
result = ''.join(chunks)
3759
def _expand_option(self, name, env, _refs):
3760
if env is not None and name in env:
3761
# Special case, values provided in env takes precedence over
3765
value = self.get(name, expand=False, convert=False)
3766
value = self._expand_options_in_string(value, env, _refs)
2759
3769
def _get_mutable_section(self):
2760
3770
"""Get the MutableSection for the Stack.
2762
3772
This is where we guarantee that the mutable section is lazily loaded:
2763
3773
this means we won't load the corresponding store before setting a value
2764
3774
or deleting an option. In practice the store will often be loaded but
2765
this allows helps catching some programming errors.
3775
this helps catching some programming errors.
2767
section = self.store.get_mutable_section(self.mutable_section_name)
3778
section = store.get_mutable_section(self.mutable_section_id)
3779
return store, section
2770
3781
def set(self, name, value):
2771
3782
"""Set a new value for the option."""
2772
section = self._get_mutable_section()
2773
section.set(name, value)
3783
store, section = self._get_mutable_section()
3784
section.set(name, store.quote(value))
2774
3785
for hook in ConfigHooks['set']:
2775
3786
hook(self, name, value)
2777
3788
def remove(self, name):
2778
3789
"""Remove an existing option."""
2779
section = self._get_mutable_section()
3790
_, section = self._get_mutable_section()
2780
3791
section.remove(name)
2781
3792
for hook in ConfigHooks['remove']:
2782
3793
hook(self, name)
2809
3849
# Force a write to persistent storage
2810
3850
self.store.save()
3852
def remove(self, name):
3855
super(_CompatibleStack, self).remove(name)
3856
# Force a write to persistent storage
2813
3860
class GlobalStack(_CompatibleStack):
3861
"""Global options only stack.
3863
The following sections are queried:
3865
* command-line overrides,
3867
* the 'DEFAULT' section in bazaar.conf
3869
This stack will use the ``DEFAULT`` section in bazaar.conf as its
2815
3873
def __init__(self):
2817
3874
gstore = GlobalStore()
2818
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
3875
super(GlobalStack, self).__init__(
3876
[self._get_overrides,
3877
NameMatcher(gstore, 'DEFAULT').get_sections],
3878
gstore, mutable_section_id='DEFAULT')
2821
3881
class LocationStack(_CompatibleStack):
3882
"""Per-location options falling back to global options stack.
3885
The following sections are queried:
3887
* command-line overrides,
3889
* the sections matching ``location`` in ``locations.conf``, the order being
3890
defined by the number of path components in the section glob, higher
3891
numbers first (from most specific section to most generic).
3893
* the 'DEFAULT' section in bazaar.conf
3895
This stack will use the ``location`` section in locations.conf as its
2823
3899
def __init__(self, location):
3900
"""Make a new stack for a location and global configuration.
3902
:param location: A URL prefix to """
2824
3903
lstore = LocationStore()
2825
matcher = LocationMatcher(lstore, location)
3904
if location.startswith('file://'):
3905
location = urlutils.local_path_from_url(location)
2826
3906
gstore = GlobalStore()
2827
3907
super(LocationStack, self).__init__(
2828
[matcher.get_sections, gstore.get_sections], lstore)
2830
class BranchStack(_CompatibleStack):
3908
[self._get_overrides,
3909
LocationMatcher(lstore, location).get_sections,
3910
NameMatcher(gstore, 'DEFAULT').get_sections],
3911
lstore, mutable_section_id=location)
3914
class BranchStack(Stack):
3915
"""Per-location options falling back to branch then global options stack.
3917
The following sections are queried:
3919
* command-line overrides,
3921
* the sections matching ``location`` in ``locations.conf``, the order being
3922
defined by the number of path components in the section glob, higher
3923
numbers first (from most specific section to most generic),
3925
* the no-name section in branch.conf,
3927
* the ``DEFAULT`` section in ``bazaar.conf``.
3929
This stack will use the no-name section in ``branch.conf`` as its
2832
3933
def __init__(self, branch):
2833
bstore = BranchStore(branch)
2834
3934
lstore = LocationStore()
2835
matcher = LocationMatcher(lstore, branch.base)
3935
bstore = branch._get_config_store()
2836
3936
gstore = GlobalStore()
2837
3937
super(BranchStack, self).__init__(
2838
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
2840
self.branch = branch
3938
[self._get_overrides,
3939
LocationMatcher(lstore, branch.base).get_sections,
3940
NameMatcher(bstore, None).get_sections,
3941
NameMatcher(gstore, 'DEFAULT').get_sections],
3943
self.branch = branch
3945
def lock_write(self, token=None):
3946
return self.branch.lock_write(token)
3949
return self.branch.unlock()
3952
def set(self, name, value):
3953
super(BranchStack, self).set(name, value)
3954
# Unlocking the branch will trigger a store.save_changes() so the last
3955
# unlock saves all the changes.
3958
def remove(self, name):
3959
super(BranchStack, self).remove(name)
3960
# Unlocking the branch will trigger a store.save_changes() so the last
3961
# unlock saves all the changes.
3964
class RemoteControlStack(_CompatibleStack):
3965
"""Remote control-only options stack."""
3967
# FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
3968
# with the stack used for remote bzr dirs. RemoteControlStack only uses
3969
# control.conf and is used only for stack options.
3971
def __init__(self, bzrdir):
3972
cstore = bzrdir._get_config_store()
3973
super(RemoteControlStack, self).__init__(
3974
[NameMatcher(cstore, None).get_sections],
3976
self.bzrdir = bzrdir
3979
class BranchOnlyStack(Stack):
3980
"""Branch-only options stack."""
3982
# FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
3983
# stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
3984
# -- vila 2011-12-16
3986
def __init__(self, branch):
3987
bstore = branch._get_config_store()
3988
super(BranchOnlyStack, self).__init__(
3989
[NameMatcher(bstore, None).get_sections],
3991
self.branch = branch
3993
def lock_write(self, token=None):
3994
return self.branch.lock_write(token)
3997
return self.branch.unlock()
4000
def set(self, name, value):
4001
super(BranchOnlyStack, self).set(name, value)
4002
# Force a write to persistent storage
4003
self.store.save_changes()
4006
def remove(self, name):
4007
super(BranchOnlyStack, self).remove(name)
4008
# Force a write to persistent storage
4009
self.store.save_changes()
2843
4012
class cmd_config(commands.Command):