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
class ConfigObj(configobj.ConfigObj):
127
def get_bool(self, section, key):
128
return self[section].as_bool(key)
130
def get_value(self, section, name):
131
# Try [] for the old DEFAULT section.
132
if section == "DEFAULT":
137
return self[section][name]
140
class Config(object):
141
"""A configuration policy - what username, editor, gpg needs etc."""
143
def get_editor(self):
144
"""Get the users pop up editor."""
145
raise NotImplementedError
147
def get_mail_client(self):
148
"""Get a mail client to use"""
149
selected_client = self.get_user_option('mail_client')
151
mail_client_class = {
152
None: mail_client.DefaultMail,
154
'emacsclient': mail_client.EmacsMail,
155
'evolution': mail_client.Evolution,
156
'kmail': mail_client.KMail,
157
'mutt': mail_client.Mutt,
158
'thunderbird': mail_client.Thunderbird,
160
'default': mail_client.DefaultMail,
161
'editor': mail_client.Editor,
162
'mapi': mail_client.MAPIClient,
163
'xdg-email': mail_client.XDGEmail,
166
raise errors.UnknownMailClient(selected_client)
167
return mail_client_class(self)
169
def _get_signature_checking(self):
170
"""Template method to override signature checking policy."""
172
def _get_signing_policy(self):
173
"""Template method to override signature creation policy."""
175
def _get_user_option(self, option_name):
176
"""Template method to provide a user option."""
179
def get_user_option(self, option_name):
180
"""Get a generic option - no special process, no default."""
181
return self._get_user_option(option_name)
183
def gpg_signing_command(self):
184
"""What program should be used to sign signatures?"""
185
result = self._gpg_signing_command()
190
def _gpg_signing_command(self):
191
"""See gpg_signing_command()."""
194
def log_format(self):
195
"""What log format should be used"""
196
result = self._log_format()
201
def _log_format(self):
202
"""See log_format()."""
206
super(Config, self).__init__()
208
def post_commit(self):
209
"""An ordered list of python functions to call.
211
Each function takes branch, rev_id as parameters.
213
return self._post_commit()
215
def _post_commit(self):
216
"""See Config.post_commit."""
219
def user_email(self):
220
"""Return just the email component of a username."""
221
return extract_email_address(self.username())
224
"""Return email-style username.
226
Something similar to 'Martin Pool <mbp@sourcefrog.net>'
228
$BZR_EMAIL can be set to override this (as well as the
229
deprecated $BZREMAIL), then
230
the concrete policy type is checked, and finally
232
If none is found, a reasonable default is (hopefully)
235
TODO: Check it's reasonably well-formed.
237
v = os.environ.get('BZR_EMAIL')
239
return v.decode(bzrlib.user_encoding)
241
v = self._get_user_id()
245
v = os.environ.get('EMAIL')
247
return v.decode(bzrlib.user_encoding)
249
name, email = _auto_user_id()
251
return '%s <%s>' % (name, email)
255
def signature_checking(self):
256
"""What is the current policy for signature checking?."""
257
policy = self._get_signature_checking()
258
if policy is not None:
260
return CHECK_IF_POSSIBLE
262
def signing_policy(self):
263
"""What is the current policy for signature checking?."""
264
policy = self._get_signing_policy()
265
if policy is not None:
267
return SIGN_WHEN_REQUIRED
269
def signature_needed(self):
270
"""Is a signature needed when committing ?."""
271
policy = self._get_signing_policy()
273
policy = self._get_signature_checking()
274
if policy is not None:
275
trace.warning("Please use create_signatures,"
276
" not check_signatures to set signing policy.")
277
if policy == CHECK_ALWAYS:
279
elif policy == SIGN_ALWAYS:
283
def get_alias(self, value):
284
return self._get_alias(value)
286
def _get_alias(self, value):
289
def get_nickname(self):
290
return self._get_nickname()
292
def _get_nickname(self):
295
def get_bzr_remote_path(self):
297
return os.environ['BZR_REMOTE_PATH']
299
path = self.get_user_option("bzr_remote_path")
305
class IniBasedConfig(Config):
306
"""A configuration policy that draws from ini files."""
308
def _get_parser(self, file=None):
309
if self._parser is not None:
312
input = self._get_filename()
316
self._parser = ConfigObj(input, encoding='utf-8')
317
except configobj.ConfigObjError, e:
318
raise errors.ParseConfigError(e.errors, e.config.filename)
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, '')]
333
def _get_section(self):
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."""
341
def _get_signature_checking(self):
342
"""See Config._get_signature_checking."""
343
policy = self._get_user_option('check_signatures')
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)
353
def _get_user_id(self):
354
"""Get the user id from the 'email' key in the current section."""
355
return self._get_user_option('email')
357
def _get_user_option(self, option_name):
358
"""See Config._get_user_option."""
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)
382
def _gpg_signing_command(self):
383
"""See Config.gpg_signing_command."""
384
return self._get_user_option('gpg_signing_command')
386
def _log_format(self):
387
"""See Config.log_format."""
388
return self._get_user_option('log_format')
390
def __init__(self, get_filename):
391
super(IniBasedConfig, self).__init__()
392
self._get_filename = get_filename
395
def _post_commit(self):
396
"""See Config.post_commit."""
397
return self._get_user_option('post_commit')
399
def _string_to_signature_policy(self, signature_string):
400
"""Convert a string to a signing policy."""
401
if signature_string.lower() == 'check-available':
402
return CHECK_IF_POSSIBLE
403
if signature_string.lower() == 'ignore':
405
if signature_string.lower() == 'require':
407
raise errors.BzrError("Invalid signatures policy '%s'"
410
def _string_to_signing_policy(self, signature_string):
411
"""Convert a string to a signing policy."""
412
if signature_string.lower() == 'when-required':
413
return SIGN_WHEN_REQUIRED
414
if signature_string.lower() == 'never':
416
if signature_string.lower() == 'always':
418
raise errors.BzrError("Invalid signing policy '%s'"
421
def _get_alias(self, value):
423
return self._get_parser().get_value("ALIASES",
428
def _get_nickname(self):
429
return self.get_user_option('nickname')
432
class GlobalConfig(IniBasedConfig):
433
"""The configuration that should be used for a specific location."""
435
def get_editor(self):
436
return self._get_user_option('editor')
439
super(GlobalConfig, self).__init__(config_filename)
441
def set_user_option(self, option, value):
442
"""Save option and its value in the configuration."""
443
self._set_option(option, value, 'DEFAULT')
445
def get_aliases(self):
446
"""Return the aliases section."""
447
if 'ALIASES' in self._get_parser():
448
return self._get_parser()['ALIASES']
452
def set_alias(self, alias_name, alias_command):
453
"""Save the alias in the configuration."""
454
self._set_option(alias_name, alias_command, 'ALIASES')
456
def unset_alias(self, alias_name):
457
"""Unset an existing alias."""
458
aliases = self._get_parser().get('ALIASES')
459
assert aliases and alias_name in aliases, (
460
"The alias should exist before this is called")
461
del aliases[alias_name]
462
self._writeConfigFile()
464
def _set_option(self, option, value, section):
465
# FIXME: RBC 20051029 This should refresh the parser and also take a
466
# file lock on bazaar.conf.
467
conf_dir = os.path.dirname(self._get_filename())
468
ensure_config_dir_exists(conf_dir)
469
if section not in self._get_parser():
470
self._get_parser()[section] = {}
471
self._get_parser()[section][option] = value
472
self._writeConfigFile()
474
def _writeConfigFile(self):
475
f = open(self._get_filename(), 'wb')
476
self._get_parser().write(f)
480
class LocationConfig(IniBasedConfig):
481
"""A configuration object that gives the policy for a location."""
483
def __init__(self, location):
484
name_generator = locations_config_filename
485
if (not os.path.exists(name_generator()) and
486
os.path.exists(branches_config_filename())):
487
if sys.platform == 'win32':
488
trace.warning('Please rename %s to %s'
489
% (branches_config_filename(),
490
locations_config_filename()))
492
trace.warning('Please rename ~/.bazaar/branches.conf'
493
' to ~/.bazaar/locations.conf')
494
name_generator = branches_config_filename
495
super(LocationConfig, self).__init__(name_generator)
496
# local file locations are looked up by local path, rather than
497
# by file url. This is because the config file is a user
498
# file, and we would rather not expose the user to file urls.
499
if location.startswith('file://'):
500
location = urlutils.local_path_from_url(location)
501
self.location = location
503
def _get_matching_sections(self):
504
"""Return an ordered list of section names matching this location."""
505
sections = self._get_parser()
506
location_names = self.location.split('/')
507
if self.location.endswith('/'):
508
del location_names[-1]
510
for section in sections:
511
# location is a local path if possible, so we need
512
# to convert 'file://' urls to local paths if necessary.
513
# This also avoids having file:///path be a more exact
514
# match than '/path'.
515
if section.startswith('file://'):
516
section_path = urlutils.local_path_from_url(section)
518
section_path = section
519
section_names = section_path.split('/')
520
if section.endswith('/'):
521
del section_names[-1]
522
names = zip(location_names, section_names)
525
if not fnmatch(name[0], name[1]):
530
# so, for the common prefix they matched.
531
# if section is longer, no match.
532
if len(section_names) > len(location_names):
534
matches.append((len(section_names), section,
535
'/'.join(location_names[len(section_names):])))
536
matches.sort(reverse=True)
538
for (length, section, extra_path) in matches:
539
sections.append((section, extra_path))
540
# should we stop looking for parent configs here?
542
if self._get_parser()[section].as_bool('ignore_parents'):
548
def _get_option_policy(self, section, option_name):
549
"""Return the policy for the given (section, option_name) pair."""
550
# check for the old 'recurse=False' flag
552
recurse = self._get_parser()[section].as_bool('recurse')
556
return POLICY_NORECURSE
558
policy_key = option_name + ':policy'
560
policy_name = self._get_parser()[section][policy_key]
564
return _policy_value[policy_name]
566
def _set_option_policy(self, section, option_name, option_policy):
567
"""Set the policy for the given option name in the given section."""
568
# The old recurse=False option affects all options in the
569
# section. To handle multiple policies in the section, we
570
# need to convert it to a policy_norecurse key.
572
recurse = self._get_parser()[section].as_bool('recurse')
576
symbol_versioning.warn(
577
'The recurse option is deprecated as of 0.14. '
578
'The section "%s" has been converted to use policies.'
581
del self._get_parser()[section]['recurse']
583
for key in self._get_parser()[section].keys():
584
if not key.endswith(':policy'):
585
self._get_parser()[section][key +
586
':policy'] = 'norecurse'
588
policy_key = option_name + ':policy'
589
policy_name = _policy_name[option_policy]
590
if policy_name is not None:
591
self._get_parser()[section][policy_key] = policy_name
593
if policy_key in self._get_parser()[section]:
594
del self._get_parser()[section][policy_key]
596
def set_user_option(self, option, value, store=STORE_LOCATION):
597
"""Save option and its value in the configuration."""
598
assert store in [STORE_LOCATION,
599
STORE_LOCATION_NORECURSE,
600
STORE_LOCATION_APPENDPATH], 'bad storage policy'
601
# FIXME: RBC 20051029 This should refresh the parser and also take a
602
# file lock on locations.conf.
603
conf_dir = os.path.dirname(self._get_filename())
604
ensure_config_dir_exists(conf_dir)
605
location = self.location
606
if location.endswith('/'):
607
location = location[:-1]
608
if (not location in self._get_parser() and
609
not location + '/' in self._get_parser()):
610
self._get_parser()[location]={}
611
elif location + '/' in self._get_parser():
612
location = location + '/'
613
self._get_parser()[location][option]=value
614
# the allowed values of store match the config policies
615
self._set_option_policy(location, option, store)
616
self._get_parser().write(file(self._get_filename(), 'wb'))
619
class BranchConfig(Config):
620
"""A configuration object giving the policy for a branch."""
622
def _get_branch_data_config(self):
623
if self._branch_data_config is None:
624
self._branch_data_config = TreeConfig(self.branch)
625
return self._branch_data_config
627
def _get_location_config(self):
628
if self._location_config is None:
629
self._location_config = LocationConfig(self.branch.base)
630
return self._location_config
632
def _get_global_config(self):
633
if self._global_config is None:
634
self._global_config = GlobalConfig()
635
return self._global_config
637
def _get_best_value(self, option_name):
638
"""This returns a user option from local, tree or global config.
640
They are tried in that order. Use get_safe_value if trusted values
643
for source in self.option_sources:
644
value = getattr(source(), option_name)()
645
if value is not None:
649
def _get_safe_value(self, option_name):
650
"""This variant of get_best_value never returns untrusted values.
652
It does not return values from the branch data, because the branch may
653
not be controlled by the user.
655
We may wish to allow locations.conf to control whether branches are
656
trusted in the future.
658
for source in (self._get_location_config, self._get_global_config):
659
value = getattr(source(), option_name)()
660
if value is not None:
664
def _get_user_id(self):
665
"""Return the full user id for the branch.
667
e.g. "John Hacker <jhacker@foo.org>"
668
This is looked up in the email controlfile for the branch.
671
return (self.branch.control_files.get_utf8("email")
673
.decode(bzrlib.user_encoding)
675
except errors.NoSuchFile, e:
678
return self._get_best_value('_get_user_id')
680
def _get_signature_checking(self):
681
"""See Config._get_signature_checking."""
682
return self._get_best_value('_get_signature_checking')
684
def _get_signing_policy(self):
685
"""See Config._get_signing_policy."""
686
return self._get_best_value('_get_signing_policy')
688
def _get_user_option(self, option_name):
689
"""See Config._get_user_option."""
690
for source in self.option_sources:
691
value = source()._get_user_option(option_name)
692
if value is not None:
696
def set_user_option(self, name, value, store=STORE_BRANCH,
698
if store == STORE_BRANCH:
699
self._get_branch_data_config().set_option(value, name)
700
elif store == STORE_GLOBAL:
701
self._get_global_config().set_user_option(name, value)
703
self._get_location_config().set_user_option(name, value, store)
706
if store in (STORE_GLOBAL, STORE_BRANCH):
707
mask_value = self._get_location_config().get_user_option(name)
708
if mask_value is not None:
709
trace.warning('Value "%s" is masked by "%s" from'
710
' locations.conf', value, mask_value)
712
if store == STORE_GLOBAL:
713
branch_config = self._get_branch_data_config()
714
mask_value = branch_config.get_user_option(name)
715
if mask_value is not None:
716
trace.warning('Value "%s" is masked by "%s" from'
717
' branch.conf', value, mask_value)
720
def _gpg_signing_command(self):
721
"""See Config.gpg_signing_command."""
722
return self._get_safe_value('_gpg_signing_command')
724
def __init__(self, branch):
725
super(BranchConfig, self).__init__()
726
self._location_config = None
727
self._branch_data_config = None
728
self._global_config = None
730
self.option_sources = (self._get_location_config,
731
self._get_branch_data_config,
732
self._get_global_config)
734
def _post_commit(self):
735
"""See Config.post_commit."""
736
return self._get_safe_value('_post_commit')
738
def _get_nickname(self):
739
value = self._get_explicit_nickname()
740
if value is not None:
742
return urlutils.unescape(self.branch.base.split('/')[-2])
744
def has_explicit_nickname(self):
745
"""Return true if a nickname has been explicitly assigned."""
746
return self._get_explicit_nickname() is not None
748
def _get_explicit_nickname(self):
749
return self._get_best_value('_get_nickname')
751
def _log_format(self):
752
"""See Config.log_format."""
753
return self._get_best_value('_log_format')
756
def ensure_config_dir_exists(path=None):
757
"""Make sure a configuration directory exists.
758
This makes sure that the directory exists.
759
On windows, since configuration directories are 2 levels deep,
760
it makes sure both the directory and the parent directory exists.
764
if not os.path.isdir(path):
765
if sys.platform == 'win32':
766
parent_dir = os.path.dirname(path)
767
if not os.path.isdir(parent_dir):
768
trace.mutter('creating config parent directory: %r', parent_dir)
770
trace.mutter('creating config directory: %r', path)
775
"""Return per-user configuration directory.
777
By default this is ~/.bazaar/
779
TODO: Global option --config-dir to override this.
781
base = os.environ.get('BZR_HOME', None)
782
if sys.platform == 'win32':
784
base = win32utils.get_appdata_location_unicode()
786
base = os.environ.get('HOME', None)
788
raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
790
return osutils.pathjoin(base, 'bazaar', '2.0')
792
# cygwin, linux, and darwin all have a $HOME directory
794
base = os.path.expanduser("~")
795
return osutils.pathjoin(base, ".bazaar")
798
def config_filename():
799
"""Return per-user configuration ini file filename."""
800
return osutils.pathjoin(config_dir(), 'bazaar.conf')
803
def branches_config_filename():
804
"""Return per-user configuration ini file filename."""
805
return osutils.pathjoin(config_dir(), 'branches.conf')
808
def locations_config_filename():
809
"""Return per-user configuration ini file filename."""
810
return osutils.pathjoin(config_dir(), 'locations.conf')
813
def authentication_config_filename():
814
"""Return per-user authentication ini file filename."""
815
return osutils.pathjoin(config_dir(), 'authentication.conf')
818
def user_ignore_config_filename():
819
"""Return the user default ignore filename"""
820
return osutils.pathjoin(config_dir(), 'ignore')
824
"""Calculate automatic user identification.
826
Returns (realname, email).
828
Only used when none is set in the environment or the id file.
830
This previously used the FQDN as the default domain, but that can
831
be very slow on machines where DNS is broken. So now we simply
836
if sys.platform == 'win32':
837
name = win32utils.get_user_name_unicode()
839
raise errors.BzrError("Cannot autodetect user name.\n"
840
"Please, set your name with command like:\n"
841
'bzr whoami "Your Name <name@domain.com>"')
842
host = win32utils.get_host_name_unicode()
844
host = socket.gethostname()
845
return name, (name + '@' + host)
850
w = pwd.getpwuid(uid)
852
# we try utf-8 first, because on many variants (like Linux),
853
# /etc/passwd "should" be in utf-8, and because it's unlikely to give
854
# false positives. (many users will have their user encoding set to
855
# latin-1, which cannot raise UnicodeError.)
857
gecos = w.pw_gecos.decode('utf-8')
861
gecos = w.pw_gecos.decode(bzrlib.user_encoding)
862
encoding = bzrlib.user_encoding
864
raise errors.BzrCommandError('Unable to determine your name. '
865
'Use "bzr whoami" to set it.')
867
username = w.pw_name.decode(encoding)
869
raise errors.BzrCommandError('Unable to determine your name. '
870
'Use "bzr whoami" to set it.')
872
comma = gecos.find(',')
876
realname = gecos[:comma]
883
realname = username = getpass.getuser().decode(bzrlib.user_encoding)
884
except UnicodeDecodeError:
885
raise errors.BzrError("Can't decode username as %s." % \
886
bzrlib.user_encoding)
888
return realname, (username + '@' + socket.gethostname())
891
def parse_username(username):
892
"""Parse e-mail username and return a (name, address) tuple."""
893
match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
895
return (username, '')
897
return (match.group(1), match.group(2))
900
def extract_email_address(e):
901
"""Return just the address part of an email string.
903
That is just the user@domain part, nothing else.
904
This part is required to contain only ascii characters.
905
If it can't be extracted, raises an error.
907
>>> extract_email_address('Jane Tester <jane@test.com>')
910
name, email = parse_username(e)
912
raise errors.NoEmailInUsername(e)
916
class TreeConfig(IniBasedConfig):
917
"""Branch configuration data associated with its contents, not location"""
919
def __init__(self, branch):
920
transport = branch.control_files._transport
921
self._config = TransportConfig(transport, 'branch.conf')
924
def _get_parser(self, file=None):
926
return IniBasedConfig._get_parser(file)
927
return self._config._get_configobj()
929
def get_option(self, name, section=None, default=None):
930
self.branch.lock_read()
932
return self._config.get_option(name, section, default)
937
def set_option(self, value, name, section=None):
938
"""Set a per-branch configuration option"""
939
self.branch.lock_write()
941
self._config.set_option(value, name, section)
946
class AuthenticationConfig(object):
947
"""The authentication configuration file based on a ini file.
949
Implements the authentication.conf file described in
950
doc/developers/authentication-ring.txt.
953
def __init__(self, _file=None):
954
self._config = None # The ConfigObj
956
self._filename = authentication_config_filename()
957
self._input = self._filename = authentication_config_filename()
959
# Tests can provide a string as _file
960
self._filename = None
963
def _get_config(self):
964
if self._config is not None:
967
# FIXME: Should we validate something here ? Includes: empty
968
# sections are useless, at least one of
969
# user/password/password_encoding should be defined, etc.
971
# Note: the encoding below declares that the file itself is utf-8
972
# encoded, but the values in the ConfigObj are always Unicode.
973
self._config = ConfigObj(self._input, encoding='utf-8')
974
except configobj.ConfigObjError, e:
975
raise errors.ParseConfigError(e.errors, e.config.filename)
979
"""Save the config file, only tests should use it for now."""
980
conf_dir = os.path.dirname(self._filename)
981
ensure_config_dir_exists(conf_dir)
982
self._get_config().write(file(self._filename, '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
raise ValueError("'port' not numeric in %s" % auth_def_name)
1029
a_verify_certificates = auth_def.as_bool('verify_certificates')
1031
a_verify_certificates = True
1034
"'verify_certificates' not boolean in %s" % auth_def_name)
1037
if a_scheme is not None and scheme != a_scheme:
1039
if a_host is not None:
1040
if not (host == a_host
1041
or (a_host.startswith('.') and host.endswith(a_host))):
1043
if a_port is not None and port != a_port:
1045
if (a_path is not None and path is not None
1046
and not path.startswith(a_path)):
1048
if (a_user is not None and user is not None
1049
and a_user != user):
1050
# Never contradict the caller about the user to be used
1055
credentials = dict(name=auth_def_name,
1056
user=a_user, password=auth_def['password'],
1057
verify_certificates=a_verify_certificates)
1058
self.decode_password(credentials,
1059
auth_def.get('password_encoding', None))
1060
if 'auth' in debug.debug_flags:
1061
trace.mutter("Using authentication section: %r", auth_def_name)
1066
def get_user(self, scheme, host, port=None,
1067
realm=None, path=None, prompt=None):
1068
"""Get a user from authentication file.
1070
:param scheme: protocol
1072
:param host: the server address
1074
:param port: the associated port (optional)
1076
:param realm: the realm sent by the server (optional)
1078
:param path: the absolute path on the server (optional)
1080
:return: The found user.
1082
credentials = self.get_credentials(scheme, host, port, user=None,
1084
if credentials is not None:
1085
user = credentials['user']
1090
def get_password(self, scheme, host, user, port=None,
1091
realm=None, path=None, prompt=None):
1092
"""Get a password from authentication file or prompt the user for one.
1094
:param scheme: protocol
1096
:param host: the server address
1098
:param port: the associated port (optional)
1102
:param realm: the realm sent by the server (optional)
1104
:param path: the absolute path on the server (optional)
1106
:return: The found password or the one entered by the user.
1108
credentials = self.get_credentials(scheme, host, port, user, path)
1109
if credentials is not None:
1110
password = credentials['password']
1113
# Prompt user only if we could't find a password
1114
if password is None:
1116
# Create a default prompt suitable for most of the cases
1117
prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1118
# Special handling for optional fields in the prompt
1119
if port is not None:
1120
prompt_host = '%s:%d' % (host, port)
1123
password = ui.ui_factory.get_password(prompt,
1124
host=prompt_host, user=user)
1127
def decode_password(self, credentials, encoding):
1131
class TransportConfig(object):
1132
"""A Config that reads/writes a config file on a Transport.
1134
It is a low-level object that considers config data to be name/value pairs
1135
that may be associated with a section. Assigning meaning to the these
1136
values is done at higher levels like TreeConfig.
1139
def __init__(self, transport, filename):
1140
self._transport = transport
1141
self._filename = filename
1143
def get_option(self, name, section=None, default=None):
1144
"""Return the value associated with a named option.
1146
:param name: The name of the value
1147
:param section: The section the option is in (if any)
1148
:param default: The value to return if the value is not set
1149
:return: The value or default value
1151
configobj = self._get_configobj()
1153
section_obj = configobj
1156
section_obj = configobj[section]
1159
return section_obj.get(name, default)
1161
def set_option(self, value, name, section=None):
1162
"""Set the value associated with a named option.
1164
:param value: The value to set
1165
:param name: The name of the value to set
1166
:param section: The section the option is in (if any)
1168
configobj = self._get_configobj()
1170
configobj[name] = value
1172
configobj.setdefault(section, {})[name] = value
1173
self._set_configobj(configobj)
1175
def _get_configobj(self):
1177
return ConfigObj(self._transport.get(self._filename),
1179
except errors.NoSuchFile:
1180
return ConfigObj(encoding='utf-8')
1182
def _set_configobj(self, configobj):
1183
out_file = StringIO()
1184
configobj.write(out_file)
1186
self._transport.put_file(self._filename, out_file)