2262
2272
The option *values* are stored in config files and found in sections.
2264
2274
Here we define various properties about the option itself, its default
2265
value, in which config files it can be stored, etc (TBC).
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.
2268
def __init__(self, name, default=None):
2279
def __init__(self, name, override_from_env=None,
2280
default=None, default_from_env=None,
2281
help=None, from_unicode=None, invalid=None, unquote=True):
2282
"""Build an option definition.
2284
:param name: the name used to refer to the option.
2286
:param override_from_env: A list of environment variables which can
2287
provide override any configuration setting.
2289
:param default: the default value to use when none exist in the config
2290
stores. This is either a string that ``from_unicode`` will convert
2291
into the proper type, a callable returning a unicode string so that
2292
``from_unicode`` can be used on the return value, or a python
2293
object that can be stringified (so only the empty list is supported
2296
:param default_from_env: A list of environment variables which can
2297
provide a default value. 'default' will be used only if none of the
2298
variables specified here are set in the environment.
2300
:param help: a doc string to explain the option to the user.
2302
:param from_unicode: a callable to convert the unicode string
2303
representing the option value in a store. This is not called for
2306
:param invalid: the action to be taken when an invalid value is
2307
encountered in a store. This is called only when from_unicode is
2308
invoked to convert a string and returns None or raise ValueError or
2309
TypeError. Accepted values are: None (ignore invalid values),
2310
'warning' (emit a warning), 'error' (emit an error message and
2313
:param unquote: should the unicode value be unquoted before conversion.
2314
This should be used only when the store providing the values cannot
2315
safely unquote them (see http://pad.lv/906897). It is provided so
2316
daughter classes can handle the quoting themselves.
2318
if override_from_env is None:
2319
override_from_env = []
2320
if default_from_env is None:
2321
default_from_env = []
2269
2322
self.name = name
2270
self.default = default
2323
self.override_from_env = override_from_env
2324
# Convert the default value to a unicode string so all values are
2325
# strings internally before conversion (via from_unicode) is attempted.
2328
elif isinstance(default, list):
2329
# Only the empty list is supported
2331
raise AssertionError(
2332
'Only empty lists are supported as default values')
2334
elif isinstance(default, (str, unicode, bool, int, float)):
2335
# Rely on python to convert strings, booleans and integers
2336
self.default = u'%s' % (default,)
2337
elif callable(default):
2338
self.default = default
2340
# other python objects are not expected
2341
raise AssertionError('%r is not supported as a default value'
2343
self.default_from_env = default_from_env
2345
self.from_unicode = from_unicode
2346
self.unquote = unquote
2347
if invalid and invalid not in ('warning', 'error'):
2348
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2349
self.invalid = invalid
2355
def convert_from_unicode(self, store, unicode_value):
2356
if self.unquote and store is not None and unicode_value is not None:
2357
unicode_value = store.unquote(unicode_value)
2358
if self.from_unicode is None or unicode_value is None:
2359
# Don't convert or nothing to convert
2360
return unicode_value
2362
converted = self.from_unicode(unicode_value)
2363
except (ValueError, TypeError):
2364
# Invalid values are ignored
2366
if converted is None and self.invalid is not None:
2367
# The conversion failed
2368
if self.invalid == 'warning':
2369
trace.warning('Value "%s" is not valid for "%s"',
2370
unicode_value, self.name)
2371
elif self.invalid == 'error':
2372
raise errors.ConfigOptionValueError(self.name, unicode_value)
2375
def get_override(self):
2377
for var in self.override_from_env:
2379
# If the env variable is defined, its value takes precedence
2380
value = os.environ[var].decode(osutils.get_user_encoding())
2272
2386
def get_default(self):
2278
option_registry = registry.Registry()
2281
option_registry.register(
2282
'editor', Option('editor'),
2283
help='The command called to launch an editor to enter a message.')
2388
for var in self.default_from_env:
2390
# If the env variable is defined, its value is the default one
2391
value = os.environ[var].decode(osutils.get_user_encoding())
2396
# Otherwise, fallback to the value defined at registration
2397
if callable(self.default):
2398
value = self.default()
2399
if not isinstance(value, unicode):
2400
raise AssertionError(
2401
'Callable default values should be unicode')
2403
value = self.default
2406
def get_help_topic(self):
2409
def get_help_text(self, additional_see_also=None, plain=True):
2411
from bzrlib import help_topics
2412
result += help_topics._format_see_also(additional_see_also)
2414
result = help_topics.help_as_plain_text(result)
2418
# Predefined converters to get proper values from store
2420
def bool_from_store(unicode_str):
2421
return ui.bool_from_string(unicode_str)
2424
def int_from_store(unicode_str):
2425
return int(unicode_str)
2428
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
2430
def int_SI_from_store(unicode_str):
2431
"""Convert a human readable size in SI units, e.g 10MB into an integer.
2433
Accepted suffixes are K,M,G. It is case-insensitive and may be followed
2434
by a trailing b (i.e. Kb, MB). This is intended to be practical and not
2437
:return Integer, expanded to its base-10 value if a proper SI unit is
2438
found, None otherwise.
2440
regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
2441
p = re.compile(regexp, re.IGNORECASE)
2442
m = p.match(unicode_str)
2445
val, _, unit = m.groups()
2449
coeff = _unit_suffixes[unit.upper()]
2451
raise ValueError(gettext('{0} is not an SI unit.').format(unit))
2456
def float_from_store(unicode_str):
2457
return float(unicode_str)
2460
# Use a an empty dict to initialize an empty configobj avoiding all
2461
# parsing and encoding checks
2462
_list_converter_config = configobj.ConfigObj(
2463
{}, encoding='utf-8', list_values=True, interpolation=False)
2466
class ListOption(Option):
2468
def __init__(self, name, default=None, default_from_env=None,
2469
help=None, invalid=None):
2470
"""A list Option definition.
2472
This overrides the base class so the conversion from a unicode string
2473
can take quoting into account.
2475
super(ListOption, self).__init__(
2476
name, default=default, default_from_env=default_from_env,
2477
from_unicode=self.from_unicode, help=help,
2478
invalid=invalid, unquote=False)
2480
def from_unicode(self, unicode_str):
2481
if not isinstance(unicode_str, basestring):
2483
# Now inject our string directly as unicode. All callers got their
2484
# value from configobj, so values that need to be quoted are already
2486
_list_converter_config.reset()
2487
_list_converter_config._parse([u"list=%s" % (unicode_str,)])
2488
maybe_list = _list_converter_config['list']
2489
if isinstance(maybe_list, basestring):
2491
# A single value, most probably the user forgot (or didn't care
2492
# to add) the final ','
2495
# The empty string, convert to empty list
2498
# We rely on ConfigObj providing us with a list already
2503
class RegistryOption(Option):
2504
"""Option for a choice from a registry."""
2506
def __init__(self, name, registry, default_from_env=None,
2507
help=None, invalid=None):
2508
"""A registry based Option definition.
2510
This overrides the base class so the conversion from a unicode string
2511
can take quoting into account.
2513
super(RegistryOption, self).__init__(
2514
name, default=lambda: unicode(registry.default_key),
2515
default_from_env=default_from_env,
2516
from_unicode=self.from_unicode, help=help,
2517
invalid=invalid, unquote=False)
2518
self.registry = registry
2520
def from_unicode(self, unicode_str):
2521
if not isinstance(unicode_str, basestring):
2524
return self.registry.get(unicode_str)
2527
"Invalid value %s for %s."
2528
"See help for a list of possible values." % (unicode_str,
2533
ret = [self._help, "\n\nThe following values are supported:\n"]
2534
for key in self.registry.keys():
2535
ret.append(" %s - %s\n" % (key, self.registry.get_help(key)))
2539
class OptionRegistry(registry.Registry):
2540
"""Register config options by their name.
2542
This overrides ``registry.Registry`` to simplify registration by acquiring
2543
some information from the option object itself.
2546
def register(self, option):
2547
"""Register a new option to its name.
2549
:param option: The option to register. Its name is used as the key.
2551
super(OptionRegistry, self).register(option.name, option,
2554
def register_lazy(self, key, module_name, member_name):
2555
"""Register a new option to be loaded on request.
2557
:param key: the key to request the option later. Since the registration
2558
is lazy, it should be provided and match the option name.
2560
:param module_name: the python path to the module. Such as 'os.path'.
2562
:param member_name: the member of the module to return. If empty or
2563
None, get() will return the module itself.
2565
super(OptionRegistry, self).register_lazy(key,
2566
module_name, member_name)
2568
def get_help(self, key=None):
2569
"""Get the help text associated with the given key"""
2570
option = self.get(key)
2571
the_help = option.help
2572
if callable(the_help):
2573
return the_help(self, key)
2577
option_registry = OptionRegistry()
2580
# Registered options in lexicographical order
2582
option_registry.register(
2583
Option('append_revisions_only',
2584
default=None, from_unicode=bool_from_store, invalid='warning',
2586
Whether to only append revisions to the mainline.
2588
If this is set to true, then it is not possible to change the
2589
existing mainline of the branch.
2591
option_registry.register(
2592
ListOption('acceptable_keys',
2595
List of GPG key patterns which are acceptable for verification.
2597
option_registry.register(
2598
Option('add.maximum_file_size',
2599
default=u'20MB', from_unicode=int_SI_from_store,
2601
Size above which files should be added manually.
2603
Files below this size are added automatically when using ``bzr add`` without
2606
A negative value means disable the size check.
2608
option_registry.register(
2610
default=None, from_unicode=bool_from_store,
2612
Is the branch bound to ``bound_location``.
2614
If set to "True", the branch should act as a checkout, and push each commit to
2615
the bound_location. This option is normally set by ``bind``/``unbind``.
2617
See also: bound_location.
2619
option_registry.register(
2620
Option('bound_location',
2623
The location that commits should go to when acting as a checkout.
2625
This option is normally set by ``bind``.
2629
option_registry.register(
2630
Option('branch.fetch_tags', default=False, from_unicode=bool_from_store,
2632
Whether revisions associated with tags should be fetched.
2634
option_registry.register_lazy(
2635
'bzr.transform.orphan_policy', 'bzrlib.transform', 'opt_transform_orphan')
2636
option_registry.register(
2637
Option('bzr.workingtree.worth_saving_limit', default=10,
2638
from_unicode=int_from_store, invalid='warning',
2640
How many changes before saving the dirstate.
2642
-1 means that we will never rewrite the dirstate file for only
2643
stat-cache changes. Regardless of this setting, we will always rewrite
2644
the dirstate file if a file is added/removed/renamed/etc. This flag only
2645
affects the behavior of updating the dirstate file after we notice that
2646
a file has been touched.
2648
option_registry.register(
2649
Option('bugtracker', default=None,
2651
Default bug tracker to use.
2653
This bug tracker will be used for example when marking bugs
2654
as fixed using ``bzr commit --fixes``, if no explicit
2655
bug tracker was specified.
2657
option_registry.register(
2658
Option('check_signatures', default=CHECK_IF_POSSIBLE,
2659
from_unicode=signature_policy_from_unicode,
2661
GPG checking policy.
2663
Possible values: require, ignore, check-available (default)
2665
this option will control whether bzr will require good gpg
2666
signatures, ignore them, or check them if they are
2669
option_registry.register(
2670
Option('child_submit_format',
2671
help='''The preferred format of submissions to this branch.'''))
2672
option_registry.register(
2673
Option('child_submit_to',
2674
help='''Where submissions to this branch are mailed to.'''))
2675
option_registry.register(
2676
Option('create_signatures', default=SIGN_WHEN_REQUIRED,
2677
from_unicode=signing_policy_from_unicode,
2681
Possible values: always, never, when-required (default)
2683
This option controls whether bzr will always create
2684
gpg signatures or not on commits.
2686
option_registry.register(
2687
Option('dirstate.fdatasync', default=True,
2688
from_unicode=bool_from_store,
2690
Flush dirstate changes onto physical disk?
2692
If true (default), working tree metadata changes are flushed through the
2693
OS buffers to physical disk. This is somewhat slower, but means data
2694
should not be lost if the machine crashes. See also repository.fdatasync.
2696
option_registry.register(
2697
ListOption('debug_flags', default=[],
2698
help='Debug flags to activate.'))
2699
option_registry.register(
2700
Option('default_format', default='2a',
2701
help='Format used when creating branches.'))
2702
option_registry.register(
2703
Option('dpush_strict', default=None,
2704
from_unicode=bool_from_store,
2706
The default value for ``dpush --strict``.
2708
If present, defines the ``--strict`` option default value for checking
2709
uncommitted changes before pushing into a different VCS without any
2710
custom bzr metadata.
2712
option_registry.register(
2714
help='The command called to launch an editor to enter a message.'))
2715
option_registry.register(
2716
Option('email', override_from_env=['BZR_EMAIL'], default=default_email,
2717
help='The users identity'))
2718
option_registry.register(
2719
Option('gpg_signing_command',
2722
Program to use use for creating signatures.
2724
This should support at least the -u and --clearsign options.
2726
option_registry.register(
2727
Option('gpg_signing_key',
2730
GPG key to use for signing.
2732
This defaults to the first key associated with the users email.
2734
option_registry.register(
2735
Option('ignore_missing_extensions', default=False,
2736
from_unicode=bool_from_store,
2738
Control the missing extensions warning display.
2740
The warning will not be emitted if set to True.
2742
option_registry.register(
2744
help='Language to translate messages into.'))
2745
option_registry.register(
2746
Option('locks.steal_dead', default=False, from_unicode=bool_from_store,
2748
Steal locks that appears to be dead.
2750
If set to True, bzr will check if a lock is supposed to be held by an
2751
active process from the same user on the same machine. If the user and
2752
machine match, but no process with the given PID is active, then bzr
2753
will automatically break the stale lock, and create a new lock for
2755
Otherwise, bzr will prompt as normal to break the lock.
2757
option_registry.register(
2758
Option('log_format', default='long',
2760
Log format to use when displaying revisions.
2762
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
2763
may be provided by plugins.
2765
option_registry.register_lazy('mail_client', 'bzrlib.mail_client',
2767
option_registry.register(
2768
Option('output_encoding',
2769
help= 'Unicode encoding for output'
2770
' (terminal encoding if not specified).'))
2771
option_registry.register(
2772
Option('parent_location',
2775
The location of the default branch for pull or merge.
2777
This option is normally set when creating a branch, the first ``pull`` or by
2778
``pull --remember``.
2780
option_registry.register(
2781
Option('post_commit', default=None,
2783
Post commit functions.
2785
An ordered list of python functions to call, separated by spaces.
2787
Each function takes branch, rev_id as parameters.
2789
option_registry.register(
2790
Option('public_branch',
2793
A publically-accessible version of this branch.
2795
This implies that the branch setting this option is not publically-accessible.
2796
Used and set by ``bzr send``.
2798
option_registry.register(
2799
Option('push_location',
2802
The location of the default branch for push.
2804
This option is normally set by the first ``push`` or ``push --remember``.
2806
option_registry.register(
2807
Option('push_strict', default=None,
2808
from_unicode=bool_from_store,
2810
The default value for ``push --strict``.
2812
If present, defines the ``--strict`` option default value for checking
2813
uncommitted changes before sending a merge directive.
2815
option_registry.register(
2816
Option('repository.fdatasync', default=True,
2817
from_unicode=bool_from_store,
2819
Flush repository changes onto physical disk?
2821
If true (default), repository changes are flushed through the OS buffers
2822
to physical disk. This is somewhat slower, but means data should not be
2823
lost if the machine crashes. See also dirstate.fdatasync.
2825
option_registry.register_lazy('smtp_server',
2826
'bzrlib.smtp_connection', 'smtp_server')
2827
option_registry.register_lazy('smtp_password',
2828
'bzrlib.smtp_connection', 'smtp_password')
2829
option_registry.register_lazy('smtp_username',
2830
'bzrlib.smtp_connection', 'smtp_username')
2831
option_registry.register(
2832
Option('selftest.timeout',
2834
from_unicode=int_from_store,
2835
help='Abort selftest if one test takes longer than this many seconds',
2838
option_registry.register(
2839
Option('send_strict', default=None,
2840
from_unicode=bool_from_store,
2842
The default value for ``send --strict``.
2844
If present, defines the ``--strict`` option default value for checking
2845
uncommitted changes before sending a bundle.
2848
option_registry.register(
2849
Option('serve.client_timeout',
2850
default=300.0, from_unicode=float_from_store,
2851
help="If we wait for a new request from a client for more than"
2852
" X seconds, consider the client idle, and hangup."))
2853
option_registry.register(
2854
Option('stacked_on_location',
2856
help="""The location where this branch is stacked on."""))
2857
option_registry.register(
2858
Option('submit_branch',
2861
The branch you intend to submit your current work to.
2863
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
2864
by the ``submit:`` revision spec.
2866
option_registry.register(
2868
help='''Where submissions from this branch are mailed to.'''))
2869
option_registry.register(
2870
ListOption('suppress_warnings',
2872
help="List of warning classes to suppress."))
2873
option_registry.register(
2874
Option('validate_signatures_in_log', default=False,
2875
from_unicode=bool_from_store, invalid='warning',
2876
help='''Whether to validate signatures in bzr log.'''))
2877
option_registry.register_lazy('ssl.ca_certs',
2878
'bzrlib.transport.http._urllib2_wrappers', 'opt_ssl_ca_certs')
2880
option_registry.register_lazy('ssl.cert_reqs',
2881
'bzrlib.transport.http._urllib2_wrappers', 'opt_ssl_cert_reqs')
2286
2884
class Section(object):
2438
3182
co_input = StringIO(bytes)
2440
3184
# The config files are always stored utf8-encoded
2441
self._config_obj = ConfigObj(co_input, encoding='utf-8')
3185
self._config_obj = ConfigObj(co_input, encoding='utf-8',
2442
3187
except configobj.ConfigObjError, e:
2443
3188
self._config_obj = None
2444
3189
raise errors.ParseConfigError(e.errors, self.external_url())
2445
3190
except UnicodeDecodeError:
2446
3191
raise errors.ConfigContentError(self.external_url())
3193
def save_changes(self):
3194
if not self.is_loaded():
3197
if not self._need_saving():
3199
# Preserve the current version
3200
dirty_sections = dict(self.dirty_sections.items())
3201
self.apply_changes(dirty_sections)
3202
# Save to the persistent storage
2448
3205
def save(self):
2449
3206
if not self.is_loaded():
2450
3207
# Nothing to save
2452
3209
out = StringIO()
2453
3210
self._config_obj.write(out)
2454
self.transport.put_bytes(self.file_name, out.getvalue())
3211
self._save_content(out.getvalue())
2455
3212
for hook in ConfigHooks['save']:
2458
def external_url(self):
2459
# FIXME: external_url should really accepts an optional relpath
2460
# parameter (bug #750169) :-/ -- vila 2011-04-04
2461
# The following will do in the interim but maybe we don't want to
2462
# expose a path here but rather a config ID and its associated
2463
# object </hand wawe>.
2464
return urlutils.join(self.transport.external_url(), self.file_name)
2466
3215
def get_sections(self):
2467
3216
"""Get the configobj section in the file order.
2469
:returns: An iterable of (name, dict).
3218
:returns: An iterable of (store, section).
2471
3220
# We need a loaded store
2474
except errors.NoSuchFile:
2475
# If the file doesn't exist, there is no sections
3223
except (errors.NoSuchFile, errors.PermissionDenied):
3224
# If the file can't be read, there is no sections
2477
3226
cobj = self._config_obj
2478
3227
if cobj.scalars:
2479
yield self.readonly_section_class(None, cobj)
3228
yield self, self.readonly_section_class(None, cobj)
2480
3229
for section_name in cobj.sections:
2481
yield self.readonly_section_class(section_name, cobj[section_name])
3231
self.readonly_section_class(section_name,
3232
cobj[section_name]))
2483
def get_mutable_section(self, section_name=None):
3234
def get_mutable_section(self, section_id=None):
2484
3235
# We need a loaded store
2487
3238
except errors.NoSuchFile:
2488
3239
# The file doesn't exist, let's pretend it was empty
2489
3240
self._load_from_string('')
2490
if section_name is None:
3241
if section_id in self.dirty_sections:
3242
# We already created a mutable section for this id
3243
return self.dirty_sections[section_id]
3244
if section_id is None:
2491
3245
section = self._config_obj
2493
section = self._config_obj.setdefault(section_name, {})
2494
return self.mutable_section_class(section_name, section)
3247
section = self._config_obj.setdefault(section_id, {})
3248
mutable_section = self.mutable_section_class(section_id, section)
3249
# All mutable sections can become dirty
3250
self.dirty_sections[section_id] = mutable_section
3251
return mutable_section
3253
def quote(self, value):
3255
# configobj conflates automagical list values and quoting
3256
self._config_obj.list_values = True
3257
return self._config_obj._quote(value)
3259
self._config_obj.list_values = False
3261
def unquote(self, value):
3262
if value and isinstance(value, basestring):
3263
# _unquote doesn't handle None nor empty strings nor anything that
3264
# is not a string, really.
3265
value = self._config_obj._unquote(value)
3268
def external_url(self):
3269
# Since an IniFileStore can be used without a file (at least in tests),
3270
# it's better to provide something than raising a NotImplementedError.
3271
# All daughter classes are supposed to provide an implementation
3273
return 'In-Process Store, no URL'
3275
class TransportIniFileStore(IniFileStore):
3276
"""IniFileStore that loads files from a transport.
3278
:ivar transport: The transport object where the config file is located.
3280
:ivar file_name: The config file basename in the transport directory.
3283
def __init__(self, transport, file_name):
3284
"""A Store using a ini file on a Transport
3286
:param transport: The transport object where the config file is located.
3287
:param file_name: The config file basename in the transport directory.
3289
super(TransportIniFileStore, self).__init__()
3290
self.transport = transport
3291
self.file_name = file_name
3293
def _load_content(self):
3295
return self.transport.get_bytes(self.file_name)
3296
except errors.PermissionDenied:
3297
trace.warning("Permission denied while trying to load "
3298
"configuration store %s.", self.external_url())
3301
def _save_content(self, content):
3302
self.transport.put_bytes(self.file_name, content)
3304
def external_url(self):
3305
# FIXME: external_url should really accepts an optional relpath
3306
# parameter (bug #750169) :-/ -- vila 2011-04-04
3307
# The following will do in the interim but maybe we don't want to
3308
# expose a path here but rather a config ID and its associated
3309
# object </hand wawe>.
3310
return urlutils.join(self.transport.external_url(), self.file_name)
2497
3313
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2715
3637
option exists or get its value, which in turn may require to discover
2716
3638
in which sections it can be defined. Both of these (section and option
2717
3639
existence) require loading the store (even partially).
3641
:param name: The queried option.
3643
:param expand: Whether options references should be expanded.
3645
:param convert: Whether the option value should be converted from
3646
unicode (do nothing for non-registered options).
3648
:returns: The value of the option.
2719
3650
# FIXME: No caching of options nor sections yet -- vila 20110503
2721
# Ensuring lazy loading is achieved by delaying section matching (which
2722
# implies querying the persistent storage) until it can't be avoided
2723
# anymore by using callables to describe (possibly empty) section
2725
for section_or_callable in self.sections_def:
2726
# Each section can expand to multiple ones when a callable is used
2727
if callable(section_or_callable):
2728
sections = section_or_callable()
2730
sections = [section_or_callable]
2731
for section in sections:
3652
found_store = None # Where the option value has been found
3653
# If the option is registered, it may provide additional info about
3656
opt = option_registry.get(name)
3661
def expand_and_convert(val):
3662
# This may need to be called in different contexts if the value is
3663
# None or ends up being None during expansion or conversion.
3666
if isinstance(val, basestring):
3667
val = self._expand_options_in_string(val)
3669
trace.warning('Cannot expand "%s":'
3670
' %s does not support option expansion'
3671
% (name, type(val)))
3673
val = found_store.unquote(val)
3675
val = opt.convert_from_unicode(found_store, val)
3678
# First of all, check if the environment can override the configuration
3680
if opt is not None and opt.override_from_env:
3681
value = opt.get_override()
3682
value = expand_and_convert(value)
3684
for store, section in self.iter_sections():
2732
3685
value = section.get(name)
2733
3686
if value is not None:
2735
if value is not None:
2738
# If the option is registered, it may provide a default value
2740
opt = option_registry.get(name)
3689
value = expand_and_convert(value)
3690
if opt is not None and value is None:
3691
# If the option is registered, it may provide a default value
2745
3692
value = opt.get_default()
3693
value = expand_and_convert(value)
2746
3694
for hook in ConfigHooks['get']:
2747
3695
hook(self, name, value)
3698
def expand_options(self, string, env=None):
3699
"""Expand option references in the string in the configuration context.
3701
:param string: The string containing option(s) to expand.
3703
:param env: An option dict defining additional configuration options or
3704
overriding existing ones.
3706
:returns: The expanded string.
3708
return self._expand_options_in_string(string, env)
3710
def _expand_options_in_string(self, string, env=None, _refs=None):
3711
"""Expand options in the string in the configuration context.
3713
:param string: The string to be expanded.
3715
:param env: An option dict defining additional configuration options or
3716
overriding existing ones.
3718
:param _refs: Private list (FIFO) containing the options being expanded
3721
:returns: The expanded string.
3724
# Not much to expand there
3727
# What references are currently resolved (to detect loops)
3730
# We need to iterate until no more refs appear ({{foo}} will need two
3731
# iterations for example).
3736
for is_ref, chunk in iter_option_refs(result):
3738
chunks.append(chunk)
3743
raise errors.OptionExpansionLoop(string, _refs)
3745
value = self._expand_option(name, env, _refs)
3747
raise errors.ExpandingUnknownOption(name, string)
3748
chunks.append(value)
3750
result = ''.join(chunks)
3753
def _expand_option(self, name, env, _refs):
3754
if env is not None and name in env:
3755
# Special case, values provided in env takes precedence over
3759
value = self.get(name, expand=False, convert=False)
3760
value = self._expand_options_in_string(value, env, _refs)
2750
3763
def _get_mutable_section(self):
2751
3764
"""Get the MutableSection for the Stack.
2753
3766
This is where we guarantee that the mutable section is lazily loaded:
2754
3767
this means we won't load the corresponding store before setting a value
2755
3768
or deleting an option. In practice the store will often be loaded but
2756
this allows helps catching some programming errors.
3769
this helps catching some programming errors.
2758
section = self.store.get_mutable_section(self.mutable_section_name)
3772
section = store.get_mutable_section(self.mutable_section_id)
3773
return store, section
2761
3775
def set(self, name, value):
2762
3776
"""Set a new value for the option."""
2763
section = self._get_mutable_section()
2764
section.set(name, value)
3777
store, section = self._get_mutable_section()
3778
section.set(name, store.quote(value))
2765
3779
for hook in ConfigHooks['set']:
2766
3780
hook(self, name, value)
2768
3782
def remove(self, name):
2769
3783
"""Remove an existing option."""
2770
section = self._get_mutable_section()
3784
_, section = self._get_mutable_section()
2771
3785
section.remove(name)
2772
3786
for hook in ConfigHooks['remove']:
2773
3787
hook(self, name)
2800
3843
# Force a write to persistent storage
2801
3844
self.store.save()
3846
def remove(self, name):
3849
super(_CompatibleStack, self).remove(name)
3850
# Force a write to persistent storage
2804
3854
class GlobalStack(_CompatibleStack):
3855
"""Global options only stack.
3857
The following sections are queried:
3859
* command-line overrides,
3861
* the 'DEFAULT' section in bazaar.conf
3863
This stack will use the ``DEFAULT`` section in bazaar.conf as its
2806
3867
def __init__(self):
2808
3868
gstore = GlobalStore()
2809
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
3869
super(GlobalStack, self).__init__(
3870
[self._get_overrides,
3871
NameMatcher(gstore, 'DEFAULT').get_sections],
3872
gstore, mutable_section_id='DEFAULT')
2812
3875
class LocationStack(_CompatibleStack):
3876
"""Per-location options falling back to global options stack.
3879
The following sections are queried:
3881
* command-line overrides,
3883
* the sections matching ``location`` in ``locations.conf``, the order being
3884
defined by the number of path components in the section glob, higher
3885
numbers first (from most specific section to most generic).
3887
* the 'DEFAULT' section in bazaar.conf
3889
This stack will use the ``location`` section in locations.conf as its
2814
3893
def __init__(self, location):
3894
"""Make a new stack for a location and global configuration.
3896
:param location: A URL prefix to """
2815
3897
lstore = LocationStore()
2816
matcher = LocationMatcher(lstore, location)
3898
if location.startswith('file://'):
3899
location = urlutils.local_path_from_url(location)
2817
3900
gstore = GlobalStore()
2818
3901
super(LocationStack, self).__init__(
2819
[matcher.get_sections, gstore.get_sections], lstore)
2821
class BranchStack(_CompatibleStack):
3902
[self._get_overrides,
3903
LocationMatcher(lstore, location).get_sections,
3904
NameMatcher(gstore, 'DEFAULT').get_sections],
3905
lstore, mutable_section_id=location)
3908
class BranchStack(Stack):
3909
"""Per-location options falling back to branch then global options stack.
3911
The following sections are queried:
3913
* command-line overrides,
3915
* the sections matching ``location`` in ``locations.conf``, the order being
3916
defined by the number of path components in the section glob, higher
3917
numbers first (from most specific section to most generic),
3919
* the no-name section in branch.conf,
3921
* the ``DEFAULT`` section in ``bazaar.conf``.
3923
This stack will use the no-name section in ``branch.conf`` as its
2823
3927
def __init__(self, branch):
2824
bstore = BranchStore(branch)
2825
3928
lstore = LocationStore()
2826
matcher = LocationMatcher(lstore, branch.base)
3929
bstore = branch._get_config_store()
2827
3930
gstore = GlobalStore()
2828
3931
super(BranchStack, self).__init__(
2829
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
2831
self.branch = branch
3932
[self._get_overrides,
3933
LocationMatcher(lstore, branch.base).get_sections,
3934
NameMatcher(bstore, None).get_sections,
3935
NameMatcher(gstore, 'DEFAULT').get_sections],
3937
self.branch = branch
3939
def lock_write(self, token=None):
3940
return self.branch.lock_write(token)
3943
return self.branch.unlock()
3946
def set(self, name, value):
3947
super(BranchStack, self).set(name, value)
3948
# Unlocking the branch will trigger a store.save_changes() so the last
3949
# unlock saves all the changes.
3952
def remove(self, name):
3953
super(BranchStack, self).remove(name)
3954
# Unlocking the branch will trigger a store.save_changes() so the last
3955
# unlock saves all the changes.
3958
class RemoteControlStack(_CompatibleStack):
3959
"""Remote control-only options stack."""
3961
# FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
3962
# with the stack used for remote bzr dirs. RemoteControlStack only uses
3963
# control.conf and is used only for stack options.
3965
def __init__(self, bzrdir):
3966
cstore = bzrdir._get_config_store()
3967
super(RemoteControlStack, self).__init__(
3968
[NameMatcher(cstore, None).get_sections],
3970
self.bzrdir = bzrdir
3973
class BranchOnlyStack(Stack):
3974
"""Branch-only options stack."""
3976
# FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
3977
# stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
3978
# -- vila 2011-12-16
3980
def __init__(self, branch):
3981
bstore = branch._get_config_store()
3982
super(BranchOnlyStack, self).__init__(
3983
[NameMatcher(bstore, None).get_sections],
3985
self.branch = branch
3987
def lock_write(self, token=None):
3988
return self.branch.lock_write(token)
3991
return self.branch.unlock()
3994
def set(self, name, value):
3995
super(BranchOnlyStack, self).set(name, value)
3996
# Force a write to persistent storage
3997
self.store.save_changes()
4000
def remove(self, name):
4001
super(BranchOnlyStack, self).remove(name)
4002
# Force a write to persistent storage
4003
self.store.save_changes()
2834
4006
class cmd_config(commands.Command):