~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Naoki INADA
  • Date: 2009-10-29 10:01:19 UTC
  • mto: (4634.97.3 2.0)
  • mto: This revision was merged to the branch mainline in revision 4798.
  • Revision ID: inada-n@klab.jp-20091029100119-uckv9t7ej2qrghw3
import doc-ja rev90

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2007, 2008 Canonical Ltd
2
2
#   Authors: Robert Collins <robert.collins@canonical.com>
3
3
#            and others
4
4
#
14
14
#
15
15
# You should have received a copy of the GNU General Public License
16
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
 
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
18
 
19
19
"""Configuration that affects the behaviour of Bazaar.
20
20
 
37
37
[/home/robertc/source]
38
38
recurse=False|True(default)
39
39
email= as above
40
 
check_signatures= as above 
 
40
check_signatures= as above
41
41
create_signatures= as above.
42
42
 
43
43
explanation of options
45
45
editor - this option sets the pop up editor to use during commits.
46
46
email - this option sets the user id bzr will use when committing.
47
47
check_signatures - this option controls whether bzr will require good gpg
48
 
                   signatures, ignore them, or check them if they are 
 
48
                   signatures, ignore them, or check them if they are
49
49
                   present.
50
 
create_signatures - this option controls whether bzr will always create 
 
50
create_signatures - this option controls whether bzr will always create
51
51
                    gpg signatures, never create them, or create them if the
52
52
                    branch is configured to require them.
53
53
log_format - this option sets the default log format.  Possible values are
78
78
    errors,
79
79
    mail_client,
80
80
    osutils,
 
81
    registry,
81
82
    symbol_versioning,
82
83
    trace,
83
84
    ui,
84
85
    urlutils,
85
86
    win32utils,
86
87
    )
87
 
import bzrlib.util.configobj.configobj as configobj
 
88
from bzrlib.util.configobj import configobj
88
89
""")
89
90
 
90
91
 
121
122
STORE_BRANCH = 3
122
123
STORE_GLOBAL = 4
123
124
 
124
 
 
125
 
class ConfigObj(configobj.ConfigObj):
126
 
 
127
 
    def get_bool(self, section, key):
128
 
        return self[section].as_bool(key)
129
 
 
130
 
    def get_value(self, section, name):
131
 
        # Try [] for the old DEFAULT section.
132
 
        if section == "DEFAULT":
133
 
            try:
134
 
                return self[name]
135
 
            except KeyError:
136
 
                pass
137
 
        return self[section][name]
 
125
_ConfigObj = None
 
126
def ConfigObj(*args, **kwargs):
 
127
    global _ConfigObj
 
128
    if _ConfigObj is None:
 
129
        class ConfigObj(configobj.ConfigObj):
 
130
 
 
131
            def get_bool(self, section, key):
 
132
                return self[section].as_bool(key)
 
133
 
 
134
            def get_value(self, section, name):
 
135
                # Try [] for the old DEFAULT section.
 
136
                if section == "DEFAULT":
 
137
                    try:
 
138
                        return self[name]
 
139
                    except KeyError:
 
140
                        pass
 
141
                return self[section][name]
 
142
        _ConfigObj = ConfigObj
 
143
    return _ConfigObj(*args, **kwargs)
138
144
 
139
145
 
140
146
class Config(object):
141
147
    """A configuration policy - what username, editor, gpg needs etc."""
142
148
 
 
149
    def __init__(self):
 
150
        super(Config, self).__init__()
 
151
 
143
152
    def get_editor(self):
144
153
        """Get the users pop up editor."""
145
154
        raise NotImplementedError
147
156
    def get_mail_client(self):
148
157
        """Get a mail client to use"""
149
158
        selected_client = self.get_user_option('mail_client')
 
159
        _registry = mail_client.mail_client_registry
150
160
        try:
151
 
            mail_client_class = {
152
 
                None: mail_client.DefaultMail,
153
 
                # Specific clients
154
 
                'evolution': mail_client.Evolution,
155
 
                'kmail': mail_client.KMail,
156
 
                'mutt': mail_client.Mutt,
157
 
                'thunderbird': mail_client.Thunderbird,
158
 
                # Generic options
159
 
                'default': mail_client.DefaultMail,
160
 
                'editor': mail_client.Editor,
161
 
                'mapi': mail_client.MAPIClient,
162
 
                'xdg-email': mail_client.XDGEmail,
163
 
            }[selected_client]
 
161
            mail_client_class = _registry.get(selected_client)
164
162
        except KeyError:
165
163
            raise errors.UnknownMailClient(selected_client)
166
164
        return mail_client_class(self)
179
177
        """Get a generic option - no special process, no default."""
180
178
        return self._get_user_option(option_name)
181
179
 
 
180
    def get_user_option_as_bool(self, option_name):
 
181
        """Get a generic option as a boolean - no special process, no default.
 
182
 
 
183
        :return None if the option doesn't exist or its value can't be
 
184
            interpreted as a boolean. Returns True or False ortherwise.
 
185
        """
 
186
        s = self._get_user_option(option_name)
 
187
        return ui.bool_from_string(s)
 
188
 
182
189
    def gpg_signing_command(self):
183
190
        """What program should be used to sign signatures?"""
184
191
        result = self._gpg_signing_command()
201
208
        """See log_format()."""
202
209
        return None
203
210
 
204
 
    def __init__(self):
205
 
        super(Config, self).__init__()
206
 
 
207
211
    def post_commit(self):
208
212
        """An ordered list of python functions to call.
209
213
 
221
225
 
222
226
    def username(self):
223
227
        """Return email-style username.
224
 
    
 
228
 
225
229
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
226
 
        
 
230
 
227
231
        $BZR_EMAIL can be set to override this (as well as the
228
232
        deprecated $BZREMAIL), then
229
233
        the concrete policy type is checked, and finally
230
234
        $EMAIL is examined.
231
235
        If none is found, a reasonable default is (hopefully)
232
236
        created.
233
 
    
 
237
 
234
238
        TODO: Check it's reasonably well-formed.
235
239
        """
236
240
        v = os.environ.get('BZR_EMAIL')
237
241
        if v:
238
 
            return v.decode(bzrlib.user_encoding)
 
242
            return v.decode(osutils.get_user_encoding())
239
243
 
240
244
        v = self._get_user_id()
241
245
        if v:
243
247
 
244
248
        v = os.environ.get('EMAIL')
245
249
        if v:
246
 
            return v.decode(bzrlib.user_encoding)
 
250
            return v.decode(osutils.get_user_encoding())
247
251
 
248
252
        name, email = _auto_user_id()
249
253
        if name:
304
308
class IniBasedConfig(Config):
305
309
    """A configuration policy that draws from ini files."""
306
310
 
 
311
    def __init__(self, get_filename):
 
312
        super(IniBasedConfig, self).__init__()
 
313
        self._get_filename = get_filename
 
314
        self._parser = None
 
315
 
307
316
    def _get_parser(self, file=None):
308
317
        if self._parser is not None:
309
318
            return self._parser
386
395
        """See Config.log_format."""
387
396
        return self._get_user_option('log_format')
388
397
 
389
 
    def __init__(self, get_filename):
390
 
        super(IniBasedConfig, self).__init__()
391
 
        self._get_filename = get_filename
392
 
        self._parser = None
393
 
        
394
398
    def _post_commit(self):
395
399
        """See Config.post_commit."""
396
400
        return self._get_user_option('post_commit')
419
423
 
420
424
    def _get_alias(self, value):
421
425
        try:
422
 
            return self._get_parser().get_value("ALIASES", 
 
426
            return self._get_parser().get_value("ALIASES",
423
427
                                                value)
424
428
        except KeyError:
425
429
            pass
439
443
 
440
444
    def set_user_option(self, option, value):
441
445
        """Save option and its value in the configuration."""
 
446
        self._set_option(option, value, 'DEFAULT')
 
447
 
 
448
    def get_aliases(self):
 
449
        """Return the aliases section."""
 
450
        if 'ALIASES' in self._get_parser():
 
451
            return self._get_parser()['ALIASES']
 
452
        else:
 
453
            return {}
 
454
 
 
455
    def set_alias(self, alias_name, alias_command):
 
456
        """Save the alias in the configuration."""
 
457
        self._set_option(alias_name, alias_command, 'ALIASES')
 
458
 
 
459
    def unset_alias(self, alias_name):
 
460
        """Unset an existing alias."""
 
461
        aliases = self._get_parser().get('ALIASES')
 
462
        if not aliases or alias_name not in aliases:
 
463
            raise errors.NoSuchAlias(alias_name)
 
464
        del aliases[alias_name]
 
465
        self._write_config_file()
 
466
 
 
467
    def _set_option(self, option, value, section):
442
468
        # FIXME: RBC 20051029 This should refresh the parser and also take a
443
469
        # file lock on bazaar.conf.
444
470
        conf_dir = os.path.dirname(self._get_filename())
445
471
        ensure_config_dir_exists(conf_dir)
446
 
        if 'DEFAULT' not in self._get_parser():
447
 
            self._get_parser()['DEFAULT'] = {}
448
 
        self._get_parser()['DEFAULT'][option] = value
 
472
        self._get_parser().setdefault(section, {})[option] = value
 
473
        self._write_config_file()
 
474
 
 
475
    def _write_config_file(self):
449
476
        f = open(self._get_filename(), 'wb')
450
477
        self._get_parser().write(f)
451
478
        f.close()
569
596
 
570
597
    def set_user_option(self, option, value, store=STORE_LOCATION):
571
598
        """Save option and its value in the configuration."""
572
 
        assert store in [STORE_LOCATION,
 
599
        if store not in [STORE_LOCATION,
573
600
                         STORE_LOCATION_NORECURSE,
574
 
                         STORE_LOCATION_APPENDPATH], 'bad storage policy'
 
601
                         STORE_LOCATION_APPENDPATH]:
 
602
            raise ValueError('bad storage policy %r for %r' %
 
603
                (store, option))
575
604
        # FIXME: RBC 20051029 This should refresh the parser and also take a
576
605
        # file lock on locations.conf.
577
606
        conf_dir = os.path.dirname(self._get_filename())
622
651
 
623
652
    def _get_safe_value(self, option_name):
624
653
        """This variant of get_best_value never returns untrusted values.
625
 
        
 
654
 
626
655
        It does not return values from the branch data, because the branch may
627
656
        not be controlled by the user.
628
657
 
637
666
 
638
667
    def _get_user_id(self):
639
668
        """Return the full user id for the branch.
640
 
    
641
 
        e.g. "John Hacker <jhacker@foo.org>"
 
669
 
 
670
        e.g. "John Hacker <jhacker@example.com>"
642
671
        This is looked up in the email controlfile for the branch.
643
672
        """
644
673
        try:
645
 
            return (self.branch.control_files.get_utf8("email") 
646
 
                    .read()
647
 
                    .decode(bzrlib.user_encoding)
 
674
            return (self.branch._transport.get_bytes("email")
 
675
                    .decode(osutils.get_user_encoding())
648
676
                    .rstrip("\r\n"))
649
677
        except errors.NoSuchFile, e:
650
678
            pass
651
 
        
 
679
 
652
680
        return self._get_best_value('_get_user_id')
653
681
 
654
682
    def _get_signature_checking(self):
690
718
                        trace.warning('Value "%s" is masked by "%s" from'
691
719
                                      ' branch.conf', value, mask_value)
692
720
 
693
 
 
694
721
    def _gpg_signing_command(self):
695
722
        """See Config.gpg_signing_command."""
696
723
        return self._get_safe_value('_gpg_signing_command')
697
 
        
 
724
 
698
725
    def __init__(self, branch):
699
726
        super(BranchConfig, self).__init__()
700
727
        self._location_config = None
701
728
        self._branch_data_config = None
702
729
        self._global_config = None
703
730
        self.branch = branch
704
 
        self.option_sources = (self._get_location_config, 
 
731
        self.option_sources = (self._get_location_config,
705
732
                               self._get_branch_data_config,
706
733
                               self._get_global_config)
707
734
 
749
776
    """Return per-user configuration directory.
750
777
 
751
778
    By default this is ~/.bazaar/
752
 
    
 
779
 
753
780
    TODO: Global option --config-dir to override this.
754
781
    """
755
782
    base = os.environ.get('BZR_HOME', None)
759
786
        if base is None:
760
787
            base = os.environ.get('HOME', None)
761
788
        if base is None:
762
 
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA, or HOME set')
 
789
            raise errors.BzrError('You must have one of BZR_HOME, APPDATA,'
 
790
                                  ' or HOME set')
763
791
        return osutils.pathjoin(base, 'bazaar', '2.0')
764
792
    else:
765
793
        # cygwin, linux, and darwin all have a $HOME directory
793
821
    return osutils.pathjoin(config_dir(), 'ignore')
794
822
 
795
823
 
 
824
def crash_dir():
 
825
    """Return the directory name to store crash files.
 
826
 
 
827
    This doesn't implicitly create it.
 
828
 
 
829
    On Windows it's in the config directory; elsewhere in the XDG cache directory.
 
830
    """
 
831
    if sys.platform == 'win32':
 
832
        return osutils.pathjoin(config_dir(), 'Crash')
 
833
    else:
 
834
        return osutils.pathjoin(xdg_cache_dir(), 'crash')
 
835
 
 
836
 
 
837
def xdg_cache_dir():
 
838
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
 
839
    # Possibly this should be different on Windows?
 
840
    e = os.environ.get('XDG_CACHE_DIR', None)
 
841
    if e:
 
842
        return e
 
843
    else:
 
844
        return os.path.expanduser('~/.cache')
 
845
 
 
846
 
796
847
def _auto_user_id():
797
848
    """Calculate automatic user identification.
798
849
 
820
871
    try:
821
872
        import pwd
822
873
        uid = os.getuid()
823
 
        w = pwd.getpwuid(uid)
 
874
        try:
 
875
            w = pwd.getpwuid(uid)
 
876
        except KeyError:
 
877
            raise errors.BzrCommandError('Unable to determine your name.  '
 
878
                'Please use "bzr whoami" to set it.')
824
879
 
825
880
        # we try utf-8 first, because on many variants (like Linux),
826
881
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
831
886
            encoding = 'utf-8'
832
887
        except UnicodeError:
833
888
            try:
834
 
                gecos = w.pw_gecos.decode(bzrlib.user_encoding)
835
 
                encoding = bzrlib.user_encoding
 
889
                encoding = osutils.get_user_encoding()
 
890
                gecos = w.pw_gecos.decode(encoding)
836
891
            except UnicodeError:
837
892
                raise errors.BzrCommandError('Unable to determine your name.  '
838
893
                   'Use "bzr whoami" to set it.')
853
908
    except ImportError:
854
909
        import getpass
855
910
        try:
856
 
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
911
            user_encoding = osutils.get_user_encoding()
 
912
            realname = username = getpass.getuser().decode(user_encoding)
857
913
        except UnicodeDecodeError:
858
914
            raise errors.BzrError("Can't decode username as %s." % \
859
 
                    bzrlib.user_encoding)
 
915
                    user_encoding)
860
916
 
861
917
    return realname, (username + '@' + socket.gethostname())
862
918
 
863
919
 
 
920
def parse_username(username):
 
921
    """Parse e-mail username and return a (name, address) tuple."""
 
922
    match = re.match(r'(.*?)\s*<?([\w+.-]+@[\w+.-]+)>?', username)
 
923
    if match is None:
 
924
        return (username, '')
 
925
    else:
 
926
        return (match.group(1), match.group(2))
 
927
 
 
928
 
864
929
def extract_email_address(e):
865
930
    """Return just the address part of an email string.
866
 
    
867
 
    That is just the user@domain part, nothing else. 
 
931
 
 
932
    That is just the user@domain part, nothing else.
868
933
    This part is required to contain only ascii characters.
869
934
    If it can't be extracted, raises an error.
870
 
    
 
935
 
871
936
    >>> extract_email_address('Jane Tester <jane@test.com>')
872
937
    "jane@test.com"
873
938
    """
874
 
    m = re.search(r'[\w+.-]+@[\w+.-]+', e)
875
 
    if not m:
 
939
    name, email = parse_username(e)
 
940
    if not email:
876
941
        raise errors.NoEmailInUsername(e)
877
 
    return m.group(0)
 
942
    return email
878
943
 
879
944
 
880
945
class TreeConfig(IniBasedConfig):
881
946
    """Branch configuration data associated with its contents, not location"""
882
947
 
 
948
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
 
949
 
883
950
    def __init__(self, branch):
 
951
        self._config = branch._get_config()
884
952
        self.branch = branch
885
953
 
886
954
    def _get_parser(self, file=None):
887
955
        if file is not None:
888
956
            return IniBasedConfig._get_parser(file)
889
 
        return self._get_config()
890
 
 
891
 
    def _get_config(self):
892
 
        try:
893
 
            obj = ConfigObj(self.branch.control_files.get('branch.conf'),
894
 
                            encoding='utf-8')
895
 
        except errors.NoSuchFile:
896
 
            obj = ConfigObj(encoding='utf=8')
897
 
        return obj
 
957
        return self._config._get_configobj()
898
958
 
899
959
    def get_option(self, name, section=None, default=None):
900
960
        self.branch.lock_read()
901
961
        try:
902
 
            obj = self._get_config()
903
 
            try:
904
 
                if section is not None:
905
 
                    obj = obj[section]
906
 
                result = obj[name]
907
 
            except KeyError:
908
 
                result = default
 
962
            return self._config.get_option(name, section, default)
909
963
        finally:
910
964
            self.branch.unlock()
911
 
        return result
912
965
 
913
966
    def set_option(self, value, name, section=None):
914
967
        """Set a per-branch configuration option"""
915
968
        self.branch.lock_write()
916
969
        try:
917
 
            cfg_obj = self._get_config()
918
 
            if section is None:
919
 
                obj = cfg_obj
920
 
            else:
921
 
                try:
922
 
                    obj = cfg_obj[section]
923
 
                except KeyError:
924
 
                    cfg_obj[section] = {}
925
 
                    obj = cfg_obj[section]
926
 
            obj[name] = value
927
 
            out_file = StringIO()
928
 
            cfg_obj.write(out_file)
929
 
            out_file.seek(0)
930
 
            self.branch.control_files.put('branch.conf', out_file)
 
970
            self._config.set_option(value, name, section)
931
971
        finally:
932
972
            self.branch.unlock()
933
973
 
980
1020
        section[option_name] = value
981
1021
        self._save()
982
1022
 
983
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None):
 
1023
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
 
1024
                        realm=None):
984
1025
        """Returns the matching credentials from authentication.conf file.
985
1026
 
986
1027
        :param scheme: protocol
992
1033
        :param user: login (optional)
993
1034
 
994
1035
        :param path: the absolute path on the server (optional)
 
1036
        
 
1037
        :param realm: the http authentication realm (optional)
995
1038
 
996
1039
        :return: A dict containing the matching credentials or None.
997
1040
           This includes:
998
1041
           - name: the section name of the credentials in the
999
1042
             authentication.conf file,
1000
 
           - user: can't de different from the provided user if any,
 
1043
           - user: can't be different from the provided user if any,
 
1044
           - scheme: the server protocol,
 
1045
           - host: the server address,
 
1046
           - port: the server port (can be None),
 
1047
           - path: the absolute server path (can be None),
 
1048
           - realm: the http specific authentication realm (can be None),
1001
1049
           - password: the decoded password, could be None if the credential
1002
1050
             defines only the user
1003
1051
           - verify_certificates: https specific, True if the server
1005
1053
        """
1006
1054
        credentials = None
1007
1055
        for auth_def_name, auth_def in self._get_config().items():
 
1056
            if type(auth_def) is not configobj.Section:
 
1057
                raise ValueError("%s defined outside a section" % auth_def_name)
 
1058
 
1008
1059
            a_scheme, a_host, a_user, a_path = map(
1009
1060
                auth_def.get, ['scheme', 'host', 'user', 'path'])
1010
1061
 
1041
1092
            if a_user is None:
1042
1093
                # Can't find a user
1043
1094
                continue
 
1095
            # Prepare a credentials dictionary with additional keys
 
1096
            # for the credential providers
1044
1097
            credentials = dict(name=auth_def_name,
1045
 
                               user=a_user, password=auth_def['password'],
 
1098
                               user=a_user,
 
1099
                               scheme=a_scheme,
 
1100
                               host=host,
 
1101
                               port=port,
 
1102
                               path=path,
 
1103
                               realm=realm,
 
1104
                               password=auth_def.get('password', None),
1046
1105
                               verify_certificates=a_verify_certificates)
 
1106
            # Decode the password in the credentials (or get one)
1047
1107
            self.decode_password(credentials,
1048
1108
                                 auth_def.get('password_encoding', None))
1049
1109
            if 'auth' in debug.debug_flags:
1050
1110
                trace.mutter("Using authentication section: %r", auth_def_name)
1051
1111
            break
1052
1112
 
 
1113
        if credentials is None:
 
1114
            # No credentials were found in authentication.conf, try the fallback
 
1115
            # credentials stores.
 
1116
            credentials = credential_store_registry.get_fallback_credentials(
 
1117
                scheme, host, port, user, path, realm)
 
1118
 
1053
1119
        return credentials
1054
1120
 
1055
 
    def get_user(self, scheme, host, port=None,
1056
 
                 realm=None, path=None, prompt=None):
 
1121
    def set_credentials(self, name, host, user, scheme=None, password=None,
 
1122
                        port=None, path=None, verify_certificates=None,
 
1123
                        realm=None):
 
1124
        """Set authentication credentials for a host.
 
1125
 
 
1126
        Any existing credentials with matching scheme, host, port and path
 
1127
        will be deleted, regardless of name.
 
1128
 
 
1129
        :param name: An arbitrary name to describe this set of credentials.
 
1130
        :param host: Name of the host that accepts these credentials.
 
1131
        :param user: The username portion of these credentials.
 
1132
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
 
1133
            to.
 
1134
        :param password: Password portion of these credentials.
 
1135
        :param port: The IP port on the host that these credentials apply to.
 
1136
        :param path: A filesystem path on the host that these credentials
 
1137
            apply to.
 
1138
        :param verify_certificates: On https, verify server certificates if
 
1139
            True.
 
1140
        :param realm: The http authentication realm (optional).
 
1141
        """
 
1142
        values = {'host': host, 'user': user}
 
1143
        if password is not None:
 
1144
            values['password'] = password
 
1145
        if scheme is not None:
 
1146
            values['scheme'] = scheme
 
1147
        if port is not None:
 
1148
            values['port'] = '%d' % port
 
1149
        if path is not None:
 
1150
            values['path'] = path
 
1151
        if verify_certificates is not None:
 
1152
            values['verify_certificates'] = str(verify_certificates)
 
1153
        if realm is not None:
 
1154
            values['realm'] = realm
 
1155
        config = self._get_config()
 
1156
        for_deletion = []
 
1157
        for section, existing_values in config.items():
 
1158
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
 
1159
                if existing_values.get(key) != values.get(key):
 
1160
                    break
 
1161
            else:
 
1162
                del config[section]
 
1163
        config.update({name: values})
 
1164
        self._save()
 
1165
 
 
1166
    def get_user(self, scheme, host, port=None, realm=None, path=None,
 
1167
                 prompt=None, ask=False, default=None):
1057
1168
        """Get a user from authentication file.
1058
1169
 
1059
1170
        :param scheme: protocol
1066
1177
 
1067
1178
        :param path: the absolute path on the server (optional)
1068
1179
 
 
1180
        :param ask: Ask the user if there is no explicitly configured username 
 
1181
                    (optional)
 
1182
 
 
1183
        :param default: The username returned if none is defined (optional).
 
1184
 
1069
1185
        :return: The found user.
1070
1186
        """
1071
1187
        credentials = self.get_credentials(scheme, host, port, user=None,
1072
 
                                           path=path)
 
1188
                                           path=path, realm=realm)
1073
1189
        if credentials is not None:
1074
1190
            user = credentials['user']
1075
1191
        else:
1076
1192
            user = None
 
1193
        if user is None:
 
1194
            if ask:
 
1195
                if prompt is None:
 
1196
                    # Create a default prompt suitable for most cases
 
1197
                    prompt = scheme.upper() + ' %(host)s username'
 
1198
                # Special handling for optional fields in the prompt
 
1199
                if port is not None:
 
1200
                    prompt_host = '%s:%d' % (host, port)
 
1201
                else:
 
1202
                    prompt_host = host
 
1203
                user = ui.ui_factory.get_username(prompt, host=prompt_host)
 
1204
            else:
 
1205
                user = default
1077
1206
        return user
1078
1207
 
1079
1208
    def get_password(self, scheme, host, user, port=None,
1094
1223
 
1095
1224
        :return: The found password or the one entered by the user.
1096
1225
        """
1097
 
        credentials = self.get_credentials(scheme, host, port, user, path)
 
1226
        credentials = self.get_credentials(scheme, host, port, user, path,
 
1227
                                           realm)
1098
1228
        if credentials is not None:
1099
1229
            password = credentials['password']
 
1230
            if password is not None and scheme is 'ssh':
 
1231
                trace.warning('password ignored in section [%s],'
 
1232
                              ' use an ssh agent instead'
 
1233
                              % credentials['name'])
 
1234
                password = None
1100
1235
        else:
1101
1236
            password = None
1102
1237
        # Prompt user only if we could't find a password
1103
1238
        if password is None:
1104
1239
            if prompt is None:
1105
 
                # Create a default prompt suitable for most of the cases
 
1240
                # Create a default prompt suitable for most cases
1106
1241
                prompt = '%s' % scheme.upper() + ' %(user)s@%(host)s password'
1107
1242
            # Special handling for optional fields in the prompt
1108
1243
            if port is not None:
1114
1249
        return password
1115
1250
 
1116
1251
    def decode_password(self, credentials, encoding):
1117
 
        return credentials
 
1252
        try:
 
1253
            cs = credential_store_registry.get_credential_store(encoding)
 
1254
        except KeyError:
 
1255
            raise ValueError('%r is not a known password_encoding' % encoding)
 
1256
        credentials['password'] = cs.decode_password(credentials)
 
1257
        return credentials
 
1258
 
 
1259
 
 
1260
class CredentialStoreRegistry(registry.Registry):
 
1261
    """A class that registers credential stores.
 
1262
 
 
1263
    A credential store provides access to credentials via the password_encoding
 
1264
    field in authentication.conf sections.
 
1265
 
 
1266
    Except for stores provided by bzr itself, most stores are expected to be
 
1267
    provided by plugins that will therefore use
 
1268
    register_lazy(password_encoding, module_name, member_name, help=help,
 
1269
    fallback=fallback) to install themselves.
 
1270
 
 
1271
    A fallback credential store is one that is queried if no credentials can be
 
1272
    found via authentication.conf.
 
1273
    """
 
1274
 
 
1275
    def get_credential_store(self, encoding=None):
 
1276
        cs = self.get(encoding)
 
1277
        if callable(cs):
 
1278
            cs = cs()
 
1279
        return cs
 
1280
 
 
1281
    def is_fallback(self, name):
 
1282
        """Check if the named credentials store should be used as fallback."""
 
1283
        return self.get_info(name)
 
1284
 
 
1285
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
 
1286
                                 path=None, realm=None):
 
1287
        """Request credentials from all fallback credentials stores.
 
1288
 
 
1289
        The first credentials store that can provide credentials wins.
 
1290
        """
 
1291
        credentials = None
 
1292
        for name in self.keys():
 
1293
            if not self.is_fallback(name):
 
1294
                continue
 
1295
            cs = self.get_credential_store(name)
 
1296
            credentials = cs.get_credentials(scheme, host, port, user,
 
1297
                                             path, realm)
 
1298
            if credentials is not None:
 
1299
                # We found some credentials
 
1300
                break
 
1301
        return credentials
 
1302
 
 
1303
    def register(self, key, obj, help=None, override_existing=False,
 
1304
                 fallback=False):
 
1305
        """Register a new object to a name.
 
1306
 
 
1307
        :param key: This is the key to use to request the object later.
 
1308
        :param obj: The object to register.
 
1309
        :param help: Help text for this entry. This may be a string or
 
1310
                a callable. If it is a callable, it should take two
 
1311
                parameters (registry, key): this registry and the key that
 
1312
                the help was registered under.
 
1313
        :param override_existing: Raise KeyErorr if False and something has
 
1314
                already been registered for that key. If True, ignore if there
 
1315
                is an existing key (always register the new value).
 
1316
        :param fallback: Whether this credential store should be 
 
1317
                used as fallback.
 
1318
        """
 
1319
        return super(CredentialStoreRegistry,
 
1320
                     self).register(key, obj, help, info=fallback,
 
1321
                                    override_existing=override_existing)
 
1322
 
 
1323
    def register_lazy(self, key, module_name, member_name,
 
1324
                      help=None, override_existing=False,
 
1325
                      fallback=False):
 
1326
        """Register a new credential store to be loaded on request.
 
1327
 
 
1328
        :param module_name: The python path to the module. Such as 'os.path'.
 
1329
        :param member_name: The member of the module to return.  If empty or
 
1330
                None, get() will return the module itself.
 
1331
        :param help: Help text for this entry. This may be a string or
 
1332
                a callable.
 
1333
        :param override_existing: If True, replace the existing object
 
1334
                with the new one. If False, if there is already something
 
1335
                registered with the same key, raise a KeyError
 
1336
        :param fallback: Whether this credential store should be 
 
1337
                used as fallback.
 
1338
        """
 
1339
        return super(CredentialStoreRegistry, self).register_lazy(
 
1340
            key, module_name, member_name, help,
 
1341
            info=fallback, override_existing=override_existing)
 
1342
 
 
1343
 
 
1344
credential_store_registry = CredentialStoreRegistry()
 
1345
 
 
1346
 
 
1347
class CredentialStore(object):
 
1348
    """An abstract class to implement storage for credentials"""
 
1349
 
 
1350
    def decode_password(self, credentials):
 
1351
        """Returns a clear text password for the provided credentials."""
 
1352
        raise NotImplementedError(self.decode_password)
 
1353
 
 
1354
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
 
1355
                        realm=None):
 
1356
        """Return the matching credentials from this credential store.
 
1357
 
 
1358
        This method is only called on fallback credential stores.
 
1359
        """
 
1360
        raise NotImplementedError(self.get_credentials)
 
1361
 
 
1362
 
 
1363
 
 
1364
class PlainTextCredentialStore(CredentialStore):
 
1365
    """Plain text credential store for the authentication.conf file."""
 
1366
 
 
1367
    def decode_password(self, credentials):
 
1368
        """See CredentialStore.decode_password."""
 
1369
        return credentials['password']
 
1370
 
 
1371
 
 
1372
credential_store_registry.register('plain', PlainTextCredentialStore,
 
1373
                                   help=PlainTextCredentialStore.__doc__)
 
1374
credential_store_registry.default_key = 'plain'
 
1375
 
 
1376
 
 
1377
class BzrDirConfig(object):
 
1378
 
 
1379
    def __init__(self, bzrdir):
 
1380
        self._bzrdir = bzrdir
 
1381
        self._config = bzrdir._get_config()
 
1382
 
 
1383
    def set_default_stack_on(self, value):
 
1384
        """Set the default stacking location.
 
1385
 
 
1386
        It may be set to a location, or None.
 
1387
 
 
1388
        This policy affects all branches contained by this bzrdir, except for
 
1389
        those under repositories.
 
1390
        """
 
1391
        if self._config is None:
 
1392
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
 
1393
        if value is None:
 
1394
            self._config.set_option('', 'default_stack_on')
 
1395
        else:
 
1396
            self._config.set_option(value, 'default_stack_on')
 
1397
 
 
1398
    def get_default_stack_on(self):
 
1399
        """Return the default stacking location.
 
1400
 
 
1401
        This will either be a location, or None.
 
1402
 
 
1403
        This policy affects all branches contained by this bzrdir, except for
 
1404
        those under repositories.
 
1405
        """
 
1406
        if self._config is None:
 
1407
            return None
 
1408
        value = self._config.get_option('default_stack_on')
 
1409
        if value == '':
 
1410
            value = None
 
1411
        return value
 
1412
 
 
1413
 
 
1414
class TransportConfig(object):
 
1415
    """A Config that reads/writes a config file on a Transport.
 
1416
 
 
1417
    It is a low-level object that considers config data to be name/value pairs
 
1418
    that may be associated with a section.  Assigning meaning to the these
 
1419
    values is done at higher levels like TreeConfig.
 
1420
    """
 
1421
 
 
1422
    def __init__(self, transport, filename):
 
1423
        self._transport = transport
 
1424
        self._filename = filename
 
1425
 
 
1426
    def get_option(self, name, section=None, default=None):
 
1427
        """Return the value associated with a named option.
 
1428
 
 
1429
        :param name: The name of the value
 
1430
        :param section: The section the option is in (if any)
 
1431
        :param default: The value to return if the value is not set
 
1432
        :return: The value or default value
 
1433
        """
 
1434
        configobj = self._get_configobj()
 
1435
        if section is None:
 
1436
            section_obj = configobj
 
1437
        else:
 
1438
            try:
 
1439
                section_obj = configobj[section]
 
1440
            except KeyError:
 
1441
                return default
 
1442
        return section_obj.get(name, default)
 
1443
 
 
1444
    def set_option(self, value, name, section=None):
 
1445
        """Set the value associated with a named option.
 
1446
 
 
1447
        :param value: The value to set
 
1448
        :param name: The name of the value to set
 
1449
        :param section: The section the option is in (if any)
 
1450
        """
 
1451
        configobj = self._get_configobj()
 
1452
        if section is None:
 
1453
            configobj[name] = value
 
1454
        else:
 
1455
            configobj.setdefault(section, {})[name] = value
 
1456
        self._set_configobj(configobj)
 
1457
 
 
1458
    def _get_config_file(self):
 
1459
        try:
 
1460
            return self._transport.get(self._filename)
 
1461
        except errors.NoSuchFile:
 
1462
            return StringIO()
 
1463
 
 
1464
    def _get_configobj(self):
 
1465
        return ConfigObj(self._get_config_file(), encoding='utf-8')
 
1466
 
 
1467
    def _set_configobj(self, configobj):
 
1468
        out_file = StringIO()
 
1469
        configobj.write(out_file)
 
1470
        out_file.seek(0)
 
1471
        self._transport.put_file(self._filename, out_file)