258
269
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
260
$BZR_EMAIL can be set to override this (as well as the
261
deprecated $BZREMAIL), then
271
$BZR_EMAIL can be set to override this, then
262
272
the concrete policy type is checked, and finally
263
273
$EMAIL is examined.
264
If none is found, a reasonable default is (hopefully)
267
TODO: Check it's reasonably well-formed.
274
If no username can be found, errors.NoWhoami exception is raised.
269
276
v = os.environ.get('BZR_EMAIL')
271
278
return v.decode(osutils.get_user_encoding())
273
279
v = self._get_user_id()
277
282
v = os.environ.get('EMAIL')
279
284
return v.decode(osutils.get_user_encoding())
281
285
name, email = _auto_user_id()
283
287
return '%s <%s>' % (name, email)
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.
287
299
def signature_checking(self):
288
300
"""What is the current policy for signature checking?."""
350
362
class IniBasedConfig(Config):
351
363
"""A configuration policy that draws from ini files."""
353
def __init__(self, get_filename):
365
def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
367
"""Base class for configuration files using an ini-like syntax.
369
:param file_name: The configuration file path.
354
371
super(IniBasedConfig, self).__init__()
355
self._get_filename = get_filename
372
self.file_name = file_name
373
if symbol_versioning.deprecated_passed(get_filename):
374
symbol_versioning.warn(
375
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
376
' Use file_name instead.',
379
if get_filename is not None:
380
self.file_name = get_filename()
382
self.file_name = file_name
356
384
self._parser = None
358
def _get_parser(self, file=None):
387
def from_string(cls, str_or_unicode, file_name=None, save=False):
388
"""Create a config object from a string.
390
:param str_or_unicode: A string representing the file content. This will
393
:param file_name: The configuration file path.
395
:param _save: Whether the file should be saved upon creation.
397
conf = cls(file_name=file_name)
398
conf._create_from_string(str_or_unicode, save)
401
def _create_from_string(self, str_or_unicode, save):
402
self._content = StringIO(str_or_unicode.encode('utf-8'))
403
# Some tests use in-memory configs, some other always need the config
404
# file to exist on disk.
406
self._write_config_file()
408
def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
359
409
if self._parser is not None:
360
410
return self._parser
362
input = self._get_filename()
411
if symbol_versioning.deprecated_passed(file):
412
symbol_versioning.warn(
413
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
414
' Use IniBasedConfig(_content=xxx) instead.',
417
if self._content is not None:
418
co_input = self._content
419
elif self.file_name is None:
420
raise AssertionError('We have no content to create the config')
422
co_input = self.file_name
366
self._parser = ConfigObj(input, encoding='utf-8')
424
self._parser = ConfigObj(co_input, encoding='utf-8')
367
425
except configobj.ConfigObjError, e:
368
426
raise errors.ParseConfigError(e.errors, e.config.filename)
427
# Make sure self.reload() will use the right file name
428
self._parser.filename = self.file_name
369
429
return self._parser
432
"""Reload the config file from disk."""
433
if self.file_name is None:
434
raise AssertionError('We need a file name to reload the config')
435
if self._parser is not None:
436
self._parser.reload()
371
438
def _get_matching_sections(self):
372
439
"""Return an ordered list of (section_name, extra_path) pairs.
384
451
"""Override this to define the section used by the config."""
454
def _get_sections(self, name=None):
455
"""Returns an iterator of the sections specified by ``name``.
457
:param name: The section name. If None is supplied, the default
458
configurations are yielded.
460
:return: A tuple (name, section, config_id) for all sections that will
461
be walked by user_get_option() in the 'right' order. The first one
462
is where set_user_option() will update the value.
464
parser = self._get_parser()
466
yield (name, parser[name], self.config_id())
468
# No section name has been given so we fallback to the configobj
469
# itself which holds the variables defined outside of any section.
470
yield (None, parser, self.config_id())
472
def _get_options(self, sections=None):
473
"""Return an ordered list of (name, value, section, config_id) tuples.
475
All options are returned with their associated value and the section
476
they appeared in. ``config_id`` is a unique identifier for the
477
configuration file the option is defined in.
479
:param sections: Default to ``_get_matching_sections`` if not
480
specified. This gives a better control to daughter classes about
481
which sections should be searched. This is a list of (name,
486
parser = self._get_parser()
488
for (section_name, _) in self._get_matching_sections():
490
section = parser[section_name]
492
# This could happen for an empty file for which we define a
493
# DEFAULT section. FIXME: Force callers to provide sections
494
# instead ? -- vila 20100930
496
sections.append((section_name, section))
497
config_id = self.config_id()
498
for (section_name, section) in sections:
499
for (name, value) in section.iteritems():
500
yield (name, parser._quote(value), section_name,
387
503
def _get_option_policy(self, section, option_name):
388
504
"""Return the policy for the given (section, option_name) pair."""
389
505
return POLICY_NONE
476
592
def _get_nickname(self):
477
593
return self.get_user_option('nickname')
480
class GlobalConfig(IniBasedConfig):
595
def remove_user_option(self, option_name, section_name=None):
596
"""Remove a user option and save the configuration file.
598
:param option_name: The option to be removed.
600
:param section_name: The section the option is defined in, default to
604
parser = self._get_parser()
605
if section_name is None:
608
section = parser[section_name]
610
del section[option_name]
612
raise errors.NoSuchConfigOption(option_name)
613
self._write_config_file()
615
def _write_config_file(self):
616
if self.file_name is None:
617
raise AssertionError('We cannot save, self.file_name is None')
618
conf_dir = os.path.dirname(self.file_name)
619
ensure_config_dir_exists(conf_dir)
620
atomic_file = atomicfile.AtomicFile(self.file_name)
621
self._get_parser().write(atomic_file)
624
osutils.copy_ownership_from_path(self.file_name)
627
class LockableConfig(IniBasedConfig):
628
"""A configuration needing explicit locking for access.
630
If several processes try to write the config file, the accesses need to be
633
Daughter classes should decorate all methods that update a config with the
634
``@needs_write_lock`` decorator (they call, directly or indirectly, the
635
``_write_config_file()`` method. These methods (typically ``set_option()``
636
and variants must reload the config file from disk before calling
637
``_write_config_file()``), this can be achieved by calling the
638
``self.reload()`` method. Note that the lock scope should cover both the
639
reading and the writing of the config file which is why the decorator can't
640
be applied to ``_write_config_file()`` only.
642
This should be enough to implement the following logic:
643
- lock for exclusive write access,
644
- reload the config file from disk,
648
This logic guarantees that a writer can update a value without erasing an
649
update made by another writer.
654
def __init__(self, file_name):
655
super(LockableConfig, self).__init__(file_name=file_name)
656
self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
657
self.transport = transport.get_transport(self.dir)
658
self._lock = lockdir.LockDir(self.transport, 'lock')
660
def _create_from_string(self, unicode_bytes, save):
661
super(LockableConfig, self)._create_from_string(unicode_bytes, False)
663
# We need to handle the saving here (as opposed to IniBasedConfig)
666
self._write_config_file()
669
def lock_write(self, token=None):
670
"""Takes a write lock in the directory containing the config file.
672
If the directory doesn't exist it is created.
674
ensure_config_dir_exists(self.dir)
675
return self._lock.lock_write(token)
680
def break_lock(self):
681
self._lock.break_lock()
684
def remove_user_option(self, option_name, section_name=None):
685
super(LockableConfig, self).remove_user_option(option_name,
688
def _write_config_file(self):
689
if self._lock is None or not self._lock.is_held:
690
# NB: if the following exception is raised it probably means a
691
# missing @needs_write_lock decorator on one of the callers.
692
raise errors.ObjectNotLocked(self)
693
super(LockableConfig, self)._write_config_file()
696
class GlobalConfig(LockableConfig):
481
697
"""The configuration that should be used for a specific location."""
700
super(GlobalConfig, self).__init__(file_name=config_filename())
706
def from_string(cls, str_or_unicode, save=False):
707
"""Create a config object from a string.
709
:param str_or_unicode: A string representing the file content. This
710
will be utf-8 encoded.
712
:param save: Whether the file should be saved upon creation.
715
conf._create_from_string(str_or_unicode, save)
483
718
def get_editor(self):
484
719
return self._get_user_option('editor')
487
super(GlobalConfig, self).__init__(config_filename)
489
722
def set_user_option(self, option, value):
490
723
"""Save option and its value in the configuration."""
491
724
self._set_option(option, value, 'DEFAULT')
510
746
self._write_config_file()
512
748
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
750
self._get_parser().setdefault(section, {})[option] = value
518
751
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):
754
def _get_sections(self, name=None):
755
"""See IniBasedConfig._get_sections()."""
756
parser = self._get_parser()
757
# We don't give access to options defined outside of any section, we
758
# used the DEFAULT section by... default.
759
if name in (None, 'DEFAULT'):
760
# This could happen for an empty file where the DEFAULT section
761
# doesn't exist yet. So we force DEFAULT when yielding
763
if 'DEFAULT' not in parser:
764
parser['DEFAULT']= {}
765
yield (name, parser[name], self.config_id())
768
def remove_user_option(self, option_name, section_name=None):
769
if section_name is None:
770
# We need to force the default section.
771
section_name = 'DEFAULT'
772
# We need to avoid the LockableConfig implementation or we'll lock
774
super(LockableConfig, self).remove_user_option(option_name,
778
class LocationConfig(LockableConfig):
529
779
"""A configuration object that gives the policy for a location."""
531
781
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)
782
super(LocationConfig, self).__init__(
783
file_name=locations_config_filename())
544
784
# local file locations are looked up by local path, rather than
545
785
# by file url. This is because the config file is a user
546
786
# file, and we would rather not expose the user to file urls.
648
916
STORE_LOCATION_APPENDPATH]:
649
917
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
920
location = self.location
656
921
if location.endswith('/'):
657
922
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():
923
parser = self._get_parser()
924
if not location in parser and not location + '/' in parser:
925
parser[location] = {}
926
elif location + '/' in parser:
662
927
location = location + '/'
663
self._get_parser()[location][option]=value
928
parser[location][option]=value
664
929
# the allowed values of store match the config policies
665
930
self._set_option_policy(location, option, store)
666
self._get_parser().write(file(self._get_filename(), 'wb'))
931
self._write_config_file()
669
934
class BranchConfig(Config):
670
935
"""A configuration object giving the policy for a branch."""
937
def __init__(self, branch):
938
super(BranchConfig, self).__init__()
939
self._location_config = None
940
self._branch_data_config = None
941
self._global_config = None
943
self.option_sources = (self._get_location_config,
944
self._get_branch_data_config,
945
self._get_global_config)
672
950
def _get_branch_data_config(self):
673
951
if self._branch_data_config is None:
674
952
self._branch_data_config = TreeConfig(self.branch)
953
self._branch_data_config.config_id = self.config_id
675
954
return self._branch_data_config
677
956
def _get_location_config(self):
1027
def _get_sections(self, name=None):
1028
"""See IniBasedConfig.get_sections()."""
1029
for source in self.option_sources:
1030
for section in source()._get_sections(name):
1033
def _get_options(self, sections=None):
1035
# First the locations options
1036
for option in self._get_location_config()._get_options():
1038
# Then the branch options
1039
branch_config = self._get_branch_data_config()
1040
if sections is None:
1041
sections = [('DEFAULT', branch_config._get_parser())]
1042
# FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
1043
# Config itself has no notion of sections :( -- vila 20101001
1044
config_id = self.config_id()
1045
for (section_name, section) in sections:
1046
for (name, value) in section.iteritems():
1047
yield (name, value, section_name,
1048
config_id, branch_config._get_parser())
1049
# Then the global options
1050
for option in self._get_global_config()._get_options():
748
1053
def set_user_option(self, name, value, store=STORE_BRANCH,
749
1054
warn_masked=False):
750
1055
if store == STORE_BRANCH:
826
1124
def config_dir():
827
1125
"""Return per-user configuration directory.
829
By default this is ~/.bazaar/
1127
By default this is %APPDATA%/bazaar/2.0 on Windows, ~/.bazaar on Mac OS X
1128
and Linux. On Linux, if there is a $XDG_CONFIG_HOME/bazaar directory,
1129
that will be used instead.
831
1131
TODO: Global option --config-dir to override this.
833
1133
base = os.environ.get('BZR_HOME', None)
834
1134
if sys.platform == 'win32':
1135
# environ variables on Windows are in user encoding/mbcs. So decode
1137
if base is not None:
1138
base = base.decode('mbcs')
835
1139
if base is None:
836
1140
base = win32utils.get_appdata_location_unicode()
837
1141
if base is None:
838
1142
base = os.environ.get('HOME', None)
1143
if base is not None:
1144
base = base.decode('mbcs')
839
1145
if base is None:
840
1146
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
842
1148
return osutils.pathjoin(base, 'bazaar', '2.0')
1149
elif sys.platform == 'darwin':
1151
# this takes into account $HOME
1152
base = os.path.expanduser("~")
1153
return osutils.pathjoin(base, '.bazaar')
844
# cygwin, linux, and darwin all have a $HOME directory
845
1155
if base is None:
1157
xdg_dir = os.environ.get('XDG_CONFIG_HOME', None)
1159
xdg_dir = osutils.pathjoin(os.path.expanduser("~"), ".config")
1160
xdg_dir = osutils.pathjoin(xdg_dir, 'bazaar')
1161
if osutils.isdir(xdg_dir):
1163
"Using configuration in XDG directory %s." % xdg_dir)
846
1166
base = os.path.expanduser("~")
847
1167
return osutils.pathjoin(base, ".bazaar")
899
1214
return os.path.expanduser('~/.cache')
1217
def _get_default_mail_domain():
1218
"""If possible, return the assumed default email domain.
1220
:returns: string mail domain, or None.
1222
if sys.platform == 'win32':
1223
# No implementation yet; patches welcome
1226
f = open('/etc/mailname')
1227
except (IOError, OSError), e:
1230
domain = f.read().strip()
902
1236
def _auto_user_id():
903
1237
"""Calculate automatic user identification.
905
Returns (realname, email).
1239
:returns: (realname, email), either of which may be None if they can't be
907
1242
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
1244
This only returns an email address if we can be fairly sure the
1245
address is reasonable, ie if /etc/mailname is set on unix.
1247
This doesn't use the FQDN as the default domain because that may be
1248
slow, and it doesn't use the hostname alone because that's not normally
1249
a reasonable address.
915
1251
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())
1252
# No implementation to reliably determine Windows default mail
1253
# address; please add one.
1256
default_mail_domain = _get_default_mail_domain()
1257
if not default_mail_domain:
1263
w = pwd.getpwuid(uid)
1265
mutter('no passwd entry for uid %d?' % uid)
1268
# we try utf-8 first, because on many variants (like Linux),
1269
# /etc/passwd "should" be in utf-8, and because it's unlikely to give
1270
# false positives. (many users will have their user encoding set to
1271
# latin-1, which cannot raise UnicodeError.)
1273
gecos = w.pw_gecos.decode('utf-8')
1275
except UnicodeError:
1277
encoding = osutils.get_user_encoding()
1278
gecos = w.pw_gecos.decode(encoding)
1279
except UnicodeError, e:
1280
mutter("cannot decode passwd entry %s" % w)
1283
username = w.pw_name.decode(encoding)
1284
except UnicodeError, e:
1285
mutter("cannot decode passwd entry %s" % w)
1288
comma = gecos.find(',')
1292
realname = gecos[:comma]
1294
return realname, (username + '@' + default_mail_domain)
975
1297
def parse_username(username):
1517
1862
return StringIO()
1519
1864
def _get_configobj(self):
1520
return ConfigObj(self._get_config_file(), encoding='utf-8')
1865
f = self._get_config_file()
1867
return ConfigObj(f, encoding='utf-8')
1522
1871
def _set_configobj(self, configobj):
1523
1872
out_file = StringIO()
1524
1873
configobj.write(out_file)
1525
1874
out_file.seek(0)
1526
1875
self._transport.put_file(self._filename, out_file)
1878
class cmd_config(commands.Command):
1879
__doc__ = """Display, set or remove a configuration option.
1881
Display the active value for a given option.
1883
If --all is specified, NAME is interpreted as a regular expression and all
1884
matching options are displayed mentioning their scope. The active value
1885
that bzr will take into account is the first one displayed for each option.
1887
If no NAME is given, --all .* is implied.
1889
Setting a value is achieved by using name=value without spaces. The value
1890
is set in the most relevant scope and can be checked by displaying the
1894
takes_args = ['name?']
1898
# FIXME: This should be a registry option so that plugins can register
1899
# their own config files (or not) -- vila 20101002
1900
commands.Option('scope', help='Reduce the scope to the specified'
1901
' configuration file',
1903
commands.Option('all',
1904
help='Display all the defined values for the matching options.',
1906
commands.Option('remove', help='Remove the option from'
1907
' the configuration file'),
1910
@commands.display_command
1911
def run(self, name=None, all=False, directory=None, scope=None,
1913
if directory is None:
1915
directory = urlutils.normalize_url(directory)
1917
raise errors.BzrError(
1918
'--all and --remove are mutually exclusive.')
1920
# Delete the option in the given scope
1921
self._remove_config_option(name, directory, scope)
1923
# Defaults to all options
1924
self._show_matching_options('.*', directory, scope)
1927
name, value = name.split('=', 1)
1929
# Display the option(s) value(s)
1931
self._show_matching_options(name, directory, scope)
1933
self._show_value(name, directory, scope)
1936
raise errors.BzrError(
1937
'Only one option can be set.')
1938
# Set the option value
1939
self._set_config_option(name, value, directory, scope)
1941
def _get_configs(self, directory, scope=None):
1942
"""Iterate the configurations specified by ``directory`` and ``scope``.
1944
:param directory: Where the configurations are derived from.
1946
:param scope: A specific config to start from.
1948
if scope is not None:
1949
if scope == 'bazaar':
1950
yield GlobalConfig()
1951
elif scope == 'locations':
1952
yield LocationConfig(directory)
1953
elif scope == 'branch':
1954
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1956
yield br.get_config()
1959
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1961
yield br.get_config()
1962
except errors.NotBranchError:
1963
yield LocationConfig(directory)
1964
yield GlobalConfig()
1966
def _show_value(self, name, directory, scope):
1968
for c in self._get_configs(directory, scope):
1971
for (oname, value, section, conf_id, parser) in c._get_options():
1973
# Display only the first value and exit
1975
# FIXME: We need to use get_user_option to take policies
1976
# into account and we need to make sure the option exists
1977
# too (hence the two for loops), this needs a better API
1979
value = c.get_user_option(name)
1980
# Quote the value appropriately
1981
value = parser._quote(value)
1982
self.outf.write('%s\n' % (value,))
1986
raise errors.NoSuchConfigOption(name)
1988
def _show_matching_options(self, name, directory, scope):
1989
name = re.compile(name)
1990
# We want any error in the regexp to be raised *now* so we need to
1991
# avoid the delay introduced by the lazy regexp.
1992
name._compile_and_collapse()
1995
for c in self._get_configs(directory, scope):
1996
for (oname, value, section, conf_id, parser) in c._get_options():
1997
if name.search(oname):
1998
if cur_conf_id != conf_id:
1999
# Explain where the options are defined
2000
self.outf.write('%s:\n' % (conf_id,))
2001
cur_conf_id = conf_id
2003
if (section not in (None, 'DEFAULT')
2004
and cur_section != section):
2005
# Display the section if it's not the default (or only)
2007
self.outf.write(' [%s]\n' % (section,))
2008
cur_section = section
2009
self.outf.write(' %s = %s\n' % (oname, value))
2011
def _set_config_option(self, name, value, directory, scope):
2012
for conf in self._get_configs(directory, scope):
2013
conf.set_user_option(name, value)
2016
raise errors.NoSuchConfig(scope)
2018
def _remove_config_option(self, name, directory, scope):
2020
raise errors.BzrCommandError(
2021
'--remove expects an option to remove.')
2023
for conf in self._get_configs(directory, scope):
2024
for (section_name, section, conf_id) in conf._get_sections():
2025
if scope is not None and conf_id != scope:
2026
# Not the right configuration file
2029
if conf_id != conf.config_id():
2030
conf = self._get_configs(directory, conf_id).next()
2031
# We use the first section in the first config where the
2032
# option is defined to remove it
2033
conf.remove_user_option(name, section_name)
2038
raise errors.NoSuchConfig(scope)
2040
raise errors.NoSuchConfigOption(name)