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
# FIXME: RBC 20051029 This should refresh the parser and also take a
444
# file lock on bazaar.conf.
445
conf_dir = os.path.dirname(self._get_filename())
446
ensure_config_dir_exists(conf_dir)
447
if 'DEFAULT' not in self._get_parser():
448
self._get_parser()['DEFAULT'] = {}
449
self._get_parser()['DEFAULT'][option] = value
450
f = open(self._get_filename(), 'wb')
451
self._get_parser().write(f)
293
455
class LocationConfig(IniBasedConfig):
294
456
"""A configuration object that gives the policy for a location."""
296
458
def __init__(self, location):
297
super(LocationConfig, self).__init__(branches_config_filename)
298
self._global_config = None
459
name_generator = locations_config_filename
460
if (not os.path.exists(name_generator()) and
461
os.path.exists(branches_config_filename())):
462
if sys.platform == 'win32':
463
trace.warning('Please rename %s to %s'
464
% (branches_config_filename(),
465
locations_config_filename()))
467
trace.warning('Please rename ~/.bazaar/branches.conf'
468
' to ~/.bazaar/locations.conf')
469
name_generator = branches_config_filename
470
super(LocationConfig, self).__init__(name_generator)
471
# local file locations are looked up by local path, rather than
472
# by file url. This is because the config file is a user
473
# file, and we would rather not expose the user to file urls.
474
if location.startswith('file://'):
475
location = urlutils.local_path_from_url(location)
299
476
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
478
def _get_matching_sections(self):
479
"""Return an ordered list of section names matching this location."""
313
480
sections = self._get_parser()
314
481
location_names = self.location.split('/')
315
482
if self.location.endswith('/'):
316
483
del location_names[-1]
318
485
for section in sections:
319
section_names = section.split('/')
486
# location is a local path if possible, so we need
487
# to convert 'file://' urls to local paths if necessary.
488
# This also avoids having file:///path be a more exact
489
# match than '/path'.
490
if section.startswith('file://'):
491
section_path = urlutils.local_path_from_url(section)
493
section_path = section
494
section_names = section_path.split('/')
320
495
if section.endswith('/'):
321
496
del section_names[-1]
322
497
names = zip(location_names, section_names)
331
506
# if section is longer, no match.
332
507
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))
509
matches.append((len(section_names), section,
510
'/'.join(location_names[len(section_names):])))
344
511
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):
513
for (length, section, extra_path) in matches:
514
sections.append((section, extra_path))
515
# should we stop looking for parent configs here?
517
if self._get_parser()[section].as_bool('ignore_parents'):
523
def _get_option_policy(self, section, option_name):
524
"""Return the policy for the given (section, option_name) pair."""
525
# check for the old 'recurse=False' flag
527
recurse = self._get_parser()[section].as_bool('recurse')
531
return POLICY_NORECURSE
533
policy_key = option_name + ':policy'
535
policy_name = self._get_parser()[section][policy_key]
539
return _policy_value[policy_name]
541
def _set_option_policy(self, section, option_name, option_policy):
542
"""Set the policy for the given option name in the given section."""
543
# The old recurse=False option affects all options in the
544
# section. To handle multiple policies in the section, we
545
# need to convert it to a policy_norecurse key.
547
recurse = self._get_parser()[section].as_bool('recurse')
551
symbol_versioning.warn(
552
'The recurse option is deprecated as of 0.14. '
553
'The section "%s" has been converted to use policies.'
556
del self._get_parser()[section]['recurse']
558
for key in self._get_parser()[section].keys():
559
if not key.endswith(':policy'):
560
self._get_parser()[section][key +
561
':policy'] = 'norecurse'
563
policy_key = option_name + ':policy'
564
policy_name = _policy_name[option_policy]
565
if policy_name is not None:
566
self._get_parser()[section][policy_key] = policy_name
568
if policy_key in self._get_parser()[section]:
569
del self._get_parser()[section][policy_key]
571
def set_user_option(self, option, value, store=STORE_LOCATION):
390
572
"""Save option and its value in the configuration."""
573
if store not in [STORE_LOCATION,
574
STORE_LOCATION_NORECURSE,
575
STORE_LOCATION_APPENDPATH]:
576
raise ValueError('bad storage policy %r for %r' %
391
578
# FIXME: RBC 20051029 This should refresh the parser and also take a
392
# file lock on branches.conf.
579
# file lock on locations.conf.
393
580
conf_dir = os.path.dirname(self._get_filename())
394
581
ensure_config_dir_exists(conf_dir)
395
582
location = self.location
401
588
elif location + '/' in self._get_parser():
402
589
location = location + '/'
403
590
self._get_parser()[location][option]=value
591
# the allowed values of store match the config policies
592
self._set_option_policy(location, option, store)
404
593
self._get_parser().write(file(self._get_filename(), 'wb'))
407
596
class BranchConfig(Config):
408
597
"""A configuration object giving the policy for a branch."""
599
def _get_branch_data_config(self):
600
if self._branch_data_config is None:
601
self._branch_data_config = TreeConfig(self.branch)
602
return self._branch_data_config
410
604
def _get_location_config(self):
411
605
if self._location_config is None:
412
606
self._location_config = LocationConfig(self.branch.base)
413
607
return self._location_config
609
def _get_global_config(self):
610
if self._global_config is None:
611
self._global_config = GlobalConfig()
612
return self._global_config
614
def _get_best_value(self, option_name):
615
"""This returns a user option from local, tree or global config.
617
They are tried in that order. Use get_safe_value if trusted values
620
for source in self.option_sources:
621
value = getattr(source(), option_name)()
622
if value is not None:
626
def _get_safe_value(self, option_name):
627
"""This variant of get_best_value never returns untrusted values.
629
It does not return values from the branch data, because the branch may
630
not be controlled by the user.
632
We may wish to allow locations.conf to control whether branches are
633
trusted in the future.
635
for source in (self._get_location_config, self._get_global_config):
636
value = getattr(source(), option_name)()
637
if value is not None:
415
641
def _get_user_id(self):
416
642
"""Return the full user id for the branch.
418
e.g. "John Hacker <jhacker@foo.org>"
644
e.g. "John Hacker <jhacker@example.com>"
419
645
This is looked up in the email controlfile for the branch.
422
return (self.branch.control_files.get_utf8("email")
648
return (self.branch._transport.get_bytes("email")
424
649
.decode(bzrlib.user_encoding)
426
651
except errors.NoSuchFile, e:
429
return self._get_location_config()._get_user_id()
654
return self._get_best_value('_get_user_id')
431
656
def _get_signature_checking(self):
432
657
"""See Config._get_signature_checking."""
433
return self._get_location_config()._get_signature_checking()
658
return self._get_best_value('_get_signature_checking')
660
def _get_signing_policy(self):
661
"""See Config._get_signing_policy."""
662
return self._get_best_value('_get_signing_policy')
435
664
def _get_user_option(self, option_name):
436
665
"""See Config._get_user_option."""
437
return self._get_location_config()._get_user_option(option_name)
666
for source in self.option_sources:
667
value = source()._get_user_option(option_name)
668
if value is not None:
672
def set_user_option(self, name, value, store=STORE_BRANCH,
674
if store == STORE_BRANCH:
675
self._get_branch_data_config().set_option(value, name)
676
elif store == STORE_GLOBAL:
677
self._get_global_config().set_user_option(name, value)
679
self._get_location_config().set_user_option(name, value, store)
682
if store in (STORE_GLOBAL, STORE_BRANCH):
683
mask_value = self._get_location_config().get_user_option(name)
684
if mask_value is not None:
685
trace.warning('Value "%s" is masked by "%s" from'
686
' locations.conf', value, mask_value)
688
if store == STORE_GLOBAL:
689
branch_config = self._get_branch_data_config()
690
mask_value = branch_config.get_user_option(name)
691
if mask_value is not None:
692
trace.warning('Value "%s" is masked by "%s" from'
693
' branch.conf', value, mask_value)
439
696
def _gpg_signing_command(self):
440
697
"""See Config.gpg_signing_command."""
441
return self._get_location_config()._gpg_signing_command()
698
return self._get_safe_value('_gpg_signing_command')
443
700
def __init__(self, branch):
444
701
super(BranchConfig, self).__init__()
445
702
self._location_config = None
703
self._branch_data_config = None
704
self._global_config = None
446
705
self.branch = branch
706
self.option_sources = (self._get_location_config,
707
self._get_branch_data_config,
708
self._get_global_config)
448
710
def _post_commit(self):
449
711
"""See Config.post_commit."""
450
return self._get_location_config()._post_commit()
712
return self._get_safe_value('_post_commit')
714
def _get_nickname(self):
715
value = self._get_explicit_nickname()
716
if value is not None:
718
return urlutils.unescape(self.branch.base.split('/')[-2])
720
def has_explicit_nickname(self):
721
"""Return true if a nickname has been explicitly assigned."""
722
return self._get_explicit_nickname() is not None
724
def _get_explicit_nickname(self):
725
return self._get_best_value('_get_nickname')
452
727
def _log_format(self):
453
728
"""See Config.log_format."""
454
return self._get_location_config()._log_format()
729
return self._get_best_value('_log_format')
457
732
def ensure_config_dir_exists(path=None):
482
757
base = os.environ.get('BZR_HOME', None)
483
758
if sys.platform == 'win32':
485
base = os.environ.get('APPDATA', None)
760
base = win32utils.get_appdata_location_unicode()
487
762
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')
764
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
766
return osutils.pathjoin(base, 'bazaar', '2.0')
492
768
# cygwin, linux, and darwin all have a $HOME directory
494
770
base = os.path.expanduser("~")
495
return pathjoin(base, ".bazaar")
771
return osutils.pathjoin(base, ".bazaar")
498
774
def config_filename():
499
775
"""Return per-user configuration ini file filename."""
500
return pathjoin(config_dir(), 'bazaar.conf')
776
return osutils.pathjoin(config_dir(), 'bazaar.conf')
503
779
def branches_config_filename():
504
780
"""Return per-user configuration ini file filename."""
505
return pathjoin(config_dir(), 'branches.conf')
781
return osutils.pathjoin(config_dir(), 'branches.conf')
784
def locations_config_filename():
785
"""Return per-user configuration ini file filename."""
786
return osutils.pathjoin(config_dir(), 'locations.conf')
789
def authentication_config_filename():
790
"""Return per-user authentication ini file filename."""
791
return osutils.pathjoin(config_dir(), 'authentication.conf')
794
def user_ignore_config_filename():
795
"""Return the user default ignore filename"""
796
return osutils.pathjoin(config_dir(), 'ignore')
508
799
def _auto_user_id():
521
# XXX: Any good way to get real user name on win32?
812
if sys.platform == 'win32':
813
name = win32utils.get_user_name_unicode()
815
raise errors.BzrError("Cannot autodetect user name.\n"
816
"Please, set your name with command like:\n"
817
'bzr whoami "Your Name <name@domain.com>"')
818
host = win32utils.get_host_name_unicode()
820
host = socket.gethostname()
821
return name, (name + '@' + host)
525
825
uid = os.getuid()
526
826
w = pwd.getpwuid(uid)
529
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
530
username = w.pw_name.decode(bzrlib.user_encoding)
531
except UnicodeDecodeError:
532
# We're using pwd, therefore we're on Unix, so /etc/passwd is ok.
533
raise errors.BzrError("Can't decode username in " \
534
"/etc/passwd as %s." % bzrlib.user_encoding)
828
# we try utf-8 first, because on many variants (like Linux),
829
# /etc/passwd "should" be in utf-8, and because it's unlikely to give
830
# false positives. (many users will have their user encoding set to
831
# latin-1, which cannot raise UnicodeError.)
833
gecos = w.pw_gecos.decode('utf-8')
837
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
838
encoding = bzrlib.user_encoding
840
raise errors.BzrCommandError('Unable to determine your name. '
841
'Use "bzr whoami" to set it.')
843
username = w.pw_name.decode(encoding)
845
raise errors.BzrCommandError('Unable to determine your name. '
846
'Use "bzr whoami" to set it.')
536
848
comma = gecos.find(',')
552
864
return realname, (username + '@' + socket.gethostname())
867
def parse_username(username):
868
"""Parse e-mail username and return a (name, address) tuple."""
869
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
871
return (username, '')
873
return (match.group(1), match.group(2))
555
876
def extract_email_address(e):
556
877
"""Return just the address part of an email string.
558
879
That is just the user@domain part, nothing else.
559
880
This part is required to contain only ascii characters.
560
881
If it can't be extracted, raises an error.
562
883
>>> 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)
571
class TreeConfig(object):
886
name, email = parse_username(e)
888
raise errors.NoEmailInUsername(e)
892
class TreeConfig(IniBasedConfig):
572
893
"""Branch configuration data associated with its contents, not location"""
895
# XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
573
897
def __init__(self, branch):
898
# XXX: Really this should be asking the branch for its configuration
899
# data, rather than relying on a Transport, so that it can work
900
# more cleanly with a RemoteBranch that has no transport.
901
self._config = TransportConfig(branch._transport, 'branch.conf')
574
902
self.branch = branch
576
def _get_config(self):
578
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
580
except errors.NoSuchFile:
581
obj = ConfigObj(encoding='utf=8')
904
def _get_parser(self, file=None):
906
return IniBasedConfig._get_parser(file)
907
return self._config._get_configobj()
584
909
def get_option(self, name, section=None, default=None):
585
910
self.branch.lock_read()
587
obj = self._get_config()
589
if section is not None:
912
return self._config.get_option(name, section, default)
595
914
self.branch.unlock()
599
918
"""Set a per-branch configuration option"""
600
919
self.branch.lock_write()
602
cfg_obj = self._get_config()
607
obj = cfg_obj[section]
609
cfg_obj[section] = {}
610
obj = cfg_obj[section]
612
out_file = StringIO()
613
cfg_obj.write(out_file)
615
self.branch.control_files.put('branch.conf', out_file)
921
self._config.set_option(value, name, section)
617
923
self.branch.unlock()
926
class AuthenticationConfig(object):
927
"""The authentication configuration file based on a ini file.
929
Implements the authentication.conf file described in
930
doc/developers/authentication-ring.txt.
933
def __init__(self, _file=None):
934
self._config = None # The ConfigObj
936
self._filename = authentication_config_filename()
937
self._input = self._filename = authentication_config_filename()
939
# Tests can provide a string as _file
940
self._filename = None
943
def _get_config(self):
944
if self._config is not None:
947
# FIXME: Should we validate something here ? Includes: empty
948
# sections are useless, at least one of
949
# user/password/password_encoding should be defined, etc.
951
# Note: the encoding below declares that the file itself is utf-8
952
# encoded, but the values in the ConfigObj are always Unicode.
953
self._config = ConfigObj(self._input, encoding='utf-8')
954
except configobj.ConfigObjError, e:
955
raise errors.ParseConfigError(e.errors, e.config.filename)
959
"""Save the config file, only tests should use it for now."""
960
conf_dir = os.path.dirname(self._filename)
961
ensure_config_dir_exists(conf_dir)
962
self._get_config().write(file(self._filename, 'wb'))
964
def _set_option(self, section_name, option_name, value):
965
"""Set an authentication configuration option"""
966
conf = self._get_config()
967
section = conf.get(section_name)
970
section = conf[section]
971
section[option_name] = value
974
def get_credentials(self, scheme, host, port=None, user=None, path=None):
975
"""Returns the matching credentials from authentication.conf file.
977
:param scheme: protocol
979
:param host: the server address
981
:param port: the associated port (optional)
983
:param user: login (optional)
985
:param path: the absolute path on the server (optional)
987
:return: A dict containing the matching credentials or None.
989
- name: the section name of the credentials in the
990
authentication.conf file,
991
- user: can't de different from the provided user if any,
992
- password: the decoded password, could be None if the credential
993
defines only the user
994
- verify_certificates: https specific, True if the server
995
certificate should be verified, False otherwise.
998
for auth_def_name, auth_def in self._get_config().items():
999
if type(auth_def) is not configobj.Section:
1000
raise ValueError("%s defined outside a section" % auth_def_name)
1002
a_scheme, a_host, a_user, a_path = map(
1003
auth_def.get, ['scheme', 'host', 'user', 'path'])
1006
a_port = auth_def.as_int('port')
1010
raise ValueError("'port' not numeric in %s" % auth_def_name)
1012
a_verify_certificates = auth_def.as_bool('verify_certificates')
1014
a_verify_certificates = True
1017
"'verify_certificates' not boolean in %s" % auth_def_name)
1020
if a_scheme is not None and scheme != a_scheme:
1022
if a_host is not None:
1023
if not (host == a_host
1024
or (a_host.startswith('.') and host.endswith(a_host))):
1026
if a_port is not None and port != a_port:
1028
if (a_path is not None and path is not None
1029
and not path.startswith(a_path)):
1031
if (a_user is not None and user is not None
1032
and a_user != user):
1033
# Never contradict the caller about the user to be used
1038
credentials = dict(name=auth_def_name,
1040
password=auth_def.get('password', None),
1041
verify_certificates=a_verify_certificates)
1042
self.decode_password(credentials,
1043
auth_def.get('password_encoding', None))
1044
if 'auth' in debug.debug_flags:
1045
trace.mutter("Using authentication section: %r", auth_def_name)
1050
def get_user(self, scheme, host, port=None,
1051
realm=None, path=None, prompt=None):
1052
"""Get a user from authentication file.
1054
:param scheme: protocol
1056
:param host: the server address
1058
:param port: the associated port (optional)
1060
:param realm: the realm sent by the server (optional)
1062
:param path: the absolute path on the server (optional)
1064
:return: The found user.
1066
credentials = self.get_credentials(scheme, host, port, user=None,
1068
if credentials is not None:
1069
user = credentials['user']
1074
def get_password(self, scheme, host, user, port=None,
1075
realm=None, path=None, prompt=None):
1076
"""Get a password from authentication file or prompt the user for one.
1078
:param scheme: protocol
1080
:param host: the server address
1082
:param port: the associated port (optional)
1086
:param realm: the realm sent by the server (optional)
1088
:param path: the absolute path on the server (optional)
1090
:return: The found password or the one entered by the user.
1092
credentials = self.get_credentials(scheme, host, port, user, path)
1093
if credentials is not None:
1094
password = credentials['password']
1095
if password is not None and scheme is 'ssh':
1096
trace.warning('password ignored in section [%s],'
1097
' use an ssh agent instead'
1098
% credentials['name'])
1102
# Prompt user only if we could't find a password
1103
if password is None:
1105
# Create a default prompt suitable for most cases
1106
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1107
# Special handling for optional fields in the prompt
1108
if port is not None:
1109
prompt_host = '%s:%d' % (host, port)
1112
password = ui.ui_factory.get_password(prompt,
1113
host=prompt_host, user=user)
1116
def decode_password(self, credentials, encoding):
1120
class TransportConfig(object):
1121
"""A Config that reads/writes a config file on a Transport.
1123
It is a low-level object that considers config data to be name/value pairs
1124
that may be associated with a section. Assigning meaning to the these
1125
values is done at higher levels like TreeConfig.
1128
def __init__(self, transport, filename):
1129
self._transport = transport
1130
self._filename = filename
1132
def get_option(self, name, section=None, default=None):
1133
"""Return the value associated with a named option.
1135
:param name: The name of the value
1136
:param section: The section the option is in (if any)
1137
:param default: The value to return if the value is not set
1138
:return: The value or default value
1140
configobj = self._get_configobj()
1142
section_obj = configobj
1145
section_obj = configobj[section]
1148
return section_obj.get(name, default)
1150
def set_option(self, value, name, section=None):
1151
"""Set the value associated with a named option.
1153
:param value: The value to set
1154
:param name: The name of the value to set
1155
:param section: The section the option is in (if any)
1157
configobj = self._get_configobj()
1159
configobj[name] = value
1161
configobj.setdefault(section, {})[name] = value
1162
self._set_configobj(configobj)
1164
def _get_configobj(self):
1166
return ConfigObj(self._transport.get(self._filename),
1168
except errors.NoSuchFile:
1169
return ConfigObj(encoding='utf-8')
1171
def _set_configobj(self, configobj):
1172
out_file = StringIO()
1173
configobj.write(out_file)
1175
self._transport.put_file(self._filename, out_file)