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
69
from bzrlib.lazy_import import lazy_import
70
lazy_import(globals(), """
72
from fnmatch import fnmatch
74
# FIXME: Why not CStringIO ? -- vila 20071019
75
from StringIO import StringIO
89
import bzrlib.util.configobj.configobj as configobj
105
POLICY_APPENDPATH = 2
109
POLICY_NORECURSE: 'norecurse',
110
POLICY_APPENDPATH: 'appendpath',
115
'norecurse': POLICY_NORECURSE,
116
'appendpath': POLICY_APPENDPATH,
120
STORE_LOCATION = POLICY_NONE
121
STORE_LOCATION_NORECURSE = POLICY_NORECURSE
122
STORE_LOCATION_APPENDPATH = POLICY_APPENDPATH
127
class ConfigObj(configobj.ConfigObj):
129
def get_bool(self, section, key):
130
return self[section].as_bool(key)
132
def get_value(self, section, name):
133
# Try [] for the old DEFAULT section.
134
if section == "DEFAULT":
139
return self[section][name]
142
class Config(object):
143
"""A configuration policy - what username, editor, gpg needs etc."""
145
def get_editor(self):
146
"""Get the users pop up editor."""
147
raise NotImplementedError
149
def get_mail_client(self):
150
"""Get a mail client to use"""
151
selected_client = self.get_user_option('mail_client')
153
mail_client_class = {
154
None: mail_client.DefaultMail,
156
'evolution': mail_client.Evolution,
157
'kmail': mail_client.KMail,
158
'mutt': mail_client.Mutt,
159
'thunderbird': mail_client.Thunderbird,
161
'default': mail_client.DefaultMail,
162
'editor': mail_client.Editor,
163
'mapi': mail_client.MAPIClient,
164
'xdg-email': mail_client.XDGEmail,
167
raise errors.UnknownMailClient(selected_client)
168
return mail_client_class(self)
170
def _get_signature_checking(self):
171
"""Template method to override signature checking policy."""
173
def _get_signing_policy(self):
174
"""Template method to override signature creation policy."""
176
def _get_user_option(self, option_name):
177
"""Template method to provide a user option."""
180
def get_user_option(self, option_name):
181
"""Get a generic option - no special process, no default."""
182
return self._get_user_option(option_name)
184
def gpg_signing_command(self):
185
"""What program should be used to sign signatures?"""
186
result = self._gpg_signing_command()
191
def _gpg_signing_command(self):
192
"""See gpg_signing_command()."""
195
def log_format(self):
196
"""What log format should be used"""
197
result = self._log_format()
202
def _log_format(self):
203
"""See log_format()."""
207
super(Config, self).__init__()
209
def post_commit(self):
210
"""An ordered list of python functions to call.
212
Each function takes branch, rev_id as parameters.
214
return self._post_commit()
216
def _post_commit(self):
217
"""See Config.post_commit."""
220
def user_email(self):
221
"""Return just the email component of a username."""
222
return extract_email_address(self.username())
225
"""Return email-style username.
227
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
229
$BZR_EMAIL can be set to override this (as well as the
230
deprecated $BZREMAIL), then
231
the concrete policy type is checked, and finally
233
If none is found, a reasonable default is (hopefully)
236
TODO: Check it's reasonably well-formed.
238
v = os.environ.get('BZR_EMAIL')
240
return v.decode(bzrlib.user_encoding)
241
v = os.environ.get('BZREMAIL')
243
# FIXME: Seems to have been deprecated since more than a year now,
244
# time to delete ? -- vila 20071019
245
trace.warning('BZREMAIL is deprecated in favor of BZR_EMAIL.'
246
' Please update your configuration.')
247
return v.decode(bzrlib.user_encoding)
249
v = self._get_user_id()
253
v = os.environ.get('EMAIL')
255
return v.decode(bzrlib.user_encoding)
257
name, email = _auto_user_id()
259
return '%s <%s>' % (name, email)
263
def signature_checking(self):
264
"""What is the current policy for signature checking?."""
265
policy = self._get_signature_checking()
266
if policy is not None:
268
return CHECK_IF_POSSIBLE
270
def signing_policy(self):
271
"""What is the current policy for signature checking?."""
272
policy = self._get_signing_policy()
273
if policy is not None:
275
return SIGN_WHEN_REQUIRED
277
def signature_needed(self):
278
"""Is a signature needed when committing ?."""
279
policy = self._get_signing_policy()
281
policy = self._get_signature_checking()
282
if policy is not None:
283
trace.warning("Please use create_signatures,"
284
" not check_signatures to set signing policy.")
285
if policy == CHECK_ALWAYS:
287
elif policy == SIGN_ALWAYS:
291
def get_alias(self, value):
292
return self._get_alias(value)
294
def _get_alias(self, value):
297
def get_nickname(self):
298
return self._get_nickname()
300
def _get_nickname(self):
303
def get_bzr_remote_path(self):
305
return os.environ['BZR_REMOTE_PATH']
307
path = self.get_user_option("bzr_remote_path")
313
class IniBasedConfig(Config):
314
"""A configuration policy that draws from ini files."""
316
def _get_parser(self, file=None):
317
if self._parser is not None:
320
input = self._get_filename()
324
self._parser = ConfigObj(input, encoding='utf-8')
325
except configobj.ConfigObjError, e:
326
raise errors.ParseConfigError(e.errors, e.config.filename)
329
def _get_matching_sections(self):
330
"""Return an ordered list of (section_name, extra_path) pairs.
332
If the section contains inherited configuration, extra_path is
333
a string containing the additional path components.
335
section = self._get_section()
336
if section is not None:
337
return [(section, '')]
341
def _get_section(self):
342
"""Override this to define the section used by the config."""
345
def _get_option_policy(self, section, option_name):
346
"""Return the policy for the given (section, option_name) pair."""
349
def _get_signature_checking(self):
350
"""See Config._get_signature_checking."""
351
policy = self._get_user_option('check_signatures')
353
return self._string_to_signature_policy(policy)
355
def _get_signing_policy(self):
356
"""See Config._get_signing_policy"""
357
policy = self._get_user_option('create_signatures')
359
return self._string_to_signing_policy(policy)
361
def _get_user_id(self):
362
"""Get the user id from the 'email' key in the current section."""
363
return self._get_user_option('email')
365
def _get_user_option(self, option_name):
366
"""See Config._get_user_option."""
367
for (section, extra_path) in self._get_matching_sections():
369
value = self._get_parser().get_value(section, option_name)
372
policy = self._get_option_policy(section, option_name)
373
if policy == POLICY_NONE:
375
elif policy == POLICY_NORECURSE:
376
# norecurse items only apply to the exact path
381
elif policy == POLICY_APPENDPATH:
383
value = urlutils.join(value, extra_path)
386
raise AssertionError('Unexpected config policy %r' % policy)
390
def _gpg_signing_command(self):
391
"""See Config.gpg_signing_command."""
392
return self._get_user_option('gpg_signing_command')
394
def _log_format(self):
395
"""See Config.log_format."""
396
return self._get_user_option('log_format')
398
def __init__(self, get_filename):
399
super(IniBasedConfig, self).__init__()
400
self._get_filename = get_filename
403
def _post_commit(self):
404
"""See Config.post_commit."""
405
return self._get_user_option('post_commit')
407
def _string_to_signature_policy(self, signature_string):
408
"""Convert a string to a signing policy."""
409
if signature_string.lower() == 'check-available':
410
return CHECK_IF_POSSIBLE
411
if signature_string.lower() == 'ignore':
413
if signature_string.lower() == 'require':
415
raise errors.BzrError("Invalid signatures policy '%s'"
418
def _string_to_signing_policy(self, signature_string):
419
"""Convert a string to a signing policy."""
420
if signature_string.lower() == 'when-required':
421
return SIGN_WHEN_REQUIRED
422
if signature_string.lower() == 'never':
424
if signature_string.lower() == 'always':
426
raise errors.BzrError("Invalid signing policy '%s'"
429
def _get_alias(self, value):
431
return self._get_parser().get_value("ALIASES",
436
def _get_nickname(self):
437
return self.get_user_option('nickname')
440
class GlobalConfig(IniBasedConfig):
441
"""The configuration that should be used for a specific location."""
443
def get_editor(self):
444
return self._get_user_option('editor')
447
super(GlobalConfig, self).__init__(config_filename)
449
def set_user_option(self, option, value):
450
"""Save option and its value in the configuration."""
451
# FIXME: RBC 20051029 This should refresh the parser and also take a
452
# file lock on bazaar.conf.
453
conf_dir = os.path.dirname(self._get_filename())
454
ensure_config_dir_exists(conf_dir)
455
if 'DEFAULT' not in self._get_parser():
456
self._get_parser()['DEFAULT'] = {}
457
self._get_parser()['DEFAULT'][option] = value
458
f = open(self._get_filename(), 'wb')
459
self._get_parser().write(f)
463
class LocationConfig(IniBasedConfig):
464
"""A configuration object that gives the policy for a location."""
466
def __init__(self, location):
467
name_generator = locations_config_filename
468
if (not os.path.exists(name_generator()) and
469
os.path.exists(branches_config_filename())):
470
if sys.platform == 'win32':
471
trace.warning('Please rename %s to %s'
472
% (branches_config_filename(),
473
locations_config_filename()))
475
trace.warning('Please rename ~/.bazaar/branches.conf'
476
' to ~/.bazaar/locations.conf')
477
name_generator = branches_config_filename
478
super(LocationConfig, self).__init__(name_generator)
479
# local file locations are looked up by local path, rather than
480
# by file url. This is because the config file is a user
481
# file, and we would rather not expose the user to file urls.
482
if location.startswith('file://'):
483
location = urlutils.local_path_from_url(location)
484
self.location = location
486
def _get_matching_sections(self):
487
"""Return an ordered list of section names matching this location."""
488
sections = self._get_parser()
489
location_names = self.location.split('/')
490
if self.location.endswith('/'):
491
del location_names[-1]
493
for section in sections:
494
# location is a local path if possible, so we need
495
# to convert 'file://' urls to local paths if necessary.
496
# This also avoids having file:///path be a more exact
497
# match than '/path'.
498
if section.startswith('file://'):
499
section_path = urlutils.local_path_from_url(section)
501
section_path = section
502
section_names = section_path.split('/')
503
if section.endswith('/'):
504
del section_names[-1]
505
names = zip(location_names, section_names)
508
if not fnmatch(name[0], name[1]):
513
# so, for the common prefix they matched.
514
# if section is longer, no match.
515
if len(section_names) > len(location_names):
517
matches.append((len(section_names), section,
518
'/'.join(location_names[len(section_names):])))
519
matches.sort(reverse=True)
521
for (length, section, extra_path) in matches:
522
sections.append((section, extra_path))
523
# should we stop looking for parent configs here?
525
if self._get_parser()[section].as_bool('ignore_parents'):
531
def _get_option_policy(self, section, option_name):
532
"""Return the policy for the given (section, option_name) pair."""
533
# check for the old 'recurse=False' flag
535
recurse = self._get_parser()[section].as_bool('recurse')
539
return POLICY_NORECURSE
541
policy_key = option_name + ':policy'
543
policy_name = self._get_parser()[section][policy_key]
547
return _policy_value[policy_name]
549
def _set_option_policy(self, section, option_name, option_policy):
550
"""Set the policy for the given option name in the given section."""
551
# The old recurse=False option affects all options in the
552
# section. To handle multiple policies in the section, we
553
# need to convert it to a policy_norecurse key.
555
recurse = self._get_parser()[section].as_bool('recurse')
559
symbol_versioning.warn(
560
'The recurse option is deprecated as of 0.14. '
561
'The section "%s" has been converted to use policies.'
564
del self._get_parser()[section]['recurse']
566
for key in self._get_parser()[section].keys():
567
if not key.endswith(':policy'):
568
self._get_parser()[section][key +
569
':policy'] = 'norecurse'
571
policy_key = option_name + ':policy'
572
policy_name = _policy_name[option_policy]
573
if policy_name is not None:
574
self._get_parser()[section][policy_key] = policy_name
576
if policy_key in self._get_parser()[section]:
577
del self._get_parser()[section][policy_key]
579
def set_user_option(self, option, value, store=STORE_LOCATION):
580
"""Save option and its value in the configuration."""
581
assert store in [STORE_LOCATION,
582
STORE_LOCATION_NORECURSE,
583
STORE_LOCATION_APPENDPATH], 'bad storage policy'
584
# FIXME: RBC 20051029 This should refresh the parser and also take a
585
# file lock on locations.conf.
586
conf_dir = os.path.dirname(self._get_filename())
587
ensure_config_dir_exists(conf_dir)
588
location = self.location
589
if location.endswith('/'):
590
location = location[:-1]
591
if (not location in self._get_parser() and
592
not location + '/' in self._get_parser()):
593
self._get_parser()[location]={}
594
elif location + '/' in self._get_parser():
595
location = location + '/'
596
self._get_parser()[location][option]=value
597
# the allowed values of store match the config policies
598
self._set_option_policy(location, option, store)
599
self._get_parser().write(file(self._get_filename(), 'wb'))
602
class BranchConfig(Config):
603
"""A configuration object giving the policy for a branch."""
605
def _get_branch_data_config(self):
606
if self._branch_data_config is None:
607
self._branch_data_config = TreeConfig(self.branch)
608
return self._branch_data_config
610
def _get_location_config(self):
611
if self._location_config is None:
612
self._location_config = LocationConfig(self.branch.base)
613
return self._location_config
615
def _get_global_config(self):
616
if self._global_config is None:
617
self._global_config = GlobalConfig()
618
return self._global_config
620
def _get_best_value(self, option_name):
621
"""This returns a user option from local, tree or global config.
623
They are tried in that order. Use get_safe_value if trusted values
626
for source in self.option_sources:
627
value = getattr(source(), option_name)()
628
if value is not None:
632
def _get_safe_value(self, option_name):
633
"""This variant of get_best_value never returns untrusted values.
635
It does not return values from the branch data, because the branch may
636
not be controlled by the user.
638
We may wish to allow locations.conf to control whether branches are
639
trusted in the future.
641
for source in (self._get_location_config, self._get_global_config):
642
value = getattr(source(), option_name)()
643
if value is not None:
647
def _get_user_id(self):
648
"""Return the full user id for the branch.
650
e.g. "John Hacker <jhacker@foo.org>"
651
This is looked up in the email controlfile for the branch.
654
return (self.branch.control_files.get_utf8("email")
656
.decode(bzrlib.user_encoding)
658
except errors.NoSuchFile, e:
661
return self._get_best_value('_get_user_id')
663
def _get_signature_checking(self):
664
"""See Config._get_signature_checking."""
665
return self._get_best_value('_get_signature_checking')
667
def _get_signing_policy(self):
668
"""See Config._get_signing_policy."""
669
return self._get_best_value('_get_signing_policy')
671
def _get_user_option(self, option_name):
672
"""See Config._get_user_option."""
673
for source in self.option_sources:
674
value = source()._get_user_option(option_name)
675
if value is not None:
679
def set_user_option(self, name, value, store=STORE_BRANCH,
681
if store == STORE_BRANCH:
682
self._get_branch_data_config().set_option(value, name)
683
elif store == STORE_GLOBAL:
684
self._get_global_config().set_user_option(name, value)
686
self._get_location_config().set_user_option(name, value, store)
689
if store in (STORE_GLOBAL, STORE_BRANCH):
690
mask_value = self._get_location_config().get_user_option(name)
691
if mask_value is not None:
692
trace.warning('Value "%s" is masked by "%s" from'
693
' locations.conf', value, mask_value)
695
if store == STORE_GLOBAL:
696
branch_config = self._get_branch_data_config()
697
mask_value = branch_config.get_user_option(name)
698
if mask_value is not None:
699
trace.warning('Value "%s" is masked by "%s" from'
700
' branch.conf', value, mask_value)
703
def _gpg_signing_command(self):
704
"""See Config.gpg_signing_command."""
705
return self._get_safe_value('_gpg_signing_command')
707
def __init__(self, branch):
708
super(BranchConfig, self).__init__()
709
self._location_config = None
710
self._branch_data_config = None
711
self._global_config = None
713
self.option_sources = (self._get_location_config,
714
self._get_branch_data_config,
715
self._get_global_config)
717
def _post_commit(self):
718
"""See Config.post_commit."""
719
return self._get_safe_value('_post_commit')
721
def _get_nickname(self):
722
value = self._get_explicit_nickname()
723
if value is not None:
725
return urlutils.unescape(self.branch.base.split('/')[-2])
727
def has_explicit_nickname(self):
728
"""Return true if a nickname has been explicitly assigned."""
729
return self._get_explicit_nickname() is not None
731
def _get_explicit_nickname(self):
732
return self._get_best_value('_get_nickname')
734
def _log_format(self):
735
"""See Config.log_format."""
736
return self._get_best_value('_log_format')
739
def ensure_config_dir_exists(path=None):
740
"""Make sure a configuration directory exists.
741
This makes sure that the directory exists.
742
On windows, since configuration directories are 2 levels deep,
743
it makes sure both the directory and the parent directory exists.
747
if not os.path.isdir(path):
748
if sys.platform == 'win32':
749
parent_dir = os.path.dirname(path)
750
if not os.path.isdir(parent_dir):
751
trace.mutter('creating config parent directory: %r', parent_dir)
753
trace.mutter('creating config directory: %r', path)
758
"""Return per-user configuration directory.
760
By default this is ~/.bazaar/
762
TODO: Global option --config-dir to override this.
764
base = os.environ.get('BZR_HOME', None)
765
if sys.platform == 'win32':
767
base = win32utils.get_appdata_location_unicode()
769
base = os.environ.get('HOME', None)
771
raise errors.BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
772
return osutils.pathjoin(base, 'bazaar', '2.0')
774
# cygwin, linux, and darwin all have a $HOME directory
776
base = os.path.expanduser("~")
777
return osutils.pathjoin(base, ".bazaar")
780
def config_filename():
781
"""Return per-user configuration ini file filename."""
782
return osutils.pathjoin(config_dir(), 'bazaar.conf')
785
def branches_config_filename():
786
"""Return per-user configuration ini file filename."""
787
return osutils.pathjoin(config_dir(), 'branches.conf')
790
def locations_config_filename():
791
"""Return per-user configuration ini file filename."""
792
return osutils.pathjoin(config_dir(), 'locations.conf')
795
def authentication_config_filename():
796
"""Return per-user authentication ini file filename."""
797
return osutils.pathjoin(config_dir(), 'authentication.conf')
800
def user_ignore_config_filename():
801
"""Return the user default ignore filename"""
802
return osutils.pathjoin(config_dir(), 'ignore')
806
"""Calculate automatic user identification.
808
Returns (realname, email).
810
Only used when none is set in the environment or the id file.
812
This previously used the FQDN as the default domain, but that can
813
be very slow on machines where DNS is broken. So now we simply
818
if sys.platform == 'win32':
819
name = win32utils.get_user_name_unicode()
821
raise errors.BzrError("Cannot autodetect user name.\n"
822
"Please, set your name with command like:\n"
823
'bzr whoami "Your Name <name@domain.com>"')
824
host = win32utils.get_host_name_unicode()
826
host = socket.gethostname()
827
return name, (name + '@' + host)
832
w = pwd.getpwuid(uid)
834
# we try utf-8 first, because on many variants (like Linux),
835
# /etc/passwd "should" be in utf-8, and because it's unlikely to give
836
# false positives. (many users will have their user encoding set to
837
# latin-1, which cannot raise UnicodeError.)
839
gecos = w.pw_gecos.decode('utf-8')
843
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
844
encoding = bzrlib.user_encoding
846
raise errors.BzrCommandError('Unable to determine your name. '
847
'Use "bzr whoami" to set it.')
849
username = w.pw_name.decode(encoding)
851
raise errors.BzrCommandError('Unable to determine your name. '
852
'Use "bzr whoami" to set it.')
854
comma = gecos.find(',')
858
realname = gecos[:comma]
865
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
866
except UnicodeDecodeError:
867
raise errors.BzrError("Can't decode username as %s." % \
868
bzrlib.user_encoding)
870
return realname, (username + '@' + socket.gethostname())
873
def extract_email_address(e):
874
"""Return just the address part of an email string.
876
That is just the user@domain part, nothing else.
877
This part is required to contain only ascii characters.
878
If it can't be extracted, raises an error.
880
>>> extract_email_address('Jane Tester <jane@test.com>')
883
m = re.search(r'[\w+.-]+@[\w+.-]+', e)
885
raise errors.NoEmailInUsername(e)
889
class TreeConfig(IniBasedConfig):
890
"""Branch configuration data associated with its contents, not location"""
892
def __init__(self, branch):
895
def _get_parser(self, file=None):
897
return IniBasedConfig._get_parser(file)
898
return self._get_config()
900
def _get_config(self):
902
obj = ConfigObj(self.branch.control_files.get('branch.conf'),
904
except errors.NoSuchFile:
905
obj = ConfigObj(encoding='utf=8')
908
def get_option(self, name, section=None, default=None):
909
self.branch.lock_read()
911
obj = self._get_config()
913
if section is not None:
922
def set_option(self, value, name, section=None):
923
"""Set a per-branch configuration option"""
924
self.branch.lock_write()
926
cfg_obj = self._get_config()
931
obj = cfg_obj[section]
933
cfg_obj[section] = {}
934
obj = cfg_obj[section]
936
out_file = StringIO()
937
cfg_obj.write(out_file)
939
self.branch.control_files.put('branch.conf', out_file)
944
class AuthenticationConfig(object):
945
"""The authentication configuration file based on a ini file.
947
Implements the authentication.conf file described in
948
doc/developers/authentication-ring.txt.
951
def __init__(self, _file=None):
952
super(AuthenticationConfig, self).__init__()
953
self._config = None # The ConfigObj
955
self._get_filename = authentication_config_filename
956
self._input = self._get_filename()
958
self._get_filename = None
961
def _get_config(self):
962
if self._config is not None:
965
# FIXME: Should we validate something here ? Includes: port must be
966
# numeric, empty sections are useless, verify_certificates is
967
# boolean, at least one of user/password/password_encoding should
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
file_name = self._get_filename()
980
conf_dir = os.path.dirname(file_name)
981
ensure_config_dir_exists(conf_dir)
982
self._get_config().write(file(file_name, 'wb'))
984
def _set_option(self, section_name, option_name, value):
985
"""Set an authentication configuration option"""
986
conf = self._get_config()
987
section = conf.get(section_name)
990
section = conf[section]
991
section[option_name] = value
994
def get_credentials(self, scheme, host, port=None, user=None, path=None):
995
"""Returns the matching credentials from authentication.conf file.
997
:param scheme: protocol
999
:param host: the server address
1001
:param port: the associated port (optional)
1003
:param user: login (optional)
1005
:param path: the absolute path on the server (optional)
1007
:return: A dict containing the matching credentials or None.
1009
- name: the section name of the credentials in the
1010
authentication.conf file,
1011
- user: can't de different from the provided user if any,
1012
- password: the decoded password, could be None if the credential
1013
defines only the user
1014
- verify_certificates: https specific, True if the server
1015
certificate should be verified, False otherwise.
1018
for auth_def_name, auth_def in self._get_config().items():
1019
a_scheme, a_host, a_user, a_path = map(
1020
auth_def.get, ['scheme', 'host', 'user', 'path'])
1023
a_port = auth_def.as_int('port')
1027
a_verify_certificates = auth_def.as_bool('verify_certificates')
1029
a_verify_certificates = True
1032
if a_scheme is not None and scheme != a_scheme:
1034
if a_host is not None:
1035
if not (host == a_host
1036
or (a_host.startswith('.') and host.endswith(a_host))):
1038
if a_port is not None and port != a_port:
1040
if (a_path is not None and path is not None
1041
and not path.startswith(a_path)):
1043
if (a_user is not None and user is not None
1044
and a_user != user):
1045
# Never contradict the caller about the user to be used
1050
a_password, a_encoding = map(auth_def.get,
1051
['password', 'password_encoding'])
1052
password = self.decode_password(a_password, a_encoding)
1053
credentials = {'name': auth_def_name,
1054
'user': a_user, 'password': password,
1055
'verify_certificates': a_verify_certificates,
1057
if 'auth' in debug.debug_flags:
1058
trace.mutter("Using authentication section: %r", auth_def_name)
1063
def get_user(self, scheme, host, port=None,
1064
realm=None, path=None, prompt=None):
1065
"""Get a user from authentication file.
1067
:param scheme: protocol
1069
:param host: the server address
1071
:param port: the associated port (optional)
1073
:param realm: the realm sent by the server (optional)
1075
:param path: the absolute path on the server (optional)
1077
:return: The found user.
1079
credentials = self.get_credentials(scheme, host, port, user=None,
1081
if credentials is not None:
1082
user = credentials['user']
1087
def get_password(self, scheme, host, user, port=None,
1088
realm=None, path=None, prompt=None):
1089
"""Get a password from authentication file or prompt the user for one.
1091
:param scheme: protocol
1093
:param host: the server address
1095
:param port: the associated port (optional)
1099
:param realm: the realm sent by the server (optional)
1101
:param path: the absolute path on the server (optional)
1103
:return: The found password or the one entered by the user.
1105
credentials = self.get_credentials(scheme, host, port, user, path)
1106
if credentials is not None:
1107
password = credentials['password']
1110
if password is None:
1111
# Prompt user only if we could't find a password
1113
prompt = ('%s' % scheme.upper()
1114
+ ' %(user)s@%(host)s%(realm)s password')
1115
# Special handling for optional fields in the prompt
1116
if port is not None:
1117
prompt_host = '%s:%d' % (host, port)
1120
if realm is not None:
1121
prompt_realm = ", Realm: '%s'" % realm
1124
password = ui.ui_factory.get_password(prompt, host=prompt_host,
1129
def decode_password(self, password, encoding):