222
318
raise errors.ParseConfigError(e.errors, e.config.filename)
223
319
return self._parser
321
def _get_matching_sections(self):
322
"""Return an ordered list of (section_name, extra_path) pairs.
324
If the section contains inherited configuration, extra_path is
325
a string containing the additional path components.
327
section = self._get_section()
328
if section is not None:
329
return [(section, '')]
225
333
def _get_section(self):
226
334
"""Override this to define the section used by the config."""
337
def _get_option_policy(self, section, option_name):
338
"""Return the policy for the given (section, option_name) pair."""
229
341
def _get_signature_checking(self):
230
342
"""See Config._get_signature_checking."""
231
343
policy = self._get_user_option('check_signatures')
233
345
return self._string_to_signature_policy(policy)
347
def _get_signing_policy(self):
348
"""See Config._get_signing_policy"""
349
policy = self._get_user_option('create_signatures')
351
return self._string_to_signing_policy(policy)
235
353
def _get_user_id(self):
236
354
"""Get the user id from the 'email' key in the current section."""
237
355
return self._get_user_option('email')
239
357
def _get_user_option(self, option_name):
240
358
"""See Config._get_user_option."""
242
return self._get_parser().get_value(self._get_section(),
359
for (section, extra_path) in self._get_matching_sections():
361
value = self._get_parser().get_value(section, option_name)
364
policy = self._get_option_policy(section, option_name)
365
if policy == POLICY_NONE:
367
elif policy == POLICY_NORECURSE:
368
# norecurse items only apply to the exact path
373
elif policy == POLICY_APPENDPATH:
375
value = urlutils.join(value, extra_path)
378
raise AssertionError('Unexpected config policy %r' % policy)
247
382
def _gpg_signing_command(self):
248
383
"""See Config.gpg_signing_command."""
289
438
def __init__(self):
290
439
super(GlobalConfig, self).__init__(config_filename)
441
def set_user_option(self, option, value):
442
"""Save option and its value in the configuration."""
443
self._set_option(option, value, 'DEFAULT')
445
def get_aliases(self):
446
"""Return the aliases section."""
447
if 'ALIASES' in self._get_parser():
448
return self._get_parser()['ALIASES']
452
def set_alias(self, alias_name, alias_command):
453
"""Save the alias in the configuration."""
454
self._set_option(alias_name, alias_command, 'ALIASES')
456
def unset_alias(self, alias_name):
457
"""Unset an existing alias."""
458
aliases = self._get_parser().get('ALIASES')
459
if not aliases or alias_name not in aliases:
460
raise errors.NoSuchAlias(alias_name)
461
del aliases[alias_name]
462
self._write_config_file()
464
def _set_option(self, option, value, section):
465
# FIXME: RBC 20051029 This should refresh the parser and also take a
466
# file lock on bazaar.conf.
467
conf_dir = os.path.dirname(self._get_filename())
468
ensure_config_dir_exists(conf_dir)
469
self._get_parser().setdefault(section, {})[option] = value
470
self._write_config_file()
472
def _write_config_file(self):
473
f = open(self._get_filename(), 'wb')
474
self._get_parser().write(f)
293
478
class LocationConfig(IniBasedConfig):
294
479
"""A configuration object that gives the policy for a location."""
296
481
def __init__(self, location):
297
super(LocationConfig, self).__init__(branches_config_filename)
298
self._global_config = None
482
name_generator = locations_config_filename
483
if (not os.path.exists(name_generator()) and
484
os.path.exists(branches_config_filename())):
485
if sys.platform == 'win32':
486
trace.warning('Please rename %s to %s'
487
% (branches_config_filename(),
488
locations_config_filename()))
490
trace.warning('Please rename ~/.bazaar/branches.conf'
491
' to ~/.bazaar/locations.conf')
492
name_generator = branches_config_filename
493
super(LocationConfig, self).__init__(name_generator)
494
# local file locations are looked up by local path, rather than
495
# by file url. This is because the config file is a user
496
# file, and we would rather not expose the user to file urls.
497
if location.startswith('file://'):
498
location = urlutils.local_path_from_url(location)
299
499
self.location = location
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
501
def _get_matching_sections(self):
502
"""Return an ordered list of section names matching this location."""
313
503
sections = self._get_parser()
314
504
location_names = self.location.split('/')
315
505
if self.location.endswith('/'):
316
506
del location_names[-1]
318
508
for section in sections:
319
section_names = section.split('/')
509
# location is a local path if possible, so we need
510
# to convert 'file://' urls to local paths if necessary.
511
# This also avoids having file:///path be a more exact
512
# match than '/path'.
513
if section.startswith('file://'):
514
section_path = urlutils.local_path_from_url(section)
516
section_path = section
517
section_names = section_path.split('/')
320
518
if section.endswith('/'):
321
519
del section_names[-1]
322
520
names = zip(location_names, section_names)
331
529
# if section is longer, no match.
332
530
if len(section_names) > len(location_names):
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))
532
matches.append((len(section_names), section,
533
'/'.join(location_names[len(section_names):])))
344
534
matches.sort(reverse=True)
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):
536
for (length, section, extra_path) in matches:
537
sections.append((section, extra_path))
538
# should we stop looking for parent configs here?
540
if self._get_parser()[section].as_bool('ignore_parents'):
546
def _get_option_policy(self, section, option_name):
547
"""Return the policy for the given (section, option_name) pair."""
548
# check for the old 'recurse=False' flag
550
recurse = self._get_parser()[section].as_bool('recurse')
554
return POLICY_NORECURSE
556
policy_key = option_name + ':policy'
558
policy_name = self._get_parser()[section][policy_key]
562
return _policy_value[policy_name]
564
def _set_option_policy(self, section, option_name, option_policy):
565
"""Set the policy for the given option name in the given section."""
566
# The old recurse=False option affects all options in the
567
# section. To handle multiple policies in the section, we
568
# need to convert it to a policy_norecurse key.
570
recurse = self._get_parser()[section].as_bool('recurse')
574
symbol_versioning.warn(
575
'The recurse option is deprecated as of 0.14. '
576
'The section "%s" has been converted to use policies.'
579
del self._get_parser()[section]['recurse']
581
for key in self._get_parser()[section].keys():
582
if not key.endswith(':policy'):
583
self._get_parser()[section][key +
584
':policy'] = 'norecurse'
586
policy_key = option_name + ':policy'
587
policy_name = _policy_name[option_policy]
588
if policy_name is not None:
589
self._get_parser()[section][policy_key] = policy_name
591
if policy_key in self._get_parser()[section]:
592
del self._get_parser()[section][policy_key]
594
def set_user_option(self, option, value, store=STORE_LOCATION):
390
595
"""Save option and its value in the configuration."""
596
if store not in [STORE_LOCATION,
597
STORE_LOCATION_NORECURSE,
598
STORE_LOCATION_APPENDPATH]:
599
raise ValueError('bad storage policy %r for %r' %
391
601
# FIXME: RBC 20051029 This should refresh the parser and also take a
392
# file lock on branches.conf.
602
# file lock on locations.conf.
393
603
conf_dir = os.path.dirname(self._get_filename())
394
604
ensure_config_dir_exists(conf_dir)
395
605
location = self.location
401
611
elif location + '/' in self._get_parser():
402
612
location = location + '/'
403
613
self._get_parser()[location][option]=value
614
# the allowed values of store match the config policies
615
self._set_option_policy(location, option, store)
404
616
self._get_parser().write(file(self._get_filename(), 'wb'))
407
619
class BranchConfig(Config):
408
620
"""A configuration object giving the policy for a branch."""
622
def _get_branch_data_config(self):
623
if self._branch_data_config is None:
624
self._branch_data_config = TreeConfig(self.branch)
625
return self._branch_data_config
410
627
def _get_location_config(self):
411
628
if self._location_config is None:
412
629
self._location_config = LocationConfig(self.branch.base)
413
630
return self._location_config
632
def _get_global_config(self):
633
if self._global_config is None:
634
self._global_config = GlobalConfig()
635
return self._global_config
637
def _get_best_value(self, option_name):
638
"""This returns a user option from local, tree or global config.
640
They are tried in that order. Use get_safe_value if trusted values
643
for source in self.option_sources:
644
value = getattr(source(), option_name)()
645
if value is not None:
649
def _get_safe_value(self, option_name):
650
"""This variant of get_best_value never returns untrusted values.
652
It does not return values from the branch data, because the branch may
653
not be controlled by the user.
655
We may wish to allow locations.conf to control whether branches are
656
trusted in the future.
658
for source in (self._get_location_config, self._get_global_config):
659
value = getattr(source(), option_name)()
660
if value is not None:
415
664
def _get_user_id(self):
416
665
"""Return the full user id for the branch.
418
e.g. "John Hacker <jhacker@foo.org>"
667
e.g. "John Hacker <jhacker@example.com>"
419
668
This is looked up in the email controlfile for the branch.
422
return (self.branch.control_files.get_utf8("email")
671
return (self.branch._transport.get_bytes("email")
424
672
.decode(bzrlib.user_encoding)
426
674
except errors.NoSuchFile, e:
429
return self._get_location_config()._get_user_id()
677
return self._get_best_value('_get_user_id')
431
679
def _get_signature_checking(self):
432
680
"""See Config._get_signature_checking."""
433
return self._get_location_config()._get_signature_checking()
681
return self._get_best_value('_get_signature_checking')
683
def _get_signing_policy(self):
684
"""See Config._get_signing_policy."""
685
return self._get_best_value('_get_signing_policy')
435
687
def _get_user_option(self, option_name):
436
688
"""See Config._get_user_option."""
437
return self._get_location_config()._get_user_option(option_name)
689
for source in self.option_sources:
690
value = source()._get_user_option(option_name)
691
if value is not None:
695
def set_user_option(self, name, value, store=STORE_BRANCH,
697
if store == STORE_BRANCH:
698
self._get_branch_data_config().set_option(value, name)
699
elif store == STORE_GLOBAL:
700
self._get_global_config().set_user_option(name, value)
702
self._get_location_config().set_user_option(name, value, store)
705
if store in (STORE_GLOBAL, STORE_BRANCH):
706
mask_value = self._get_location_config().get_user_option(name)
707
if mask_value is not None:
708
trace.warning('Value "%s" is masked by "%s" from'
709
' locations.conf', value, mask_value)
711
if store == STORE_GLOBAL:
712
branch_config = self._get_branch_data_config()
713
mask_value = branch_config.get_user_option(name)
714
if mask_value is not None:
715
trace.warning('Value "%s" is masked by "%s" from'
716
' branch.conf', value, mask_value)
439
719
def _gpg_signing_command(self):
440
720
"""See Config.gpg_signing_command."""
441
return self._get_location_config()._gpg_signing_command()
721
return self._get_safe_value('_gpg_signing_command')
443
723
def __init__(self, branch):
444
724
super(BranchConfig, self).__init__()
445
725
self._location_config = None
726
self._branch_data_config = None
727
self._global_config = None
446
728
self.branch = branch
729
self.option_sources = (self._get_location_config,
730
self._get_branch_data_config,
731
self._get_global_config)
448
733
def _post_commit(self):
449
734
"""See Config.post_commit."""
450
return self._get_location_config()._post_commit()
735
return self._get_safe_value('_post_commit')
737
def _get_nickname(self):
738
value = self._get_explicit_nickname()
739
if value is not None:
741
return urlutils.unescape(self.branch.base.split('/')[-2])
743
def has_explicit_nickname(self):
744
"""Return true if a nickname has been explicitly assigned."""
745
return self._get_explicit_nickname() is not None
747
def _get_explicit_nickname(self):
748
return self._get_best_value('_get_nickname')
452
750
def _log_format(self):
453
751
"""See Config.log_format."""
454
return self._get_location_config()._log_format()
752
return self._get_best_value('_log_format')
457
755
def ensure_config_dir_exists(path=None):
482
780
base = os.environ.get('BZR_HOME', None)
483
781
if sys.platform == 'win32':
485
base = os.environ.get('APPDATA', None)
783
base = win32utils.get_appdata_location_unicode()
487
785
base = os.environ.get('HOME', None)
489
raise BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
490
return pathjoin(base, 'bazaar', '2.0')
787
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
789
return osutils.pathjoin(base, 'bazaar', '2.0')
492
791
# cygwin, linux, and darwin all have a $HOME directory
494
793
base = os.path.expanduser("~")
495
return pathjoin(base, ".bazaar")
794
return osutils.pathjoin(base, ".bazaar")
498
797
def config_filename():
499
798
"""Return per-user configuration ini file filename."""
500
return pathjoin(config_dir(), 'bazaar.conf')
799
return osutils.pathjoin(config_dir(), 'bazaar.conf')
503
802
def branches_config_filename():
504
803
"""Return per-user configuration ini file filename."""
505
return pathjoin(config_dir(), 'branches.conf')
804
return osutils.pathjoin(config_dir(), 'branches.conf')
807
def locations_config_filename():
808
"""Return per-user configuration ini file filename."""
809
return osutils.pathjoin(config_dir(), 'locations.conf')
812
def authentication_config_filename():
813
"""Return per-user authentication ini file filename."""
814
return osutils.pathjoin(config_dir(), 'authentication.conf')
817
def user_ignore_config_filename():
818
"""Return the user default ignore filename"""
819
return osutils.pathjoin(config_dir(), 'ignore')
508
822
def _auto_user_id():
552
887
return realname, (username + '@' + socket.gethostname())
890
def parse_username(username):
891
"""Parse e-mail username and return a (name, address) tuple."""
892
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
894
return (username, '')
896
return (match.group(1), match.group(2))
555
899
def extract_email_address(e):
556
900
"""Return just the address part of an email string.
558
902
That is just the user@domain part, nothing else.
559
903
This part is required to contain only ascii characters.
560
904
If it can't be extracted, raises an error.
562
906
>>> extract_email_address('Jane Tester <jane@test.com>')
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):
909
name, email = parse_username(e)
911
raise errors.NoEmailInUsername(e)
915
class TreeConfig(IniBasedConfig):
573
916
"""Branch configuration data associated with its contents, not location"""
918
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
574
920
def __init__(self, branch):
921
# XXX: Really this should be asking the branch for its configuration
922
# data, rather than relying on a Transport, so that it can work
923
# more cleanly with a RemoteBranch that has no transport.
924
self._config = TransportConfig(branch._transport, 'branch.conf')
575
925
self.branch = branch
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')
927
def _get_parser(self, file=None):
929
return IniBasedConfig._get_parser(file)
930
return self._config._get_configobj()
585
932
def get_option(self, name, section=None, default=None):
586
933
self.branch.lock_read()
588
obj = self._get_config()
590
if section is not None:
935
return self._config.get_option(name, section, default)
596
937
self.branch.unlock()
600
941
"""Set a per-branch configuration option"""
601
942
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)
944
self._config.set_option(value, name, section)
618
946
self.branch.unlock()
949
class AuthenticationConfig(object):
950
"""The authentication configuration file based on a ini file.
952
Implements the authentication.conf file described in
953
doc/developers/authentication-ring.txt.
956
def __init__(self, _file=None):
957
self._config = None # The ConfigObj
959
self._filename = authentication_config_filename()
960
self._input = self._filename = authentication_config_filename()
962
# Tests can provide a string as _file
963
self._filename = None
966
def _get_config(self):
967
if self._config is not None:
970
# FIXME: Should we validate something here ? Includes: empty
971
# sections are useless, at least one of
972
# user/password/password_encoding should be defined, etc.
974
# Note: the encoding below declares that the file itself is utf-8
975
# encoded, but the values in the ConfigObj are always Unicode.
976
self._config = ConfigObj(self._input, encoding='utf-8')
977
except configobj.ConfigObjError, e:
978
raise errors.ParseConfigError(e.errors, e.config.filename)
982
"""Save the config file, only tests should use it for now."""
983
conf_dir = os.path.dirname(self._filename)
984
ensure_config_dir_exists(conf_dir)
985
self._get_config().write(file(self._filename, 'wb'))
987
def _set_option(self, section_name, option_name, value):
988
"""Set an authentication configuration option"""
989
conf = self._get_config()
990
section = conf.get(section_name)
993
section = conf[section]
994
section[option_name] = value
997
def get_credentials(self, scheme, host, port=None, user=None, path=None):
998
"""Returns the matching credentials from authentication.conf file.
1000
:param scheme: protocol
1002
:param host: the server address
1004
:param port: the associated port (optional)
1006
:param user: login (optional)
1008
:param path: the absolute path on the server (optional)
1010
:return: A dict containing the matching credentials or None.
1012
- name: the section name of the credentials in the
1013
authentication.conf file,
1014
- user: can't de different from the provided user if any,
1015
- password: the decoded password, could be None if the credential
1016
defines only the user
1017
- verify_certificates: https specific, True if the server
1018
certificate should be verified, False otherwise.
1021
for auth_def_name, auth_def in self._get_config().items():
1022
if type(auth_def) is not configobj.Section:
1023
raise ValueError("%s defined outside a section" % auth_def_name)
1025
a_scheme, a_host, a_user, a_path = map(
1026
auth_def.get, ['scheme', 'host', 'user', 'path'])
1029
a_port = auth_def.as_int('port')
1033
raise ValueError("'port' not numeric in %s" % auth_def_name)
1035
a_verify_certificates = auth_def.as_bool('verify_certificates')
1037
a_verify_certificates = True
1040
"'verify_certificates' not boolean in %s" % auth_def_name)
1043
if a_scheme is not None and scheme != a_scheme:
1045
if a_host is not None:
1046
if not (host == a_host
1047
or (a_host.startswith('.') and host.endswith(a_host))):
1049
if a_port is not None and port != a_port:
1051
if (a_path is not None and path is not None
1052
and not path.startswith(a_path)):
1054
if (a_user is not None and user is not None
1055
and a_user != user):
1056
# Never contradict the caller about the user to be used
1061
credentials = dict(name=auth_def_name,
1063
password=auth_def.get('password', None),
1064
verify_certificates=a_verify_certificates)
1065
self.decode_password(credentials,
1066
auth_def.get('password_encoding', None))
1067
if 'auth' in debug.debug_flags:
1068
trace.mutter("Using authentication section: %r", auth_def_name)
1073
def get_user(self, scheme, host, port=None,
1074
realm=None, path=None, prompt=None):
1075
"""Get a user from authentication file.
1077
:param scheme: protocol
1079
:param host: the server address
1081
:param port: the associated port (optional)
1083
:param realm: the realm sent by the server (optional)
1085
:param path: the absolute path on the server (optional)
1087
:return: The found user.
1089
credentials = self.get_credentials(scheme, host, port, user=None,
1091
if credentials is not None:
1092
user = credentials['user']
1097
def get_password(self, scheme, host, user, port=None,
1098
realm=None, path=None, prompt=None):
1099
"""Get a password from authentication file or prompt the user for one.
1101
:param scheme: protocol
1103
:param host: the server address
1105
:param port: the associated port (optional)
1109
:param realm: the realm sent by the server (optional)
1111
:param path: the absolute path on the server (optional)
1113
:return: The found password or the one entered by the user.
1115
credentials = self.get_credentials(scheme, host, port, user, path)
1116
if credentials is not None:
1117
password = credentials['password']
1118
if password is not None and scheme is 'ssh':
1119
trace.warning('password ignored in section [%s],'
1120
' use an ssh agent instead'
1121
% credentials['name'])
1125
# Prompt user only if we could't find a password
1126
if password is None:
1128
# Create a default prompt suitable for most cases
1129
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1130
# Special handling for optional fields in the prompt
1131
if port is not None:
1132
prompt_host = '%s:%d' % (host, port)
1135
password = ui.ui_factory.get_password(prompt,
1136
host=prompt_host, user=user)
1139
def decode_password(self, credentials, encoding):
1143
class BzrDirConfig(object):
1145
def __init__(self, transport):
1146
self._config = TransportConfig(transport, 'control.conf')
1148
def set_default_stack_on(self, value):
1149
"""Set the default stacking location.
1151
It may be set to a location, or None.
1153
This policy affects all branches contained by this bzrdir, except for
1154
those under repositories.
1157
self._config.set_option('', 'default_stack_on')
1159
self._config.set_option(value, 'default_stack_on')
1161
def get_default_stack_on(self):
1162
"""Return the default stacking location.
1164
This will either be a location, or None.
1166
This policy affects all branches contained by this bzrdir, except for
1167
those under repositories.
1169
value = self._config.get_option('default_stack_on')
1175
class TransportConfig(object):
1176
"""A Config that reads/writes a config file on a Transport.
1178
It is a low-level object that considers config data to be name/value pairs
1179
that may be associated with a section. Assigning meaning to the these
1180
values is done at higher levels like TreeConfig.
1183
def __init__(self, transport, filename):
1184
self._transport = transport
1185
self._filename = filename
1187
def get_option(self, name, section=None, default=None):
1188
"""Return the value associated with a named option.
1190
:param name: The name of the value
1191
:param section: The section the option is in (if any)
1192
:param default: The value to return if the value is not set
1193
:return: The value or default value
1195
configobj = self._get_configobj()
1197
section_obj = configobj
1200
section_obj = configobj[section]
1203
return section_obj.get(name, default)
1205
def set_option(self, value, name, section=None):
1206
"""Set the value associated with a named option.
1208
:param value: The value to set
1209
:param name: The name of the value to set
1210
:param section: The section the option is in (if any)
1212
configobj = self._get_configobj()
1214
configobj[name] = value
1216
configobj.setdefault(section, {})[name] = value
1217
self._set_configobj(configobj)
1219
def _get_configobj(self):
1221
return ConfigObj(self._transport.get(self._filename),
1223
except errors.NoSuchFile:
1224
return ConfigObj(encoding='utf-8')
1226
def _set_configobj(self, configobj):
1227
out_file = StringIO()
1228
configobj.write(out_file)
1230
self._transport.put_file(self._filename, out_file)