1
# Copyright (C) 2005-2011 Canonical Ltd
2
# Authors: Robert Collins <robert.collins@canonical.com>
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
"""Configuration that affects the behaviour of Bazaar.
21
Currently this configuration resides in ~/.bazaar/bazaar.conf
22
and ~/.bazaar/locations.conf, which is written to by bzr.
24
In bazaar.conf the following options may be set:
26
editor=name-of-program
27
email=Your Name <your@email.address>
28
check_signatures=require|ignore|check-available(default)
29
create_signatures=always|never|when-required(default)
30
gpg_signing_command=name-of-program
31
log_format=name-of-format
33
in locations.conf, you specify the url of a branch and options for it.
34
Wildcards may be used - * and ? as normal in shell completion. Options
35
set in both bazaar.conf and locations.conf are overridden by the locations.conf
37
[/home/robertc/source]
38
recurse=False|True(default)
40
check_signatures= as above
41
create_signatures= as above.
43
explanation of options
44
----------------------
45
editor - this option sets the pop up editor to use during commits.
46
email - this option sets the user id bzr will use when committing.
47
check_signatures - this option controls whether bzr will require good gpg
48
signatures, ignore them, or check them if they are
50
create_signatures - this option controls whether bzr will always create
51
gpg signatures, never create them, or create them if the
52
branch is configured to require them.
53
log_format - this option sets the default log format. Possible values are
54
long, short, line, or a plugin can register new formats.
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
59
lastlog=log --line -r-10..-1
60
ll=log --line -r-10..-1
68
from bzrlib import commands
69
from bzrlib.decorators import needs_write_lock
70
from bzrlib.lazy_import import lazy_import
71
lazy_import(globals(), """
75
from cStringIO import StringIO
95
from bzrlib.util.configobj import configobj
111
POLICY_APPENDPATH = 2
115
POLICY_NORECURSE: 'norecurse',
116
POLICY_APPENDPATH: 'appendpath',
121
'norecurse': POLICY_NORECURSE,
122
'appendpath': POLICY_APPENDPATH,
126
STORE_LOCATION = POLICY_NONE
127
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
128
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
133
def ConfigObj(*args, **kwargs):
135
if _ConfigObj is None:
136
class ConfigObj(configobj.ConfigObj):
138
def get_bool(self, section, key):
139
return self[section].as_bool(key)
141
def get_value(self, section, name):
142
# Try [] for the old DEFAULT section.
143
if section == "DEFAULT":
148
return self[section][name]
149
_ConfigObj = ConfigObj
150
return _ConfigObj(*args, **kwargs)
153
class Config(object):
154
"""A configuration policy - what username, editor, gpg needs etc."""
157
super(Config, self).__init__()
160
"""Returns a unique ID for the config."""
161
raise NotImplementedError(self.config_id)
163
def get_editor(self):
164
"""Get the users pop up editor."""
165
raise NotImplementedError
167
def get_change_editor(self, old_tree, new_tree):
168
from bzrlib import diff
169
cmd = self._get_change_editor()
172
return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
176
def get_mail_client(self):
177
"""Get a mail client to use"""
178
selected_client = self.get_user_option('mail_client')
179
_registry = mail_client.mail_client_registry
181
mail_client_class = _registry.get(selected_client)
183
raise errors.UnknownMailClient(selected_client)
184
return mail_client_class(self)
186
def _get_signature_checking(self):
187
"""Template method to override signature checking policy."""
189
def _get_signing_policy(self):
190
"""Template method to override signature creation policy."""
192
def _get_user_option(self, option_name):
193
"""Template method to provide a user option."""
196
def get_user_option(self, option_name):
197
"""Get a generic option - no special process, no default."""
198
return self._get_user_option(option_name)
200
def get_user_option_as_bool(self, option_name):
201
"""Get a generic option as a boolean - no special process, no default.
203
:return None if the option doesn't exist or its value can't be
204
interpreted as a boolean. Returns True or False otherwise.
206
s = self._get_user_option(option_name)
208
# The option doesn't exist
210
val = ui.bool_from_string(s)
212
# The value can't be interpreted as a boolean
213
trace.warning('Value "%s" is not a boolean for "%s"',
217
def get_user_option_as_list(self, option_name):
218
"""Get a generic option as a list - no special process, no default.
220
:return None if the option doesn't exist. Returns the value as a list
223
l = self._get_user_option(option_name)
224
if isinstance(l, (str, unicode)):
225
# A single value, most probably the user forgot the final ','
229
def gpg_signing_command(self):
230
"""What program should be used to sign signatures?"""
231
result = self._gpg_signing_command()
236
def _gpg_signing_command(self):
237
"""See gpg_signing_command()."""
240
def log_format(self):
241
"""What log format should be used"""
242
result = self._log_format()
247
def _log_format(self):
248
"""See log_format()."""
251
def post_commit(self):
252
"""An ordered list of python functions to call.
254
Each function takes branch, rev_id as parameters.
256
return self._post_commit()
258
def _post_commit(self):
259
"""See Config.post_commit."""
262
def user_email(self):
263
"""Return just the email component of a username."""
264
return extract_email_address(self.username())
267
"""Return email-style username.
269
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
271
$BZR_EMAIL can be set to override this, then
272
the concrete policy type is checked, and finally
274
If no username can be found, errors.NoWhoami exception is raised.
276
TODO: Check it's reasonably well-formed.
278
v = os.environ.get('BZR_EMAIL')
280
return v.decode(osutils.get_user_encoding())
282
v = self._get_user_id()
286
v = os.environ.get('EMAIL')
288
return v.decode(osutils.get_user_encoding())
290
raise errors.NoWhoami()
292
def ensure_username(self):
293
"""Raise errors.NoWhoami if username is not set.
295
This method relies on the username() function raising the error.
299
def signature_checking(self):
300
"""What is the current policy for signature checking?."""
301
policy = self._get_signature_checking()
302
if policy is not None:
304
return CHECK_IF_POSSIBLE
306
def signing_policy(self):
307
"""What is the current policy for signature checking?."""
308
policy = self._get_signing_policy()
309
if policy is not None:
311
return SIGN_WHEN_REQUIRED
313
def signature_needed(self):
314
"""Is a signature needed when committing ?."""
315
policy = self._get_signing_policy()
317
policy = self._get_signature_checking()
318
if policy is not None:
319
trace.warning("Please use create_signatures,"
320
" not check_signatures to set signing policy.")
321
if policy == CHECK_ALWAYS:
323
elif policy == SIGN_ALWAYS:
327
def get_alias(self, value):
328
return self._get_alias(value)
330
def _get_alias(self, value):
333
def get_nickname(self):
334
return self._get_nickname()
336
def _get_nickname(self):
339
def get_bzr_remote_path(self):
341
return os.environ['BZR_REMOTE_PATH']
343
path = self.get_user_option("bzr_remote_path")
348
def suppress_warning(self, warning):
349
"""Should the warning be suppressed or emitted.
351
:param warning: The name of the warning being tested.
353
:returns: True if the warning should be suppressed, False otherwise.
355
warnings = self.get_user_option_as_list('suppress_warnings')
356
if warnings is None or warning not in warnings:
361
def get_merge_tools(self):
363
for (oname, value, section, conf_id, parser) in self._get_options():
364
if oname.startswith('bzr.mergetool.'):
365
tool_name = oname[len('bzr.mergetool.'):]
366
tools[tool_name] = value
367
trace.mutter('loaded merge tools: %r' % tools)
370
def find_merge_tool(self, name):
371
# We fake a defaults mechanism here by checking if the given name can
372
# be found in the known_merge_tools if it's not found in the config.
373
# This should be done through the proposed config defaults mechanism
374
# when it becomes available in the future.
375
command_line = (self.get_user_option('bzr.mergetool.%s' % name) or
376
mergetools.known_merge_tools.get(name, None))
380
class IniBasedConfig(Config):
381
"""A configuration policy that draws from ini files."""
383
def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
385
"""Base class for configuration files using an ini-like syntax.
387
:param file_name: The configuration file path.
389
super(IniBasedConfig, self).__init__()
390
self.file_name = file_name
391
if symbol_versioning.deprecated_passed(get_filename):
392
symbol_versioning.warn(
393
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
394
' Use file_name instead.',
397
if get_filename is not None:
398
self.file_name = get_filename()
400
self.file_name = file_name
405
def from_string(cls, str_or_unicode, file_name=None, save=False):
406
"""Create a config object from a string.
408
:param str_or_unicode: A string representing the file content. This will
411
:param file_name: The configuration file path.
413
:param _save: Whether the file should be saved upon creation.
415
conf = cls(file_name=file_name)
416
conf._create_from_string(str_or_unicode, save)
419
def _create_from_string(self, str_or_unicode, save):
420
self._content = StringIO(str_or_unicode.encode('utf-8'))
421
# Some tests use in-memory configs, some other always need the config
422
# file to exist on disk.
424
self._write_config_file()
426
def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
427
if self._parser is not None:
429
if symbol_versioning.deprecated_passed(file):
430
symbol_versioning.warn(
431
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
432
' Use IniBasedConfig(_content=xxx) instead.',
435
if self._content is not None:
436
co_input = self._content
437
elif self.file_name is None:
438
raise AssertionError('We have no content to create the config')
440
co_input = self.file_name
442
self._parser = ConfigObj(co_input, encoding='utf-8')
443
except configobj.ConfigObjError, e:
444
raise errors.ParseConfigError(e.errors, e.config.filename)
445
# Make sure self.reload() will use the right file name
446
self._parser.filename = self.file_name
450
"""Reload the config file from disk."""
451
if self.file_name is None:
452
raise AssertionError('We need a file name to reload the config')
453
if self._parser is not None:
454
self._parser.reload()
456
def _get_matching_sections(self):
457
"""Return an ordered list of (section_name, extra_path) pairs.
459
If the section contains inherited configuration, extra_path is
460
a string containing the additional path components.
462
section = self._get_section()
463
if section is not None:
464
return [(section, '')]
468
def _get_section(self):
469
"""Override this to define the section used by the config."""
472
def _get_sections(self, name=None):
473
"""Returns an iterator of the sections specified by ``name``.
475
:param name: The section name. If None is supplied, the default
476
configurations are yielded.
478
:return: A tuple (name, section, config_id) for all sections that will
479
be walked by user_get_option() in the 'right' order. The first one
480
is where set_user_option() will update the value.
482
parser = self._get_parser()
484
yield (name, parser[name], self.config_id())
486
# No section name has been given so we fallback to the configobj
487
# itself which holds the variables defined outside of any section.
488
yield (None, parser, self.config_id())
490
def _get_options(self, sections=None):
491
"""Return an ordered list of (name, value, section, config_id) tuples.
493
All options are returned with their associated value and the section
494
they appeared in. ``config_id`` is a unique identifier for the
495
configuration file the option is defined in.
497
:param sections: Default to ``_get_matching_sections`` if not
498
specified. This gives a better control to daughter classes about
499
which sections should be searched. This is a list of (name,
504
parser = self._get_parser()
506
for (section_name, _) in self._get_matching_sections():
508
section = parser[section_name]
510
# This could happen for an empty file for which we define a
511
# DEFAULT section. FIXME: Force callers to provide sections
512
# instead ? -- vila 20100930
514
sections.append((section_name, section))
515
config_id = self.config_id()
516
for (section_name, section) in sections:
517
for (name, value) in section.iteritems():
518
yield (name, parser._quote(value), section_name,
521
def _get_option_policy(self, section, option_name):
522
"""Return the policy for the given (section, option_name) pair."""
525
def _get_change_editor(self):
526
return self.get_user_option('change_editor')
528
def _get_signature_checking(self):
529
"""See Config._get_signature_checking."""
530
policy = self._get_user_option('check_signatures')
532
return self._string_to_signature_policy(policy)
534
def _get_signing_policy(self):
535
"""See Config._get_signing_policy"""
536
policy = self._get_user_option('create_signatures')
538
return self._string_to_signing_policy(policy)
540
def _get_user_id(self):
541
"""Get the user id from the 'email' key in the current section."""
542
return self._get_user_option('email')
544
def _get_user_option(self, option_name):
545
"""See Config._get_user_option."""
546
for (section, extra_path) in self._get_matching_sections():
548
value = self._get_parser().get_value(section, option_name)
551
policy = self._get_option_policy(section, option_name)
552
if policy == POLICY_NONE:
554
elif policy == POLICY_NORECURSE:
555
# norecurse items only apply to the exact path
560
elif policy == POLICY_APPENDPATH:
562
value = urlutils.join(value, extra_path)
565
raise AssertionError('Unexpected config policy %r' % policy)
569
def _gpg_signing_command(self):
570
"""See Config.gpg_signing_command."""
571
return self._get_user_option('gpg_signing_command')
573
def _log_format(self):
574
"""See Config.log_format."""
575
return self._get_user_option('log_format')
577
def _post_commit(self):
578
"""See Config.post_commit."""
579
return self._get_user_option('post_commit')
581
def _string_to_signature_policy(self, signature_string):
582
"""Convert a string to a signing policy."""
583
if signature_string.lower() == 'check-available':
584
return CHECK_IF_POSSIBLE
585
if signature_string.lower() == 'ignore':
587
if signature_string.lower() == 'require':
589
raise errors.BzrError("Invalid signatures policy '%s'"
592
def _string_to_signing_policy(self, signature_string):
593
"""Convert a string to a signing policy."""
594
if signature_string.lower() == 'when-required':
595
return SIGN_WHEN_REQUIRED
596
if signature_string.lower() == 'never':
598
if signature_string.lower() == 'always':
600
raise errors.BzrError("Invalid signing policy '%s'"
603
def _get_alias(self, value):
605
return self._get_parser().get_value("ALIASES",
610
def _get_nickname(self):
611
return self.get_user_option('nickname')
613
def remove_user_option(self, option_name, section_name=None):
614
"""Remove a user option and save the configuration file.
616
:param option_name: The option to be removed.
618
:param section_name: The section the option is defined in, default to
622
parser = self._get_parser()
623
if section_name is None:
626
section = parser[section_name]
628
del section[option_name]
630
raise errors.NoSuchConfigOption(option_name)
631
self._write_config_file()
633
def _write_config_file(self):
634
if self.file_name is None:
635
raise AssertionError('We cannot save, self.file_name is None')
636
conf_dir = os.path.dirname(self.file_name)
637
ensure_config_dir_exists(conf_dir)
638
atomic_file = atomicfile.AtomicFile(self.file_name)
639
self._get_parser().write(atomic_file)
642
osutils.copy_ownership_from_path(self.file_name)
645
class LockableConfig(IniBasedConfig):
646
"""A configuration needing explicit locking for access.
648
If several processes try to write the config file, the accesses need to be
651
Daughter classes should decorate all methods that update a config with the
652
``@needs_write_lock`` decorator (they call, directly or indirectly, the
653
``_write_config_file()`` method. These methods (typically ``set_option()``
654
and variants must reload the config file from disk before calling
655
``_write_config_file()``), this can be achieved by calling the
656
``self.reload()`` method. Note that the lock scope should cover both the
657
reading and the writing of the config file which is why the decorator can't
658
be applied to ``_write_config_file()`` only.
660
This should be enough to implement the following logic:
661
- lock for exclusive write access,
662
- reload the config file from disk,
666
This logic guarantees that a writer can update a value without erasing an
667
update made by another writer.
672
def __init__(self, file_name):
673
super(LockableConfig, self).__init__(file_name=file_name)
674
self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
675
self.transport = transport.get_transport(self.dir)
676
self._lock = lockdir.LockDir(self.transport, 'lock')
678
def _create_from_string(self, unicode_bytes, save):
679
super(LockableConfig, self)._create_from_string(unicode_bytes, False)
681
# We need to handle the saving here (as opposed to IniBasedConfig)
684
self._write_config_file()
687
def lock_write(self, token=None):
688
"""Takes a write lock in the directory containing the config file.
690
If the directory doesn't exist it is created.
692
ensure_config_dir_exists(self.dir)
693
return self._lock.lock_write(token)
698
def break_lock(self):
699
self._lock.break_lock()
702
def remove_user_option(self, option_name, section_name=None):
703
super(LockableConfig, self).remove_user_option(option_name,
706
def _write_config_file(self):
707
if self._lock is None or not self._lock.is_held:
708
# NB: if the following exception is raised it probably means a
709
# missing @needs_write_lock decorator on one of the callers.
710
raise errors.ObjectNotLocked(self)
711
super(LockableConfig, self)._write_config_file()
714
class GlobalConfig(LockableConfig):
715
"""The configuration that should be used for a specific location."""
718
super(GlobalConfig, self).__init__(file_name=config_filename())
724
def from_string(cls, str_or_unicode, save=False):
725
"""Create a config object from a string.
727
:param str_or_unicode: A string representing the file content. This
728
will be utf-8 encoded.
730
:param save: Whether the file should be saved upon creation.
733
conf._create_from_string(str_or_unicode, save)
736
def get_editor(self):
737
return self._get_user_option('editor')
740
def set_user_option(self, option, value):
741
"""Save option and its value in the configuration."""
742
self._set_option(option, value, 'DEFAULT')
744
def get_aliases(self):
745
"""Return the aliases section."""
746
if 'ALIASES' in self._get_parser():
747
return self._get_parser()['ALIASES']
752
def set_alias(self, alias_name, alias_command):
753
"""Save the alias in the configuration."""
754
self._set_option(alias_name, alias_command, 'ALIASES')
757
def unset_alias(self, alias_name):
758
"""Unset an existing alias."""
760
aliases = self._get_parser().get('ALIASES')
761
if not aliases or alias_name not in aliases:
762
raise errors.NoSuchAlias(alias_name)
763
del aliases[alias_name]
764
self._write_config_file()
766
def _set_option(self, option, value, section):
768
self._get_parser().setdefault(section, {})[option] = value
769
self._write_config_file()
772
def _get_sections(self, name=None):
773
"""See IniBasedConfig._get_sections()."""
774
parser = self._get_parser()
775
# We don't give access to options defined outside of any section, we
776
# used the DEFAULT section by... default.
777
if name in (None, 'DEFAULT'):
778
# This could happen for an empty file where the DEFAULT section
779
# doesn't exist yet. So we force DEFAULT when yielding
781
if 'DEFAULT' not in parser:
782
parser['DEFAULT']= {}
783
yield (name, parser[name], self.config_id())
786
def remove_user_option(self, option_name, section_name=None):
787
if section_name is None:
788
# We need to force the default section.
789
section_name = 'DEFAULT'
790
# We need to avoid the LockableConfig implementation or we'll lock
792
super(LockableConfig, self).remove_user_option(option_name,
796
class LocationConfig(LockableConfig):
797
"""A configuration object that gives the policy for a location."""
799
def __init__(self, location):
800
super(LocationConfig, self).__init__(
801
file_name=locations_config_filename())
802
# local file locations are looked up by local path, rather than
803
# by file url. This is because the config file is a user
804
# file, and we would rather not expose the user to file urls.
805
if location.startswith('file://'):
806
location = urlutils.local_path_from_url(location)
807
self.location = location
813
def from_string(cls, str_or_unicode, location, save=False):
814
"""Create a config object from a string.
816
:param str_or_unicode: A string representing the file content. This will
819
:param location: The location url to filter the configuration.
821
:param save: Whether the file should be saved upon creation.
824
conf._create_from_string(str_or_unicode, save)
827
def _get_matching_sections(self):
828
"""Return an ordered list of section names matching this location."""
829
sections = self._get_parser()
830
location_names = self.location.split('/')
831
if self.location.endswith('/'):
832
del location_names[-1]
834
for section in sections:
835
# location is a local path if possible, so we need
836
# to convert 'file://' urls to local paths if necessary.
837
# This also avoids having file:///path be a more exact
838
# match than '/path'.
839
if section.startswith('file://'):
840
section_path = urlutils.local_path_from_url(section)
842
section_path = section
843
section_names = section_path.split('/')
844
if section.endswith('/'):
845
del section_names[-1]
846
names = zip(location_names, section_names)
849
if not fnmatch.fnmatch(name[0], name[1]):
854
# so, for the common prefix they matched.
855
# if section is longer, no match.
856
if len(section_names) > len(location_names):
858
matches.append((len(section_names), section,
859
'/'.join(location_names[len(section_names):])))
860
# put the longest (aka more specific) locations first
861
matches.sort(reverse=True)
863
for (length, section, extra_path) in matches:
864
sections.append((section, extra_path))
865
# should we stop looking for parent configs here?
867
if self._get_parser()[section].as_bool('ignore_parents'):
873
def _get_sections(self, name=None):
874
"""See IniBasedConfig._get_sections()."""
875
# We ignore the name here as the only sections handled are named with
876
# the location path and we don't expose embedded sections either.
877
parser = self._get_parser()
878
for name, extra_path in self._get_matching_sections():
879
yield (name, parser[name], self.config_id())
881
def _get_option_policy(self, section, option_name):
882
"""Return the policy for the given (section, option_name) pair."""
883
# check for the old 'recurse=False' flag
885
recurse = self._get_parser()[section].as_bool('recurse')
889
return POLICY_NORECURSE
891
policy_key = option_name + ':policy'
893
policy_name = self._get_parser()[section][policy_key]
897
return _policy_value[policy_name]
899
def _set_option_policy(self, section, option_name, option_policy):
900
"""Set the policy for the given option name in the given section."""
901
# The old recurse=False option affects all options in the
902
# section. To handle multiple policies in the section, we
903
# need to convert it to a policy_norecurse key.
905
recurse = self._get_parser()[section].as_bool('recurse')
909
symbol_versioning.warn(
910
'The recurse option is deprecated as of 0.14. '
911
'The section "%s" has been converted to use policies.'
914
del self._get_parser()[section]['recurse']
916
for key in self._get_parser()[section].keys():
917
if not key.endswith(':policy'):
918
self._get_parser()[section][key +
919
':policy'] = 'norecurse'
921
policy_key = option_name + ':policy'
922
policy_name = _policy_name[option_policy]
923
if policy_name is not None:
924
self._get_parser()[section][policy_key] = policy_name
926
if policy_key in self._get_parser()[section]:
927
del self._get_parser()[section][policy_key]
930
def set_user_option(self, option, value, store=STORE_LOCATION):
931
"""Save option and its value in the configuration."""
932
if store not in [STORE_LOCATION,
933
STORE_LOCATION_NORECURSE,
934
STORE_LOCATION_APPENDPATH]:
935
raise ValueError('bad storage policy %r for %r' %
938
location = self.location
939
if location.endswith('/'):
940
location = location[:-1]
941
parser = self._get_parser()
942
if not location in parser and not location + '/' in parser:
943
parser[location] = {}
944
elif location + '/' in parser:
945
location = location + '/'
946
parser[location][option]=value
947
# the allowed values of store match the config policies
948
self._set_option_policy(location, option, store)
949
self._write_config_file()
952
class BranchConfig(Config):
953
"""A configuration object giving the policy for a branch."""
955
def __init__(self, branch):
956
super(BranchConfig, self).__init__()
957
self._location_config = None
958
self._branch_data_config = None
959
self._global_config = None
961
self.option_sources = (self._get_location_config,
962
self._get_branch_data_config,
963
self._get_global_config)
968
def _get_branch_data_config(self):
969
if self._branch_data_config is None:
970
self._branch_data_config = TreeConfig(self.branch)
971
self._branch_data_config.config_id = self.config_id
972
return self._branch_data_config
974
def _get_location_config(self):
975
if self._location_config is None:
976
self._location_config = LocationConfig(self.branch.base)
977
return self._location_config
979
def _get_global_config(self):
980
if self._global_config is None:
981
self._global_config = GlobalConfig()
982
return self._global_config
984
def _get_best_value(self, option_name):
985
"""This returns a user option from local, tree or global config.
987
They are tried in that order. Use get_safe_value if trusted values
990
for source in self.option_sources:
991
value = getattr(source(), option_name)()
992
if value is not None:
996
def _get_safe_value(self, option_name):
997
"""This variant of get_best_value never returns untrusted values.
999
It does not return values from the branch data, because the branch may
1000
not be controlled by the user.
1002
We may wish to allow locations.conf to control whether branches are
1003
trusted in the future.
1005
for source in (self._get_location_config, self._get_global_config):
1006
value = getattr(source(), option_name)()
1007
if value is not None:
1011
def _get_user_id(self):
1012
"""Return the full user id for the branch.
1014
e.g. "John Hacker <jhacker@example.com>"
1015
This is looked up in the email controlfile for the branch.
1018
return (self.branch._transport.get_bytes("email")
1019
.decode(osutils.get_user_encoding())
1021
except errors.NoSuchFile, e:
1024
return self._get_best_value('_get_user_id')
1026
def _get_change_editor(self):
1027
return self._get_best_value('_get_change_editor')
1029
def _get_signature_checking(self):
1030
"""See Config._get_signature_checking."""
1031
return self._get_best_value('_get_signature_checking')
1033
def _get_signing_policy(self):
1034
"""See Config._get_signing_policy."""
1035
return self._get_best_value('_get_signing_policy')
1037
def _get_user_option(self, option_name):
1038
"""See Config._get_user_option."""
1039
for source in self.option_sources:
1040
value = source()._get_user_option(option_name)
1041
if value is not None:
1045
def _get_sections(self, name=None):
1046
"""See IniBasedConfig.get_sections()."""
1047
for source in self.option_sources:
1048
for section in source()._get_sections(name):
1051
def _get_options(self, sections=None):
1053
# First the locations options
1054
for option in self._get_location_config()._get_options():
1056
# Then the branch options
1057
branch_config = self._get_branch_data_config()
1058
if sections is None:
1059
sections = [('DEFAULT', branch_config._get_parser())]
1060
# FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
1061
# Config itself has no notion of sections :( -- vila 20101001
1062
config_id = self.config_id()
1063
for (section_name, section) in sections:
1064
for (name, value) in section.iteritems():
1065
yield (name, value, section_name,
1066
config_id, branch_config._get_parser())
1067
# Then the global options
1068
for option in self._get_global_config()._get_options():
1071
def set_user_option(self, name, value, store=STORE_BRANCH,
1073
if store == STORE_BRANCH:
1074
self._get_branch_data_config().set_option(value, name)
1075
elif store == STORE_GLOBAL:
1076
self._get_global_config().set_user_option(name, value)
1078
self._get_location_config().set_user_option(name, value, store)
1081
if store in (STORE_GLOBAL, STORE_BRANCH):
1082
mask_value = self._get_location_config().get_user_option(name)
1083
if mask_value is not None:
1084
trace.warning('Value "%s" is masked by "%s" from'
1085
' locations.conf', value, mask_value)
1087
if store == STORE_GLOBAL:
1088
branch_config = self._get_branch_data_config()
1089
mask_value = branch_config.get_user_option(name)
1090
if mask_value is not None:
1091
trace.warning('Value "%s" is masked by "%s" from'
1092
' branch.conf', value, mask_value)
1094
def remove_user_option(self, option_name, section_name=None):
1095
self._get_branch_data_config().remove_option(option_name, section_name)
1097
def _gpg_signing_command(self):
1098
"""See Config.gpg_signing_command."""
1099
return self._get_safe_value('_gpg_signing_command')
1101
def _post_commit(self):
1102
"""See Config.post_commit."""
1103
return self._get_safe_value('_post_commit')
1105
def _get_nickname(self):
1106
value = self._get_explicit_nickname()
1107
if value is not None:
1109
return urlutils.unescape(self.branch.base.split('/')[-2])
1111
def has_explicit_nickname(self):
1112
"""Return true if a nickname has been explicitly assigned."""
1113
return self._get_explicit_nickname() is not None
1115
def _get_explicit_nickname(self):
1116
return self._get_best_value('_get_nickname')
1118
def _log_format(self):
1119
"""See Config.log_format."""
1120
return self._get_best_value('_log_format')
1123
def ensure_config_dir_exists(path=None):
1124
"""Make sure a configuration directory exists.
1125
This makes sure that the directory exists.
1126
On windows, since configuration directories are 2 levels deep,
1127
it makes sure both the directory and the parent directory exists.
1131
if not os.path.isdir(path):
1132
if sys.platform == 'win32':
1133
parent_dir = os.path.dirname(path)
1134
if not os.path.isdir(parent_dir):
1135
trace.mutter('creating config parent directory: %r', parent_dir)
1136
os.mkdir(parent_dir)
1137
trace.mutter('creating config directory: %r', path)
1139
osutils.copy_ownership_from_path(path)
1143
"""Return per-user configuration directory.
1145
By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
1146
and Linux. On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
1147
that will be used instead.
1149
TODO: Global option --config-dir to override this.
1151
base = os.environ.get('BZR_HOME', None)
1152
if sys.platform == 'win32':
1153
# environ variables on Windows are in user encoding/mbcs. So decode
1155
if base is not None:
1156
base = base.decode('mbcs')
1158
base = win32utils.get_appdata_location_unicode()
1160
base = os.environ.get('HOME', None)
1161
if base is not None:
1162
base = base.decode('mbcs')
1164
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1166
return osutils.pathjoin(base, 'bazaar', '2.0')
1167
elif sys.platform == 'darwin':
1169
# this takes into account $HOME
1170
base = os.path.expanduser("~")
1171
return osutils.pathjoin(base, '.bazaar')
1175
xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
1177
xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
1178
xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
1179
if osutils.isdir(xdg_dir):
1181
"Using configuration in XDG directory %s." % xdg_dir)
1184
base = os.path.expanduser("~")
1185
return osutils.pathjoin(base, ".bazaar")
1188
def config_filename():
1189
"""Return per-user configuration ini file filename."""
1190
return osutils.pathjoin(config_dir(), 'bazaar.conf')
1193
def locations_config_filename():
1194
"""Return per-user configuration ini file filename."""
1195
return osutils.pathjoin(config_dir(), 'locations.conf')
1198
def authentication_config_filename():
1199
"""Return per-user authentication ini file filename."""
1200
return osutils.pathjoin(config_dir(), 'authentication.conf')
1203
def user_ignore_config_filename():
1204
"""Return the user default ignore filename"""
1205
return osutils.pathjoin(config_dir(), 'ignore')
1209
"""Return the directory name to store crash files.
1211
This doesn't implicitly create it.
1213
On Windows it's in the config directory; elsewhere it's /var/crash
1214
which may be monitored by apport. It can be overridden by
1217
if sys.platform == 'win32':
1218
return osutils.pathjoin(config_dir(), 'Crash')
1220
# XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
1222
return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
1225
def xdg_cache_dir():
1226
# See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
1227
# Possibly this should be different on Windows?
1228
e = os.environ.get('XDG_CACHE_DIR', None)
1232
return os.path.expanduser('~/.cache')
1235
def parse_username(username):
1236
"""Parse e-mail username and return a (name, address) tuple."""
1237
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1239
return (username, '')
1241
return (match.group(1), match.group(2))
1244
def extract_email_address(e):
1245
"""Return just the address part of an email string.
1247
That is just the user@domain part, nothing else.
1248
This part is required to contain only ascii characters.
1249
If it can't be extracted, raises an error.
1251
>>> extract_email_address('Jane Tester <jane@test.com>')
1254
name, email = parse_username(e)
1256
raise errors.NoEmailInUsername(e)
1260
class TreeConfig(IniBasedConfig):
1261
"""Branch configuration data associated with its contents, not location"""
1263
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
1265
def __init__(self, branch):
1266
self._config = branch._get_config()
1267
self.branch = branch
1269
def _get_parser(self, file=None):
1270
if file is not None:
1271
return IniBasedConfig._get_parser(file)
1272
return self._config._get_configobj()
1274
def get_option(self, name, section=None, default=None):
1275
self.branch.lock_read()
1277
return self._config.get_option(name, section, default)
1279
self.branch.unlock()
1281
def set_option(self, value, name, section=None):
1282
"""Set a per-branch configuration option"""
1283
# FIXME: We shouldn't need to lock explicitly here but rather rely on
1284
# higher levels providing the right lock -- vila 20101004
1285
self.branch.lock_write()
1287
self._config.set_option(value, name, section)
1289
self.branch.unlock()
1291
def remove_option(self, option_name, section_name=None):
1292
# FIXME: We shouldn't need to lock explicitly here but rather rely on
1293
# higher levels providing the right lock -- vila 20101004
1294
self.branch.lock_write()
1296
self._config.remove_option(option_name, section_name)
1298
self.branch.unlock()
1301
class AuthenticationConfig(object):
1302
"""The authentication configuration file based on a ini file.
1304
Implements the authentication.conf file described in
1305
doc/developers/authentication-ring.txt.
1308
def __init__(self, _file=None):
1309
self._config = None # The ConfigObj
1311
self._filename = authentication_config_filename()
1312
self._input = self._filename = authentication_config_filename()
1314
# Tests can provide a string as _file
1315
self._filename = None
1318
def _get_config(self):
1319
if self._config is not None:
1322
# FIXME: Should we validate something here ? Includes: empty
1323
# sections are useless, at least one of
1324
# user/password/password_encoding should be defined, etc.
1326
# Note: the encoding below declares that the file itself is utf-8
1327
# encoded, but the values in the ConfigObj are always Unicode.
1328
self._config = ConfigObj(self._input, encoding='utf-8')
1329
except configobj.ConfigObjError, e:
1330
raise errors.ParseConfigError(e.errors, e.config.filename)
1334
"""Save the config file, only tests should use it for now."""
1335
conf_dir = os.path.dirname(self._filename)
1336
ensure_config_dir_exists(conf_dir)
1337
f = file(self._filename, 'wb')
1339
self._get_config().write(f)
1343
def _set_option(self, section_name, option_name, value):
1344
"""Set an authentication configuration option"""
1345
conf = self._get_config()
1346
section = conf.get(section_name)
1349
section = conf[section]
1350
section[option_name] = value
1353
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1355
"""Returns the matching credentials from authentication.conf file.
1357
:param scheme: protocol
1359
:param host: the server address
1361
:param port: the associated port (optional)
1363
:param user: login (optional)
1365
:param path: the absolute path on the server (optional)
1367
:param realm: the http authentication realm (optional)
1369
:return: A dict containing the matching credentials or None.
1371
- name: the section name of the credentials in the
1372
authentication.conf file,
1373
- user: can't be different from the provided user if any,
1374
- scheme: the server protocol,
1375
- host: the server address,
1376
- port: the server port (can be None),
1377
- path: the absolute server path (can be None),
1378
- realm: the http specific authentication realm (can be None),
1379
- password: the decoded password, could be None if the credential
1380
defines only the user
1381
- verify_certificates: https specific, True if the server
1382
certificate should be verified, False otherwise.
1385
for auth_def_name, auth_def in self._get_config().items():
1386
if type(auth_def) is not configobj.Section:
1387
raise ValueError("%s defined outside a section" % auth_def_name)
1389
a_scheme, a_host, a_user, a_path = map(
1390
auth_def.get, ['scheme', 'host', 'user', 'path'])
1393
a_port = auth_def.as_int('port')
1397
raise ValueError("'port' not numeric in %s" % auth_def_name)
1399
a_verify_certificates = auth_def.as_bool('verify_certificates')
1401
a_verify_certificates = True
1404
"'verify_certificates' not boolean in %s" % auth_def_name)
1407
if a_scheme is not None and scheme != a_scheme:
1409
if a_host is not None:
1410
if not (host == a_host
1411
or (a_host.startswith('.') and host.endswith(a_host))):
1413
if a_port is not None and port != a_port:
1415
if (a_path is not None and path is not None
1416
and not path.startswith(a_path)):
1418
if (a_user is not None and user is not None
1419
and a_user != user):
1420
# Never contradict the caller about the user to be used
1425
# Prepare a credentials dictionary with additional keys
1426
# for the credential providers
1427
credentials = dict(name=auth_def_name,
1434
password=auth_def.get('password', None),
1435
verify_certificates=a_verify_certificates)
1436
# Decode the password in the credentials (or get one)
1437
self.decode_password(credentials,
1438
auth_def.get('password_encoding', None))
1439
if 'auth' in debug.debug_flags:
1440
trace.mutter("Using authentication section: %r", auth_def_name)
1443
if credentials is None:
1444
# No credentials were found in authentication.conf, try the fallback
1445
# credentials stores.
1446
credentials = credential_store_registry.get_fallback_credentials(
1447
scheme, host, port, user, path, realm)
1451
def set_credentials(self, name, host, user, scheme=None, password=None,
1452
port=None, path=None, verify_certificates=None,
1454
"""Set authentication credentials for a host.
1456
Any existing credentials with matching scheme, host, port and path
1457
will be deleted, regardless of name.
1459
:param name: An arbitrary name to describe this set of credentials.
1460
:param host: Name of the host that accepts these credentials.
1461
:param user: The username portion of these credentials.
1462
:param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1464
:param password: Password portion of these credentials.
1465
:param port: The IP port on the host that these credentials apply to.
1466
:param path: A filesystem path on the host that these credentials
1468
:param verify_certificates: On https, verify server certificates if
1470
:param realm: The http authentication realm (optional).
1472
values = {'host': host, 'user': user}
1473
if password is not None:
1474
values['password'] = password
1475
if scheme is not None:
1476
values['scheme'] = scheme
1477
if port is not None:
1478
values['port'] = '%d' % port
1479
if path is not None:
1480
values['path'] = path
1481
if verify_certificates is not None:
1482
values['verify_certificates'] = str(verify_certificates)
1483
if realm is not None:
1484
values['realm'] = realm
1485
config = self._get_config()
1487
for section, existing_values in config.items():
1488
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1489
if existing_values.get(key) != values.get(key):
1493
config.update({name: values})
1496
def get_user(self, scheme, host, port=None, realm=None, path=None,
1497
prompt=None, ask=False, default=None):
1498
"""Get a user from authentication file.
1500
:param scheme: protocol
1502
:param host: the server address
1504
:param port: the associated port (optional)
1506
:param realm: the realm sent by the server (optional)
1508
:param path: the absolute path on the server (optional)
1510
:param ask: Ask the user if there is no explicitly configured username
1513
:param default: The username returned if none is defined (optional).
1515
:return: The found user.
1517
credentials = self.get_credentials(scheme, host, port, user=None,
1518
path=path, realm=realm)
1519
if credentials is not None:
1520
user = credentials['user']
1526
# Create a default prompt suitable for most cases
1527
prompt = scheme.upper() + ' %(host)s username'
1528
# Special handling for optional fields in the prompt
1529
if port is not None:
1530
prompt_host = '%s:%d' % (host, port)
1533
user = ui.ui_factory.get_username(prompt, host=prompt_host)
1538
def get_password(self, scheme, host, user, port=None,
1539
realm=None, path=None, prompt=None):
1540
"""Get a password from authentication file or prompt the user for one.
1542
:param scheme: protocol
1544
:param host: the server address
1546
:param port: the associated port (optional)
1550
:param realm: the realm sent by the server (optional)
1552
:param path: the absolute path on the server (optional)
1554
:return: The found password or the one entered by the user.
1556
credentials = self.get_credentials(scheme, host, port, user, path,
1558
if credentials is not None:
1559
password = credentials['password']
1560
if password is not None and scheme is 'ssh':
1561
trace.warning('password ignored in section [%s],'
1562
' use an ssh agent instead'
1563
% credentials['name'])
1567
# Prompt user only if we could't find a password
1568
if password is None:
1570
# Create a default prompt suitable for most cases
1571
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1572
# Special handling for optional fields in the prompt
1573
if port is not None:
1574
prompt_host = '%s:%d' % (host, port)
1577
password = ui.ui_factory.get_password(prompt,
1578
host=prompt_host, user=user)
1581
def decode_password(self, credentials, encoding):
1583
cs = credential_store_registry.get_credential_store(encoding)
1585
raise ValueError('%r is not a known password_encoding' % encoding)
1586
credentials['password'] = cs.decode_password(credentials)
1590
class CredentialStoreRegistry(registry.Registry):
1591
"""A class that registers credential stores.
1593
A credential store provides access to credentials via the password_encoding
1594
field in authentication.conf sections.
1596
Except for stores provided by bzr itself, most stores are expected to be
1597
provided by plugins that will therefore use
1598
register_lazy(password_encoding, module_name, member_name, help=help,
1599
fallback=fallback) to install themselves.
1601
A fallback credential store is one that is queried if no credentials can be
1602
found via authentication.conf.
1605
def get_credential_store(self, encoding=None):
1606
cs = self.get(encoding)
1611
def is_fallback(self, name):
1612
"""Check if the named credentials store should be used as fallback."""
1613
return self.get_info(name)
1615
def get_fallback_credentials(self, scheme, host, port=None, user=None,
1616
path=None, realm=None):
1617
"""Request credentials from all fallback credentials stores.
1619
The first credentials store that can provide credentials wins.
1622
for name in self.keys():
1623
if not self.is_fallback(name):
1625
cs = self.get_credential_store(name)
1626
credentials = cs.get_credentials(scheme, host, port, user,
1628
if credentials is not None:
1629
# We found some credentials
1633
def register(self, key, obj, help=None, override_existing=False,
1635
"""Register a new object to a name.
1637
:param key: This is the key to use to request the object later.
1638
:param obj: The object to register.
1639
:param help: Help text for this entry. This may be a string or
1640
a callable. If it is a callable, it should take two
1641
parameters (registry, key): this registry and the key that
1642
the help was registered under.
1643
:param override_existing: Raise KeyErorr if False and something has
1644
already been registered for that key. If True, ignore if there
1645
is an existing key (always register the new value).
1646
:param fallback: Whether this credential store should be
1649
return super(CredentialStoreRegistry,
1650
self).register(key, obj, help, info=fallback,
1651
override_existing=override_existing)
1653
def register_lazy(self, key, module_name, member_name,
1654
help=None, override_existing=False,
1656
"""Register a new credential store to be loaded on request.
1658
:param module_name: The python path to the module. Such as 'os.path'.
1659
:param member_name: The member of the module to return. If empty or
1660
None, get() will return the module itself.
1661
:param help: Help text for this entry. This may be a string or
1663
:param override_existing: If True, replace the existing object
1664
with the new one. If False, if there is already something
1665
registered with the same key, raise a KeyError
1666
:param fallback: Whether this credential store should be
1669
return super(CredentialStoreRegistry, self).register_lazy(
1670
key, module_name, member_name, help,
1671
info=fallback, override_existing=override_existing)
1674
credential_store_registry = CredentialStoreRegistry()
1677
class CredentialStore(object):
1678
"""An abstract class to implement storage for credentials"""
1680
def decode_password(self, credentials):
1681
"""Returns a clear text password for the provided credentials."""
1682
raise NotImplementedError(self.decode_password)
1684
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1686
"""Return the matching credentials from this credential store.
1688
This method is only called on fallback credential stores.
1690
raise NotImplementedError(self.get_credentials)
1694
class PlainTextCredentialStore(CredentialStore):
1695
__doc__ = """Plain text credential store for the authentication.conf file"""
1697
def decode_password(self, credentials):
1698
"""See CredentialStore.decode_password."""
1699
return credentials['password']
1702
credential_store_registry.register('plain', PlainTextCredentialStore,
1703
help=PlainTextCredentialStore.__doc__)
1704
credential_store_registry.default_key = 'plain'
1707
class BzrDirConfig(object):
1709
def __init__(self, bzrdir):
1710
self._bzrdir = bzrdir
1711
self._config = bzrdir._get_config()
1713
def set_default_stack_on(self, value):
1714
"""Set the default stacking location.
1716
It may be set to a location, or None.
1718
This policy affects all branches contained by this bzrdir, except for
1719
those under repositories.
1721
if self._config is None:
1722
raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1724
self._config.set_option('', 'default_stack_on')
1726
self._config.set_option(value, 'default_stack_on')
1728
def get_default_stack_on(self):
1729
"""Return the default stacking location.
1731
This will either be a location, or None.
1733
This policy affects all branches contained by this bzrdir, except for
1734
those under repositories.
1736
if self._config is None:
1738
value = self._config.get_option('default_stack_on')
1744
class TransportConfig(object):
1745
"""A Config that reads/writes a config file on a Transport.
1747
It is a low-level object that considers config data to be name/value pairs
1748
that may be associated with a section. Assigning meaning to these values
1749
is done at higher levels like TreeConfig.
1752
def __init__(self, transport, filename):
1753
self._transport = transport
1754
self._filename = filename
1756
def get_option(self, name, section=None, default=None):
1757
"""Return the value associated with a named option.
1759
:param name: The name of the value
1760
:param section: The section the option is in (if any)
1761
:param default: The value to return if the value is not set
1762
:return: The value or default value
1764
configobj = self._get_configobj()
1766
section_obj = configobj
1769
section_obj = configobj[section]
1772
return section_obj.get(name, default)
1774
def set_option(self, value, name, section=None):
1775
"""Set the value associated with a named option.
1777
:param value: The value to set
1778
:param name: The name of the value to set
1779
:param section: The section the option is in (if any)
1781
configobj = self._get_configobj()
1783
configobj[name] = value
1785
configobj.setdefault(section, {})[name] = value
1786
self._set_configobj(configobj)
1788
def remove_option(self, option_name, section_name=None):
1789
configobj = self._get_configobj()
1790
if section_name is None:
1791
del configobj[option_name]
1793
del configobj[section_name][option_name]
1794
self._set_configobj(configobj)
1796
def _get_config_file(self):
1798
return StringIO(self._transport.get_bytes(self._filename))
1799
except errors.NoSuchFile:
1802
def _get_configobj(self):
1803
f = self._get_config_file()
1805
return ConfigObj(f, encoding='utf-8')
1809
def _set_configobj(self, configobj):
1810
out_file = StringIO()
1811
configobj.write(out_file)
1813
self._transport.put_file(self._filename, out_file)
1816
class cmd_config(commands.Command):
1817
__doc__ = """Display, set or remove a configuration option.
1819
Display the active value for a given option.
1821
If --all is specified, NAME is interpreted as a regular expression and all
1822
matching options are displayed mentioning their scope. The active value
1823
that bzr will take into account is the first one displayed for each option.
1825
If no NAME is given, --all .* is implied.
1827
Setting a value is achieved by using name=value without spaces. The value
1828
is set in the most relevant scope and can be checked by displaying the
1832
takes_args = ['name?']
1836
# FIXME: This should be a registry option so that plugins can register
1837
# their own config files (or not) -- vila 20101002
1838
commands.Option('scope', help='Reduce the scope to the specified'
1839
' configuration file',
1841
commands.Option('all',
1842
help='Display all the defined values for the matching options.',
1844
commands.Option('remove', help='Remove the option from'
1845
' the configuration file'),
1848
@commands.display_command
1849
def run(self, name=None, all=False, directory=None, scope=None,
1851
if directory is None:
1853
directory = urlutils.normalize_url(directory)
1855
raise errors.BzrError(
1856
'--all and --remove are mutually exclusive.')
1858
# Delete the option in the given scope
1859
self._remove_config_option(name, directory, scope)
1861
# Defaults to all options
1862
self._show_matching_options('.*', directory, scope)
1865
name, value = name.split('=', 1)
1867
# Display the option(s) value(s)
1869
self._show_matching_options(name, directory, scope)
1871
self._show_value(name, directory, scope)
1874
raise errors.BzrError(
1875
'Only one option can be set.')
1876
# Set the option value
1877
self._set_config_option(name, value, directory, scope)
1879
def _get_configs(self, directory, scope=None):
1880
"""Iterate the configurations specified by ``directory`` and ``scope``.
1882
:param directory: Where the configurations are derived from.
1884
:param scope: A specific config to start from.
1886
if scope is not None:
1887
if scope == 'bazaar':
1888
yield GlobalConfig()
1889
elif scope == 'locations':
1890
yield LocationConfig(directory)
1891
elif scope == 'branch':
1892
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1894
yield br.get_config()
1897
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1899
yield br.get_config()
1900
except errors.NotBranchError:
1901
yield LocationConfig(directory)
1902
yield GlobalConfig()
1904
def _show_value(self, name, directory, scope):
1906
for c in self._get_configs(directory, scope):
1909
for (oname, value, section, conf_id, parser) in c._get_options():
1911
# Display only the first value and exit
1913
# FIXME: We need to use get_user_option to take policies
1914
# into account and we need to make sure the option exists
1915
# too (hence the two for loops), this needs a better API
1917
value = c.get_user_option(name)
1918
# Quote the value appropriately
1919
value = parser._quote(value)
1920
self.outf.write('%s\n' % (value,))
1924
raise errors.NoSuchConfigOption(name)
1926
def _show_matching_options(self, name, directory, scope):
1927
name = re.compile(name)
1928
# We want any error in the regexp to be raised *now* so we need to
1929
# avoid the delay introduced by the lazy regexp.
1930
name._compile_and_collapse()
1933
for c in self._get_configs(directory, scope):
1934
for (oname, value, section, conf_id, parser) in c._get_options():
1935
if name.search(oname):
1936
if cur_conf_id != conf_id:
1937
# Explain where the options are defined
1938
self.outf.write('%s:\n' % (conf_id,))
1939
cur_conf_id = conf_id
1941
if (section not in (None, 'DEFAULT')
1942
and cur_section != section):
1943
# Display the section if it's not the default (or only)
1945
self.outf.write(' [%s]\n' % (section,))
1946
cur_section = section
1947
self.outf.write(' %s = %s\n' % (oname, value))
1949
def _set_config_option(self, name, value, directory, scope):
1950
for conf in self._get_configs(directory, scope):
1951
conf.set_user_option(name, value)
1954
raise errors.NoSuchConfig(scope)
1956
def _remove_config_option(self, name, directory, scope):
1958
raise errors.BzrCommandError(
1959
'--remove expects an option to remove.')
1961
for conf in self._get_configs(directory, scope):
1962
for (section_name, section, conf_id) in conf._get_sections():
1963
if scope is not None and conf_id != scope:
1964
# Not the right configuration file
1967
if conf_id != conf.config_id():
1968
conf = self._get_configs(directory, conf_id).next()
1969
# We use the first section in the first config where the
1970
# option is defined to remove it
1971
conf.remove_user_option(name, section_name)
1976
raise errors.NoSuchConfig(scope)
1978
raise errors.NoSuchConfigOption(name)