1
# Copyright (C) 2005, 2007 Canonical Ltd
2
# Authors: Robert Collins <robert.collins@canonical.com>
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
# GNU General Public License for more details.
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
"""Configuration that affects the behaviour of Bazaar.
21
Currently this configuration resides in ~/.bazaar/bazaar.conf
22
and ~/.bazaar/locations.conf, which is written to by bzr.
24
In bazaar.conf the following options may be set:
26
editor=name-of-program
27
email=Your Name <your@email.address>
28
check_signatures=require|ignore|check-available(default)
29
create_signatures=always|never|when-required(default)
30
gpg_signing_command=name-of-program
31
log_format=name-of-format
33
in locations.conf, you specify the url of a branch and options for it.
34
Wildcards may be used - * and ? as normal in shell completion. Options
35
set in both bazaar.conf and locations.conf are overridden by the locations.conf
37
[/home/robertc/source]
38
recurse=False|True(default)
40
check_signatures= as above
41
create_signatures= as above.
43
explanation of options
44
----------------------
45
editor - this option sets the pop up editor to use during commits.
46
email - this option sets the user id bzr will use when committing.
47
check_signatures - this option controls whether bzr will require good gpg
48
signatures, ignore them, or check them if they are
50
create_signatures - this option controls whether bzr will always create
51
gpg signatures, never create them, or create them if the
52
branch is configured to require them.
53
log_format - this option sets the default log format. Possible values are
54
long, short, line, or a plugin can register new formats.
56
In bazaar.conf you can also define aliases in the ALIASES sections, example
59
lastlog=log --line -r-10..-1
60
ll=log --line -r-10..-1
68
from bzrlib.lazy_import import lazy_import
69
lazy_import(globals(), """
71
from fnmatch import fnmatch
73
from cStringIO import StringIO
87
from bzrlib.util.configobj import configobj
103
POLICY_APPENDPATH = 2
107
POLICY_NORECURSE: 'norecurse',
108
POLICY_APPENDPATH: 'appendpath',
113
'norecurse': POLICY_NORECURSE,
114
'appendpath': POLICY_APPENDPATH,
118
STORE_LOCATION = POLICY_NONE
119
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
120
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
125
def ConfigObj(*args, **kwargs):
127
if _ConfigObj is None:
128
class ConfigObj(configobj.ConfigObj):
130
def get_bool(self, section, key):
131
return self[section].as_bool(key)
133
def get_value(self, section, name):
134
# Try [] for the old DEFAULT section.
135
if section == "DEFAULT":
140
return self[section][name]
141
_ConfigObj = ConfigObj
142
return _ConfigObj(*args, **kwargs)
145
class Config(object):
146
"""A configuration policy - what username, editor, gpg needs etc."""
148
def get_editor(self):
149
"""Get the users pop up editor."""
150
raise NotImplementedError
152
def get_mail_client(self):
153
"""Get a mail client to use"""
154
selected_client = self.get_user_option('mail_client')
156
mail_client_class = {
157
None: mail_client.DefaultMail,
159
'evolution': mail_client.Evolution,
160
'kmail': mail_client.KMail,
161
'mutt': mail_client.Mutt,
162
'thunderbird': mail_client.Thunderbird,
164
'default': mail_client.DefaultMail,
165
'editor': mail_client.Editor,
166
'mapi': mail_client.MAPIClient,
167
'xdg-email': mail_client.XDGEmail,
170
raise errors.UnknownMailClient(selected_client)
171
return mail_client_class(self)
173
def _get_signature_checking(self):
174
"""Template method to override signature checking policy."""
176
def _get_signing_policy(self):
177
"""Template method to override signature creation policy."""
179
def _get_user_option(self, option_name):
180
"""Template method to provide a user option."""
183
def get_user_option(self, option_name):
184
"""Get a generic option - no special process, no default."""
185
return self._get_user_option(option_name)
187
def gpg_signing_command(self):
188
"""What program should be used to sign signatures?"""
189
result = self._gpg_signing_command()
194
def _gpg_signing_command(self):
195
"""See gpg_signing_command()."""
198
def log_format(self):
199
"""What log format should be used"""
200
result = self._log_format()
205
def _log_format(self):
206
"""See log_format()."""
210
super(Config, self).__init__()
212
def post_commit(self):
213
"""An ordered list of python functions to call.
215
Each function takes branch, rev_id as parameters.
217
return self._post_commit()
219
def _post_commit(self):
220
"""See Config.post_commit."""
223
def user_email(self):
224
"""Return just the email component of a username."""
225
return extract_email_address(self.username())
228
"""Return email-style username.
230
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
232
$BZR_EMAIL can be set to override this (as well as the
233
deprecated $BZREMAIL), then
234
the concrete policy type is checked, and finally
236
If none is found, a reasonable default is (hopefully)
239
TODO: Check it's reasonably well-formed.
241
v = os.environ.get('BZR_EMAIL')
243
return v.decode(osutils.get_user_encoding())
245
v = self._get_user_id()
249
v = os.environ.get('EMAIL')
251
return v.decode(osutils.get_user_encoding())
253
name, email = _auto_user_id()
255
return '%s <%s>' % (name, email)
259
def signature_checking(self):
260
"""What is the current policy for signature checking?."""
261
policy = self._get_signature_checking()
262
if policy is not None:
264
return CHECK_IF_POSSIBLE
266
def signing_policy(self):
267
"""What is the current policy for signature checking?."""
268
policy = self._get_signing_policy()
269
if policy is not None:
271
return SIGN_WHEN_REQUIRED
273
def signature_needed(self):
274
"""Is a signature needed when committing ?."""
275
policy = self._get_signing_policy()
277
policy = self._get_signature_checking()
278
if policy is not None:
279
trace.warning("Please use create_signatures,"
280
" not check_signatures to set signing policy.")
281
if policy == CHECK_ALWAYS:
283
elif policy == SIGN_ALWAYS:
287
def get_alias(self, value):
288
return self._get_alias(value)
290
def _get_alias(self, value):
293
def get_nickname(self):
294
return self._get_nickname()
296
def _get_nickname(self):
299
def get_bzr_remote_path(self):
301
return os.environ['BZR_REMOTE_PATH']
303
path = self.get_user_option("bzr_remote_path")
309
class IniBasedConfig(Config):
310
"""A configuration policy that draws from ini files."""
312
def _get_parser(self, file=None):
313
if self._parser is not None:
316
input = self._get_filename()
320
self._parser = ConfigObj(input, encoding='utf-8')
321
except configobj.ConfigObjError, e:
322
raise errors.ParseConfigError(e.errors, e.config.filename)
325
def _get_matching_sections(self):
326
"""Return an ordered list of (section_name, extra_path) pairs.
328
If the section contains inherited configuration, extra_path is
329
a string containing the additional path components.
331
section = self._get_section()
332
if section is not None:
333
return [(section, '')]
337
def _get_section(self):
338
"""Override this to define the section used by the config."""
341
def _get_option_policy(self, section, option_name):
342
"""Return the policy for the given (section, option_name) pair."""
345
def _get_signature_checking(self):
346
"""See Config._get_signature_checking."""
347
policy = self._get_user_option('check_signatures')
349
return self._string_to_signature_policy(policy)
351
def _get_signing_policy(self):
352
"""See Config._get_signing_policy"""
353
policy = self._get_user_option('create_signatures')
355
return self._string_to_signing_policy(policy)
357
def _get_user_id(self):
358
"""Get the user id from the 'email' key in the current section."""
359
return self._get_user_option('email')
361
def _get_user_option(self, option_name):
362
"""See Config._get_user_option."""
363
for (section, extra_path) in self._get_matching_sections():
365
value = self._get_parser().get_value(section, option_name)
368
policy = self._get_option_policy(section, option_name)
369
if policy == POLICY_NONE:
371
elif policy == POLICY_NORECURSE:
372
# norecurse items only apply to the exact path
377
elif policy == POLICY_APPENDPATH:
379
value = urlutils.join(value, extra_path)
382
raise AssertionError('Unexpected config policy %r' % policy)
386
def _gpg_signing_command(self):
387
"""See Config.gpg_signing_command."""
388
return self._get_user_option('gpg_signing_command')
390
def _log_format(self):
391
"""See Config.log_format."""
392
return self._get_user_option('log_format')
394
def __init__(self, get_filename):
395
super(IniBasedConfig, self).__init__()
396
self._get_filename = get_filename
399
def _post_commit(self):
400
"""See Config.post_commit."""
401
return self._get_user_option('post_commit')
403
def _string_to_signature_policy(self, signature_string):
404
"""Convert a string to a signing policy."""
405
if signature_string.lower() == 'check-available':
406
return CHECK_IF_POSSIBLE
407
if signature_string.lower() == 'ignore':
409
if signature_string.lower() == 'require':
411
raise errors.BzrError("Invalid signatures policy '%s'"
414
def _string_to_signing_policy(self, signature_string):
415
"""Convert a string to a signing policy."""
416
if signature_string.lower() == 'when-required':
417
return SIGN_WHEN_REQUIRED
418
if signature_string.lower() == 'never':
420
if signature_string.lower() == 'always':
422
raise errors.BzrError("Invalid signing policy '%s'"
425
def _get_alias(self, value):
427
return self._get_parser().get_value("ALIASES",
432
def _get_nickname(self):
433
return self.get_user_option('nickname')
436
class GlobalConfig(IniBasedConfig):
437
"""The configuration that should be used for a specific location."""
439
def get_editor(self):
440
return self._get_user_option('editor')
443
super(GlobalConfig, self).__init__(config_filename)
445
def set_user_option(self, option, value):
446
"""Save option and its value in the configuration."""
447
# FIXME: RBC 20051029 This should refresh the parser and also take a
448
# file lock on bazaar.conf.
449
conf_dir = os.path.dirname(self._get_filename())
450
ensure_config_dir_exists(conf_dir)
451
if 'DEFAULT' not in self._get_parser():
452
self._get_parser()['DEFAULT'] = {}
453
self._get_parser()['DEFAULT'][option] = value
454
f = open(self._get_filename(), 'wb')
455
self._get_parser().write(f)
459
class LocationConfig(IniBasedConfig):
460
"""A configuration object that gives the policy for a location."""
462
def __init__(self, location):
463
name_generator = locations_config_filename
464
if (not os.path.exists(name_generator()) and
465
os.path.exists(branches_config_filename())):
466
if sys.platform == 'win32':
467
trace.warning('Please rename %s to %s'
468
% (branches_config_filename(),
469
locations_config_filename()))
471
trace.warning('Please rename ~/.bazaar/branches.conf'
472
' to ~/.bazaar/locations.conf')
473
name_generator = branches_config_filename
474
super(LocationConfig, self).__init__(name_generator)
475
# local file locations are looked up by local path, rather than
476
# by file url. This is because the config file is a user
477
# file, and we would rather not expose the user to file urls.
478
if location.startswith('file://'):
479
location = urlutils.local_path_from_url(location)
480
self.location = location
482
def _get_matching_sections(self):
483
"""Return an ordered list of section names matching this location."""
484
sections = self._get_parser()
485
location_names = self.location.split('/')
486
if self.location.endswith('/'):
487
del location_names[-1]
489
for section in sections:
490
# location is a local path if possible, so we need
491
# to convert 'file://' urls to local paths if necessary.
492
# This also avoids having file:///path be a more exact
493
# match than '/path'.
494
if section.startswith('file://'):
495
section_path = urlutils.local_path_from_url(section)
497
section_path = section
498
section_names = section_path.split('/')
499
if section.endswith('/'):
500
del section_names[-1]
501
names = zip(location_names, section_names)
504
if not fnmatch(name[0], name[1]):
509
# so, for the common prefix they matched.
510
# if section is longer, no match.
511
if len(section_names) > len(location_names):
513
matches.append((len(section_names), section,
514
'/'.join(location_names[len(section_names):])))
515
matches.sort(reverse=True)
517
for (length, section, extra_path) in matches:
518
sections.append((section, extra_path))
519
# should we stop looking for parent configs here?
521
if self._get_parser()[section].as_bool('ignore_parents'):
527
def _get_option_policy(self, section, option_name):
528
"""Return the policy for the given (section, option_name) pair."""
529
# check for the old 'recurse=False' flag
531
recurse = self._get_parser()[section].as_bool('recurse')
535
return POLICY_NORECURSE
537
policy_key = option_name + ':policy'
539
policy_name = self._get_parser()[section][policy_key]
543
return _policy_value[policy_name]
545
def _set_option_policy(self, section, option_name, option_policy):
546
"""Set the policy for the given option name in the given section."""
547
# The old recurse=False option affects all options in the
548
# section. To handle multiple policies in the section, we
549
# need to convert it to a policy_norecurse key.
551
recurse = self._get_parser()[section].as_bool('recurse')
555
symbol_versioning.warn(
556
'The recurse option is deprecated as of 0.14. '
557
'The section "%s" has been converted to use policies.'
560
del self._get_parser()[section]['recurse']
562
for key in self._get_parser()[section].keys():
563
if not key.endswith(':policy'):
564
self._get_parser()[section][key +
565
':policy'] = 'norecurse'
567
policy_key = option_name + ':policy'
568
policy_name = _policy_name[option_policy]
569
if policy_name is not None:
570
self._get_parser()[section][policy_key] = policy_name
572
if policy_key in self._get_parser()[section]:
573
del self._get_parser()[section][policy_key]
575
def set_user_option(self, option, value, store=STORE_LOCATION):
576
"""Save option and its value in the configuration."""
577
assert store in [STORE_LOCATION,
578
STORE_LOCATION_NORECURSE,
579
STORE_LOCATION_APPENDPATH], 'bad storage policy'
580
# FIXME: RBC 20051029 This should refresh the parser and also take a
581
# file lock on locations.conf.
582
conf_dir = os.path.dirname(self._get_filename())
583
ensure_config_dir_exists(conf_dir)
584
location = self.location
585
if location.endswith('/'):
586
location = location[:-1]
587
if (not location in self._get_parser() and
588
not location + '/' in self._get_parser()):
589
self._get_parser()[location]={}
590
elif location + '/' in self._get_parser():
591
location = location + '/'
592
self._get_parser()[location][option]=value
593
# the allowed values of store match the config policies
594
self._set_option_policy(location, option, store)
595
self._get_parser().write(file(self._get_filename(), 'wb'))
598
class BranchConfig(Config):
599
"""A configuration object giving the policy for a branch."""
601
def _get_branch_data_config(self):
602
if self._branch_data_config is None:
603
self._branch_data_config = TreeConfig(self.branch)
604
return self._branch_data_config
606
def _get_location_config(self):
607
if self._location_config is None:
608
self._location_config = LocationConfig(self.branch.base)
609
return self._location_config
611
def _get_global_config(self):
612
if self._global_config is None:
613
self._global_config = GlobalConfig()
614
return self._global_config
616
def _get_best_value(self, option_name):
617
"""This returns a user option from local, tree or global config.
619
They are tried in that order. Use get_safe_value if trusted values
622
for source in self.option_sources:
623
value = getattr(source(), option_name)()
624
if value is not None:
628
def _get_safe_value(self, option_name):
629
"""This variant of get_best_value never returns untrusted values.
631
It does not return values from the branch data, because the branch may
632
not be controlled by the user.
634
We may wish to allow locations.conf to control whether branches are
635
trusted in the future.
637
for source in (self._get_location_config, self._get_global_config):
638
value = getattr(source(), option_name)()
639
if value is not None:
643
def _get_user_id(self):
644
"""Return the full user id for the branch.
646
e.g. "John Hacker <jhacker@foo.org>"
647
This is looked up in the email controlfile for the branch.
650
return (self.branch.control_files.get_utf8("email")
652
.decode(osutils.get_user_encoding())
654
except errors.NoSuchFile, e:
657
return self._get_best_value('_get_user_id')
659
def _get_signature_checking(self):
660
"""See Config._get_signature_checking."""
661
return self._get_best_value('_get_signature_checking')
663
def _get_signing_policy(self):
664
"""See Config._get_signing_policy."""
665
return self._get_best_value('_get_signing_policy')
667
def _get_user_option(self, option_name):
668
"""See Config._get_user_option."""
669
for source in self.option_sources:
670
value = source()._get_user_option(option_name)
671
if value is not None:
675
def set_user_option(self, name, value, store=STORE_BRANCH,
677
if store == STORE_BRANCH:
678
self._get_branch_data_config().set_option(value, name)
679
elif store == STORE_GLOBAL:
680
self._get_global_config().set_user_option(name, value)
682
self._get_location_config().set_user_option(name, value, store)
685
if store in (STORE_GLOBAL, STORE_BRANCH):
686
mask_value = self._get_location_config().get_user_option(name)
687
if mask_value is not None:
688
trace.warning('Value "%s" is masked by "%s" from'
689
' locations.conf', value, mask_value)
691
if store == STORE_GLOBAL:
692
branch_config = self._get_branch_data_config()
693
mask_value = branch_config.get_user_option(name)
694
if mask_value is not None:
695
trace.warning('Value "%s" is masked by "%s" from'
696
' branch.conf', value, mask_value)
699
def _gpg_signing_command(self):
700
"""See Config.gpg_signing_command."""
701
return self._get_safe_value('_gpg_signing_command')
703
def __init__(self, branch):
704
super(BranchConfig, self).__init__()
705
self._location_config = None
706
self._branch_data_config = None
707
self._global_config = None
709
self.option_sources = (self._get_location_config,
710
self._get_branch_data_config,
711
self._get_global_config)
713
def _post_commit(self):
714
"""See Config.post_commit."""
715
return self._get_safe_value('_post_commit')
717
def _get_nickname(self):
718
value = self._get_explicit_nickname()
719
if value is not None:
721
return urlutils.unescape(self.branch.base.split('/')[-2])
723
def has_explicit_nickname(self):
724
"""Return true if a nickname has been explicitly assigned."""
725
return self._get_explicit_nickname() is not None
727
def _get_explicit_nickname(self):
728
return self._get_best_value('_get_nickname')
730
def _log_format(self):
731
"""See Config.log_format."""
732
return self._get_best_value('_log_format')
735
def ensure_config_dir_exists(path=None):
736
"""Make sure a configuration directory exists.
737
This makes sure that the directory exists.
738
On windows, since configuration directories are 2 levels deep,
739
it makes sure both the directory and the parent directory exists.
743
if not os.path.isdir(path):
744
if sys.platform == 'win32':
745
parent_dir = os.path.dirname(path)
746
if not os.path.isdir(parent_dir):
747
trace.mutter('creating config parent directory: %r', parent_dir)
749
trace.mutter('creating config directory: %r', path)
754
"""Return per-user configuration directory.
756
By default this is ~/.bazaar/
758
TODO: Global option --config-dir to override this.
760
base = os.environ.get('BZR_HOME', None)
761
if sys.platform == 'win32':
763
base = win32utils.get_appdata_location_unicode()
765
base = os.environ.get('HOME', None)
767
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
769
return osutils.pathjoin(base, 'bazaar', '2.0')
771
# cygwin, linux, and darwin all have a $HOME directory
773
base = os.path.expanduser("~")
774
return osutils.pathjoin(base, ".bazaar")
777
def config_filename():
778
"""Return per-user configuration ini file filename."""
779
return osutils.pathjoin(config_dir(), 'bazaar.conf')
782
def branches_config_filename():
783
"""Return per-user configuration ini file filename."""
784
return osutils.pathjoin(config_dir(), 'branches.conf')
787
def locations_config_filename():
788
"""Return per-user configuration ini file filename."""
789
return osutils.pathjoin(config_dir(), 'locations.conf')
792
def authentication_config_filename():
793
"""Return per-user authentication ini file filename."""
794
return osutils.pathjoin(config_dir(), 'authentication.conf')
797
def user_ignore_config_filename():
798
"""Return the user default ignore filename"""
799
return osutils.pathjoin(config_dir(), 'ignore')
803
"""Calculate automatic user identification.
805
Returns (realname, email).
807
Only used when none is set in the environment or the id file.
809
This previously used the FQDN as the default domain, but that can
810
be very slow on machines where DNS is broken. So now we simply
815
if sys.platform == 'win32':
816
name = win32utils.get_user_name_unicode()
818
raise errors.BzrError("Cannot autodetect user name.\n"
819
"Please, set your name with command like:\n"
820
'bzr whoami "Your Name <name@domain.com>"')
821
host = win32utils.get_host_name_unicode()
823
host = socket.gethostname()
824
return name, (name + '@' + host)
829
w = pwd.getpwuid(uid)
831
# we try utf-8 first, because on many variants (like Linux),
832
# /etc/passwd "should" be in utf-8, and because it's unlikely to give
833
# false positives. (many users will have their user encoding set to
834
# latin-1, which cannot raise UnicodeError.)
836
gecos = w.pw_gecos.decode('utf-8')
840
encoding = osutils.get_user_encoding()
841
gecos = w.pw_gecos.decode(encoding)
843
raise errors.BzrCommandError('Unable to determine your name. '
844
'Use "bzr whoami" to set it.')
846
username = w.pw_name.decode(encoding)
848
raise errors.BzrCommandError('Unable to determine your name. '
849
'Use "bzr whoami" to set it.')
851
comma = gecos.find(',')
855
realname = gecos[:comma]
862
user_encoding = osutils.get_user_encoding()
863
realname = username = getpass.getuser().decode(user_encoding)
864
except UnicodeDecodeError:
865
raise errors.BzrError("Can't decode username as %s." % \
868
return realname, (username + '@' + socket.gethostname())
871
def parse_username(username):
872
"""Parse e-mail username and return a (name, address) tuple."""
873
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
875
return (username, '')
877
return (match.group(1), match.group(2))
880
def extract_email_address(e):
881
"""Return just the address part of an email string.
883
That is just the user@domain part, nothing else.
884
This part is required to contain only ascii characters.
885
If it can't be extracted, raises an error.
887
>>> extract_email_address('Jane Tester <jane@test.com>')
890
name, email = parse_username(e)
892
raise errors.NoEmailInUsername(e)
896
class TreeConfig(IniBasedConfig):
897
"""Branch configuration data associated with its contents, not location"""
899
def __init__(self, branch):
902
def _get_parser(self, file=None):
904
return IniBasedConfig._get_parser(file)
905
return self._get_config()
907
def _get_config(self):
909
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
911
except errors.NoSuchFile:
912
obj = ConfigObj(encoding='utf=8')
915
def get_option(self, name, section=None, default=None):
916
self.branch.lock_read()
918
obj = self._get_config()
920
if section is not None:
929
def set_option(self, value, name, section=None):
930
"""Set a per-branch configuration option"""
931
self.branch.lock_write()
933
cfg_obj = self._get_config()
938
obj = cfg_obj[section]
940
cfg_obj[section] = {}
941
obj = cfg_obj[section]
943
out_file = StringIO()
944
cfg_obj.write(out_file)
946
self.branch.control_files.put('branch.conf', out_file)
951
class AuthenticationConfig(object):
952
"""The authentication configuration file based on a ini file.
954
Implements the authentication.conf file described in
955
doc/developers/authentication-ring.txt.
958
def __init__(self, _file=None):
959
self._config = None # The ConfigObj
961
self._filename = authentication_config_filename()
962
self._input = self._filename = authentication_config_filename()
964
# Tests can provide a string as _file
965
self._filename = None
968
def _get_config(self):
969
if self._config is not None:
972
# FIXME: Should we validate something here ? Includes: empty
973
# sections are useless, at least one of
974
# user/password/password_encoding should be defined, etc.
976
# Note: the encoding below declares that the file itself is utf-8
977
# encoded, but the values in the ConfigObj are always Unicode.
978
self._config = ConfigObj(self._input, encoding='utf-8')
979
except configobj.ConfigObjError, e:
980
raise errors.ParseConfigError(e.errors, e.config.filename)
984
"""Save the config file, only tests should use it for now."""
985
conf_dir = os.path.dirname(self._filename)
986
ensure_config_dir_exists(conf_dir)
987
self._get_config().write(file(self._filename, 'wb'))
989
def _set_option(self, section_name, option_name, value):
990
"""Set an authentication configuration option"""
991
conf = self._get_config()
992
section = conf.get(section_name)
995
section = conf[section]
996
section[option_name] = value
999
def get_credentials(self, scheme, host, port=None, user=None, path=None):
1000
"""Returns the matching credentials from authentication.conf file.
1002
:param scheme: protocol
1004
:param host: the server address
1006
:param port: the associated port (optional)
1008
:param user: login (optional)
1010
:param path: the absolute path on the server (optional)
1012
:return: A dict containing the matching credentials or None.
1014
- name: the section name of the credentials in the
1015
authentication.conf file,
1016
- user: can't de different from the provided user if any,
1017
- password: the decoded password, could be None if the credential
1018
defines only the user
1019
- verify_certificates: https specific, True if the server
1020
certificate should be verified, False otherwise.
1023
for auth_def_name, auth_def in self._get_config().items():
1024
a_scheme, a_host, a_user, a_path = map(
1025
auth_def.get, ['scheme', 'host', 'user', 'path'])
1028
a_port = auth_def.as_int('port')
1032
raise ValueError("'port' not numeric in %s" % auth_def_name)
1034
a_verify_certificates = auth_def.as_bool('verify_certificates')
1036
a_verify_certificates = True
1039
"'verify_certificates' not boolean in %s" % auth_def_name)
1042
if a_scheme is not None and scheme != a_scheme:
1044
if a_host is not None:
1045
if not (host == a_host
1046
or (a_host.startswith('.') and host.endswith(a_host))):
1048
if a_port is not None and port != a_port:
1050
if (a_path is not None and path is not None
1051
and not path.startswith(a_path)):
1053
if (a_user is not None and user is not None
1054
and a_user != user):
1055
# Never contradict the caller about the user to be used
1060
credentials = dict(name=auth_def_name,
1061
user=a_user, password=auth_def['password'],
1062
verify_certificates=a_verify_certificates)
1063
self.decode_password(credentials,
1064
auth_def.get('password_encoding', None))
1065
if 'auth' in debug.debug_flags:
1066
trace.mutter("Using authentication section: %r", auth_def_name)
1071
def get_user(self, scheme, host, port=None,
1072
realm=None, path=None, prompt=None):
1073
"""Get a user from authentication file.
1075
:param scheme: protocol
1077
:param host: the server address
1079
:param port: the associated port (optional)
1081
:param realm: the realm sent by the server (optional)
1083
:param path: the absolute path on the server (optional)
1085
:return: The found user.
1087
credentials = self.get_credentials(scheme, host, port, user=None,
1089
if credentials is not None:
1090
user = credentials['user']
1095
def get_password(self, scheme, host, user, port=None,
1096
realm=None, path=None, prompt=None):
1097
"""Get a password from authentication file or prompt the user for one.
1099
:param scheme: protocol
1101
:param host: the server address
1103
:param port: the associated port (optional)
1107
:param realm: the realm sent by the server (optional)
1109
:param path: the absolute path on the server (optional)
1111
:return: The found password or the one entered by the user.
1113
credentials = self.get_credentials(scheme, host, port, user, path)
1114
if credentials is not None:
1115
password = credentials['password']
1118
# Prompt user only if we could't find a password
1119
if password is None:
1121
# Create a default prompt suitable for most of the cases
1122
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1123
# Special handling for optional fields in the prompt
1124
if port is not None:
1125
prompt_host = '%s:%d' % (host, port)
1128
password = ui.ui_factory.get_password(prompt,
1129
host=prompt_host, user=user)
1132
def decode_password(self, credentials, encoding):