155
def signature_policy_from_unicode(signature_string):
156
"""Convert a string to a signing policy."""
157
if signature_string.lower() == 'check-available':
158
return CHECK_IF_POSSIBLE
159
if signature_string.lower() == 'ignore':
161
if signature_string.lower() == 'require':
163
raise ValueError("Invalid signatures policy '%s'"
167
def signing_policy_from_unicode(signature_string):
168
"""Convert a string to a signing policy."""
169
if signature_string.lower() == 'when-required':
170
return SIGN_WHEN_REQUIRED
171
if signature_string.lower() == 'never':
173
if signature_string.lower() == 'always':
175
raise ValueError("Invalid signing policy '%s'"
152
179
class ConfigObj(configobj.ConfigObj):
154
181
def __init__(self, infile=None, **kwargs):
414
441
# add) the final ','
418
def get_user_option_as_int_from_SI(self, option_name, default=None):
445
@deprecated_method(deprecated_in((2, 5, 0)))
446
def get_user_option_as_int_from_SI(self, option_name, default=None):
419
447
"""Get a generic option from a human readable size in SI units, e.g 10MB
421
449
Accepted suffixes are K,M,G. It is case-insensitive and may be followed
422
450
by a trailing b (i.e. Kb, MB). This is intended to be practical and not
425
453
:return Integer, expanded to its base-10 value if a proper SI unit is
426
454
found. If the option doesn't exist, or isn't a value in
427
455
SI units, return default (which defaults to None)
922
949
"""See Config.post_commit."""
923
950
return self._get_user_option('post_commit')
925
def _string_to_signature_policy(self, signature_string):
926
"""Convert a string to a signing policy."""
927
if signature_string.lower() == 'check-available':
928
return CHECK_IF_POSSIBLE
929
if signature_string.lower() == 'ignore':
931
if signature_string.lower() == 'require':
933
raise errors.BzrError("Invalid signatures policy '%s'"
936
def _string_to_signing_policy(self, signature_string):
937
"""Convert a string to a signing policy."""
938
if signature_string.lower() == 'when-required':
939
return SIGN_WHEN_REQUIRED
940
if signature_string.lower() == 'never':
942
if signature_string.lower() == 'always':
944
raise errors.BzrError("Invalid signing policy '%s'"
947
952
def _get_alias(self, value):
949
954
return self._get_parser().get_value("ALIASES",
2314
2332
encoutered, in which config files it can be stored.
2317
def __init__(self, name, default=None, default_from_env=None,
2319
from_unicode=None, invalid=None):
2335
def __init__(self, name, override_from_env=None,
2336
default=None, default_from_env=None,
2337
help=None, from_unicode=None, invalid=None, unquote=True):
2320
2338
"""Build an option definition.
2322
2340
:param name: the name used to refer to the option.
2342
:param override_from_env: A list of environment variables which can
2343
provide override any configuration setting.
2324
2345
:param default: the default value to use when none exist in the config
2325
2346
stores. This is either a string that ``from_unicode`` will convert
2326
into the proper type or a python object that can be stringified (so
2327
only the empty list is supported for example).
2347
into the proper type, a callable returning a unicode string so that
2348
``from_unicode`` can be used on the return value, or a python
2349
object that can be stringified (so only the empty list is supported
2329
2352
:param default_from_env: A list of environment variables which can
2330
2353
provide a default value. 'default' will be used only if none of the
2388
2424
raise errors.ConfigOptionValueError(self.name, unicode_value)
2389
2425
return converted
2427
def get_override(self):
2429
for var in self.override_from_env:
2431
# If the env variable is defined, its value takes precedence
2432
value = os.environ[var].decode(osutils.get_user_encoding())
2391
2438
def get_default(self):
2393
2440
for var in self.default_from_env:
2395
2442
# If the env variable is defined, its value is the default one
2396
value = os.environ[var]
2443
value = os.environ[var].decode(osutils.get_user_encoding())
2398
2445
except KeyError:
2400
2447
if value is None:
2401
2448
# Otherwise, fallback to the value defined at registration
2402
value = self.default
2449
if callable(self.default):
2450
value = self.default()
2451
if not isinstance(value, unicode):
2452
raise AssertionError(
2453
'Callable default values should be unicode')
2455
value = self.default
2405
2458
def get_help_text(self, additional_see_also=None, plain=True):
2421
2474
return int(unicode_str)
2424
def list_from_store(unicode_str):
2425
# ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
2426
if isinstance(unicode_str, (str, unicode)):
2428
# A single value, most probably the user forgot (or didn't care to
2429
# add) the final ','
2477
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
2479
def int_SI_from_store(unicode_str):
2480
"""Convert a human readable size in SI units, e.g 10MB into an integer.
2482
Accepted suffixes are K,M,G. It is case-insensitive and may be followed
2483
by a trailing b (i.e. Kb, MB). This is intended to be practical and not
2486
:return Integer, expanded to its base-10 value if a proper SI unit is
2487
found, None otherwise.
2489
regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
2490
p = re.compile(regexp, re.IGNORECASE)
2491
m = p.match(unicode_str)
2494
val, _, unit = m.groups()
2498
coeff = _unit_suffixes[unit.upper()]
2500
raise ValueError(gettext('{0} is not an SI unit.').format(unit))
2505
def float_from_store(unicode_str):
2506
return float(unicode_str)
2509
# Use a an empty dict to initialize an empty configobj avoiding all
2510
# parsing and encoding checks
2511
_list_converter_config = configobj.ConfigObj(
2512
{}, encoding='utf-8', list_values=True, interpolation=False)
2515
class ListOption(Option):
2517
def __init__(self, name, default=None, default_from_env=None,
2518
help=None, invalid=None):
2519
"""A list Option definition.
2521
This overrides the base class so the conversion from a unicode string
2522
can take quoting into account.
2524
super(ListOption, self).__init__(
2525
name, default=default, default_from_env=default_from_env,
2526
from_unicode=self.from_unicode, help=help,
2527
invalid=invalid, unquote=False)
2529
def from_unicode(self, unicode_str):
2530
if not isinstance(unicode_str, basestring):
2532
# Now inject our string directly as unicode. All callers got their
2533
# value from configobj, so values that need to be quoted are already
2535
_list_converter_config.reset()
2536
_list_converter_config._parse([u"list=%s" % (unicode_str,)])
2537
maybe_list = _list_converter_config['list']
2538
if isinstance(maybe_list, basestring):
2540
# A single value, most probably the user forgot (or didn't care
2541
# to add) the final ','
2544
# The empty string, convert to empty list
2432
# The empty string, convert to empty list
2435
# We rely on ConfigObj providing us with a list already
2547
# We rely on ConfigObj providing us with a list already
2440
2552
class OptionRegistry(registry.Registry):
2481
2593
# Registered options in lexicographical order
2483
2595
option_registry.register(
2596
Option('append_revisions_only',
2597
default=None, from_unicode=bool_from_store, invalid='warning',
2599
Whether to only append revisions to the mainline.
2601
If this is set to true, then it is not possible to change the
2602
existing mainline of the branch.
2604
option_registry.register(
2605
ListOption('acceptable_keys',
2608
List of GPG key patterns which are acceptable for verification.
2610
option_registry.register(
2611
Option('add.maximum_file_size',
2612
default=u'20MB', from_unicode=int_SI_from_store,
2614
Size above which files should be added manually.
2616
Files below this size are added automatically when using ``bzr add`` without
2619
A negative value means disable the size check.
2621
option_registry.register(
2623
default=None, from_unicode=bool_from_store,
2625
Is the branch bound to ``bound_location``.
2627
If set to "True", the branch should act as a checkout, and push each commit to
2628
the bound_location. This option is normally set by ``bind``/``unbind``.
2630
See also: bound_location.
2632
option_registry.register(
2633
Option('bound_location',
2636
The location that commits should go to when acting as a checkout.
2638
This option is normally set by ``bind``.
2642
option_registry.register(
2643
Option('branch.fetch_tags', default=False, from_unicode=bool_from_store,
2645
Whether revisions associated with tags should be fetched.
2647
option_registry.register(
2484
2648
Option('bzr.workingtree.worth_saving_limit', default=10,
2485
2649
from_unicode=int_from_store, invalid='warning',
2493
2657
a file has been touched.
2495
2659
option_registry.register(
2660
Option('check_signatures', default=CHECK_IF_POSSIBLE,
2661
from_unicode=signature_policy_from_unicode,
2663
GPG checking policy.
2665
Possible values: require, ignore, check-available (default)
2667
this option will control whether bzr will require good gpg
2668
signatures, ignore them, or check them if they are
2671
option_registry.register(
2672
Option('create_signatures', default=SIGN_WHEN_REQUIRED,
2673
from_unicode=signing_policy_from_unicode,
2677
Possible values: always, never, when-required (default)
2679
This option controls whether bzr will always create
2680
gpg signatures or not on commits.
2682
option_registry.register(
2496
2683
Option('dirstate.fdatasync', default=True,
2497
2684
from_unicode=bool_from_store,
2503
2690
should not be lost if the machine crashes. See also repository.fdatasync.
2505
2692
option_registry.register(
2506
Option('debug_flags', default=[], from_unicode=list_from_store,
2693
ListOption('debug_flags', default=[],
2507
2694
help='Debug flags to activate.'))
2508
2695
option_registry.register(
2509
2696
Option('default_format', default='2a',
2510
2697
help='Format used when creating branches.'))
2511
2698
option_registry.register(
2699
Option('dpush_strict', default=None,
2700
from_unicode=bool_from_store,
2702
The default value for ``dpush --strict``.
2704
If present, defines the ``--strict`` option default value for checking
2705
uncommitted changes before pushing into a different VCS without any
2706
custom bzr metadata.
2708
option_registry.register(
2512
2709
Option('editor',
2513
2710
help='The command called to launch an editor to enter a message.'))
2514
2711
option_registry.register(
2712
Option('email', override_from_env=['BZR_EMAIL'], default=default_email,
2713
help='The users identity'))
2714
option_registry.register(
2715
Option('gpg_signing_command',
2718
Program to use use for creating signatures.
2720
This should support at least the -u and --clearsign options.
2722
option_registry.register(
2723
Option('gpg_signing_key',
2726
GPG key to use for signing.
2728
This defaults to the first key associated with the users email.
2730
option_registry.register(
2515
2731
Option('ignore_missing_extensions', default=False,
2516
2732
from_unicode=bool_from_store,
2535
2751
Otherwise, bzr will prompt as normal to break the lock.
2537
2753
option_registry.register(
2754
Option('log_format', default='long',
2756
Log format to use when displaying revisions.
2758
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
2759
may be provided by plugins.
2761
option_registry.register(
2538
2762
Option('output_encoding',
2539
2763
help= 'Unicode encoding for output'
2540
2764
' (terminal encoding if not specified).'))
2541
2765
option_registry.register(
2766
Option('parent_location',
2769
The location of the default branch for pull or merge.
2771
This option is normally set when creating a branch, the first ``pull`` or by
2772
``pull --remember``.
2774
option_registry.register(
2775
Option('post_commit', default=None,
2777
Post commit functions.
2779
An ordered list of python functions to call, separated by spaces.
2781
Each function takes branch, rev_id as parameters.
2783
option_registry.register(
2784
Option('public_branch',
2787
A publically-accessible version of this branch.
2789
This implies that the branch setting this option is not publically-accessible.
2790
Used and set by ``bzr send``.
2792
option_registry.register(
2793
Option('push_location',
2796
The location of the default branch for push.
2798
This option is normally set by the first ``push`` or ``push --remember``.
2800
option_registry.register(
2801
Option('push_strict', default=None,
2802
from_unicode=bool_from_store,
2804
The default value for ``push --strict``.
2806
If present, defines the ``--strict`` option default value for checking
2807
uncommitted changes before sending a merge directive.
2809
option_registry.register(
2542
2810
Option('repository.fdatasync', default=True,
2543
2811
from_unicode=bool_from_store,
2548
2816
to physical disk. This is somewhat slower, but means data should not be
2549
2817
lost if the machine crashes. See also dirstate.fdatasync.
2819
option_registry.register_lazy('smtp_server',
2820
'bzrlib.smtp_connection', 'smtp_server')
2821
option_registry.register_lazy('smtp_password',
2822
'bzrlib.smtp_connection', 'smtp_password')
2823
option_registry.register_lazy('smtp_username',
2824
'bzrlib.smtp_connection', 'smtp_username')
2825
option_registry.register(
2826
Option('selftest.timeout',
2828
from_unicode=int_from_store,
2829
help='Abort selftest if one test takes longer than this many seconds',
2832
option_registry.register(
2833
Option('send_strict', default=None,
2834
from_unicode=bool_from_store,
2836
The default value for ``send --strict``.
2838
If present, defines the ``--strict`` option default value for checking
2839
uncommitted changes before sending a bundle.
2842
option_registry.register(
2843
Option('serve.client_timeout',
2844
default=300.0, from_unicode=float_from_store,
2845
help="If we wait for a new request from a client for more than"
2846
" X seconds, consider the client idle, and hangup."))
2847
option_registry.register(
2848
Option('stacked_on_location',
2850
help="""The location where this branch is stacked on."""))
2851
option_registry.register(
2852
Option('submit_branch',
2855
The branch you intend to submit your current work to.
2857
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
2858
by the ``submit:`` revision spec.
2553
2862
class Section(object):
2657
2984
self.external_url())
2987
class CommandLineStore(Store):
2988
"A store to carry command line overrides for the config options."""
2990
def __init__(self, opts=None):
2991
super(CommandLineStore, self).__init__()
2998
# The dict should be cleared but not replaced so it can be shared.
2999
self.options.clear()
3001
def _from_cmdline(self, overrides):
3002
# Reset before accepting new definitions
3004
for over in overrides:
3006
name, value = over.split('=', 1)
3008
raise errors.BzrCommandError(
3009
gettext("Invalid '%s', should be of the form 'name=value'")
3011
self.options[name] = value
3013
def external_url(self):
3014
# Not an url but it makes debugging easier and is never needed
3018
def get_sections(self):
3019
yield self, self.readonly_section_class(None, self.options)
2660
3022
class IniFileStore(Store):
2661
3023
"""A config Store using ConfigObj for storage.
2719
3094
out = StringIO()
2720
3095
self._config_obj.write(out)
2721
self.transport.put_bytes(self.file_name, out.getvalue())
3096
self._save_content(out.getvalue())
2722
3097
for hook in ConfigHooks['save']:
2725
def external_url(self):
2726
# FIXME: external_url should really accepts an optional relpath
2727
# parameter (bug #750169) :-/ -- vila 2011-04-04
2728
# The following will do in the interim but maybe we don't want to
2729
# expose a path here but rather a config ID and its associated
2730
# object </hand wawe>.
2731
return urlutils.join(self.transport.external_url(), self.file_name)
2733
3100
def get_sections(self):
2734
3101
"""Get the configobj section in the file order.
2736
:returns: An iterable of (name, dict).
3103
:returns: An iterable of (store, section).
2738
3105
# We need a loaded store
2741
except errors.NoSuchFile:
2742
# If the file doesn't exist, there is no sections
3108
except (errors.NoSuchFile, errors.PermissionDenied):
3109
# If the file can't be read, there is no sections
2744
3111
cobj = self._config_obj
2745
3112
if cobj.scalars:
2746
yield self.readonly_section_class(None, cobj)
3113
yield self, self.readonly_section_class(None, cobj)
2747
3114
for section_name in cobj.sections:
2748
yield self.readonly_section_class(section_name, cobj[section_name])
3116
self.readonly_section_class(section_name,
3117
cobj[section_name]))
2750
def get_mutable_section(self, section_name=None):
3119
def get_mutable_section(self, section_id=None):
2751
3120
# We need a loaded store
2754
3123
except errors.NoSuchFile:
2755
3124
# The file doesn't exist, let's pretend it was empty
2756
3125
self._load_from_string('')
2757
if section_name is None:
3126
if section_id is None:
2758
3127
section = self._config_obj
2760
section = self._config_obj.setdefault(section_name, {})
2761
return self.mutable_section_class(section_name, section)
3129
section = self._config_obj.setdefault(section_id, {})
3130
return self.mutable_section_class(section_id, section)
3132
def quote(self, value):
3134
# configobj conflates automagical list values and quoting
3135
self._config_obj.list_values = True
3136
return self._config_obj._quote(value)
3138
self._config_obj.list_values = False
3140
def unquote(self, value):
3141
if value and isinstance(value, basestring):
3142
# _unquote doesn't handle None nor empty strings nor anything that
3143
# is not a string, really.
3144
value = self._config_obj._unquote(value)
3148
class TransportIniFileStore(IniFileStore):
3149
"""IniFileStore that loads files from a transport.
3152
def __init__(self, transport, file_name):
3153
"""A Store using a ini file on a Transport
3155
:param transport: The transport object where the config file is located.
3156
:param file_name: The config file basename in the transport directory.
3158
super(TransportIniFileStore, self).__init__()
3159
self.transport = transport
3160
self.file_name = file_name
3162
def _load_content(self):
3164
return self.transport.get_bytes(self.file_name)
3165
except errors.PermissionDenied:
3166
trace.warning("Permission denied while trying to load "
3167
"configuration store %s.", self.external_url())
3170
def _save_content(self, content):
3171
self.transport.put_bytes(self.file_name, content)
3173
def external_url(self):
3174
# FIXME: external_url should really accepts an optional relpath
3175
# parameter (bug #750169) :-/ -- vila 2011-04-04
3176
# The following will do in the interim but maybe we don't want to
3177
# expose a path here but rather a config ID and its associated
3178
# object </hand wawe>.
3179
return urlutils.join(self.transport.external_url(), self.file_name)
2764
3182
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2879
3301
sections = self.store.get_sections()
2880
3302
# Walk the revisions in the order provided
3303
for store, s in sections:
2882
3304
if self.match(s):
2885
def match(self, secion):
3307
def match(self, section):
3308
"""Does the proposed section match.
3310
:param section: A Section object.
3312
:returns: True if the section matches, False otherwise.
2886
3314
raise NotImplementedError(self.match)
3317
class NameMatcher(SectionMatcher):
3319
def __init__(self, store, section_id):
3320
super(NameMatcher, self).__init__(store)
3321
self.section_id = section_id
3323
def match(self, section):
3324
return section.id == self.section_id
2889
3327
class LocationSection(Section):
2891
3329
def __init__(self, section, length, extra_path):
2892
3330
super(LocationSection, self).__init__(section.id, section.options)
2893
3331
self.length = length
2894
3332
self.extra_path = extra_path
3333
self.locals = {'relpath': extra_path,
3334
'basename': urlutils.basename(extra_path)}
2896
def get(self, name, default=None):
3336
def get(self, name, default=None, expand=True):
2897
3337
value = super(LocationSection, self).get(name, default)
2898
if value is not None:
3338
if value is not None and expand:
2899
3339
policy_name = self.get(name + ':policy', None)
2900
3340
policy = _policy_value.get(policy_name, POLICY_NONE)
2901
3341
if policy == POLICY_APPENDPATH:
2902
3342
value = urlutils.join(value, self.extra_path)
3343
# expand section local options right now (since POLICY_APPENDPATH
3344
# will never add options references, it's ok to expand after it).
3346
for is_ref, chunk in iter_option_refs(value):
3348
chunks.append(chunk)
3351
if ref in self.locals:
3352
chunks.append(self.locals[ref])
3354
chunks.append(chunk)
3355
value = ''.join(chunks)
2964
3417
# Finally, we have a valid section
3418
yield self.store, section
3421
_option_ref_re = lazy_regex.lazy_compile('({[^{}\n]+})')
3422
"""Describes an expandable option reference.
3424
We want to match the most embedded reference first.
3426
I.e. for '{{foo}}' we will get '{foo}',
3427
for '{bar{baz}}' we will get '{baz}'
3430
def iter_option_refs(string):
3431
# Split isolate refs so every other chunk is a ref
3433
for chunk in _option_ref_re.split(string):
2968
3438
class Stack(object):
2969
3439
"""A stack of configurations where an option can be defined"""
2971
def __init__(self, sections_def, store=None, mutable_section_name=None):
3441
def __init__(self, sections_def, store=None, mutable_section_id=None):
2972
3442
"""Creates a stack of sections with an optional store for changes.
2974
3444
:param sections_def: A list of Section or callables that returns an
2994
3464
option exists or get its value, which in turn may require to discover
2995
3465
in which sections it can be defined. Both of these (section and option
2996
3466
existence) require loading the store (even partially).
3468
:param name: The queried option.
3470
:param expand: Whether options references should be expanded.
3472
:returns: The value of the option.
2998
3474
# FIXME: No caching of options nor sections yet -- vila 20110503
3476
expand = _get_expand_default_value()
3000
# Ensuring lazy loading is achieved by delaying section matching (which
3001
# implies querying the persistent storage) until it can't be avoided
3002
# anymore by using callables to describe (possibly empty) section
3004
for section_or_callable in self.sections_def:
3005
# Each section can expand to multiple ones when a callable is used
3006
if callable(section_or_callable):
3007
sections = section_or_callable()
3009
sections = [section_or_callable]
3010
for section in sections:
3011
value = section.get(name)
3012
if value is not None:
3014
if value is not None:
3478
found_store = None # Where the option value has been found
3016
3479
# If the option is registered, it may provide additional info about
3017
3480
# value handling
3020
3483
except KeyError:
3021
3484
# Not registered
3024
value = opt.convert_from_unicode(value)
3026
# The conversion failed or there was no value to convert,
3027
# fallback to the default value
3028
value = opt.convert_from_unicode(opt.get_default())
3487
def expand_and_convert(val):
3488
# This may need to be called in different contexts if the value is
3489
# None or ends up being None during expansion or conversion.
3492
if isinstance(val, basestring):
3493
val = self._expand_options_in_string(val)
3495
trace.warning('Cannot expand "%s":'
3496
' %s does not support option expansion'
3497
% (name, type(val)))
3499
val = found_store.unquote(val)
3501
val = opt.convert_from_unicode(found_store, val)
3504
# First of all, check if the environment can override the configuration
3506
if opt is not None and opt.override_from_env:
3507
value = opt.get_override()
3508
value = expand_and_convert(value)
3510
# Ensuring lazy loading is achieved by delaying section matching
3511
# (which implies querying the persistent storage) until it can't be
3512
# avoided anymore by using callables to describe (possibly empty)
3514
for sections in self.sections_def:
3515
for store, section in sections():
3516
value = section.get(name)
3517
if value is not None:
3520
if value is not None:
3522
value = expand_and_convert(value)
3523
if opt is not None and value is None:
3524
# If the option is registered, it may provide a default value
3525
value = opt.get_default()
3526
value = expand_and_convert(value)
3029
3527
for hook in ConfigHooks['get']:
3030
3528
hook(self, name, value)
3531
def expand_options(self, string, env=None):
3532
"""Expand option references in the string in the configuration context.
3534
:param string: The string containing option(s) to expand.
3536
:param env: An option dict defining additional configuration options or
3537
overriding existing ones.
3539
:returns: The expanded string.
3541
return self._expand_options_in_string(string, env)
3543
def _expand_options_in_string(self, string, env=None, _refs=None):
3544
"""Expand options in the string in the configuration context.
3546
:param string: The string to be expanded.
3548
:param env: An option dict defining additional configuration options or
3549
overriding existing ones.
3551
:param _refs: Private list (FIFO) containing the options being expanded
3554
:returns: The expanded string.
3557
# Not much to expand there
3560
# What references are currently resolved (to detect loops)
3563
# We need to iterate until no more refs appear ({{foo}} will need two
3564
# iterations for example).
3569
for is_ref, chunk in iter_option_refs(result):
3571
chunks.append(chunk)
3576
raise errors.OptionExpansionLoop(string, _refs)
3578
value = self._expand_option(name, env, _refs)
3580
raise errors.ExpandingUnknownOption(name, string)
3581
chunks.append(value)
3583
result = ''.join(chunks)
3586
def _expand_option(self, name, env, _refs):
3587
if env is not None and name in env:
3588
# Special case, values provided in env takes precedence over
3592
value = self.get(name, expand=False)
3593
value = self._expand_options_in_string(value, env, _refs)
3033
3596
def _get_mutable_section(self):
3034
3597
"""Get the MutableSection for the Stack.
3036
3599
This is where we guarantee that the mutable section is lazily loaded:
3037
3600
this means we won't load the corresponding store before setting a value
3038
3601
or deleting an option. In practice the store will often be loaded but
3039
this allows helps catching some programming errors.
3602
this helps catching some programming errors.
3041
section = self.store.get_mutable_section(self.mutable_section_name)
3605
section = store.get_mutable_section(self.mutable_section_id)
3606
return store, section
3044
3608
def set(self, name, value):
3045
3609
"""Set a new value for the option."""
3046
section = self._get_mutable_section()
3047
section.set(name, value)
3610
store, section = self._get_mutable_section()
3611
section.set(name, store.quote(value))
3048
3612
for hook in ConfigHooks['set']:
3049
3613
hook(self, name, value)
3051
3615
def remove(self, name):
3052
3616
"""Remove an existing option."""
3053
section = self._get_mutable_section()
3617
_, section = self._get_mutable_section()
3054
3618
section.remove(name)
3055
3619
for hook in ConfigHooks['remove']:
3056
3620
hook(self, name)
3059
3623
# Mostly for debugging use
3060
3624
return "<config.%s(%s)>" % (self.__class__.__name__, id(self))
3626
def _get_overrides(self):
3627
# Hack around library_state.initialize never called
3628
if bzrlib.global_state is not None:
3629
return bzrlib.global_state.cmdline_overrides.get_sections()
3633
class MemoryStack(Stack):
3634
"""A configuration stack defined from a string.
3636
This is mainly intended for tests and requires no disk resources.
3639
def __init__(self, content=None):
3640
"""Create an in-memory stack from a given content.
3642
It uses a single store based on configobj and support reading and
3645
:param content: The initial content of the store. If None, the store is
3646
not loaded and ``_load_from_string`` can and should be used if
3649
store = IniFileStore()
3650
if content is not None:
3651
store._load_from_string(content)
3652
super(MemoryStack, self).__init__(
3653
[store.get_sections], store)
3063
3656
class _CompatibleStack(Stack):
3064
3657
"""Place holder for compatibility with previous design.
3083
3676
# Force a write to persistent storage
3084
3677
self.store.save()
3679
def remove(self, name):
3682
super(_CompatibleStack, self).remove(name)
3683
# Force a write to persistent storage
3087
3687
class GlobalStack(_CompatibleStack):
3088
"""Global options only stack."""
3688
"""Global options only stack.
3690
The following sections are queried:
3692
* command-line overrides,
3694
* the 'DEFAULT' section in bazaar.conf
3696
This stack will use the ``DEFAULT`` section in bazaar.conf as its
3090
3700
def __init__(self):
3092
3701
gstore = GlobalStore()
3093
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
3702
super(GlobalStack, self).__init__(
3703
[self._get_overrides,
3704
NameMatcher(gstore, 'DEFAULT').get_sections],
3705
gstore, mutable_section_id='DEFAULT')
3096
3708
class LocationStack(_CompatibleStack):
3097
"""Per-location options falling back to global options stack."""
3709
"""Per-location options falling back to global options stack.
3712
The following sections are queried:
3714
* command-line overrides,
3716
* the sections matching ``location`` in ``locations.conf``, the order being
3717
defined by the number of path components in the section glob, higher
3718
numbers first (from most specific section to most generic).
3720
* the 'DEFAULT' section in bazaar.conf
3722
This stack will use the ``location`` section in locations.conf as its
3099
3726
def __init__(self, location):
3100
3727
"""Make a new stack for a location and global configuration.
3102
3729
:param location: A URL prefix to """
3103
3730
lstore = LocationStore()
3104
matcher = LocationMatcher(lstore, location)
3731
if location.startswith('file://'):
3732
location = urlutils.local_path_from_url(location)
3105
3733
gstore = GlobalStore()
3106
3734
super(LocationStack, self).__init__(
3107
[matcher.get_sections, gstore.get_sections], lstore)
3735
[self._get_overrides,
3736
LocationMatcher(lstore, location).get_sections,
3737
NameMatcher(gstore, 'DEFAULT').get_sections],
3738
lstore, mutable_section_id=location)
3110
3741
class BranchStack(_CompatibleStack):
3111
"""Per-location options falling back to branch then global options stack."""
3742
"""Per-location options falling back to branch then global options stack.
3744
The following sections are queried:
3746
* command-line overrides,
3748
* the sections matching ``location`` in ``locations.conf``, the order being
3749
defined by the number of path components in the section glob, higher
3750
numbers first (from most specific section to most generic),
3752
* the no-name section in branch.conf,
3754
* the ``DEFAULT`` section in ``bazaar.conf``.
3756
This stack will use the no-name section in ``branch.conf`` as its
3113
3760
def __init__(self, branch):
3114
bstore = BranchStore(branch)
3115
3761
lstore = LocationStore()
3116
matcher = LocationMatcher(lstore, branch.base)
3762
bstore = branch._get_config_store()
3117
3763
gstore = GlobalStore()
3118
3764
super(BranchStack, self).__init__(
3119
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
3765
[self._get_overrides,
3766
LocationMatcher(lstore, branch.base).get_sections,
3767
NameMatcher(bstore, None).get_sections,
3768
NameMatcher(gstore, 'DEFAULT').get_sections],
3121
3770
self.branch = branch
3124
3773
class RemoteControlStack(_CompatibleStack):
3125
3774
"""Remote control-only options stack."""
3776
# FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
3777
# with the stack used for remote bzr dirs. RemoteControlStack only uses
3778
# control.conf and is used only for stack options.
3127
3780
def __init__(self, bzrdir):
3128
cstore = ControlStore(bzrdir)
3781
cstore = bzrdir._get_config_store()
3129
3782
super(RemoteControlStack, self).__init__(
3130
[cstore.get_sections],
3783
[NameMatcher(cstore, None).get_sections],
3132
3785
self.bzrdir = bzrdir
3135
class RemoteBranchStack(_CompatibleStack):
3136
"""Remote branch-only options stack."""
3788
class BranchOnlyStack(_CompatibleStack):
3789
"""Branch-only options stack."""
3791
# FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
3792
# stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
3793
# -- vila 2011-12-16
3138
3795
def __init__(self, branch):
3139
bstore = BranchStore(branch)
3140
super(RemoteBranchStack, self).__init__(
3141
[bstore.get_sections],
3796
bstore = branch._get_config_store()
3797
super(BranchOnlyStack, self).__init__(
3798
[NameMatcher(bstore, None).get_sections],
3143
3800
self.branch = branch
3803
# Use a an empty dict to initialize an empty configobj avoiding all
3804
# parsing and encoding checks
3805
_quoting_config = configobj.ConfigObj(
3806
{}, encoding='utf-8', interpolation=False, list_values=True)
3146
3808
class cmd_config(commands.Command):
3147
3809
__doc__ = """Display, set or remove a configuration option.
3208
3871
# Set the option value
3209
3872
self._set_config_option(name, value, directory, scope)
3211
def _get_configs(self, directory, scope=None):
3212
"""Iterate the configurations specified by ``directory`` and ``scope``.
3874
def _get_stack(self, directory, scope=None):
3875
"""Get the configuration stack specified by ``directory`` and ``scope``.
3214
3877
:param directory: Where the configurations are derived from.
3216
3879
:param scope: A specific config to start from.
3881
# FIXME: scope should allow access to plugin-specific stacks (even
3882
# reduced to the plugin-specific store), related to
3883
# http://pad.lv/788991 -- vila 2011-11-15
3218
3884
if scope is not None:
3219
3885
if scope == 'bazaar':
3220
yield GlobalConfig()
3886
return GlobalStack()
3221
3887
elif scope == 'locations':
3222
yield LocationConfig(directory)
3888
return LocationStack(directory)
3223
3889
elif scope == 'branch':
3224
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3226
yield br.get_config()
3891
controldir.ControlDir.open_containing_tree_or_branch(
3893
return br.get_config_stack()
3894
raise errors.NoSuchConfig(scope)
3229
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3231
yield br.get_config()
3898
controldir.ControlDir.open_containing_tree_or_branch(
3900
return br.get_config_stack()
3232
3901
except errors.NotBranchError:
3233
yield LocationConfig(directory)
3234
yield GlobalConfig()
3902
return LocationStack(directory)
3236
3904
def _show_value(self, name, directory, scope):
3238
for c in self._get_configs(directory, scope):
3241
for (oname, value, section, conf_id, parser) in c._get_options():
3243
# Display only the first value and exit
3245
# FIXME: We need to use get_user_option to take policies
3246
# into account and we need to make sure the option exists
3247
# too (hence the two for loops), this needs a better API
3249
value = c.get_user_option(name)
3250
# Quote the value appropriately
3251
value = parser._quote(value)
3252
self.outf.write('%s\n' % (value,))
3905
conf = self._get_stack(directory, scope)
3906
value = conf.get(name, expand=True)
3907
if value is not None:
3908
# Quote the value appropriately
3909
value = _quoting_config._quote(value)
3910
self.outf.write('%s\n' % (value,))
3256
3912
raise errors.NoSuchConfigOption(name)
3258
3914
def _show_matching_options(self, name, directory, scope):
3261
3917
# avoid the delay introduced by the lazy regexp. But, we still do
3262
3918
# want the nicer errors raised by lazy_regex.
3263
3919
name._compile_and_collapse()
3265
3921
cur_section = None
3266
for c in self._get_configs(directory, scope):
3267
for (oname, value, section, conf_id, parser) in c._get_options():
3268
if name.search(oname):
3269
if cur_conf_id != conf_id:
3270
# Explain where the options are defined
3271
self.outf.write('%s:\n' % (conf_id,))
3272
cur_conf_id = conf_id
3274
if (section not in (None, 'DEFAULT')
3275
and cur_section != section):
3276
# Display the section if it's not the default (or only)
3278
self.outf.write(' [%s]\n' % (section,))
3279
cur_section = section
3280
self.outf.write(' %s = %s\n' % (oname, value))
3922
conf = self._get_stack(directory, scope)
3923
for sections in conf.sections_def:
3924
for store, section in sections():
3925
for oname in section.iter_option_names():
3926
if name.search(oname):
3927
if cur_store_id != store.id:
3928
# Explain where the options are defined
3929
self.outf.write('%s:\n' % (store.id,))
3930
cur_store_id = store.id
3932
if (section.id is not None
3933
and cur_section != section.id):
3934
# Display the section id as it appears in the store
3935
# (None doesn't appear by definition)
3936
self.outf.write(' [%s]\n' % (section.id,))
3937
cur_section = section.id
3938
value = section.get(oname, expand=False)
3939
# Since we don't use the stack, we need to restore a
3942
opt = option_registry.get(oname)
3943
value = opt.convert_from_unicode(store, value)
3945
value = store.unquote(value)
3946
value = _quoting_config._quote(value)
3947
self.outf.write(' %s = %s\n' % (oname, value))
3282
3949
def _set_config_option(self, name, value, directory, scope):
3283
for conf in self._get_configs(directory, scope):
3284
conf.set_user_option(name, value)
3287
raise errors.NoSuchConfig(scope)
3950
conf = self._get_stack(directory, scope)
3951
conf.set(name, value)
3289
3953
def _remove_config_option(self, name, directory, scope):
3290
3954
if name is None:
3291
3955
raise errors.BzrCommandError(
3292
3956
'--remove expects an option to remove.')
3294
for conf in self._get_configs(directory, scope):
3295
for (section_name, section, conf_id) in conf._get_sections():
3296
if scope is not None and conf_id != scope:
3297
# Not the right configuration file
3300
if conf_id != conf.config_id():
3301
conf = self._get_configs(directory, conf_id).next()
3302
# We use the first section in the first config where the
3303
# option is defined to remove it
3304
conf.remove_user_option(name, section_name)
3309
raise errors.NoSuchConfig(scope)
3957
conf = self._get_stack(directory, scope)
3311
3961
raise errors.NoSuchConfigOption(name)
3313
3964
# Test registries
3315
3966
# We need adapters that can build a Store or a Stack in a test context. Test