315
self._parser = ConfigObj(input, encoding='utf-8')
200
self._parser = ConfigObj(input)
316
201
except configobj.ConfigObjError, e:
317
202
raise errors.ParseConfigError(e.errors, e.config.filename)
318
203
return self._parser
320
def _get_matching_sections(self):
321
"""Return an ordered list of (section_name, extra_path) pairs.
323
If the section contains inherited configuration, extra_path is
324
a string containing the additional path components.
326
section = self._get_section()
327
if section is not None:
328
return [(section, '')]
332
205
def _get_section(self):
333
206
"""Override this to define the section used by the config."""
336
def _get_option_policy(self, section, option_name):
337
"""Return the policy for the given (section, option_name) pair."""
340
209
def _get_signature_checking(self):
341
210
"""See Config._get_signature_checking."""
342
211
policy = self._get_user_option('check_signatures')
344
213
return self._string_to_signature_policy(policy)
346
def _get_signing_policy(self):
347
"""See Config._get_signing_policy"""
348
policy = self._get_user_option('create_signatures')
350
return self._string_to_signing_policy(policy)
352
215
def _get_user_id(self):
353
216
"""Get the user id from the 'email' key in the current section."""
354
217
return self._get_user_option('email')
356
219
def _get_user_option(self, option_name):
357
220
"""See Config._get_user_option."""
358
for (section, extra_path) in self._get_matching_sections():
360
value = self._get_parser().get_value(section, option_name)
363
policy = self._get_option_policy(section, option_name)
364
if policy == POLICY_NONE:
366
elif policy == POLICY_NORECURSE:
367
# norecurse items only apply to the exact path
372
elif policy == POLICY_APPENDPATH:
374
value = urlutils.join(value, extra_path)
377
raise AssertionError('Unexpected config policy %r' % policy)
222
return self._get_parser().get_value(self._get_section(),
381
227
def _gpg_signing_command(self):
382
228
"""See Config.gpg_signing_command."""
383
229
return self._get_user_option('gpg_signing_command')
385
def _log_format(self):
386
"""See Config.log_format."""
387
return self._get_user_option('log_format')
389
231
def __init__(self, get_filename):
390
232
super(IniBasedConfig, self).__init__()
391
233
self._get_filename = get_filename
437
258
def __init__(self):
438
259
super(GlobalConfig, self).__init__(config_filename)
440
def set_user_option(self, option, value):
441
"""Save option and its value in the configuration."""
442
# FIXME: RBC 20051029 This should refresh the parser and also take a
443
# file lock on bazaar.conf.
444
conf_dir = os.path.dirname(self._get_filename())
445
ensure_config_dir_exists(conf_dir)
446
if 'DEFAULT' not in self._get_parser():
447
self._get_parser()['DEFAULT'] = {}
448
self._get_parser()['DEFAULT'][option] = value
449
f = open(self._get_filename(), 'wb')
450
self._get_parser().write(f)
454
262
class LocationConfig(IniBasedConfig):
455
263
"""A configuration object that gives the policy for a location."""
457
265
def __init__(self, location):
458
name_generator = locations_config_filename
459
if (not os.path.exists(name_generator()) and
460
os.path.exists(branches_config_filename())):
461
if sys.platform == 'win32':
462
trace.warning('Please rename %s to %s'
463
% (branches_config_filename(),
464
locations_config_filename()))
466
trace.warning('Please rename ~/.bazaar/branches.conf'
467
' to ~/.bazaar/locations.conf')
468
name_generator = branches_config_filename
469
super(LocationConfig, self).__init__(name_generator)
470
# local file locations are looked up by local path, rather than
471
# by file url. This is because the config file is a user
472
# file, and we would rather not expose the user to file urls.
473
if location.startswith('file://'):
474
location = urlutils.local_path_from_url(location)
266
super(LocationConfig, self).__init__(branches_config_filename)
267
self._global_config = None
475
268
self.location = location
477
def _get_matching_sections(self):
478
"""Return an ordered list of section names matching this location."""
270
def _get_global_config(self):
271
if self._global_config is None:
272
self._global_config = GlobalConfig()
273
return self._global_config
275
def _get_section(self):
276
"""Get the section we should look in for config items.
278
Returns None if none exists.
279
TODO: perhaps return a NullSection that thunks through to the
479
282
sections = self._get_parser()
480
283
location_names = self.location.split('/')
481
284
if self.location.endswith('/'):
482
285
del location_names[-1]
484
287
for section in sections:
485
# location is a local path if possible, so we need
486
# to convert 'file://' urls to local paths if necessary.
487
# This also avoids having file:///path be a more exact
488
# match than '/path'.
489
if section.startswith('file://'):
490
section_path = urlutils.local_path_from_url(section)
492
section_path = section
493
section_names = section_path.split('/')
288
section_names = section.split('/')
494
289
if section.endswith('/'):
495
290
del section_names[-1]
496
291
names = zip(location_names, section_names)
505
300
# if section is longer, no match.
506
301
if len(section_names) > len(location_names):
508
matches.append((len(section_names), section,
509
'/'.join(location_names[len(section_names):])))
303
# if path is longer, and recurse is not true, no match
304
if len(section_names) < len(location_names):
306
if not self._get_parser().get_bool(section, 'recurse'):
310
matches.append((len(section_names), section))
510
313
matches.sort(reverse=True)
512
for (length, section, extra_path) in matches:
513
sections.append((section, extra_path))
514
# should we stop looking for parent configs here?
516
if self._get_parser()[section].as_bool('ignore_parents'):
522
def _get_option_policy(self, section, option_name):
523
"""Return the policy for the given (section, option_name) pair."""
524
# check for the old 'recurse=False' flag
526
recurse = self._get_parser()[section].as_bool('recurse')
530
return POLICY_NORECURSE
532
policy_key = option_name + ':policy'
534
policy_name = self._get_parser()[section][policy_key]
538
return _policy_value[policy_name]
540
def _set_option_policy(self, section, option_name, option_policy):
541
"""Set the policy for the given option name in the given section."""
542
# The old recurse=False option affects all options in the
543
# section. To handle multiple policies in the section, we
544
# need to convert it to a policy_norecurse key.
546
recurse = self._get_parser()[section].as_bool('recurse')
550
symbol_versioning.warn(
551
'The recurse option is deprecated as of 0.14. '
552
'The section "%s" has been converted to use policies.'
555
del self._get_parser()[section]['recurse']
557
for key in self._get_parser()[section].keys():
558
if not key.endswith(':policy'):
559
self._get_parser()[section][key +
560
':policy'] = 'norecurse'
562
policy_key = option_name + ':policy'
563
policy_name = _policy_name[option_policy]
564
if policy_name is not None:
565
self._get_parser()[section][policy_key] = policy_name
567
if policy_key in self._get_parser()[section]:
568
del self._get_parser()[section][policy_key]
570
def set_user_option(self, option, value, store=STORE_LOCATION):
316
def _gpg_signing_command(self):
317
"""See Config.gpg_signing_command."""
318
command = super(LocationConfig, self)._gpg_signing_command()
319
if command is not None:
321
return self._get_global_config()._gpg_signing_command()
323
def _get_user_id(self):
324
user_id = super(LocationConfig, self)._get_user_id()
325
if user_id is not None:
327
return self._get_global_config()._get_user_id()
329
def _get_user_option(self, option_name):
330
"""See Config._get_user_option."""
331
option_value = super(LocationConfig,
332
self)._get_user_option(option_name)
333
if option_value is not None:
335
return self._get_global_config()._get_user_option(option_name)
337
def _get_signature_checking(self):
338
"""See Config._get_signature_checking."""
339
check = super(LocationConfig, self)._get_signature_checking()
340
if check is not None:
342
return self._get_global_config()._get_signature_checking()
344
def _post_commit(self):
345
"""See Config.post_commit."""
346
hook = self._get_user_option('post_commit')
349
return self._get_global_config()._post_commit()
351
def set_user_option(self, option, value):
571
352
"""Save option and its value in the configuration."""
572
assert store in [STORE_LOCATION,
573
STORE_LOCATION_NORECURSE,
574
STORE_LOCATION_APPENDPATH], 'bad storage policy'
575
353
# FIXME: RBC 20051029 This should refresh the parser and also take a
576
# file lock on locations.conf.
577
conf_dir = os.path.dirname(self._get_filename())
578
ensure_config_dir_exists(conf_dir)
354
# file lock on branches.conf.
355
if not os.path.isdir(os.path.dirname(self._get_filename())):
356
os.mkdir(os.path.dirname(self._get_filename()))
579
357
location = self.location
580
358
if location.endswith('/'):
581
359
location = location[:-1]
585
363
elif location + '/' in self._get_parser():
586
364
location = location + '/'
587
365
self._get_parser()[location][option]=value
588
# the allowed values of store match the config policies
589
self._set_option_policy(location, option, store)
590
self._get_parser().write(file(self._get_filename(), 'wb'))
366
self._get_parser().write()
593
369
class BranchConfig(Config):
594
370
"""A configuration object giving the policy for a branch."""
596
def _get_branch_data_config(self):
597
if self._branch_data_config is None:
598
self._branch_data_config = TreeConfig(self.branch)
599
return self._branch_data_config
601
372
def _get_location_config(self):
602
373
if self._location_config is None:
603
374
self._location_config = LocationConfig(self.branch.base)
604
375
return self._location_config
606
def _get_global_config(self):
607
if self._global_config is None:
608
self._global_config = GlobalConfig()
609
return self._global_config
611
def _get_best_value(self, option_name):
612
"""This returns a user option from local, tree or global config.
614
They are tried in that order. Use get_safe_value if trusted values
617
for source in self.option_sources:
618
value = getattr(source(), option_name)()
619
if value is not None:
623
def _get_safe_value(self, option_name):
624
"""This variant of get_best_value never returns untrusted values.
626
It does not return values from the branch data, because the branch may
627
not be controlled by the user.
629
We may wish to allow locations.conf to control whether branches are
630
trusted in the future.
632
for source in (self._get_location_config, self._get_global_config):
633
value = getattr(source(), option_name)()
634
if value is not None:
638
377
def _get_user_id(self):
639
378
"""Return the full user id for the branch.
642
381
This is looked up in the email controlfile for the branch.
645
return (self.branch.control_files.get_utf8("email")
384
return (self.branch.controlfile("email", "r")
647
386
.decode(bzrlib.user_encoding)
649
388
except errors.NoSuchFile, e:
652
return self._get_best_value('_get_user_id')
391
return self._get_location_config()._get_user_id()
654
393
def _get_signature_checking(self):
655
394
"""See Config._get_signature_checking."""
656
return self._get_best_value('_get_signature_checking')
658
def _get_signing_policy(self):
659
"""See Config._get_signing_policy."""
660
return self._get_best_value('_get_signing_policy')
395
return self._get_location_config()._get_signature_checking()
662
397
def _get_user_option(self, option_name):
663
398
"""See Config._get_user_option."""
664
for source in self.option_sources:
665
value = source()._get_user_option(option_name)
666
if value is not None:
670
def set_user_option(self, name, value, store=STORE_BRANCH,
672
if store == STORE_BRANCH:
673
self._get_branch_data_config().set_option(value, name)
674
elif store == STORE_GLOBAL:
675
self._get_global_config().set_user_option(name, value)
677
self._get_location_config().set_user_option(name, value, store)
680
if store in (STORE_GLOBAL, STORE_BRANCH):
681
mask_value = self._get_location_config().get_user_option(name)
682
if mask_value is not None:
683
trace.warning('Value "%s" is masked by "%s" from'
684
' locations.conf', value, mask_value)
686
if store == STORE_GLOBAL:
687
branch_config = self._get_branch_data_config()
688
mask_value = branch_config.get_user_option(name)
689
if mask_value is not None:
690
trace.warning('Value "%s" is masked by "%s" from'
691
' branch.conf', value, mask_value)
399
return self._get_location_config()._get_user_option(option_name)
694
401
def _gpg_signing_command(self):
695
402
"""See Config.gpg_signing_command."""
696
return self._get_safe_value('_gpg_signing_command')
403
return self._get_location_config()._gpg_signing_command()
698
405
def __init__(self, branch):
699
406
super(BranchConfig, self).__init__()
700
407
self._location_config = None
701
self._branch_data_config = None
702
self._global_config = None
703
408
self.branch = branch
704
self.option_sources = (self._get_location_config,
705
self._get_branch_data_config,
706
self._get_global_config)
708
410
def _post_commit(self):
709
411
"""See Config.post_commit."""
710
return self._get_safe_value('_post_commit')
712
def _get_nickname(self):
713
value = self._get_explicit_nickname()
714
if value is not None:
716
return urlutils.unescape(self.branch.base.split('/')[-2])
718
def has_explicit_nickname(self):
719
"""Return true if a nickname has been explicitly assigned."""
720
return self._get_explicit_nickname() is not None
722
def _get_explicit_nickname(self):
723
return self._get_best_value('_get_nickname')
725
def _log_format(self):
726
"""See Config.log_format."""
727
return self._get_best_value('_log_format')
730
def ensure_config_dir_exists(path=None):
731
"""Make sure a configuration directory exists.
732
This makes sure that the directory exists.
733
On windows, since configuration directories are 2 levels deep,
734
it makes sure both the directory and the parent directory exists.
738
if not os.path.isdir(path):
739
if sys.platform == 'win32':
740
parent_dir = os.path.dirname(path)
741
if not os.path.isdir(parent_dir):
742
trace.mutter('creating config parent directory: %r', parent_dir)
744
trace.mutter('creating config directory: %r', path)
412
return self._get_location_config()._post_commit()
748
415
def config_dir():
753
420
TODO: Global option --config-dir to override this.
755
base = os.environ.get('BZR_HOME', None)
756
if sys.platform == 'win32':
758
base = win32utils.get_appdata_location_unicode()
760
base = os.environ.get('HOME', None)
762
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
764
return osutils.pathjoin(base, 'bazaar', '2.0')
766
# cygwin, linux, and darwin all have a $HOME directory
768
base = os.path.expanduser("~")
769
return osutils.pathjoin(base, ".bazaar")
422
return os.path.join(os.path.expanduser("~"), ".bazaar")
772
425
def config_filename():
773
426
"""Return per-user configuration ini file filename."""
774
return osutils.pathjoin(config_dir(), 'bazaar.conf')
427
return os.path.join(config_dir(), 'bazaar.conf')
777
430
def branches_config_filename():
778
431
"""Return per-user configuration ini file filename."""
779
return osutils.pathjoin(config_dir(), 'branches.conf')
782
def locations_config_filename():
783
"""Return per-user configuration ini file filename."""
784
return osutils.pathjoin(config_dir(), 'locations.conf')
787
def authentication_config_filename():
788
"""Return per-user authentication ini file filename."""
789
return osutils.pathjoin(config_dir(), 'authentication.conf')
792
def user_ignore_config_filename():
793
"""Return the user default ignore filename"""
794
return osutils.pathjoin(config_dir(), 'ignore')
432
return os.path.join(config_dir(), 'branches.conf')
797
435
def _auto_user_id():
854
464
except ImportError:
857
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
858
except UnicodeDecodeError:
859
raise errors.BzrError("Can't decode username as %s." % \
860
bzrlib.user_encoding)
466
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
862
468
return realname, (username + '@' + socket.gethostname())
865
def parse_username(username):
866
"""Parse e-mail username and return a (name, address) tuple."""
867
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
869
return (username, '')
871
return (match.group(1), match.group(2))
874
471
def extract_email_address(e):
875
472
"""Return just the address part of an email string.
877
474
That is just the user@domain part, nothing else.
878
475
This part is required to contain only ascii characters.
879
476
If it can't be extracted, raises an error.
881
478
>>> extract_email_address('Jane Tester <jane@test.com>')
884
name, email = parse_username(e)
886
raise errors.NoEmailInUsername(e)
890
class TreeConfig(IniBasedConfig):
891
"""Branch configuration data associated with its contents, not location"""
893
def __init__(self, branch):
896
def _get_parser(self, file=None):
898
return IniBasedConfig._get_parser(file)
899
return self._get_config()
901
def _get_config(self):
903
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
905
except errors.NoSuchFile:
906
obj = ConfigObj(encoding='utf=8')
909
def get_option(self, name, section=None, default=None):
910
self.branch.lock_read()
912
obj = self._get_config()
914
if section is not None:
923
def set_option(self, value, name, section=None):
924
"""Set a per-branch configuration option"""
925
self.branch.lock_write()
927
cfg_obj = self._get_config()
932
obj = cfg_obj[section]
934
cfg_obj[section] = {}
935
obj = cfg_obj[section]
937
out_file = StringIO()
938
cfg_obj.write(out_file)
940
self.branch.control_files.put('branch.conf', out_file)
945
class AuthenticationConfig(object):
946
"""The authentication configuration file based on a ini file.
948
Implements the authentication.conf file described in
949
doc/developers/authentication-ring.txt.
952
def __init__(self, _file=None):
953
self._config = None # The ConfigObj
955
self._filename = authentication_config_filename()
956
self._input = self._filename = authentication_config_filename()
958
# Tests can provide a string as _file
959
self._filename = None
962
def _get_config(self):
963
if self._config is not None:
966
# FIXME: Should we validate something here ? Includes: empty
967
# sections are useless, at least one of
968
# user/password/password_encoding should be defined, etc.
970
# Note: the encoding below declares that the file itself is utf-8
971
# encoded, but the values in the ConfigObj are always Unicode.
972
self._config = ConfigObj(self._input, encoding='utf-8')
973
except configobj.ConfigObjError, e:
974
raise errors.ParseConfigError(e.errors, e.config.filename)
978
"""Save the config file, only tests should use it for now."""
979
conf_dir = os.path.dirname(self._filename)
980
ensure_config_dir_exists(conf_dir)
981
self._get_config().write(file(self._filename, 'wb'))
983
def _set_option(self, section_name, option_name, value):
984
"""Set an authentication configuration option"""
985
conf = self._get_config()
986
section = conf.get(section_name)
989
section = conf[section]
990
section[option_name] = value
993
def get_credentials(self, scheme, host, port=None, user=None, path=None):
994
"""Returns the matching credentials from authentication.conf file.
996
:param scheme: protocol
998
:param host: the server address
1000
:param port: the associated port (optional)
1002
:param user: login (optional)
1004
:param path: the absolute path on the server (optional)
1006
:return: A dict containing the matching credentials or None.
1008
- name: the section name of the credentials in the
1009
authentication.conf file,
1010
- user: can't de different from the provided user if any,
1011
- password: the decoded password, could be None if the credential
1012
defines only the user
1013
- verify_certificates: https specific, True if the server
1014
certificate should be verified, False otherwise.
1017
for auth_def_name, auth_def in self._get_config().items():
1018
a_scheme, a_host, a_user, a_path = map(
1019
auth_def.get, ['scheme', 'host', 'user', 'path'])
1022
a_port = auth_def.as_int('port')
1026
raise ValueError("'port' not numeric in %s" % auth_def_name)
1028
a_verify_certificates = auth_def.as_bool('verify_certificates')
1030
a_verify_certificates = True
1033
"'verify_certificates' not boolean in %s" % auth_def_name)
1036
if a_scheme is not None and scheme != a_scheme:
1038
if a_host is not None:
1039
if not (host == a_host
1040
or (a_host.startswith('.') and host.endswith(a_host))):
1042
if a_port is not None and port != a_port:
1044
if (a_path is not None and path is not None
1045
and not path.startswith(a_path)):
1047
if (a_user is not None and user is not None
1048
and a_user != user):
1049
# Never contradict the caller about the user to be used
1054
credentials = dict(name=auth_def_name,
1055
user=a_user, password=auth_def['password'],
1056
verify_certificates=a_verify_certificates)
1057
self.decode_password(credentials,
1058
auth_def.get('password_encoding', None))
1059
if 'auth' in debug.debug_flags:
1060
trace.mutter("Using authentication section: %r", auth_def_name)
1065
def get_user(self, scheme, host, port=None,
1066
realm=None, path=None, prompt=None):
1067
"""Get a user from authentication file.
1069
:param scheme: protocol
1071
:param host: the server address
1073
:param port: the associated port (optional)
1075
:param realm: the realm sent by the server (optional)
1077
:param path: the absolute path on the server (optional)
1079
:return: The found user.
1081
credentials = self.get_credentials(scheme, host, port, user=None,
1083
if credentials is not None:
1084
user = credentials['user']
1089
def get_password(self, scheme, host, user, port=None,
1090
realm=None, path=None, prompt=None):
1091
"""Get a password from authentication file or prompt the user for one.
1093
:param scheme: protocol
1095
:param host: the server address
1097
:param port: the associated port (optional)
1101
:param realm: the realm sent by the server (optional)
1103
:param path: the absolute path on the server (optional)
1105
:return: The found password or the one entered by the user.
1107
credentials = self.get_credentials(scheme, host, port, user, path)
1108
if credentials is not None:
1109
password = credentials['password']
1112
# Prompt user only if we could't find a password
1113
if password is None:
1115
# Create a default prompt suitable for most of the cases
1116
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1117
# Special handling for optional fields in the prompt
1118
if port is not None:
1119
prompt_host = '%s:%d' % (host, port)
1122
password = ui.ui_factory.get_password(prompt,
1123
host=prompt_host, user=user)
1126
def decode_password(self, credentials, encoding):
481
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
483
raise BzrError("%r doesn't seem to contain "
484
"a reasonable email address" % e)