1536
1492
TODO: Global option --config-dir to override this.
1538
base = os.environ.get('BZR_HOME', None)
1494
base = osutils.path_from_environ('BZR_HOME')
1539
1495
if sys.platform == 'win32':
1540
# environ variables on Windows are in user encoding/mbcs. So decode
1542
if base is not None:
1543
base = base.decode('mbcs')
1545
base = win32utils.get_appdata_location_unicode()
1547
base = os.environ.get('HOME', None)
1548
if base is not None:
1549
base = base.decode('mbcs')
1551
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1497
base = win32utils.get_appdata_location()
1499
base = win32utils.get_home_location()
1500
# GZ 2012-02-01: Really the two level subdirs only make sense inside
1501
# APPDATA, but hard to move. See bug 348640 for more.
1553
1502
return osutils.pathjoin(base, 'bazaar', '2.0')
1555
if base is not None:
1556
base = base.decode(osutils._fs_enc)
1557
if sys.platform == 'darwin':
1559
# this takes into account $HOME
1560
base = os.path.expanduser("~")
1561
return osutils.pathjoin(base, '.bazaar')
1564
xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
1504
# GZ 2012-02-01: What should OSX use instead of XDG if anything?
1505
if sys.platform != 'darwin':
1506
xdg_dir = osutils.path_from_environ('XDG_CONFIG_HOME')
1565
1507
if xdg_dir is None:
1566
xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
1508
xdg_dir = osutils.pathjoin(osutils._get_home_dir(), ".config")
1567
1509
xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
1568
1510
if osutils.isdir(xdg_dir):
1570
1512
"Using configuration in XDG directory %s." % xdg_dir)
1572
base = os.path.expanduser("~")
1573
return osutils.pathjoin(base, ".bazaar")
1514
base = osutils._get_home_dir()
1515
return osutils.pathjoin(base, ".bazaar")
1576
1518
def config_filename():
2319
2276
encoutered, in which config files it can be stored.
2322
def __init__(self, name, default=None, default_from_env=None,
2324
from_unicode=None, invalid=None):
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):
2325
2282
"""Build an option definition.
2327
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.
2329
2289
:param default: the default value to use when none exist in the config
2330
2290
stores. This is either a string that ``from_unicode`` will convert
2331
into the proper type or a python object that can be stringified (so
2332
only the empty list is supported for example).
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
2334
2296
:param default_from_env: A list of environment variables which can
2335
2297
provide a default value. 'default' will be used only if none of the
2361
2331
raise AssertionError(
2362
2332
'Only empty lists are supported as default values')
2363
2333
self.default = u','
2364
elif isinstance(default, (str, unicode, bool, int)):
2334
elif isinstance(default, (str, unicode, bool, int, float)):
2365
2335
# Rely on python to convert strings, booleans and integers
2366
2336
self.default = u'%s' % (default,)
2337
elif callable(default):
2338
self.default = default
2368
2340
# other python objects are not expected
2369
2341
raise AssertionError('%r is not supported as a default value'
2371
2343
self.default_from_env = default_from_env
2373
2345
self.from_unicode = from_unicode
2346
self.unquote = unquote
2374
2347
if invalid and invalid not in ('warning', 'error'):
2375
2348
raise AssertionError("%s not supported for 'invalid'" % (invalid,))
2376
2349
self.invalid = invalid
2378
def convert_from_unicode(self, unicode_value):
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)
2379
2358
if self.from_unicode is None or unicode_value is None:
2380
2359
# Don't convert or nothing to convert
2381
2360
return unicode_value
2426
2426
return int(unicode_str)
2429
_unit_suffixes = dict(K=10**3, M=10**6, G=10**9)
2431
def int_SI_from_store(unicode_str):
2432
"""Convert a human readable size in SI units, e.g 10MB into an integer.
2434
Accepted suffixes are K,M,G. It is case-insensitive and may be followed
2435
by a trailing b (i.e. Kb, MB). This is intended to be practical and not
2438
:return Integer, expanded to its base-10 value if a proper SI unit is
2439
found, None otherwise.
2441
regexp = "^(\d+)(([" + ''.join(_unit_suffixes) + "])b?)?$"
2442
p = re.compile(regexp, re.IGNORECASE)
2443
m = p.match(unicode_str)
2446
val, _, unit = m.groups()
2450
coeff = _unit_suffixes[unit.upper()]
2452
raise ValueError(gettext('{0} is not an SI unit.').format(unit))
2457
def float_from_store(unicode_str):
2458
return float(unicode_str)
2429
2461
# Use a an empty dict to initialize an empty configobj avoiding all
2430
2462
# parsing and encoding checks
2431
2463
_list_converter_config = configobj.ConfigObj(
2432
2464
{}, encoding='utf-8', list_values=True, interpolation=False)
2435
def list_from_store(unicode_str):
2436
if not isinstance(unicode_str, basestring):
2438
# Now inject our string directly as unicode. All callers got their value
2439
# from configobj, so values that need to be quoted are already properly
2441
_list_converter_config.reset()
2442
_list_converter_config._parse([u"list=%s" % (unicode_str,)])
2443
maybe_list = _list_converter_config['list']
2444
# ConfigObj return '' instead of u''. Use 'str' below to catch all cases.
2445
if isinstance(maybe_list, basestring):
2447
# A single value, most probably the user forgot (or didn't care to
2448
# add) the final ','
2467
class ListOption(Option):
2469
def __init__(self, name, default=None, default_from_env=None,
2470
help=None, invalid=None):
2471
"""A list Option definition.
2473
This overrides the base class so the conversion from a unicode string
2474
can take quoting into account.
2476
super(ListOption, self).__init__(
2477
name, default=default, default_from_env=default_from_env,
2478
from_unicode=self.from_unicode, help=help,
2479
invalid=invalid, unquote=False)
2481
def from_unicode(self, unicode_str):
2482
if not isinstance(unicode_str, basestring):
2484
# Now inject our string directly as unicode. All callers got their
2485
# value from configobj, so values that need to be quoted are already
2487
_list_converter_config.reset()
2488
_list_converter_config._parse([u"list=%s" % (unicode_str,)])
2489
maybe_list = _list_converter_config['list']
2490
if isinstance(maybe_list, basestring):
2492
# A single value, most probably the user forgot (or didn't care
2493
# to add) the final ','
2496
# The empty string, convert to empty list
2451
# The empty string, convert to empty list
2454
# We rely on ConfigObj providing us with a list already
2499
# We rely on ConfigObj providing us with a list already
2504
class RegistryOption(Option):
2505
"""Option for a choice from a registry."""
2507
def __init__(self, name, registry, default_from_env=None,
2508
help=None, invalid=None):
2509
"""A registry based Option definition.
2511
This overrides the base class so the conversion from a unicode string
2512
can take quoting into account.
2514
super(RegistryOption, self).__init__(
2515
name, default=lambda: unicode(registry.default_key),
2516
default_from_env=default_from_env,
2517
from_unicode=self.from_unicode, help=help,
2518
invalid=invalid, unquote=False)
2519
self.registry = registry
2521
def from_unicode(self, unicode_str):
2522
if not isinstance(unicode_str, basestring):
2525
return self.registry.get(unicode_str)
2528
"Invalid value %s for %s."
2529
"See help for a list of possible values." % (unicode_str,
2534
ret = [self._help, "\n\nThe following values are supported:\n"]
2535
for key in self.registry.keys():
2536
ret.append(" %s - %s\n" % (key, self.registry.get_help(key)))
2459
2540
class OptionRegistry(registry.Registry):
2500
2581
# Registered options in lexicographical order
2502
2583
option_registry.register(
2584
Option('append_revisions_only',
2585
default=None, from_unicode=bool_from_store, invalid='warning',
2587
Whether to only append revisions to the mainline.
2589
If this is set to true, then it is not possible to change the
2590
existing mainline of the branch.
2592
option_registry.register(
2593
ListOption('acceptable_keys',
2596
List of GPG key patterns which are acceptable for verification.
2598
option_registry.register(
2599
Option('add.maximum_file_size',
2600
default=u'20MB', from_unicode=int_SI_from_store,
2602
Size above which files should be added manually.
2604
Files below this size are added automatically when using ``bzr add`` without
2607
A negative value means disable the size check.
2609
option_registry.register(
2611
default=None, from_unicode=bool_from_store,
2613
Is the branch bound to ``bound_location``.
2615
If set to "True", the branch should act as a checkout, and push each commit to
2616
the bound_location. This option is normally set by ``bind``/``unbind``.
2618
See also: bound_location.
2620
option_registry.register(
2621
Option('bound_location',
2624
The location that commits should go to when acting as a checkout.
2626
This option is normally set by ``bind``.
2630
option_registry.register(
2631
Option('branch.fetch_tags', default=False, from_unicode=bool_from_store,
2633
Whether revisions associated with tags should be fetched.
2635
option_registry.register_lazy(
2636
'bzr.transform.orphan_policy', 'bzrlib.transform', 'opt_transform_orphan')
2637
option_registry.register(
2503
2638
Option('bzr.workingtree.worth_saving_limit', default=10,
2504
2639
from_unicode=int_from_store, invalid='warning',
2512
2647
a file has been touched.
2514
2649
option_registry.register(
2650
Option('bugtracker', default=None,
2652
Default bug tracker to use.
2654
This bug tracker will be used for example when marking bugs
2655
as fixed using ``bzr commit --fixes``, if no explicit
2656
bug tracker was specified.
2658
option_registry.register(
2659
Option('check_signatures', default=CHECK_IF_POSSIBLE,
2660
from_unicode=signature_policy_from_unicode,
2662
GPG checking policy.
2664
Possible values: require, ignore, check-available (default)
2666
this option will control whether bzr will require good gpg
2667
signatures, ignore them, or check them if they are
2670
option_registry.register(
2671
Option('child_submit_format',
2672
help='''The preferred format of submissions to this branch.'''))
2673
option_registry.register(
2674
Option('child_submit_to',
2675
help='''Where submissions to this branch are mailed to.'''))
2676
option_registry.register(
2677
Option('create_signatures', default=SIGN_WHEN_REQUIRED,
2678
from_unicode=signing_policy_from_unicode,
2682
Possible values: always, never, when-required (default)
2684
This option controls whether bzr will always create
2685
gpg signatures or not on commits.
2687
option_registry.register(
2515
2688
Option('dirstate.fdatasync', default=True,
2516
2689
from_unicode=bool_from_store,
2564
2756
Otherwise, bzr will prompt as normal to break the lock.
2566
2758
option_registry.register(
2759
Option('log_format', default='long',
2761
Log format to use when displaying revisions.
2763
Standard log formats are ``long``, ``short`` and ``line``. Additional formats
2764
may be provided by plugins.
2766
option_registry.register_lazy('mail_client', 'bzrlib.mail_client',
2768
option_registry.register(
2567
2769
Option('output_encoding',
2568
2770
help= 'Unicode encoding for output'
2569
2771
' (terminal encoding if not specified).'))
2570
2772
option_registry.register(
2773
Option('parent_location',
2776
The location of the default branch for pull or merge.
2778
This option is normally set when creating a branch, the first ``pull`` or by
2779
``pull --remember``.
2781
option_registry.register(
2782
Option('post_commit', default=None,
2784
Post commit functions.
2786
An ordered list of python functions to call, separated by spaces.
2788
Each function takes branch, rev_id as parameters.
2790
option_registry.register(
2791
Option('public_branch',
2794
A publically-accessible version of this branch.
2796
This implies that the branch setting this option is not publically-accessible.
2797
Used and set by ``bzr send``.
2799
option_registry.register(
2800
Option('push_location',
2803
The location of the default branch for push.
2805
This option is normally set by the first ``push`` or ``push --remember``.
2807
option_registry.register(
2571
2808
Option('push_strict', default=None,
2572
2809
from_unicode=bool_from_store,
2593
2843
The default value for ``send --strict``.
2595
2845
If present, defines the ``--strict`` option default value for checking
2596
uncommitted changes before pushing.
2846
uncommitted changes before sending a bundle.
2849
option_registry.register(
2850
Option('serve.client_timeout',
2851
default=300.0, from_unicode=float_from_store,
2852
help="If we wait for a new request from a client for more than"
2853
" X seconds, consider the client idle, and hangup."))
2854
option_registry.register(
2855
Option('stacked_on_location',
2857
help="""The location where this branch is stacked on."""))
2858
option_registry.register(
2859
Option('submit_branch',
2862
The branch you intend to submit your current work to.
2864
This is automatically set by ``bzr send`` and ``bzr merge``, and is also used
2865
by the ``submit:`` revision spec.
2867
option_registry.register(
2869
help='''Where submissions from this branch are mailed to.'''))
2870
option_registry.register(
2871
ListOption('suppress_warnings',
2873
help="List of warning classes to suppress."))
2874
option_registry.register(
2875
Option('validate_signatures_in_log', default=False,
2876
from_unicode=bool_from_store, invalid='warning',
2877
help='''Whether to validate signatures in bzr log.'''))
2878
option_registry.register_lazy('ssl.ca_certs',
2879
'bzrlib.transport.http._urllib2_wrappers', 'opt_ssl_ca_certs')
2881
option_registry.register_lazy('ssl.cert_reqs',
2882
'bzrlib.transport.http._urllib2_wrappers', 'opt_ssl_cert_reqs')
2600
2885
class Section(object):
2601
2886
"""A section defines a dict of option name => value.
2642
2933
self.orig[name] = self.get(name, None)
2643
2934
del self.options[name]
2936
def reset_changes(self):
2939
def apply_changes(self, dirty, store):
2940
"""Apply option value changes.
2942
``self`` has been reloaded from the persistent storage. ``dirty``
2943
contains the changes made since the previous loading.
2945
:param dirty: the mutable section containing the changes.
2947
:param store: the store containing the section
2949
for k, expected in dirty.orig.iteritems():
2950
actual = dirty.get(k, _DeletedOption)
2951
reloaded = self.get(k, _NewlyCreatedOption)
2952
if actual is _DeletedOption:
2953
if k in self.options:
2957
# Report concurrent updates in an ad-hoc way. This should only
2958
# occurs when different processes try to update the same option
2959
# which is not supported (as in: the config framework is not meant
2960
# to be used as a sharing mechanism).
2961
if expected != reloaded:
2962
if actual is _DeletedOption:
2963
actual = '<DELETED>'
2964
if reloaded is _NewlyCreatedOption:
2965
reloaded = '<CREATED>'
2966
if expected is _NewlyCreatedOption:
2967
expected = '<CREATED>'
2968
# Someone changed the value since we get it from the persistent
2970
trace.warning(gettext(
2971
"Option {0} in section {1} of {2} was changed"
2972
" from {3} to {4}. The {5} value will be saved.".format(
2973
k, self.id, store.external_url(), expected,
2975
# No need to keep track of these changes
2976
self.reset_changes()
2646
2979
class Store(object):
2647
2980
"""Abstract interface to persistent storage for configuration options."""
2678
3016
raise NotImplementedError(self.unload)
3018
def quote(self, value):
3019
"""Quote a configuration option value for storing purposes.
3021
This allows Stacks to present values as they will be stored.
3025
def unquote(self, value):
3026
"""Unquote a configuration option value into unicode.
3028
The received value is quoted as stored.
2680
3032
def save(self):
2681
3033
"""Saves the Store to persistent storage."""
2682
3034
raise NotImplementedError(self.save)
3036
def _need_saving(self):
3037
for s in self.dirty_sections.values():
3039
# At least one dirty section contains a modification
3043
def apply_changes(self, dirty_sections):
3044
"""Apply changes from dirty sections while checking for coherency.
3046
The Store content is discarded and reloaded from persistent storage to
3047
acquire up-to-date values.
3049
Dirty sections are MutableSection which kept track of the value they
3050
are expected to update.
3052
# We need an up-to-date version from the persistent storage, unload the
3053
# store. The reload will occur when needed (triggered by the first
3054
# get_mutable_section() call below.
3056
# Apply the changes from the preserved dirty sections
3057
for section_id, dirty in dirty_sections.iteritems():
3058
clean = self.get_mutable_section(section_id)
3059
clean.apply_changes(dirty, self)
3060
# Everything is clean now
3061
self.dirty_sections = {}
3063
def save_changes(self):
3064
"""Saves the Store to persistent storage if changes occurred.
3066
Apply the changes recorded in the mutable sections to a store content
3067
refreshed from persistent storage.
3069
raise NotImplementedError(self.save_changes)
2684
3071
def external_url(self):
2685
3072
raise NotImplementedError(self.external_url)
2687
3074
def get_sections(self):
2688
3075
"""Returns an ordered iterable of existing sections.
2690
:returns: An iterable of (name, dict).
3077
:returns: An iterable of (store, section).
2692
3079
raise NotImplementedError(self.get_sections)
2694
def get_mutable_section(self, section_name=None):
3081
def get_mutable_section(self, section_id=None):
2695
3082
"""Returns the specified mutable section.
2697
:param section_name: The section identifier
3084
:param section_id: The section identifier
2699
3086
raise NotImplementedError(self.get_mutable_section)
2704
3091
self.external_url())
3094
class CommandLineStore(Store):
3095
"A store to carry command line overrides for the config options."""
3097
def __init__(self, opts=None):
3098
super(CommandLineStore, self).__init__()
3105
# The dict should be cleared but not replaced so it can be shared.
3106
self.options.clear()
3108
def _from_cmdline(self, overrides):
3109
# Reset before accepting new definitions
3111
for over in overrides:
3113
name, value = over.split('=', 1)
3115
raise errors.BzrCommandError(
3116
gettext("Invalid '%s', should be of the form 'name=value'")
3118
self.options[name] = value
3120
def external_url(self):
3121
# Not an url but it makes debugging easier and is never needed
3125
def get_sections(self):
3126
yield self, self.readonly_section_class(None, self.options)
2707
3129
class IniFileStore(Store):
2708
3130
"""A config Store using ConfigObj for storage.
2710
:ivar transport: The transport object where the config file is located.
2712
:ivar file_name: The config file basename in the transport directory.
2714
3132
:ivar _config_obj: Private member to hold the ConfigObj instance used to
2715
3133
serialize/deserialize the config file.
2718
def __init__(self, transport, file_name):
2719
3137
"""A config Store using ConfigObj for storage.
2721
:param transport: The transport object where the config file is located.
2723
:param file_name: The config file basename in the transport directory.
2725
3139
super(IniFileStore, self).__init__()
2726
self.transport = transport
2727
self.file_name = file_name
2728
3140
self._config_obj = None
2730
3142
def is_loaded(self):
2797
3227
cobj = self._config_obj
2798
3228
if cobj.scalars:
2799
yield self.readonly_section_class(None, cobj)
3229
yield self, self.readonly_section_class(None, cobj)
2800
3230
for section_name in cobj.sections:
2801
yield self.readonly_section_class(section_name, cobj[section_name])
3232
self.readonly_section_class(section_name,
3233
cobj[section_name]))
2803
def get_mutable_section(self, section_name=None):
3235
def get_mutable_section(self, section_id=None):
2804
3236
# We need a loaded store
2807
3239
except errors.NoSuchFile:
2808
3240
# The file doesn't exist, let's pretend it was empty
2809
3241
self._load_from_string('')
2810
if section_name is None:
3242
if section_id in self.dirty_sections:
3243
# We already created a mutable section for this id
3244
return self.dirty_sections[section_id]
3245
if section_id is None:
2811
3246
section = self._config_obj
2813
section = self._config_obj.setdefault(section_name, {})
2814
return self.mutable_section_class(section_name, section)
3248
section = self._config_obj.setdefault(section_id, {})
3249
mutable_section = self.mutable_section_class(section_id, section)
3250
# All mutable sections can become dirty
3251
self.dirty_sections[section_id] = mutable_section
3252
return mutable_section
3254
def quote(self, value):
3256
# configobj conflates automagical list values and quoting
3257
self._config_obj.list_values = True
3258
return self._config_obj._quote(value)
3260
self._config_obj.list_values = False
3262
def unquote(self, value):
3263
if value and isinstance(value, basestring):
3264
# _unquote doesn't handle None nor empty strings nor anything that
3265
# is not a string, really.
3266
value = self._config_obj._unquote(value)
3269
def external_url(self):
3270
# Since an IniFileStore can be used without a file (at least in tests),
3271
# it's better to provide something than raising a NotImplementedError.
3272
# All daughter classes are supposed to provide an implementation
3274
return 'In-Process Store, no URL'
3276
class TransportIniFileStore(IniFileStore):
3277
"""IniFileStore that loads files from a transport.
3279
:ivar transport: The transport object where the config file is located.
3281
:ivar file_name: The config file basename in the transport directory.
3284
def __init__(self, transport, file_name):
3285
"""A Store using a ini file on a Transport
3287
:param transport: The transport object where the config file is located.
3288
:param file_name: The config file basename in the transport directory.
3290
super(TransportIniFileStore, self).__init__()
3291
self.transport = transport
3292
self.file_name = file_name
3294
def _load_content(self):
3296
return self.transport.get_bytes(self.file_name)
3297
except errors.PermissionDenied:
3298
trace.warning("Permission denied while trying to load "
3299
"configuration store %s.", self.external_url())
3302
def _save_content(self, content):
3303
self.transport.put_bytes(self.file_name, content)
3305
def external_url(self):
3306
# FIXME: external_url should really accepts an optional relpath
3307
# parameter (bug #750169) :-/ -- vila 2011-04-04
3308
# The following will do in the interim but maybe we don't want to
3309
# expose a path here but rather a config ID and its associated
3310
# object </hand wawe>.
3311
return urlutils.join(self.transport.external_url(), self.file_name)
2817
3314
# Note that LockableConfigObjStore inherits from ConfigObjStore because we need
2958
3445
class LocationSection(Section):
2960
def __init__(self, section, length, extra_path):
3447
def __init__(self, section, extra_path, branch_name=None):
2961
3448
super(LocationSection, self).__init__(section.id, section.options)
2962
self.length = length
2963
3449
self.extra_path = extra_path
3450
if branch_name is None:
3452
self.locals = {'relpath': extra_path,
3453
'basename': urlutils.basename(extra_path),
3454
'branchname': branch_name}
2965
def get(self, name, default=None):
3456
def get(self, name, default=None, expand=True):
2966
3457
value = super(LocationSection, self).get(name, default)
2967
if value is not None:
3458
if value is not None and expand:
2968
3459
policy_name = self.get(name + ':policy', None)
2969
3460
policy = _policy_value.get(policy_name, POLICY_NONE)
2970
3461
if policy == POLICY_APPENDPATH:
2971
3462
value = urlutils.join(value, self.extra_path)
3463
# expand section local options right now (since POLICY_APPENDPATH
3464
# will never add options references, it's ok to expand after it).
3466
for is_ref, chunk in iter_option_refs(value):
3468
chunks.append(chunk)
3471
if ref in self.locals:
3472
chunks.append(self.locals[ref])
3474
chunks.append(chunk)
3475
value = ''.join(chunks)
3479
class StartingPathMatcher(SectionMatcher):
3480
"""Select sections for a given location respecting the Store order."""
3482
# FIXME: Both local paths and urls can be used for section names as well as
3483
# ``location`` to stay consistent with ``LocationMatcher`` which itself
3484
# inherited the fuzziness from the previous ``LocationConfig``
3485
# implementation. We probably need to revisit which encoding is allowed for
3486
# both ``location`` and section names and how we normalize
3487
# them. http://pad.lv/85479, http://pad.lv/437009 and http://359320 are
3488
# related too. -- vila 2012-01-04
3490
def __init__(self, store, location):
3491
super(StartingPathMatcher, self).__init__(store)
3492
if location.startswith('file://'):
3493
location = urlutils.local_path_from_url(location)
3494
self.location = location
3496
def get_sections(self):
3497
"""Get all sections matching ``location`` in the store.
3499
The most generic sections are described first in the store, then more
3500
specific ones can be provided for reduced scopes.
3502
The returned section are therefore returned in the reversed order so
3503
the most specific ones can be found first.
3505
location_parts = self.location.rstrip('/').split('/')
3508
# Later sections are more specific, they should be returned first
3509
for _, section in reversed(list(store.get_sections())):
3510
if section.id is None:
3511
# The no-name section is always included if present
3512
yield store, LocationSection(section, self.location)
3514
section_path = section.id
3515
if section_path.startswith('file://'):
3516
# the location is already a local path or URL, convert the
3517
# section id to the same format
3518
section_path = urlutils.local_path_from_url(section_path)
3519
if (self.location.startswith(section_path)
3520
or fnmatch.fnmatch(self.location, section_path)):
3521
section_parts = section_path.rstrip('/').split('/')
3522
extra_path = '/'.join(location_parts[len(section_parts):])
3523
yield store, LocationSection(section, extra_path)
2975
3526
class LocationMatcher(SectionMatcher):
2977
3528
def __init__(self, store, location):
2978
3529
super(LocationMatcher, self).__init__(store)
3530
url, params = urlutils.split_segment_parameters(location)
2979
3531
if location.startswith('file://'):
2980
3532
location = urlutils.local_path_from_url(location)
2981
3533
self.location = location
3534
branch_name = params.get('branch')
3535
if branch_name is None:
3536
self.branch_name = urlutils.basename(self.location)
3538
self.branch_name = urlutils.unescape(branch_name)
2983
3540
def _get_matching_sections(self):
2984
3541
"""Get all sections matching ``location``."""
3033
3591
# Finally, we have a valid section
3592
yield self.store, section
3595
_option_ref_re = lazy_regex.lazy_compile('({[^{}\n]+})')
3596
"""Describes an expandable option reference.
3598
We want to match the most embedded reference first.
3600
I.e. for '{{foo}}' we will get '{foo}',
3601
for '{bar{baz}}' we will get '{baz}'
3604
def iter_option_refs(string):
3605
# Split isolate refs so every other chunk is a ref
3607
for chunk in _option_ref_re.split(string):
3037
3612
class Stack(object):
3038
3613
"""A stack of configurations where an option can be defined"""
3040
_option_ref_re = lazy_regex.lazy_compile('({[^{}]+})')
3041
"""Describes an exandable option reference.
3043
We want to match the most embedded reference first.
3045
I.e. for '{{foo}}' we will get '{foo}',
3046
for '{bar{baz}}' we will get '{baz}'
3049
def __init__(self, sections_def, store=None, mutable_section_name=None):
3615
def __init__(self, sections_def, store=None, mutable_section_id=None):
3050
3616
"""Creates a stack of sections with an optional store for changes.
3052
3618
:param sections_def: A list of Section or callables that returns an
3056
3622
:param store: The optional Store where modifications will be
3057
3623
recorded. If none is specified, no modifications can be done.
3059
:param mutable_section_name: The name of the MutableSection where
3060
changes are recorded. This requires the ``store`` parameter to be
3625
:param mutable_section_id: The id of the MutableSection where changes
3626
are recorded. This requires the ``store`` parameter to be
3063
3629
self.sections_def = sections_def
3064
3630
self.store = store
3065
self.mutable_section_name = mutable_section_name
3067
def get(self, name, expand=None):
3631
self.mutable_section_id = mutable_section_id
3633
def iter_sections(self):
3634
"""Iterate all the defined sections."""
3635
# Ensuring lazy loading is achieved by delaying section matching (which
3636
# implies querying the persistent storage) until it can't be avoided
3637
# anymore by using callables to describe (possibly empty) section
3639
for sections in self.sections_def:
3640
for store, section in sections():
3641
yield store, section
3643
def get(self, name, expand=True, convert=True):
3068
3644
"""Return the *first* option value found in the sections.
3070
3646
This is where we guarantee that sections coming from Store are loaded
3117
3680
trace.warning('Cannot expand "%s":'
3118
3681
' %s does not support option expansion'
3119
3682
% (name, type(val)))
3121
val = opt.convert_from_unicode(val)
3684
val = found_store.unquote(val)
3686
val = opt.convert_from_unicode(found_store, val)
3123
value = expand_and_convert(value)
3124
if opt is not None and value is None:
3125
# If the option is registered, it may provide a default value
3126
value = opt.get_default()
3127
value = expand_and_convert(value)
3689
# First of all, check if the environment can override the configuration
3691
if opt is not None and opt.override_from_env:
3692
value = opt.get_override()
3693
value = expand_and_convert(value)
3695
for store, section in self.iter_sections():
3696
value = section.get(name)
3697
if value is not None:
3700
value = expand_and_convert(value)
3701
if opt is not None and value is None:
3702
# If the option is registered, it may provide a default value
3703
value = opt.get_default()
3704
value = expand_and_convert(value)
3128
3705
for hook in ConfigHooks['get']:
3129
3706
hook(self, name, value)
3257
3854
# Force a write to persistent storage
3258
3855
self.store.save()
3857
def remove(self, name):
3860
super(_CompatibleStack, self).remove(name)
3861
# Force a write to persistent storage
3261
3865
class GlobalStack(_CompatibleStack):
3262
"""Global options only stack."""
3866
"""Global options only stack.
3868
The following sections are queried:
3870
* command-line overrides,
3872
* the 'DEFAULT' section in bazaar.conf
3874
This stack will use the ``DEFAULT`` section in bazaar.conf as its
3264
3878
def __init__(self):
3266
3879
gstore = GlobalStore()
3267
super(GlobalStack, self).__init__([gstore.get_sections], gstore)
3880
super(GlobalStack, self).__init__(
3881
[self._get_overrides,
3882
NameMatcher(gstore, 'DEFAULT').get_sections],
3883
gstore, mutable_section_id='DEFAULT')
3270
3886
class LocationStack(_CompatibleStack):
3271
"""Per-location options falling back to global options stack."""
3887
"""Per-location options falling back to global options stack.
3890
The following sections are queried:
3892
* command-line overrides,
3894
* the sections matching ``location`` in ``locations.conf``, the order being
3895
defined by the number of path components in the section glob, higher
3896
numbers first (from most specific section to most generic).
3898
* the 'DEFAULT' section in bazaar.conf
3900
This stack will use the ``location`` section in locations.conf as its
3273
3904
def __init__(self, location):
3274
3905
"""Make a new stack for a location and global configuration.
3276
3907
:param location: A URL prefix to """
3277
3908
lstore = LocationStore()
3278
matcher = LocationMatcher(lstore, location)
3909
if location.startswith('file://'):
3910
location = urlutils.local_path_from_url(location)
3279
3911
gstore = GlobalStore()
3280
3912
super(LocationStack, self).__init__(
3281
[matcher.get_sections, gstore.get_sections], lstore)
3284
class BranchStack(_CompatibleStack):
3285
"""Per-location options falling back to branch then global options stack."""
3913
[self._get_overrides,
3914
LocationMatcher(lstore, location).get_sections,
3915
NameMatcher(gstore, 'DEFAULT').get_sections],
3916
lstore, mutable_section_id=location)
3919
class BranchStack(Stack):
3920
"""Per-location options falling back to branch then global options stack.
3922
The following sections are queried:
3924
* command-line overrides,
3926
* the sections matching ``location`` in ``locations.conf``, the order being
3927
defined by the number of path components in the section glob, higher
3928
numbers first (from most specific section to most generic),
3930
* the no-name section in branch.conf,
3932
* the ``DEFAULT`` section in ``bazaar.conf``.
3934
This stack will use the no-name section in ``branch.conf`` as its
3287
3938
def __init__(self, branch):
3288
bstore = BranchStore(branch)
3289
3939
lstore = LocationStore()
3290
matcher = LocationMatcher(lstore, branch.base)
3940
bstore = branch._get_config_store()
3291
3941
gstore = GlobalStore()
3292
3942
super(BranchStack, self).__init__(
3293
[matcher.get_sections, bstore.get_sections, gstore.get_sections],
3943
[self._get_overrides,
3944
LocationMatcher(lstore, branch.base).get_sections,
3945
NameMatcher(bstore, None).get_sections,
3946
NameMatcher(gstore, 'DEFAULT').get_sections],
3295
3948
self.branch = branch
3950
def lock_write(self, token=None):
3951
return self.branch.lock_write(token)
3954
return self.branch.unlock()
3957
def set(self, name, value):
3958
super(BranchStack, self).set(name, value)
3959
# Unlocking the branch will trigger a store.save_changes() so the last
3960
# unlock saves all the changes.
3963
def remove(self, name):
3964
super(BranchStack, self).remove(name)
3965
# Unlocking the branch will trigger a store.save_changes() so the last
3966
# unlock saves all the changes.
3298
3969
class RemoteControlStack(_CompatibleStack):
3299
3970
"""Remote control-only options stack."""
3972
# FIXME 2011-11-22 JRV This should probably be renamed to avoid confusion
3973
# with the stack used for remote bzr dirs. RemoteControlStack only uses
3974
# control.conf and is used only for stack options.
3301
3976
def __init__(self, bzrdir):
3302
cstore = ControlStore(bzrdir)
3977
cstore = bzrdir._get_config_store()
3303
3978
super(RemoteControlStack, self).__init__(
3304
[cstore.get_sections],
3979
[NameMatcher(cstore, None).get_sections],
3306
3981
self.bzrdir = bzrdir
3309
class RemoteBranchStack(_CompatibleStack):
3310
"""Remote branch-only options stack."""
3984
class BranchOnlyStack(Stack):
3985
"""Branch-only options stack."""
3987
# FIXME: _BranchOnlyStack only uses branch.conf and is used only for the
3988
# stacked_on_location options waiting for http://pad.lv/832042 to be fixed.
3989
# -- vila 2011-12-16
3312
3991
def __init__(self, branch):
3313
bstore = BranchStore(branch)
3314
super(RemoteBranchStack, self).__init__(
3315
[bstore.get_sections],
3992
bstore = branch._get_config_store()
3993
super(BranchOnlyStack, self).__init__(
3994
[NameMatcher(bstore, None).get_sections],
3317
3996
self.branch = branch
3998
def lock_write(self, token=None):
3999
return self.branch.lock_write(token)
4002
return self.branch.unlock()
4005
def set(self, name, value):
4006
super(BranchOnlyStack, self).set(name, value)
4007
# Force a write to persistent storage
4008
self.store.save_changes()
4011
def remove(self, name):
4012
super(BranchOnlyStack, self).remove(name)
4013
# Force a write to persistent storage
4014
self.store.save_changes()
3320
4017
class cmd_config(commands.Command):
3321
4018
__doc__ = """Display, set or remove a configuration option.
3382
4080
# Set the option value
3383
4081
self._set_config_option(name, value, directory, scope)
3385
def _get_configs(self, directory, scope=None):
3386
"""Iterate the configurations specified by ``directory`` and ``scope``.
4083
def _get_stack(self, directory, scope=None, write_access=False):
4084
"""Get the configuration stack specified by ``directory`` and ``scope``.
3388
4086
:param directory: Where the configurations are derived from.
3390
4088
:param scope: A specific config to start from.
4090
:param write_access: Whether a write access to the stack will be
4093
# FIXME: scope should allow access to plugin-specific stacks (even
4094
# reduced to the plugin-specific store), related to
4095
# http://pad.lv/788991 -- vila 2011-11-15
3392
4096
if scope is not None:
3393
4097
if scope == 'bazaar':
3394
yield GlobalConfig()
4098
return GlobalStack()
3395
4099
elif scope == 'locations':
3396
yield LocationConfig(directory)
4100
return LocationStack(directory)
3397
4101
elif scope == 'branch':
3398
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3400
yield br.get_config()
4103
controldir.ControlDir.open_containing_tree_or_branch(
4106
self.add_cleanup(br.lock_write().unlock)
4107
return br.get_config_stack()
4108
raise errors.NoSuchConfig(scope)
3403
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
3405
yield br.get_config()
4112
controldir.ControlDir.open_containing_tree_or_branch(
4115
self.add_cleanup(br.lock_write().unlock)
4116
return br.get_config_stack()
3406
4117
except errors.NotBranchError:
3407
yield LocationConfig(directory)
3408
yield GlobalConfig()
4118
return LocationStack(directory)
4120
def _quote_multiline(self, value):
4122
value = '"""' + value + '"""'
3410
4125
def _show_value(self, name, directory, scope):
3412
for c in self._get_configs(directory, scope):
3415
for (oname, value, section, conf_id, parser) in c._get_options():
3417
# Display only the first value and exit
3419
# FIXME: We need to use get_user_option to take policies
3420
# into account and we need to make sure the option exists
3421
# too (hence the two for loops), this needs a better API
3423
value = c.get_user_option(name)
3424
# Quote the value appropriately
3425
value = parser._quote(value)
3426
self.outf.write('%s\n' % (value,))
4126
conf = self._get_stack(directory, scope)
4127
value = conf.get(name, expand=True, convert=False)
4128
if value is not None:
4129
# Quote the value appropriately
4130
value = self._quote_multiline(value)
4131
self.outf.write('%s\n' % (value,))
3430
4133
raise errors.NoSuchConfigOption(name)
3432
4135
def _show_matching_options(self, name, directory, scope):
3435
4138
# avoid the delay introduced by the lazy regexp. But, we still do
3436
4139
# want the nicer errors raised by lazy_regex.
3437
4140
name._compile_and_collapse()
3439
4142
cur_section = None
3440
for c in self._get_configs(directory, scope):
3441
for (oname, value, section, conf_id, parser) in c._get_options():
4143
conf = self._get_stack(directory, scope)
4144
for store, section in conf.iter_sections():
4145
for oname in section.iter_option_names():
3442
4146
if name.search(oname):
3443
if cur_conf_id != conf_id:
4147
if cur_store_id != store.id:
3444
4148
# Explain where the options are defined
3445
self.outf.write('%s:\n' % (conf_id,))
3446
cur_conf_id = conf_id
4149
self.outf.write('%s:\n' % (store.id,))
4150
cur_store_id = store.id
3447
4151
cur_section = None
3448
if (section not in (None, 'DEFAULT')
3449
and cur_section != section):
3450
# Display the section if it's not the default (or only)
3452
self.outf.write(' [%s]\n' % (section,))
3453
cur_section = section
4152
if (section.id is not None and cur_section != section.id):
4153
# Display the section id as it appears in the store
4154
# (None doesn't appear by definition)
4155
self.outf.write(' [%s]\n' % (section.id,))
4156
cur_section = section.id
4157
value = section.get(oname, expand=False)
4158
# Quote the value appropriately
4159
value = self._quote_multiline(value)
3454
4160
self.outf.write(' %s = %s\n' % (oname, value))
3456
4162
def _set_config_option(self, name, value, directory, scope):
3457
for conf in self._get_configs(directory, scope):
3458
conf.set_user_option(name, value)
3461
raise errors.NoSuchConfig(scope)
4163
conf = self._get_stack(directory, scope, write_access=True)
4164
conf.set(name, value)
3463
4166
def _remove_config_option(self, name, directory, scope):
3464
4167
if name is None:
3465
4168
raise errors.BzrCommandError(
3466
4169
'--remove expects an option to remove.')
3468
for conf in self._get_configs(directory, scope):
3469
for (section_name, section, conf_id) in conf._get_sections():
3470
if scope is not None and conf_id != scope:
3471
# Not the right configuration file
3474
if conf_id != conf.config_id():
3475
conf = self._get_configs(directory, conf_id).next()
3476
# We use the first section in the first config where the
3477
# option is defined to remove it
3478
conf.remove_user_option(name, section_name)
3483
raise errors.NoSuchConfig(scope)
4170
conf = self._get_stack(directory, scope, write_access=True)
3485
4174
raise errors.NoSuchConfigOption(name)
3487
4177
# Test registries
3489
4179
# We need adapters that can build a Store or a Stack in a test context. Test