329
205
def _get_alias(self, value):
332
def get_nickname(self):
333
return self._get_nickname()
335
def _get_nickname(self):
338
def get_bzr_remote_path(self):
340
return os.environ['BZR_REMOTE_PATH']
342
path = self.get_user_option("bzr_remote_path")
347
def suppress_warning(self, warning):
348
"""Should the warning be suppressed or emitted.
350
:param warning: The name of the warning being tested.
352
:returns: True if the warning should be suppressed, False otherwise.
354
warnings = self.get_user_option_as_list('suppress_warnings')
355
if warnings is None or warning not in warnings:
361
209
class IniBasedConfig(Config):
362
210
"""A configuration policy that draws from ini files."""
364
def __init__(self, get_filename=symbol_versioning.DEPRECATED_PARAMETER,
366
"""Base class for configuration files using an ini-like syntax.
368
:param file_name: The configuration file path.
370
super(IniBasedConfig, self).__init__()
371
self.file_name = file_name
372
if symbol_versioning.deprecated_passed(get_filename):
373
symbol_versioning.warn(
374
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
375
' Use file_name instead.',
378
if get_filename is not None:
379
self.file_name = get_filename()
381
self.file_name = file_name
386
def from_string(cls, str_or_unicode, file_name=None, save=False):
387
"""Create a config object from a string.
389
:param str_or_unicode: A string representing the file content. This will
392
:param file_name: The configuration file path.
394
:param _save: Whether the file should be saved upon creation.
396
conf = cls(file_name=file_name)
397
conf._create_from_string(str_or_unicode, save)
400
def _create_from_string(self, str_or_unicode, save):
401
self._content = StringIO(str_or_unicode.encode('utf-8'))
402
# Some tests use in-memory configs, some other always need the config
403
# file to exist on disk.
405
self._write_config_file()
407
def _get_parser(self, file=symbol_versioning.DEPRECATED_PARAMETER):
212
def _get_parser(self, file=None):
408
213
if self._parser is not None:
409
214
return self._parser
410
if symbol_versioning.deprecated_passed(file):
411
symbol_versioning.warn(
412
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
413
' Use IniBasedConfig(_content=xxx) instead.',
416
if self._content is not None:
417
co_input = self._content
418
elif self.file_name is None:
419
raise AssertionError('We have no content to create the config')
216
input = self._get_filename()
421
co_input = self.file_name
423
self._parser = ConfigObj(co_input, encoding='utf-8')
220
self._parser = ConfigObj(input, encoding='utf-8')
424
221
except configobj.ConfigObjError, e:
425
222
raise errors.ParseConfigError(e.errors, e.config.filename)
426
# Make sure self.reload() will use the right file name
427
self._parser.filename = self.file_name
428
223
return self._parser
431
"""Reload the config file from disk."""
432
if self.file_name is None:
433
raise AssertionError('We need a file name to reload the config')
434
if self._parser is not None:
435
self._parser.reload()
437
def _get_matching_sections(self):
438
"""Return an ordered list of (section_name, extra_path) pairs.
440
If the section contains inherited configuration, extra_path is
441
a string containing the additional path components.
443
section = self._get_section()
444
if section is not None:
445
return [(section, '')]
449
225
def _get_section(self):
450
226
"""Override this to define the section used by the config."""
453
def _get_sections(self, name=None):
454
"""Returns an iterator of the sections specified by ``name``.
456
:param name: The section name. If None is supplied, the default
457
configurations are yielded.
459
:return: A tuple (name, section, config_id) for all sections that will
460
be walked by user_get_option() in the 'right' order. The first one
461
is where set_user_option() will update the value.
463
parser = self._get_parser()
465
yield (name, parser[name], self.config_id())
467
# No section name has been given so we fallback to the configobj
468
# itself which holds the variables defined outside of any section.
469
yield (None, parser, self.config_id())
471
def _get_options(self, sections=None):
472
"""Return an ordered list of (name, value, section, config_id) tuples.
474
All options are returned with their associated value and the section
475
they appeared in. ``config_id`` is a unique identifier for the
476
configuration file the option is defined in.
478
:param sections: Default to ``_get_matching_sections`` if not
479
specified. This gives a better control to daughter classes about
480
which sections should be searched. This is a list of (name,
485
parser = self._get_parser()
487
for (section_name, _) in self._get_matching_sections():
489
section = parser[section_name]
491
# This could happen for an empty file for which we define a
492
# DEFAULT section. FIXME: Force callers to provide sections
493
# instead ? -- vila 20100930
495
sections.append((section_name, section))
496
config_id = self.config_id()
497
for (section_name, section) in sections:
498
for (name, value) in section.iteritems():
499
yield (name, value, section_name, config_id)
501
def _get_option_policy(self, section, option_name):
502
"""Return the policy for the given (section, option_name) pair."""
505
def _get_change_editor(self):
506
return self.get_user_option('change_editor')
508
229
def _get_signature_checking(self):
509
230
"""See Config._get_signature_checking."""
510
231
policy = self._get_user_option('check_signatures')
512
233
return self._string_to_signature_policy(policy)
514
def _get_signing_policy(self):
515
"""See Config._get_signing_policy"""
516
policy = self._get_user_option('create_signatures')
518
return self._string_to_signing_policy(policy)
520
235
def _get_user_id(self):
521
236
"""Get the user id from the 'email' key in the current section."""
522
237
return self._get_user_option('email')
524
239
def _get_user_option(self, option_name):
525
240
"""See Config._get_user_option."""
526
for (section, extra_path) in self._get_matching_sections():
528
value = self._get_parser().get_value(section, option_name)
531
policy = self._get_option_policy(section, option_name)
532
if policy == POLICY_NONE:
534
elif policy == POLICY_NORECURSE:
535
# norecurse items only apply to the exact path
540
elif policy == POLICY_APPENDPATH:
542
value = urlutils.join(value, extra_path)
545
raise AssertionError('Unexpected config policy %r' % policy)
242
return self._get_parser().get_value(self._get_section(),
549
247
def _gpg_signing_command(self):
550
248
"""See Config.gpg_signing_command."""
569
272
raise errors.BzrError("Invalid signatures policy '%s'"
570
273
% signature_string)
572
def _string_to_signing_policy(self, signature_string):
573
"""Convert a string to a signing policy."""
574
if signature_string.lower() == 'when-required':
575
return SIGN_WHEN_REQUIRED
576
if signature_string.lower() == 'never':
578
if signature_string.lower() == 'always':
580
raise errors.BzrError("Invalid signing policy '%s'"
583
275
def _get_alias(self, value):
585
return self._get_parser().get_value("ALIASES",
277
return self._get_parser().get_value("ALIASES",
590
def _get_nickname(self):
591
return self.get_user_option('nickname')
593
def remove_user_option(self, option_name, section_name=None):
594
"""Remove a user option and save the configuration file.
596
:param option_name: The option to be removed.
598
:param section_name: The section the option is defined in, default to
602
parser = self._get_parser()
603
if section_name is None:
606
section = parser[section_name]
608
del section[option_name]
610
raise errors.NoSuchConfigOption(option_name)
611
self._write_config_file()
613
def _write_config_file(self):
614
if self.file_name is None:
615
raise AssertionError('We cannot save, self.file_name is None')
616
conf_dir = os.path.dirname(self.file_name)
617
ensure_config_dir_exists(conf_dir)
618
atomic_file = atomicfile.AtomicFile(self.file_name)
619
self._get_parser().write(atomic_file)
622
osutils.copy_ownership_from_path(self.file_name)
625
class LockableConfig(IniBasedConfig):
626
"""A configuration needing explicit locking for access.
628
If several processes try to write the config file, the accesses need to be
631
Daughter classes should decorate all methods that update a config with the
632
``@needs_write_lock`` decorator (they call, directly or indirectly, the
633
``_write_config_file()`` method. These methods (typically ``set_option()``
634
and variants must reload the config file from disk before calling
635
``_write_config_file()``), this can be achieved by calling the
636
``self.reload()`` method. Note that the lock scope should cover both the
637
reading and the writing of the config file which is why the decorator can't
638
be applied to ``_write_config_file()`` only.
640
This should be enough to implement the following logic:
641
- lock for exclusive write access,
642
- reload the config file from disk,
646
This logic guarantees that a writer can update a value without erasing an
647
update made by another writer.
652
def __init__(self, file_name):
653
super(LockableConfig, self).__init__(file_name=file_name)
654
self.dir = osutils.dirname(osutils.safe_unicode(self.file_name))
655
self.transport = transport.get_transport(self.dir)
656
self._lock = lockdir.LockDir(self.transport, 'lock')
658
def _create_from_string(self, unicode_bytes, save):
659
super(LockableConfig, self)._create_from_string(unicode_bytes, False)
661
# We need to handle the saving here (as opposed to IniBasedConfig)
664
self._write_config_file()
667
def lock_write(self, token=None):
668
"""Takes a write lock in the directory containing the config file.
670
If the directory doesn't exist it is created.
672
ensure_config_dir_exists(self.dir)
673
return self._lock.lock_write(token)
678
def break_lock(self):
679
self._lock.break_lock()
682
def remove_user_option(self, option_name, section_name=None):
683
super(LockableConfig, self).remove_user_option(option_name,
686
def _write_config_file(self):
687
if self._lock is None or not self._lock.is_held:
688
# NB: if the following exception is raised it probably means a
689
# missing @needs_write_lock decorator on one of the callers.
690
raise errors.ObjectNotLocked(self)
691
super(LockableConfig, self)._write_config_file()
694
class GlobalConfig(LockableConfig):
283
class GlobalConfig(IniBasedConfig):
695
284
"""The configuration that should be used for a specific location."""
698
super(GlobalConfig, self).__init__(file_name=config_filename())
704
def from_string(cls, str_or_unicode, save=False):
705
"""Create a config object from a string.
707
:param str_or_unicode: A string representing the file content. This
708
will be utf-8 encoded.
710
:param save: Whether the file should be saved upon creation.
713
conf._create_from_string(str_or_unicode, save)
716
286
def get_editor(self):
717
287
return self._get_user_option('editor')
720
def set_user_option(self, option, value):
721
"""Save option and its value in the configuration."""
722
self._set_option(option, value, 'DEFAULT')
724
def get_aliases(self):
725
"""Return the aliases section."""
726
if 'ALIASES' in self._get_parser():
727
return self._get_parser()['ALIASES']
732
def set_alias(self, alias_name, alias_command):
733
"""Save the alias in the configuration."""
734
self._set_option(alias_name, alias_command, 'ALIASES')
737
def unset_alias(self, alias_name):
738
"""Unset an existing alias."""
740
aliases = self._get_parser().get('ALIASES')
741
if not aliases or alias_name not in aliases:
742
raise errors.NoSuchAlias(alias_name)
743
del aliases[alias_name]
744
self._write_config_file()
746
def _set_option(self, option, value, section):
748
self._get_parser().setdefault(section, {})[option] = value
749
self._write_config_file()
752
def _get_sections(self, name=None):
753
"""See IniBasedConfig._get_sections()."""
754
parser = self._get_parser()
755
# We don't give access to options defined outside of any section, we
756
# used the DEFAULT section by... default.
757
if name in (None, 'DEFAULT'):
758
# This could happen for an empty file where the DEFAULT section
759
# doesn't exist yet. So we force DEFAULT when yielding
761
if 'DEFAULT' not in parser:
762
parser['DEFAULT']= {}
763
yield (name, parser[name], self.config_id())
766
def remove_user_option(self, option_name, section_name=None):
767
if section_name is None:
768
# We need to force the default section.
769
section_name = 'DEFAULT'
770
# We need to avoid the LockableConfig implementation or we'll lock
772
super(LockableConfig, self).remove_user_option(option_name,
776
class LocationConfig(LockableConfig):
290
super(GlobalConfig, self).__init__(config_filename)
293
class LocationConfig(IniBasedConfig):
777
294
"""A configuration object that gives the policy for a location."""
779
296
def __init__(self, location):
780
super(LocationConfig, self).__init__(
781
file_name=locations_config_filename())
782
# local file locations are looked up by local path, rather than
783
# by file url. This is because the config file is a user
784
# file, and we would rather not expose the user to file urls.
785
if location.startswith('file://'):
786
location = urlutils.local_path_from_url(location)
297
super(LocationConfig, self).__init__(branches_config_filename)
298
self._global_config = None
787
299
self.location = location
793
def from_string(cls, str_or_unicode, location, save=False):
794
"""Create a config object from a string.
796
:param str_or_unicode: A string representing the file content. This will
799
:param location: The location url to filter the configuration.
801
:param save: Whether the file should be saved upon creation.
301
def _get_global_config(self):
302
if self._global_config is None:
303
self._global_config = GlobalConfig()
304
return self._global_config
306
def _get_section(self):
307
"""Get the section we should look in for config items.
309
Returns None if none exists.
310
TODO: perhaps return a NullSection that thunks through to the
804
conf._create_from_string(str_or_unicode, save)
807
def _get_matching_sections(self):
808
"""Return an ordered list of section names matching this location."""
809
313
sections = self._get_parser()
810
314
location_names = self.location.split('/')
811
315
if self.location.endswith('/'):
812
316
del location_names[-1]
814
318
for section in sections:
815
# location is a local path if possible, so we need
816
# to convert 'file://' urls to local paths if necessary.
817
# This also avoids having file:///path be a more exact
818
# match than '/path'.
819
if section.startswith('file://'):
820
section_path = urlutils.local_path_from_url(section)
822
section_path = section
823
section_names = section_path.split('/')
319
section_names = section.split('/')
824
320
if section.endswith('/'):
825
321
del section_names[-1]
826
322
names = zip(location_names, section_names)
828
324
for name in names:
829
if not fnmatch.fnmatch(name[0], name[1]):
325
if not fnmatch(name[0], name[1]):
835
331
# if section is longer, no match.
836
332
if len(section_names) > len(location_names):
838
matches.append((len(section_names), section,
839
'/'.join(location_names[len(section_names):])))
840
# put the longest (aka more specific) locations first
334
# if path is longer, and recurse is not true, no match
335
if len(section_names) < len(location_names):
337
if not self._get_parser()[section].as_bool('recurse'):
341
matches.append((len(section_names), section))
841
344
matches.sort(reverse=True)
843
for (length, section, extra_path) in matches:
844
sections.append((section, extra_path))
845
# should we stop looking for parent configs here?
847
if self._get_parser()[section].as_bool('ignore_parents'):
853
def _get_sections(self, name=None):
854
"""See IniBasedConfig._get_sections()."""
855
# We ignore the name here as the only sections handled are named with
856
# the location path and we don't expose embedded sections either.
857
parser = self._get_parser()
858
for name, extra_path in self._get_matching_sections():
859
yield (name, parser[name], self.config_id())
861
def _get_option_policy(self, section, option_name):
862
"""Return the policy for the given (section, option_name) pair."""
863
# check for the old 'recurse=False' flag
865
recurse = self._get_parser()[section].as_bool('recurse')
869
return POLICY_NORECURSE
871
policy_key = option_name + ':policy'
873
policy_name = self._get_parser()[section][policy_key]
877
return _policy_value[policy_name]
879
def _set_option_policy(self, section, option_name, option_policy):
880
"""Set the policy for the given option name in the given section."""
881
# The old recurse=False option affects all options in the
882
# section. To handle multiple policies in the section, we
883
# need to convert it to a policy_norecurse key.
885
recurse = self._get_parser()[section].as_bool('recurse')
889
symbol_versioning.warn(
890
'The recurse option is deprecated as of 0.14. '
891
'The section "%s" has been converted to use policies.'
894
del self._get_parser()[section]['recurse']
896
for key in self._get_parser()[section].keys():
897
if not key.endswith(':policy'):
898
self._get_parser()[section][key +
899
':policy'] = 'norecurse'
901
policy_key = option_name + ':policy'
902
policy_name = _policy_name[option_policy]
903
if policy_name is not None:
904
self._get_parser()[section][policy_key] = policy_name
906
if policy_key in self._get_parser()[section]:
907
del self._get_parser()[section][policy_key]
910
def set_user_option(self, option, value, store=STORE_LOCATION):
347
def _gpg_signing_command(self):
348
"""See Config.gpg_signing_command."""
349
command = super(LocationConfig, self)._gpg_signing_command()
350
if command is not None:
352
return self._get_global_config()._gpg_signing_command()
354
def _log_format(self):
355
"""See Config.log_format."""
356
command = super(LocationConfig, self)._log_format()
357
if command is not None:
359
return self._get_global_config()._log_format()
361
def _get_user_id(self):
362
user_id = super(LocationConfig, self)._get_user_id()
363
if user_id is not None:
365
return self._get_global_config()._get_user_id()
367
def _get_user_option(self, option_name):
368
"""See Config._get_user_option."""
369
option_value = super(LocationConfig,
370
self)._get_user_option(option_name)
371
if option_value is not None:
373
return self._get_global_config()._get_user_option(option_name)
375
def _get_signature_checking(self):
376
"""See Config._get_signature_checking."""
377
check = super(LocationConfig, self)._get_signature_checking()
378
if check is not None:
380
return self._get_global_config()._get_signature_checking()
382
def _post_commit(self):
383
"""See Config.post_commit."""
384
hook = self._get_user_option('post_commit')
387
return self._get_global_config()._post_commit()
389
def set_user_option(self, option, value):
911
390
"""Save option and its value in the configuration."""
912
if store not in [STORE_LOCATION,
913
STORE_LOCATION_NORECURSE,
914
STORE_LOCATION_APPENDPATH]:
915
raise ValueError('bad storage policy %r for %r' %
391
# FIXME: RBC 20051029 This should refresh the parser and also take a
392
# file lock on branches.conf.
393
conf_dir = os.path.dirname(self._get_filename())
394
ensure_config_dir_exists(conf_dir)
918
395
location = self.location
919
396
if location.endswith('/'):
920
397
location = location[:-1]
921
parser = self._get_parser()
922
if not location in parser and not location + '/' in parser:
923
parser[location] = {}
924
elif location + '/' in parser:
398
if (not location in self._get_parser() and
399
not location + '/' in self._get_parser()):
400
self._get_parser()[location]={}
401
elif location + '/' in self._get_parser():
925
402
location = location + '/'
926
parser[location][option]=value
927
# the allowed values of store match the config policies
928
self._set_option_policy(location, option, store)
929
self._write_config_file()
403
self._get_parser()[location][option]=value
404
self._get_parser().write(file(self._get_filename(), 'wb'))
932
407
class BranchConfig(Config):
933
408
"""A configuration object giving the policy for a branch."""
935
def __init__(self, branch):
936
super(BranchConfig, self).__init__()
937
self._location_config = None
938
self._branch_data_config = None
939
self._global_config = None
941
self.option_sources = (self._get_location_config,
942
self._get_branch_data_config,
943
self._get_global_config)
948
def _get_branch_data_config(self):
949
if self._branch_data_config is None:
950
self._branch_data_config = TreeConfig(self.branch)
951
self._branch_data_config.config_id = self.config_id
952
return self._branch_data_config
954
410
def _get_location_config(self):
955
411
if self._location_config is None:
956
412
self._location_config = LocationConfig(self.branch.base)
957
413
return self._location_config
959
def _get_global_config(self):
960
if self._global_config is None:
961
self._global_config = GlobalConfig()
962
return self._global_config
964
def _get_best_value(self, option_name):
965
"""This returns a user option from local, tree or global config.
967
They are tried in that order. Use get_safe_value if trusted values
970
for source in self.option_sources:
971
value = getattr(source(), option_name)()
972
if value is not None:
976
def _get_safe_value(self, option_name):
977
"""This variant of get_best_value never returns untrusted values.
979
It does not return values from the branch data, because the branch may
980
not be controlled by the user.
982
We may wish to allow locations.conf to control whether branches are
983
trusted in the future.
985
for source in (self._get_location_config, self._get_global_config):
986
value = getattr(source(), option_name)()
987
if value is not None:
991
415
def _get_user_id(self):
992
416
"""Return the full user id for the branch.
994
e.g. "John Hacker <jhacker@example.com>"
418
e.g. "John Hacker <jhacker@foo.org>"
995
419
This is looked up in the email controlfile for the branch.
998
return (self.branch._transport.get_bytes("email")
999
.decode(osutils.get_user_encoding())
422
return (self.branch.control_files.get_utf8("email")
424
.decode(bzrlib.user_encoding)
1000
425
.rstrip("\r\n"))
1001
426
except errors.NoSuchFile, e:
1004
return self._get_best_value('_get_user_id')
1006
def _get_change_editor(self):
1007
return self._get_best_value('_get_change_editor')
429
return self._get_location_config()._get_user_id()
1009
431
def _get_signature_checking(self):
1010
432
"""See Config._get_signature_checking."""
1011
return self._get_best_value('_get_signature_checking')
1013
def _get_signing_policy(self):
1014
"""See Config._get_signing_policy."""
1015
return self._get_best_value('_get_signing_policy')
433
return self._get_location_config()._get_signature_checking()
1017
435
def _get_user_option(self, option_name):
1018
436
"""See Config._get_user_option."""
1019
for source in self.option_sources:
1020
value = source()._get_user_option(option_name)
1021
if value is not None:
1025
def _get_sections(self, name=None):
1026
"""See IniBasedConfig.get_sections()."""
1027
for source in self.option_sources:
1028
for section in source()._get_sections(name):
1031
def _get_options(self, sections=None):
1033
# First the locations options
1034
for option in self._get_location_config()._get_options():
1036
# Then the branch options
1037
branch_config = self._get_branch_data_config()
1038
if sections is None:
1039
sections = [('DEFAULT', branch_config._get_parser())]
1040
# FIXME: We shouldn't have to duplicate the code in IniBasedConfig but
1041
# Config itself has no notion of sections :( -- vila 20101001
1042
config_id = self.config_id()
1043
for (section_name, section) in sections:
1044
for (name, value) in section.iteritems():
1045
yield (name, value, section_name, config_id)
1046
# Then the global options
1047
for option in self._get_global_config()._get_options():
1050
def set_user_option(self, name, value, store=STORE_BRANCH,
1052
if store == STORE_BRANCH:
1053
self._get_branch_data_config().set_option(value, name)
1054
elif store == STORE_GLOBAL:
1055
self._get_global_config().set_user_option(name, value)
1057
self._get_location_config().set_user_option(name, value, store)
1060
if store in (STORE_GLOBAL, STORE_BRANCH):
1061
mask_value = self._get_location_config().get_user_option(name)
1062
if mask_value is not None:
1063
trace.warning('Value "%s" is masked by "%s" from'
1064
' locations.conf', value, mask_value)
1066
if store == STORE_GLOBAL:
1067
branch_config = self._get_branch_data_config()
1068
mask_value = branch_config.get_user_option(name)
1069
if mask_value is not None:
1070
trace.warning('Value "%s" is masked by "%s" from'
1071
' branch.conf', value, mask_value)
1073
def remove_user_option(self, option_name, section_name=None):
1074
self._get_branch_data_config().remove_option(option_name, section_name)
437
return self._get_location_config()._get_user_option(option_name)
1076
439
def _gpg_signing_command(self):
1077
440
"""See Config.gpg_signing_command."""
1078
return self._get_safe_value('_gpg_signing_command')
441
return self._get_location_config()._gpg_signing_command()
443
def __init__(self, branch):
444
super(BranchConfig, self).__init__()
445
self._location_config = None
1080
448
def _post_commit(self):
1081
449
"""See Config.post_commit."""
1082
return self._get_safe_value('_post_commit')
1084
def _get_nickname(self):
1085
value = self._get_explicit_nickname()
1086
if value is not None:
1088
return urlutils.unescape(self.branch.base.split('/')[-2])
1090
def has_explicit_nickname(self):
1091
"""Return true if a nickname has been explicitly assigned."""
1092
return self._get_explicit_nickname() is not None
1094
def _get_explicit_nickname(self):
1095
return self._get_best_value('_get_nickname')
450
return self._get_location_config()._post_commit()
1097
452
def _log_format(self):
1098
453
"""See Config.log_format."""
1099
return self._get_best_value('_log_format')
454
return self._get_location_config()._log_format()
1102
457
def ensure_config_dir_exists(path=None):
1111
466
if sys.platform == 'win32':
1112
467
parent_dir = os.path.dirname(path)
1113
468
if not os.path.isdir(parent_dir):
1114
trace.mutter('creating config parent directory: %r', parent_dir)
1115
os.mkdir(parent_dir)
1116
trace.mutter('creating config directory: %r', path)
469
mutter('creating config parent directory: %r', parent_dir)
471
mutter('creating config directory: %r', path)
1118
osutils.copy_ownership_from_path(path)
1121
475
def config_dir():
1122
476
"""Return per-user configuration directory.
1124
478
By default this is ~/.bazaar/
1126
480
TODO: Global option --config-dir to override this.
1128
482
base = os.environ.get('BZR_HOME', None)
1129
483
if sys.platform == 'win32':
1130
484
if base is None:
1131
base = win32utils.get_appdata_location_unicode()
485
base = os.environ.get('APPDATA', None)
1132
486
if base is None:
1133
487
base = os.environ.get('HOME', None)
1134
488
if base is None:
1135
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1137
return osutils.pathjoin(base, 'bazaar', '2.0')
489
raise errors.BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
490
return pathjoin(base, 'bazaar', '2.0')
492
# cygwin, linux, and darwin all have a $HOME directory
1139
493
if base is None:
1140
494
base = os.path.expanduser("~")
1141
return osutils.pathjoin(base, ".bazaar")
495
return pathjoin(base, ".bazaar")
1144
498
def config_filename():
1145
499
"""Return per-user configuration ini file filename."""
1146
return osutils.pathjoin(config_dir(), 'bazaar.conf')
1149
def locations_config_filename():
500
return pathjoin(config_dir(), 'bazaar.conf')
503
def branches_config_filename():
1150
504
"""Return per-user configuration ini file filename."""
1151
return osutils.pathjoin(config_dir(), 'locations.conf')
1154
def authentication_config_filename():
1155
"""Return per-user authentication ini file filename."""
1156
return osutils.pathjoin(config_dir(), 'authentication.conf')
1159
def user_ignore_config_filename():
1160
"""Return the user default ignore filename"""
1161
return osutils.pathjoin(config_dir(), 'ignore')
1165
"""Return the directory name to store crash files.
1167
This doesn't implicitly create it.
1169
On Windows it's in the config directory; elsewhere it's /var/crash
1170
which may be monitored by apport. It can be overridden by
505
return pathjoin(config_dir(), 'branches.conf')
509
"""Calculate automatic user identification.
511
Returns (realname, email).
513
Only used when none is set in the environment or the id file.
515
This previously used the FQDN as the default domain, but that can
516
be very slow on machines where DNS is broken. So now we simply
1173
if sys.platform == 'win32':
1174
return osutils.pathjoin(config_dir(), 'Crash')
1176
# XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
1178
return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
1181
def xdg_cache_dir():
1182
# See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
1183
# Possibly this should be different on Windows?
1184
e = os.environ.get('XDG_CACHE_DIR', None)
1188
return os.path.expanduser('~/.cache')
1191
def parse_username(username):
1192
"""Parse e-mail username and return a (name, address) tuple."""
1193
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
1195
return (username, '')
1197
return (match.group(1), match.group(2))
521
# XXX: Any good way to get real user name on win32?
526
w = pwd.getpwuid(uid)
529
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
530
username = w.pw_name.decode(bzrlib.user_encoding)
531
except UnicodeDecodeError:
532
# We're using pwd, therefore we're on Unix, so /etc/passwd is ok.
533
raise errors.BzrError("Can't decode username in " \
534
"/etc/passwd as %s." % bzrlib.user_encoding)
536
comma = gecos.find(',')
540
realname = gecos[:comma]
547
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
548
except UnicodeDecodeError:
549
raise errors.BzrError("Can't decode username as %s." % \
550
bzrlib.user_encoding)
552
return realname, (username + '@' + socket.gethostname())
1200
555
def extract_email_address(e):
1201
556
"""Return just the address part of an email string.
1203
That is just the user@domain part, nothing else.
558
That is just the user@domain part, nothing else.
1204
559
This part is required to contain only ascii characters.
1205
560
If it can't be extracted, raises an error.
1207
562
>>> extract_email_address('Jane Tester <jane@test.com>')
1210
name, email = parse_username(e)
1212
raise errors.NoEmailInUsername(e)
1216
class TreeConfig(IniBasedConfig):
565
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
567
raise errors.BzrError("%r doesn't seem to contain "
568
"a reasonable email address" % e)
572
class TreeConfig(object):
1217
573
"""Branch configuration data associated with its contents, not location"""
1219
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
1221
574
def __init__(self, branch):
1222
self._config = branch._get_config()
1223
575
self.branch = branch
1225
def _get_parser(self, file=None):
1226
if file is not None:
1227
return IniBasedConfig._get_parser(file)
1228
return self._config._get_configobj()
577
def _get_config(self):
579
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
581
except errors.NoSuchFile:
582
obj = ConfigObj(encoding='utf=8')
1230
585
def get_option(self, name, section=None, default=None):
1231
586
self.branch.lock_read()
1233
return self._config.get_option(name, section, default)
588
obj = self._get_config()
590
if section is not None:
1235
596
self.branch.unlock()
1237
599
def set_option(self, value, name, section=None):
1238
600
"""Set a per-branch configuration option"""
1239
# FIXME: We shouldn't need to lock explicitly here but rather rely on
1240
# higher levels providing the right lock -- vila 20101004
1241
self.branch.lock_write()
1243
self._config.set_option(value, name, section)
1245
self.branch.unlock()
1247
def remove_option(self, option_name, section_name=None):
1248
# FIXME: We shouldn't need to lock explicitly here but rather rely on
1249
# higher levels providing the right lock -- vila 20101004
1250
self.branch.lock_write()
1252
self._config.remove_option(option_name, section_name)
1254
self.branch.unlock()
1257
class AuthenticationConfig(object):
1258
"""The authentication configuration file based on a ini file.
1260
Implements the authentication.conf file described in
1261
doc/developers/authentication-ring.txt.
1264
def __init__(self, _file=None):
1265
self._config = None # The ConfigObj
1267
self._filename = authentication_config_filename()
1268
self._input = self._filename = authentication_config_filename()
1270
# Tests can provide a string as _file
1271
self._filename = None
1274
def _get_config(self):
1275
if self._config is not None:
1278
# FIXME: Should we validate something here ? Includes: empty
1279
# sections are useless, at least one of
1280
# user/password/password_encoding should be defined, etc.
1282
# Note: the encoding below declares that the file itself is utf-8
1283
# encoded, but the values in the ConfigObj are always Unicode.
1284
self._config = ConfigObj(self._input, encoding='utf-8')
1285
except configobj.ConfigObjError, e:
1286
raise errors.ParseConfigError(e.errors, e.config.filename)
1290
"""Save the config file, only tests should use it for now."""
1291
conf_dir = os.path.dirname(self._filename)
1292
ensure_config_dir_exists(conf_dir)
1293
f = file(self._filename, 'wb')
1295
self._get_config().write(f)
1299
def _set_option(self, section_name, option_name, value):
1300
"""Set an authentication configuration option"""
1301
conf = self._get_config()
1302
section = conf.get(section_name)
1305
section = conf[section]
1306
section[option_name] = value
1309
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1311
"""Returns the matching credentials from authentication.conf file.
1313
:param scheme: protocol
1315
:param host: the server address
1317
:param port: the associated port (optional)
1319
:param user: login (optional)
1321
:param path: the absolute path on the server (optional)
1323
:param realm: the http authentication realm (optional)
1325
:return: A dict containing the matching credentials or None.
1327
- name: the section name of the credentials in the
1328
authentication.conf file,
1329
- user: can't be different from the provided user if any,
1330
- scheme: the server protocol,
1331
- host: the server address,
1332
- port: the server port (can be None),
1333
- path: the absolute server path (can be None),
1334
- realm: the http specific authentication realm (can be None),
1335
- password: the decoded password, could be None if the credential
1336
defines only the user
1337
- verify_certificates: https specific, True if the server
1338
certificate should be verified, False otherwise.
1341
for auth_def_name, auth_def in self._get_config().items():
1342
if type(auth_def) is not configobj.Section:
1343
raise ValueError("%s defined outside a section" % auth_def_name)
1345
a_scheme, a_host, a_user, a_path = map(
1346
auth_def.get, ['scheme', 'host', 'user', 'path'])
1349
a_port = auth_def.as_int('port')
1353
raise ValueError("'port' not numeric in %s" % auth_def_name)
1355
a_verify_certificates = auth_def.as_bool('verify_certificates')
1357
a_verify_certificates = True
1360
"'verify_certificates' not boolean in %s" % auth_def_name)
1363
if a_scheme is not None and scheme != a_scheme:
1365
if a_host is not None:
1366
if not (host == a_host
1367
or (a_host.startswith('.') and host.endswith(a_host))):
1369
if a_port is not None and port != a_port:
1371
if (a_path is not None and path is not None
1372
and not path.startswith(a_path)):
1374
if (a_user is not None and user is not None
1375
and a_user != user):
1376
# Never contradict the caller about the user to be used
1381
# Prepare a credentials dictionary with additional keys
1382
# for the credential providers
1383
credentials = dict(name=auth_def_name,
1390
password=auth_def.get('password', None),
1391
verify_certificates=a_verify_certificates)
1392
# Decode the password in the credentials (or get one)
1393
self.decode_password(credentials,
1394
auth_def.get('password_encoding', None))
1395
if 'auth' in debug.debug_flags:
1396
trace.mutter("Using authentication section: %r", auth_def_name)
1399
if credentials is None:
1400
# No credentials were found in authentication.conf, try the fallback
1401
# credentials stores.
1402
credentials = credential_store_registry.get_fallback_credentials(
1403
scheme, host, port, user, path, realm)
1407
def set_credentials(self, name, host, user, scheme=None, password=None,
1408
port=None, path=None, verify_certificates=None,
1410
"""Set authentication credentials for a host.
1412
Any existing credentials with matching scheme, host, port and path
1413
will be deleted, regardless of name.
1415
:param name: An arbitrary name to describe this set of credentials.
1416
:param host: Name of the host that accepts these credentials.
1417
:param user: The username portion of these credentials.
1418
:param scheme: The URL scheme (e.g. ssh, http) the credentials apply
1420
:param password: Password portion of these credentials.
1421
:param port: The IP port on the host that these credentials apply to.
1422
:param path: A filesystem path on the host that these credentials
1424
:param verify_certificates: On https, verify server certificates if
1426
:param realm: The http authentication realm (optional).
1428
values = {'host': host, 'user': user}
1429
if password is not None:
1430
values['password'] = password
1431
if scheme is not None:
1432
values['scheme'] = scheme
1433
if port is not None:
1434
values['port'] = '%d' % port
1435
if path is not None:
1436
values['path'] = path
1437
if verify_certificates is not None:
1438
values['verify_certificates'] = str(verify_certificates)
1439
if realm is not None:
1440
values['realm'] = realm
1441
config = self._get_config()
1443
for section, existing_values in config.items():
1444
for key in ('scheme', 'host', 'port', 'path', 'realm'):
1445
if existing_values.get(key) != values.get(key):
1449
config.update({name: values})
1452
def get_user(self, scheme, host, port=None, realm=None, path=None,
1453
prompt=None, ask=False, default=None):
1454
"""Get a user from authentication file.
1456
:param scheme: protocol
1458
:param host: the server address
1460
:param port: the associated port (optional)
1462
:param realm: the realm sent by the server (optional)
1464
:param path: the absolute path on the server (optional)
1466
:param ask: Ask the user if there is no explicitly configured username
1469
:param default: The username returned if none is defined (optional).
1471
:return: The found user.
1473
credentials = self.get_credentials(scheme, host, port, user=None,
1474
path=path, realm=realm)
1475
if credentials is not None:
1476
user = credentials['user']
1482
# Create a default prompt suitable for most cases
1483
prompt = scheme.upper() + ' %(host)s username'
1484
# Special handling for optional fields in the prompt
1485
if port is not None:
1486
prompt_host = '%s:%d' % (host, port)
1489
user = ui.ui_factory.get_username(prompt, host=prompt_host)
1494
def get_password(self, scheme, host, user, port=None,
1495
realm=None, path=None, prompt=None):
1496
"""Get a password from authentication file or prompt the user for one.
1498
:param scheme: protocol
1500
:param host: the server address
1502
: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
:return: The found password or the one entered by the user.
1512
credentials = self.get_credentials(scheme, host, port, user, path,
1514
if credentials is not None:
1515
password = credentials['password']
1516
if password is not None and scheme is 'ssh':
1517
trace.warning('password ignored in section [%s],'
1518
' use an ssh agent instead'
1519
% credentials['name'])
1523
# Prompt user only if we could't find a password
1524
if password is None:
1526
# Create a default prompt suitable for most cases
1527
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1528
# Special handling for optional fields in the prompt
1529
if port is not None:
1530
prompt_host = '%s:%d' % (host, port)
1533
password = ui.ui_factory.get_password(prompt,
1534
host=prompt_host, user=user)
1537
def decode_password(self, credentials, encoding):
1539
cs = credential_store_registry.get_credential_store(encoding)
1541
raise ValueError('%r is not a known password_encoding' % encoding)
1542
credentials['password'] = cs.decode_password(credentials)
1546
class CredentialStoreRegistry(registry.Registry):
1547
"""A class that registers credential stores.
1549
A credential store provides access to credentials via the password_encoding
1550
field in authentication.conf sections.
1552
Except for stores provided by bzr itself, most stores are expected to be
1553
provided by plugins that will therefore use
1554
register_lazy(password_encoding, module_name, member_name, help=help,
1555
fallback=fallback) to install themselves.
1557
A fallback credential store is one that is queried if no credentials can be
1558
found via authentication.conf.
1561
def get_credential_store(self, encoding=None):
1562
cs = self.get(encoding)
1567
def is_fallback(self, name):
1568
"""Check if the named credentials store should be used as fallback."""
1569
return self.get_info(name)
1571
def get_fallback_credentials(self, scheme, host, port=None, user=None,
1572
path=None, realm=None):
1573
"""Request credentials from all fallback credentials stores.
1575
The first credentials store that can provide credentials wins.
1578
for name in self.keys():
1579
if not self.is_fallback(name):
1581
cs = self.get_credential_store(name)
1582
credentials = cs.get_credentials(scheme, host, port, user,
1584
if credentials is not None:
1585
# We found some credentials
1589
def register(self, key, obj, help=None, override_existing=False,
1591
"""Register a new object to a name.
1593
:param key: This is the key to use to request the object later.
1594
:param obj: The object to register.
1595
:param help: Help text for this entry. This may be a string or
1596
a callable. If it is a callable, it should take two
1597
parameters (registry, key): this registry and the key that
1598
the help was registered under.
1599
:param override_existing: Raise KeyErorr if False and something has
1600
already been registered for that key. If True, ignore if there
1601
is an existing key (always register the new value).
1602
:param fallback: Whether this credential store should be
1605
return super(CredentialStoreRegistry,
1606
self).register(key, obj, help, info=fallback,
1607
override_existing=override_existing)
1609
def register_lazy(self, key, module_name, member_name,
1610
help=None, override_existing=False,
1612
"""Register a new credential store to be loaded on request.
1614
:param module_name: The python path to the module. Such as 'os.path'.
1615
:param member_name: The member of the module to return. If empty or
1616
None, get() will return the module itself.
1617
:param help: Help text for this entry. This may be a string or
1619
:param override_existing: If True, replace the existing object
1620
with the new one. If False, if there is already something
1621
registered with the same key, raise a KeyError
1622
:param fallback: Whether this credential store should be
1625
return super(CredentialStoreRegistry, self).register_lazy(
1626
key, module_name, member_name, help,
1627
info=fallback, override_existing=override_existing)
1630
credential_store_registry = CredentialStoreRegistry()
1633
class CredentialStore(object):
1634
"""An abstract class to implement storage for credentials"""
1636
def decode_password(self, credentials):
1637
"""Returns a clear text password for the provided credentials."""
1638
raise NotImplementedError(self.decode_password)
1640
def get_credentials(self, scheme, host, port=None, user=None, path=None,
1642
"""Return the matching credentials from this credential store.
1644
This method is only called on fallback credential stores.
1646
raise NotImplementedError(self.get_credentials)
1650
class PlainTextCredentialStore(CredentialStore):
1651
__doc__ = """Plain text credential store for the authentication.conf file"""
1653
def decode_password(self, credentials):
1654
"""See CredentialStore.decode_password."""
1655
return credentials['password']
1658
credential_store_registry.register('plain', PlainTextCredentialStore,
1659
help=PlainTextCredentialStore.__doc__)
1660
credential_store_registry.default_key = 'plain'
1663
class BzrDirConfig(object):
1665
def __init__(self, bzrdir):
1666
self._bzrdir = bzrdir
1667
self._config = bzrdir._get_config()
1669
def set_default_stack_on(self, value):
1670
"""Set the default stacking location.
1672
It may be set to a location, or None.
1674
This policy affects all branches contained by this bzrdir, except for
1675
those under repositories.
1677
if self._config is None:
1678
raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1680
self._config.set_option('', 'default_stack_on')
1682
self._config.set_option(value, 'default_stack_on')
1684
def get_default_stack_on(self):
1685
"""Return the default stacking location.
1687
This will either be a location, or None.
1689
This policy affects all branches contained by this bzrdir, except for
1690
those under repositories.
1692
if self._config is None:
1694
value = self._config.get_option('default_stack_on')
1700
class TransportConfig(object):
1701
"""A Config that reads/writes a config file on a Transport.
1703
It is a low-level object that considers config data to be name/value pairs
1704
that may be associated with a section. Assigning meaning to these values
1705
is done at higher levels like TreeConfig.
1708
def __init__(self, transport, filename):
1709
self._transport = transport
1710
self._filename = filename
1712
def get_option(self, name, section=None, default=None):
1713
"""Return the value associated with a named option.
1715
:param name: The name of the value
1716
:param section: The section the option is in (if any)
1717
:param default: The value to return if the value is not set
1718
:return: The value or default value
1720
configobj = self._get_configobj()
1722
section_obj = configobj
1725
section_obj = configobj[section]
1728
return section_obj.get(name, default)
1730
def set_option(self, value, name, section=None):
1731
"""Set the value associated with a named option.
1733
:param value: The value to set
1734
:param name: The name of the value to set
1735
:param section: The section the option is in (if any)
1737
configobj = self._get_configobj()
1739
configobj[name] = value
1741
configobj.setdefault(section, {})[name] = value
1742
self._set_configobj(configobj)
1744
def remove_option(self, option_name, section_name=None):
1745
configobj = self._get_configobj()
1746
if section_name is None:
1747
del configobj[option_name]
1749
del configobj[section_name][option_name]
1750
self._set_configobj(configobj)
1752
def _get_config_file(self):
1754
return StringIO(self._transport.get_bytes(self._filename))
1755
except errors.NoSuchFile:
1758
def _get_configobj(self):
1759
f = self._get_config_file()
1761
return ConfigObj(f, encoding='utf-8')
1765
def _set_configobj(self, configobj):
1766
out_file = StringIO()
1767
configobj.write(out_file)
1769
self._transport.put_file(self._filename, out_file)
1772
class cmd_config(commands.Command):
1773
__doc__ = """Display, set or remove a configuration option.
1775
Display the MATCHING configuration options mentioning their scope (the
1776
configuration file they are defined in). The active value that bzr will
1777
take into account is the first one displayed.
1779
Setting a value is achieved by using name=value without spaces. The value
1780
is set in the most relevant scope and can be checked by displaying the
1785
takes_args = ['matching?']
1789
# FIXME: This should be a registry option so that plugins can register
1790
# their own config files (or not) -- vila 20101002
1791
commands.Option('scope', help='Reduce the scope to the specified'
1792
' configuration file',
1794
commands.Option('remove', help='Remove the option from'
1795
' the configuration file'),
1798
@commands.display_command
1799
def run(self, matching=None, directory=None, scope=None, remove=False):
1800
if directory is None:
1802
directory = urlutils.normalize_url(directory)
1803
if matching is None:
1804
self._show_config('*', directory)
1807
self._remove_config_option(matching, directory, scope)
1809
pos = matching.find('=')
1811
self._show_config(matching, directory)
1813
self._set_config_option(matching[:pos], matching[pos+1:],
1816
def _get_configs(self, directory, scope=None):
1817
"""Iterate the configurations specified by ``directory`` and ``scope``.
1819
:param directory: Where the configurations are derived from.
1821
:param scope: A specific config to start from.
1823
if scope is not None:
1824
if scope == 'bazaar':
1825
yield GlobalConfig()
1826
elif scope == 'locations':
1827
yield LocationConfig(directory)
1828
elif scope == 'branch':
1829
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1831
yield br.get_config()
1834
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1836
yield br.get_config()
1837
except errors.NotBranchError:
1838
yield LocationConfig(directory)
1839
yield GlobalConfig()
1841
def _show_config(self, matching, directory):
1842
# Turn the glob into a regexp
1843
matching_re = re.compile(fnmatch.translate(matching))
1845
for c in self._get_configs(directory):
1846
for (name, value, section, conf_id) in c._get_options():
1847
if matching_re.search(name):
1848
if cur_conf_id != conf_id:
1849
self.outf.write('%s:\n' % (conf_id,))
1850
cur_conf_id = conf_id
1851
self.outf.write(' %s = %s\n' % (name, value))
1853
def _set_config_option(self, name, value, directory, scope):
1854
for conf in self._get_configs(directory, scope):
1855
conf.set_user_option(name, value)
1858
raise errors.NoSuchConfig(scope)
1860
def _remove_config_option(self, name, directory, scope):
1862
for conf in self._get_configs(directory, scope):
1863
for (section_name, section, conf_id) in conf._get_sections():
1864
if scope is not None and conf_id != scope:
1865
# Not the right configuration file
1868
if conf_id != conf.config_id():
1869
conf = self._get_configs(directory, conf_id).next()
1870
# We use the first section in the first config where the
1871
# option is defined to remove it
1872
conf.remove_user_option(name, section_name)
1877
raise errors.NoSuchConfig(scope)
1879
raise errors.NoSuchConfigOption(name)
601
self.branch.lock_write()
603
cfg_obj = self._get_config()
608
obj = cfg_obj[section]
610
cfg_obj[section] = {}
611
obj = cfg_obj[section]
613
out_file = StringIO()
614
cfg_obj.write(out_file)
616
self.branch.control_files.put('branch.conf', out_file)