175
303
return CHECK_IF_POSSIBLE
305
def signing_policy(self):
306
"""What is the current policy for signature checking?."""
307
policy = self._get_signing_policy()
308
if policy is not None:
310
return SIGN_WHEN_REQUIRED
177
312
def signature_needed(self):
178
313
"""Is a signature needed when committing ?."""
179
policy = self._get_signature_checking()
180
if policy == CHECK_ALWAYS:
314
policy = self._get_signing_policy()
316
policy = self._get_signature_checking()
317
if policy is not None:
318
trace.warning("Please use create_signatures,"
319
" not check_signatures to set signing policy.")
320
if policy == CHECK_ALWAYS:
322
elif policy == SIGN_ALWAYS:
326
def get_alias(self, value):
327
return self._get_alias(value)
329
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:
185
361
class IniBasedConfig(Config):
186
362
"""A configuration policy that draws from ini files."""
188
def _get_parser(self, file=None):
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):
189
408
if self._parser is not None:
190
409
return self._parser
192
input = self._get_filename()
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')
421
co_input = self.file_name
196
self._parser = ConfigObj(input)
423
self._parser = ConfigObj(co_input, encoding='utf-8')
197
424
except configobj.ConfigObjError, e:
198
425
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
199
428
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, '')]
201
449
def _get_section(self):
202
450
"""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')
205
508
def _get_signature_checking(self):
206
509
"""See Config._get_signature_checking."""
207
510
policy = self._get_user_option('check_signatures')
209
512
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)
211
520
def _get_user_id(self):
212
521
"""Get the user id from the 'email' key in the current section."""
213
522
return self._get_user_option('email')
215
524
def _get_user_option(self, option_name):
216
525
"""See Config._get_user_option."""
218
return self._get_parser().get_value(self._get_section(),
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)
223
549
def _gpg_signing_command(self):
224
550
"""See Config.gpg_signing_command."""
225
551
return self._get_user_option('gpg_signing_command')
227
def __init__(self, get_filename):
228
super(IniBasedConfig, self).__init__()
229
self._get_filename = get_filename
553
def _log_format(self):
554
"""See Config.log_format."""
555
return self._get_user_option('log_format')
232
557
def _post_commit(self):
233
558
"""See Config.post_commit."""
234
559
return self._get_user_option('post_commit')
244
569
raise errors.BzrError("Invalid signatures policy '%s'"
245
570
% signature_string)
248
class GlobalConfig(IniBasedConfig):
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
def _get_alias(self, value):
585
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):
249
695
"""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)
251
716
def get_editor(self):
252
717
return self._get_user_option('editor')
255
super(GlobalConfig, self).__init__(config_filename)
258
class LocationConfig(IniBasedConfig):
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):
259
777
"""A configuration object that gives the policy for a location."""
261
779
def __init__(self, location):
262
super(LocationConfig, self).__init__(branches_config_filename)
263
self._global_config = None
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)
264
787
self.location = location
266
def _get_global_config(self):
267
if self._global_config is None:
268
self._global_config = GlobalConfig()
269
return self._global_config
271
def _get_section(self):
272
"""Get the section we should look in for config items.
274
Returns None if none exists.
275
TODO: perhaps return a NullSection that thunks through to the
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.
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."""
278
809
sections = self._get_parser()
279
810
location_names = self.location.split('/')
280
811
if self.location.endswith('/'):
281
812
del location_names[-1]
283
814
for section in sections:
284
section_names = section.split('/')
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('/')
285
824
if section.endswith('/'):
286
825
del section_names[-1]
287
826
names = zip(location_names, section_names)
289
828
for name in names:
290
if not fnmatch(name[0], name[1]):
829
if not fnmatch.fnmatch(name[0], name[1]):
296
835
# if section is longer, no match.
297
836
if len(section_names) > len(location_names):
299
# if path is longer, and recurse is not true, no match
300
if len(section_names) < len(location_names):
302
if not self._get_parser().get_bool(section, 'recurse'):
306
matches.append((len(section_names), section))
838
matches.append((len(section_names), section,
839
'/'.join(location_names[len(section_names):])))
840
# put the longest (aka more specific) locations first
309
841
matches.sort(reverse=True)
312
def _gpg_signing_command(self):
313
"""See Config.gpg_signing_command."""
314
command = super(LocationConfig, self)._gpg_signing_command()
315
if command is not None:
317
return self._get_global_config()._gpg_signing_command()
319
def _get_user_id(self):
320
user_id = super(LocationConfig, self)._get_user_id()
321
if user_id is not None:
323
return self._get_global_config()._get_user_id()
325
def _get_user_option(self, option_name):
326
"""See Config._get_user_option."""
327
option_value = super(LocationConfig,
328
self)._get_user_option(option_name)
329
if option_value is not None:
331
return self._get_global_config()._get_user_option(option_name)
333
def _get_signature_checking(self):
334
"""See Config._get_signature_checking."""
335
check = super(LocationConfig, self)._get_signature_checking()
336
if check is not None:
338
return self._get_global_config()._get_signature_checking()
340
def _post_commit(self):
341
"""See Config.post_commit."""
342
hook = self._get_user_option('post_commit')
345
return self._get_global_config()._post_commit()
347
def set_user_option(self, option, value):
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):
348
911
"""Save option and its value in the configuration."""
349
# FIXME: RBC 20051029 This should refresh the parser and also take a
350
# file lock on branches.conf.
351
if not os.path.isdir(os.path.dirname(self._get_filename())):
352
os.mkdir(os.path.dirname(self._get_filename()))
912
if store not in [STORE_LOCATION,
913
STORE_LOCATION_NORECURSE,
914
STORE_LOCATION_APPENDPATH]:
915
raise ValueError('bad storage policy %r for %r' %
353
918
location = self.location
354
919
if location.endswith('/'):
355
920
location = location[:-1]
356
if (not location in self._get_parser() and
357
not location + '/' in self._get_parser()):
358
self._get_parser()[location]={}
359
elif location + '/' in self._get_parser():
921
parser = self._get_parser()
922
if not location in parser and not location + '/' in parser:
923
parser[location] = {}
924
elif location + '/' in parser:
360
925
location = location + '/'
361
self._get_parser()[location][option]=value
362
self._get_parser().write()
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()
365
932
class BranchConfig(Config):
366
933
"""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
368
954
def _get_location_config(self):
369
955
if self._location_config is None:
370
956
self._location_config = LocationConfig(self.branch.base)
371
957
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:
373
991
def _get_user_id(self):
374
992
"""Return the full user id for the branch.
376
e.g. "John Hacker <jhacker@foo.org>"
994
e.g. "John Hacker <jhacker@example.com>"
377
995
This is looked up in the email controlfile for the branch.
380
return (self.branch.controlfile("email", "r")
382
.decode(bzrlib.user_encoding)
998
return (self.branch._transport.get_bytes("email")
999
.decode(osutils.get_user_encoding())
383
1000
.rstrip("\r\n"))
384
1001
except errors.NoSuchFile, e:
387
return self._get_location_config()._get_user_id()
1004
return self._get_best_value('_get_user_id')
1006
def _get_change_editor(self):
1007
return self._get_best_value('_get_change_editor')
389
1009
def _get_signature_checking(self):
390
1010
"""See Config._get_signature_checking."""
391
return self._get_location_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')
393
1017
def _get_user_option(self, option_name):
394
1018
"""See Config._get_user_option."""
395
return self._get_location_config()._get_user_option(option_name)
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)
397
1076
def _gpg_signing_command(self):
398
1077
"""See Config.gpg_signing_command."""
399
return self._get_location_config()._gpg_signing_command()
401
def __init__(self, branch):
402
super(BranchConfig, self).__init__()
403
self._location_config = None
1078
return self._get_safe_value('_gpg_signing_command')
406
1080
def _post_commit(self):
407
1081
"""See Config.post_commit."""
408
return self._get_location_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')
1097
def _log_format(self):
1098
"""See Config.log_format."""
1099
return self._get_best_value('_log_format')
1102
def ensure_config_dir_exists(path=None):
1103
"""Make sure a configuration directory exists.
1104
This makes sure that the directory exists.
1105
On windows, since configuration directories are 2 levels deep,
1106
it makes sure both the directory and the parent directory exists.
1110
if not os.path.isdir(path):
1111
if sys.platform == 'win32':
1112
parent_dir = os.path.dirname(path)
1113
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)
1118
osutils.copy_ownership_from_path(path)
411
1121
def config_dir():
412
1122
"""Return per-user configuration directory.
414
1124
By default this is ~/.bazaar/
416
1126
TODO: Global option --config-dir to override this.
418
1128
base = os.environ.get('BZR_HOME', None)
419
1129
if sys.platform == 'win32':
420
1130
if base is None:
421
base = os.environ.get('APPDATA', None)
1131
base = win32utils.get_appdata_location_unicode()
422
1132
if base is None:
423
1133
base = os.environ.get('HOME', None)
424
1134
if base is None:
425
raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
426
return os.path.join(base, 'bazaar', '2.0')
1135
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
1137
return osutils.pathjoin(base, 'bazaar', '2.0')
428
# cygwin, linux, and darwin all have a $HOME directory
429
1139
if base is None:
430
1140
base = os.path.expanduser("~")
431
return os.path.join(base, ".bazaar")
1141
return osutils.pathjoin(base, ".bazaar")
434
1144
def config_filename():
435
1145
"""Return per-user configuration ini file filename."""
436
return os.path.join(config_dir(), 'bazaar.conf')
439
def branches_config_filename():
1146
return osutils.pathjoin(config_dir(), 'bazaar.conf')
1149
def locations_config_filename():
440
1150
"""Return per-user configuration ini file filename."""
441
return os.path.join(config_dir(), 'branches.conf')
445
"""Calculate automatic user identification.
447
Returns (realname, email).
449
Only used when none is set in the environment or the id file.
451
This previously used the FQDN as the default domain, but that can
452
be very slow on machines where DNS is broken. So now we simply
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
457
# XXX: Any good way to get real user name on win32?
462
w = pwd.getpwuid(uid)
463
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
464
username = w.pw_name.decode(bzrlib.user_encoding)
465
comma = gecos.find(',')
469
realname = gecos[:comma]
475
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
477
return realname, (username + '@' + socket.gethostname())
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))
480
1200
def extract_email_address(e):
481
1201
"""Return just the address part of an email string.
483
That is just the user@domain part, nothing else.
1203
That is just the user@domain part, nothing else.
484
1204
This part is required to contain only ascii characters.
485
1205
If it can't be extracted, raises an error.
487
1207
>>> extract_email_address('Jane Tester <jane@test.com>')
490
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
492
raise errors.BzrError("%r doesn't seem to contain "
493
"a reasonable email address" % e)
496
class TreeConfig(object):
1210
name, email = parse_username(e)
1212
raise errors.NoEmailInUsername(e)
1216
class TreeConfig(IniBasedConfig):
497
1217
"""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
498
1221
def __init__(self, branch):
1222
self._config = branch._get_config()
499
1223
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()
1230
def get_option(self, name, section=None, default=None):
1231
self.branch.lock_read()
1233
return self._config.get_option(name, section, default)
1235
self.branch.unlock()
1237
def set_option(self, value, name, section=None):
1238
"""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
501
1274
def _get_config(self):
503
obj = ConfigObj(self.branch.controlfile('branch.conf',
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))
506
1755
except errors.NoSuchFile:
510
def get_option(self, name, section=None, default=None):
511
self.branch.lock_read()
1758
def _get_configobj(self):
1759
f = self._get_config_file()
513
obj = self._get_config()
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 active value for a given option.
1777
If --all is specified, NAME is interpreted as a regular expression and all
1778
matching options are displayed mentioning their scope. The active value
1779
that bzr will take into account is the first one displayed for each option.
1781
If no NAME is given, --all .* is implied.
1783
Setting a value is achieved by using name=value without spaces. The value
1784
is set in the most relevant scope and can be checked by displaying the
1788
takes_args = ['name?']
1792
# FIXME: This should be a registry option so that plugins can register
1793
# their own config files (or not) -- vila 20101002
1794
commands.Option('scope', help='Reduce the scope to the specified'
1795
' configuration file',
1797
commands.Option('all',
1798
help='Display all the defined values for the matching options.',
1800
commands.Option('remove', help='Remove the option from'
1801
' the configuration file'),
1804
@commands.display_command
1805
def run(self, name=None, all=False, directory=None, scope=None,
1807
if directory is None:
1809
directory = urlutils.normalize_url(directory)
1811
raise errors.BzrError(
1812
'--all and --remove are mutually exclusive.')
1814
# Delete the option in the given scope
1815
self._remove_config_option(name, directory, scope)
1817
# Defaults to all options
1818
self._show_matching_options('.*', directory, scope)
515
if section is not None:
524
def set_option(self, value, name, section=None):
525
"""Set a per-branch configuration option"""
526
self.branch.lock_write()
528
cfg_obj = self._get_config()
1821
name, value = name.split('=', 1)
1823
# Display the option(s) value(s)
1825
self._show_matching_options(name, directory, scope)
1827
self._show_value(name, directory, scope)
533
obj = cfg_obj[section]
535
cfg_obj[section] = {}
536
obj = cfg_obj[section]
538
cfg_obj.encode('UTF-8')
539
out_file = StringIO(''.join([l+'\n' for l in cfg_obj.write()]))
541
self.branch.put_controlfile('branch.conf', out_file, encode=False)
1830
raise errors.BzrError(
1831
'Only one option can be set.')
1832
# Set the option value
1833
self._set_config_option(name, value, directory, scope)
1835
def _get_configs(self, directory, scope=None):
1836
"""Iterate the configurations specified by ``directory`` and ``scope``.
1838
:param directory: Where the configurations are derived from.
1840
:param scope: A specific config to start from.
1842
if scope is not None:
1843
if scope == 'bazaar':
1844
yield GlobalConfig()
1845
elif scope == 'locations':
1846
yield LocationConfig(directory)
1847
elif scope == 'branch':
1848
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1850
yield br.get_config()
1853
(_, br, _) = bzrdir.BzrDir.open_containing_tree_or_branch(
1855
yield br.get_config()
1856
except errors.NotBranchError:
1857
yield LocationConfig(directory)
1858
yield GlobalConfig()
1860
def _show_value(self, name, directory, scope):
1862
for c in self._get_configs(directory, scope):
1865
for (oname, value, section, conf_id) in c._get_options():
1867
# Display only the first value and exit
1868
self.outf.write('%s\n' % (value))
1872
raise errors.NoSuchConfigOption(name)
1874
def _show_matching_options(self, name, directory, scope):
1875
name = re.compile(name)
1876
# We want any error in the regexp to be raised *now* so we need to
1877
# avoid the delay introduced by the lazy regexp.
1878
name._compile_and_collapse()
1880
for c in self._get_configs(directory, scope):
1881
for (oname, value, section, conf_id) in c._get_options():
1882
if name.search(oname):
1883
if cur_conf_id != conf_id:
1884
# Explain where the options are defined
1885
self.outf.write('%s:\n' % (conf_id,))
1886
cur_conf_id = conf_id
1887
self.outf.write(' %s = %s\n' % (oname, value))
1889
def _set_config_option(self, name, value, directory, scope):
1890
for conf in self._get_configs(directory, scope):
1891
conf.set_user_option(name, value)
1894
raise errors.NoSuchConfig(scope)
1896
def _remove_config_option(self, name, directory, scope):
1898
raise errors.BzrCommandError(
1899
'--remove expects an option to remove.')
1901
for conf in self._get_configs(directory, scope):
1902
for (section_name, section, conf_id) in conf._get_sections():
1903
if scope is not None and conf_id != scope:
1904
# Not the right configuration file
1907
if conf_id != conf.config_id():
1908
conf = self._get_configs(directory, conf_id).next()
1909
# We use the first section in the first config where the
1910
# option is defined to remove it
1911
conf.remove_user_option(name, section_name)
1916
raise errors.NoSuchConfig(scope)
1918
raise errors.NoSuchConfigOption(name)