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
tools.append(mergetools.MergeTool(oname[len('bzr.mergetool.'):],
367
trace.mutter('loaded merge tools: %r' % tools)
370
def set_merge_tools(self, tools):
371
# remove entries from config for tools which do not appear in
373
tool_names = [tool.name for tool in tools]
374
for (oname, value, section, conf_id, parser) in self._get_options():
375
if oname.startswith('bzr.mergetool.'):
376
if oname[len('bzr.mergetool.'):] not in tool_names:
377
self.remove_user_option(oname)
380
oname = 'bzr.mergetool.%s' % tool.name
381
value = tool.command_line
382
if oname == '' or value == '':
384
self.set_user_option(oname, value)
386
def _find_merge_tool(self, name):
387
commandline = self.get_user_option('bzr.mergetool.%s' % name)
388
if commandline is None:
390
return mergetools.MergeTool(name, commandline)
392
def get_default_merge_tool(self):
393
name = self.get_user_option('bzr.default_mergetool')
395
trace.mutter('no default merge tool defined')
397
tool = self._find_merge_tool(name)
398
trace.mutter('found default merge tool: %r', tool)
401
def set_default_merge_tool(self, name):
403
self.remove_user_option('bzr.default_mergetool')
405
if isinstance(name, mergetools.MergeTool):
406
name = name.get_name()
407
if self._find_merge_tool(name) is None:
408
raise errors.BzrError('invalid merge tool name: %r' % name)
409
trace.mutter('setting default merge tool: %s', name)
410
self.set_user_option('bzr.default_mergetool', name)
350
413
class IniBasedConfig(Config):
351
414
"""A configuration policy that draws from ini files."""
353
def __init__(self, get_filename):
416
def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
418
"""Base class for configuration files using an ini-like syntax.
420
:param file_name: The configuration file path.
354
422
super(IniBasedConfig, self).__init__()
355
self._get_filename = get_filename
423
self.file_name = file_name
424
if symbol_versioning.deprecated_passed(get_filename):
425
symbol_versioning.warn(
426
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
427
' Use file_name instead.',
430
if get_filename is not None:
431
self.file_name = get_filename()
433
self.file_name = file_name
356
435
self._parser = None
358
def _get_parser(self, file=None):
438
def from_string(cls, str_or_unicode, file_name=None, save=False):
439
"""Create a config object from a string.
441
:param str_or_unicode: A string representing the file content. This will
444
:param file_name: The configuration file path.
446
:param _save: Whether the file should be saved upon creation.
448
conf = cls(file_name=file_name)
449
conf._create_from_string(str_or_unicode, save)
452
def _create_from_string(self, str_or_unicode, save):
453
self._content = StringIO(str_or_unicode.encode('utf-8'))
454
# Some tests use in-memory configs, some other always need the config
455
# file to exist on disk.
457
self._write_config_file()
459
def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
359
460
if self._parser is not None:
360
461
return self._parser
362
input = self._get_filename()
462
if symbol_versioning.deprecated_passed(file):
463
symbol_versioning.warn(
464
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
465
' Use IniBasedConfig(_content=xxx) instead.',
468
if self._content is not None:
469
co_input = self._content
470
elif self.file_name is None:
471
raise AssertionError('We have no content to create the config')
473
co_input = self.file_name
366
self._parser = ConfigObj(input, encoding='utf-8')
475
self._parser = ConfigObj(co_input, encoding='utf-8')
367
476
except configobj.ConfigObjError, e:
368
477
raise errors.ParseConfigError(e.errors, e.config.filename)
478
# Make sure self.reload() will use the right file name
479
self._parser.filename = self.file_name
369
480
return self._parser
483
"""Reload the config file from disk."""
484
if self.file_name is None:
485
raise AssertionError('We need a file name to reload the config')
486
if self._parser is not None:
487
self._parser.reload()
371
489
def _get_matching_sections(self):
372
490
"""Return an ordered list of (section_name, extra_path) pairs.
384
502
"""Override this to define the section used by the config."""
505
def _get_sections(self, name=None):
506
"""Returns an iterator of the sections specified by ``name``.
508
:param name: The section name. If None is supplied, the default
509
configurations are yielded.
511
:return: A tuple (name, section, config_id) for all sections that will
512
be walked by user_get_option() in the 'right' order. The first one
513
is where set_user_option() will update the value.
515
parser = self._get_parser()
517
yield (name, parser[name], self.config_id())
519
# No section name has been given so we fallback to the configobj
520
# itself which holds the variables defined outside of any section.
521
yield (None, parser, self.config_id())
523
def _get_options(self, sections=None):
524
"""Return an ordered list of (name, value, section, config_id) tuples.
526
All options are returned with their associated value and the section
527
they appeared in. ``config_id`` is a unique identifier for the
528
configuration file the option is defined in.
530
:param sections: Default to ``_get_matching_sections`` if not
531
specified. This gives a better control to daughter classes about
532
which sections should be searched. This is a list of (name,
537
parser = self._get_parser()
539
for (section_name, _) in self._get_matching_sections():
541
section = parser[section_name]
543
# This could happen for an empty file for which we define a
544
# DEFAULT section. FIXME: Force callers to provide sections
545
# instead ? -- vila 20100930
547
sections.append((section_name, section))
548
config_id = self.config_id()
549
for (section_name, section) in sections:
550
for (name, value) in section.iteritems():
551
yield (name, parser._quote(value), section_name,
387
554
def _get_option_policy(self, section, option_name):
388
555
"""Return the policy for the given (section, option_name) pair."""
389
556
return POLICY_NONE
476
643
def _get_nickname(self):
477
644
return self.get_user_option('nickname')
480
class GlobalConfig(IniBasedConfig):
646
def remove_user_option(self, option_name, section_name=None):
647
"""Remove a user option and save the configuration file.
649
:param option_name: The option to be removed.
651
:param section_name: The section the option is defined in, default to
655
parser = self._get_parser()
656
if section_name is None:
659
section = parser[section_name]
661
del section[option_name]
663
raise errors.NoSuchConfigOption(option_name)
664
self._write_config_file()
666
def _write_config_file(self):
667
if self.file_name is None:
668
raise AssertionError('We cannot save, self.file_name is None')
669
conf_dir = os.path.dirname(self.file_name)
670
ensure_config_dir_exists(conf_dir)
671
atomic_file = atomicfile.AtomicFile(self.file_name)
672
self._get_parser().write(atomic_file)
675
osutils.copy_ownership_from_path(self.file_name)
678
class LockableConfig(IniBasedConfig):
679
"""A configuration needing explicit locking for access.
681
If several processes try to write the config file, the accesses need to be
684
Daughter classes should decorate all methods that update a config with the
685
``@needs_write_lock`` decorator (they call, directly or indirectly, the
686
``_write_config_file()`` method. These methods (typically ``set_option()``
687
and variants must reload the config file from disk before calling
688
``_write_config_file()``), this can be achieved by calling the
689
``self.reload()`` method. Note that the lock scope should cover both the
690
reading and the writing of the config file which is why the decorator can't
691
be applied to ``_write_config_file()`` only.
693
This should be enough to implement the following logic:
694
- lock for exclusive write access,
695
- reload the config file from disk,
699
This logic guarantees that a writer can update a value without erasing an
700
update made by another writer.
705
def __init__(self, file_name):
706
super(LockableConfig, self).__init__(file_name=file_name)
707
self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
708
self.transport = transport.get_transport(self.dir)
709
self._lock = lockdir.LockDir(self.transport, 'lock')
711
def _create_from_string(self, unicode_bytes, save):
712
super(LockableConfig, self)._create_from_string(unicode_bytes, False)
714
# We need to handle the saving here (as opposed to IniBasedConfig)
717
self._write_config_file()
720
def lock_write(self, token=None):
721
"""Takes a write lock in the directory containing the config file.
723
If the directory doesn't exist it is created.
725
ensure_config_dir_exists(self.dir)
726
return self._lock.lock_write(token)
731
def break_lock(self):
732
self._lock.break_lock()
735
def remove_user_option(self, option_name, section_name=None):
736
super(LockableConfig, self).remove_user_option(option_name,
739
def _write_config_file(self):
740
if self._lock is None or not self._lock.is_held:
741
# NB: if the following exception is raised it probably means a
742
# missing @needs_write_lock decorator on one of the callers.
743
raise errors.ObjectNotLocked(self)
744
super(LockableConfig, self)._write_config_file()
747
class GlobalConfig(LockableConfig):
481
748
"""The configuration that should be used for a specific location."""
751
super(GlobalConfig, self).__init__(file_name=config_filename())
757
def from_string(cls, str_or_unicode, save=False):
758
"""Create a config object from a string.
760
:param str_or_unicode: A string representing the file content. This
761
will be utf-8 encoded.
763
:param save: Whether the file should be saved upon creation.
766
conf._create_from_string(str_or_unicode, save)
483
769
def get_editor(self):
484
770
return self._get_user_option('editor')
487
super(GlobalConfig, self).__init__(config_filename)
489
773
def set_user_option(self, option, value):
490
774
"""Save option and its value in the configuration."""
491
775
self._set_option(option, value, 'DEFAULT')
510
797
self._write_config_file()
512
799
def _set_option(self, option, value, section):
513
# FIXME: RBC 20051029 This should refresh the parser and also take a
514
# file lock on bazaar.conf.
515
conf_dir = os.path.dirname(self._get_filename())
516
ensure_config_dir_exists(conf_dir)
517
801
self._get_parser().setdefault(section, {})[option] = value
518
802
self._write_config_file()
520
def _write_config_file(self):
521
path = self._get_filename()
523
osutils.copy_ownership_from_path(path)
524
self._get_parser().write(f)
528
class LocationConfig(IniBasedConfig):
805
def _get_sections(self, name=None):
806
"""See IniBasedConfig._get_sections()."""
807
parser = self._get_parser()
808
# We don't give access to options defined outside of any section, we
809
# used the DEFAULT section by... default.
810
if name in (None, 'DEFAULT'):
811
# This could happen for an empty file where the DEFAULT section
812
# doesn't exist yet. So we force DEFAULT when yielding
814
if 'DEFAULT' not in parser:
815
parser['DEFAULT']= {}
816
yield (name, parser[name], self.config_id())
819
def remove_user_option(self, option_name, section_name=None):
820
if section_name is None:
821
# We need to force the default section.
822
section_name = 'DEFAULT'
823
# We need to avoid the LockableConfig implementation or we'll lock
825
super(LockableConfig, self).remove_user_option(option_name,
829
class LocationConfig(LockableConfig):
529
830
"""A configuration object that gives the policy for a location."""
531
832
def __init__(self, location):
532
name_generator = locations_config_filename
533
if (not os.path.exists(name_generator()) and
534
os.path.exists(branches_config_filename())):
535
if sys.platform == 'win32':
536
trace.warning('Please rename %s to %s'
537
% (branches_config_filename(),
538
locations_config_filename()))
540
trace.warning('Please rename ~/.bazaar/branches.conf'
541
' to ~/.bazaar/locations.conf')
542
name_generator = branches_config_filename
543
super(LocationConfig, self).__init__(name_generator)
833
super(LocationConfig, self).__init__(
834
file_name=locations_config_filename())
544
835
# local file locations are looked up by local path, rather than
545
836
# by file url. This is because the config file is a user
546
837
# file, and we would rather not expose the user to file urls.
648
967
STORE_LOCATION_APPENDPATH]:
649
968
raise ValueError('bad storage policy %r for %r' %
651
# FIXME: RBC 20051029 This should refresh the parser and also take a
652
# file lock on locations.conf.
653
conf_dir = os.path.dirname(self._get_filename())
654
ensure_config_dir_exists(conf_dir)
655
971
location = self.location
656
972
if location.endswith('/'):
657
973
location = location[:-1]
658
if (not location in self._get_parser() and
659
not location + '/' in self._get_parser()):
660
self._get_parser()[location]={}
661
elif location + '/' in self._get_parser():
974
parser = self._get_parser()
975
if not location in parser and not location + '/' in parser:
976
parser[location] = {}
977
elif location + '/' in parser:
662
978
location = location + '/'
663
self._get_parser()[location][option]=value
979
parser[location][option]=value
664
980
# the allowed values of store match the config policies
665
981
self._set_option_policy(location, option, store)
666
self._get_parser().write(file(self._get_filename(), 'wb'))
982
self._write_config_file()
669
985
class BranchConfig(Config):
670
986
"""A configuration object giving the policy for a branch."""
988
def __init__(self, branch):
989
super(BranchConfig, self).__init__()
990
self._location_config = None
991
self._branch_data_config = None
992
self._global_config = None
994
self.option_sources = (self._get_location_config,
995
self._get_branch_data_config,
996
self._get_global_config)
672
1001
def _get_branch_data_config(self):
673
1002
if self._branch_data_config is None:
674
1003
self._branch_data_config = TreeConfig(self.branch)
1004
self._branch_data_config.config_id = self.config_id
675
1005
return self._branch_data_config
677
1007
def _get_location_config(self):
1078
def _get_sections(self, name=None):
1079
"""See IniBasedConfig.get_sections()."""
1080
for source in self.option_sources:
1081
for section in source()._get_sections(name):
1084
def _get_options(self, sections=None):
1086
# First the locations options
1087
for option in self._get_location_config()._get_options():
1089
# Then the branch options
1090
branch_config = self._get_branch_data_config()
1091
if sections is None:
1092
sections = [('DEFAULT', branch_config._get_parser())]
1093
# FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
1094
# Config itself has no notion of sections :( -- vila 20101001
1095
config_id = self.config_id()
1096
for (section_name, section) in sections:
1097
for (name, value) in section.iteritems():
1098
yield (name, value, section_name,
1099
config_id, branch_config._get_parser())
1100
# Then the global options
1101
for option in self._get_global_config()._get_options():
748
1104
def set_user_option(self, name, value, store=STORE_BRANCH,
749
1105
warn_masked=False):
750
1106
if store == STORE_BRANCH:
899
1259
return os.path.expanduser('~/.cache')
903
"""Calculate automatic user identification.
905
Returns (realname, email).
907
Only used when none is set in the environment or the id file.
909
This previously used the FQDN as the default domain, but that can
910
be very slow on machines where DNS is broken. So now we simply
915
if sys.platform == 'win32':
916
name = win32utils.get_user_name_unicode()
918
raise errors.BzrError("Cannot autodetect user name.\n"
919
"Please, set your name with command like:\n"
920
'bzr whoami "Your Name <name@domain.com>"')
921
host = win32utils.get_host_name_unicode()
923
host = socket.gethostname()
924
return name, (name + '@' + host)
930
w = pwd.getpwuid(uid)
932
raise errors.BzrCommandError('Unable to determine your name. '
933
'Please use "bzr whoami" to set it.')
935
# we try utf-8 first, because on many variants (like Linux),
936
# /etc/passwd "should" be in utf-8, and because it's unlikely to give
937
# false positives. (many users will have their user encoding set to
938
# latin-1, which cannot raise UnicodeError.)
940
gecos = w.pw_gecos.decode('utf-8')
944
encoding = osutils.get_user_encoding()
945
gecos = w.pw_gecos.decode(encoding)
947
raise errors.BzrCommandError('Unable to determine your name. '
948
'Use "bzr whoami" to set it.')
950
username = w.pw_name.decode(encoding)
952
raise errors.BzrCommandError('Unable to determine your name. '
953
'Use "bzr whoami" to set it.')
955
comma = gecos.find(',')
959
realname = gecos[:comma]
966
user_encoding = osutils.get_user_encoding()
967
realname = username = getpass.getuser().decode(user_encoding)
968
except UnicodeDecodeError:
969
raise errors.BzrError("Can't decode username as %s." % \
972
return realname, (username + '@' + socket.gethostname())
975
1262
def parse_username(username):
976
1263
"""Parse e-mail username and return a (name, address) tuple."""
977
1264
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1517
1827
return StringIO()
1519
1829
def _get_configobj(self):
1520
return ConfigObj(self._get_config_file(), encoding='utf-8')
1830
f = self._get_config_file()
1832
return ConfigObj(f, encoding='utf-8')
1522
1836
def _set_configobj(self, configobj):
1523
1837
out_file = StringIO()
1524
1838
configobj.write(out_file)
1525
1839
out_file.seek(0)
1526
1840
self._transport.put_file(self._filename, out_file)
1843
class cmd_config(commands.Command):
1844
__doc__ = """Display, set or remove a configuration option.
1846
Display the active value for a given option.
1848
If --all is specified, NAME is interpreted as a regular expression and all
1849
matching options are displayed mentioning their scope. The active value
1850
that bzr will take into account is the first one displayed for each option.
1852
If no NAME is given, --all .* is implied.
1854
Setting a value is achieved by using name=value without spaces. The value
1855
is set in the most relevant scope and can be checked by displaying the
1859
takes_args = ['name?']
1863
# FIXME: This should be a registry option so that plugins can register
1864
# their own config files (or not) -- vila 20101002
1865
commands.Option('scope', help='Reduce the scope to the specified'
1866
' configuration file',
1868
commands.Option('all',
1869
help='Display all the defined values for the matching options.',
1871
commands.Option('remove', help='Remove the option from'
1872
' the configuration file'),
1875
@commands.display_command
1876
def run(self, name=None, all=False, directory=None, scope=None,
1878
if directory is None:
1880
directory = urlutils.normalize_url(directory)
1882
raise errors.BzrError(
1883
'--all and --remove are mutually exclusive.')
1885
# Delete the option in the given scope
1886
self._remove_config_option(name, directory, scope)
1888
# Defaults to all options
1889
self._show_matching_options('.*', directory, scope)
1892
name, value = name.split('=', 1)
1894
# Display the option(s) value(s)
1896
self._show_matching_options(name, directory, scope)
1898
self._show_value(name, directory, scope)
1901
raise errors.BzrError(
1902
'Only one option can be set.')
1903
# Set the option value
1904
self._set_config_option(name, value, directory, scope)
1906
def _get_configs(self, directory, scope=None):
1907
"""Iterate the configurations specified by ``directory`` and ``scope``.
1909
:param directory: Where the configurations are derived from.
1911
:param scope: A specific config to start from.
1913
if scope is not None:
1914
if scope == 'bazaar':
1915
yield GlobalConfig()
1916
elif scope == 'locations':
1917
yield LocationConfig(directory)
1918
elif scope == 'branch':
1919
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1921
yield br.get_config()
1924
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1926
yield br.get_config()
1927
except errors.NotBranchError:
1928
yield LocationConfig(directory)
1929
yield GlobalConfig()
1931
def _show_value(self, name, directory, scope):
1933
for c in self._get_configs(directory, scope):
1936
for (oname, value, section, conf_id, parser) in c._get_options():
1938
# Display only the first value and exit
1940
# FIXME: We need to use get_user_option to take policies
1941
# into account and we need to make sure the option exists
1942
# too (hence the two for loops), this needs a better API
1944
value = c.get_user_option(name)
1945
# Quote the value appropriately
1946
value = parser._quote(value)
1947
self.outf.write('%s\n' % (value,))
1951
raise errors.NoSuchConfigOption(name)
1953
def _show_matching_options(self, name, directory, scope):
1954
name = re.compile(name)
1955
# We want any error in the regexp to be raised *now* so we need to
1956
# avoid the delay introduced by the lazy regexp.
1957
name._compile_and_collapse()
1960
for c in self._get_configs(directory, scope):
1961
for (oname, value, section, conf_id, parser) in c._get_options():
1962
if name.search(oname):
1963
if cur_conf_id != conf_id:
1964
# Explain where the options are defined
1965
self.outf.write('%s:\n' % (conf_id,))
1966
cur_conf_id = conf_id
1968
if (section not in (None, 'DEFAULT')
1969
and cur_section != section):
1970
# Display the section if it's not the default (or only)
1972
self.outf.write(' [%s]\n' % (section,))
1973
cur_section = section
1974
self.outf.write(' %s = %s\n' % (oname, value))
1976
def _set_config_option(self, name, value, directory, scope):
1977
for conf in self._get_configs(directory, scope):
1978
conf.set_user_option(name, value)
1981
raise errors.NoSuchConfig(scope)
1983
def _remove_config_option(self, name, directory, scope):
1985
raise errors.BzrCommandError(
1986
'--remove expects an option to remove.')
1988
for conf in self._get_configs(directory, scope):
1989
for (section_name, section, conf_id) in conf._get_sections():
1990
if scope is not None and conf_id != scope:
1991
# Not the right configuration file
1994
if conf_id != conf.config_id():
1995
conf = self._get_configs(directory, conf_id).next()
1996
# We use the first section in the first config where the
1997
# option is defined to remove it
1998
conf.remove_user_option(name, section_name)
2003
raise errors.NoSuchConfig(scope)
2005
raise errors.NoSuchConfigOption(name)