~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Jelmer Vernooij
  • Date: 2009-02-10 04:10:44 UTC
  • mto: This revision was merged to the branch mainline in revision 3995.
  • Revision ID: jelmer@samba.org-20090210041044-42lmb09hskt9lt9l
Review from Ian.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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
74
74
 
75
75
import bzrlib
76
76
from bzrlib import (
77
 
    atomicfile,
78
77
    debug,
79
78
    errors,
80
79
    mail_client,
147
146
class Config(object):
148
147
    """A configuration policy - what username, editor, gpg needs etc."""
149
148
 
150
 
    def __init__(self):
151
 
        super(Config, self).__init__()
152
 
 
153
149
    def get_editor(self):
154
150
        """Get the users pop up editor."""
155
151
        raise NotImplementedError
156
152
 
157
 
    def get_change_editor(self, old_tree, new_tree):
158
 
        from bzrlib import diff
159
 
        cmd = self._get_change_editor()
160
 
        if cmd is None:
161
 
            return None
162
 
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
163
 
                                             sys.stdout)
164
 
 
165
 
 
166
153
    def get_mail_client(self):
167
154
        """Get a mail client to use"""
168
155
        selected_client = self.get_user_option('mail_client')
187
174
        """Get a generic option - no special process, no default."""
188
175
        return self._get_user_option(option_name)
189
176
 
190
 
    def get_user_option_as_bool(self, option_name):
191
 
        """Get a generic option as a boolean - no special process, no default.
192
 
 
193
 
        :return None if the option doesn't exist or its value can't be
194
 
            interpreted as a boolean. Returns True or False otherwise.
195
 
        """
196
 
        s = self._get_user_option(option_name)
197
 
        if s is None:
198
 
            # The option doesn't exist
199
 
            return None
200
 
        val = ui.bool_from_string(s)
201
 
        if val is None:
202
 
            # The value can't be interpreted as a boolean
203
 
            trace.warning('Value "%s" is not a boolean for "%s"',
204
 
                          s, option_name)
205
 
        return val
206
 
 
207
 
    def get_user_option_as_list(self, option_name):
208
 
        """Get a generic option as a list - no special process, no default.
209
 
 
210
 
        :return None if the option doesn't exist. Returns the value as a list
211
 
            otherwise.
212
 
        """
213
 
        l = self._get_user_option(option_name)
214
 
        if isinstance(l, (str, unicode)):
215
 
            # A single value, most probably the user forgot the final ','
216
 
            l = [l]
217
 
        return l
218
 
 
219
177
    def gpg_signing_command(self):
220
178
        """What program should be used to sign signatures?"""
221
179
        result = self._gpg_signing_command()
238
196
        """See log_format()."""
239
197
        return None
240
198
 
 
199
    def __init__(self):
 
200
        super(Config, self).__init__()
 
201
 
241
202
    def post_commit(self):
242
203
        """An ordered list of python functions to call.
243
204
 
255
216
 
256
217
    def username(self):
257
218
        """Return email-style username.
258
 
 
 
219
    
259
220
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
260
 
 
261
 
        $BZR_EMAIL can be set to override this, then
 
221
        
 
222
        $BZR_EMAIL can be set to override this (as well as the
 
223
        deprecated $BZREMAIL), then
262
224
        the concrete policy type is checked, and finally
263
225
        $EMAIL is examined.
264
 
        If no username can be found, errors.NoWhoami exception is raised.
265
 
 
 
226
        If none is found, a reasonable default is (hopefully)
 
227
        created.
 
228
    
266
229
        TODO: Check it's reasonably well-formed.
267
230
        """
268
231
        v = os.environ.get('BZR_EMAIL')
277
240
        if v:
278
241
            return v.decode(osutils.get_user_encoding())
279
242
 
280
 
        raise errors.NoWhoami()
281
 
 
282
 
    def ensure_username(self):
283
 
        """Raise errors.NoWhoami if username is not set.
284
 
 
285
 
        This method relies on the username() function raising the error.
286
 
        """
287
 
        self.username()
 
243
        name, email = _auto_user_id()
 
244
        if name:
 
245
            return '%s <%s>' % (name, email)
 
246
        else:
 
247
            return email
288
248
 
289
249
    def signature_checking(self):
290
250
        """What is the current policy for signature checking?."""
335
295
                path = 'bzr'
336
296
            return path
337
297
 
338
 
    def suppress_warning(self, warning):
339
 
        """Should the warning be suppressed or emitted.
340
 
 
341
 
        :param warning: The name of the warning being tested.
342
 
 
343
 
        :returns: True if the warning should be suppressed, False otherwise.
344
 
        """
345
 
        warnings = self.get_user_option_as_list('suppress_warnings')
346
 
        if warnings is None or warning not in warnings:
347
 
            return False
348
 
        else:
349
 
            return True
350
 
 
351
298
 
352
299
class IniBasedConfig(Config):
353
300
    """A configuration policy that draws from ini files."""
354
301
 
355
 
    def __init__(self, get_filename):
356
 
        super(IniBasedConfig, self).__init__()
357
 
        self._get_filename = get_filename
358
 
        self._parser = None
359
 
 
360
302
    def _get_parser(self, file=None):
361
303
        if self._parser is not None:
362
304
            return self._parser
390
332
        """Return the policy for the given (section, option_name) pair."""
391
333
        return POLICY_NONE
392
334
 
393
 
    def _get_change_editor(self):
394
 
        return self.get_user_option('change_editor')
395
 
 
396
335
    def _get_signature_checking(self):
397
336
        """See Config._get_signature_checking."""
398
337
        policy = self._get_user_option('check_signatures')
442
381
        """See Config.log_format."""
443
382
        return self._get_user_option('log_format')
444
383
 
 
384
    def __init__(self, get_filename):
 
385
        super(IniBasedConfig, self).__init__()
 
386
        self._get_filename = get_filename
 
387
        self._parser = None
 
388
        
445
389
    def _post_commit(self):
446
390
        """See Config.post_commit."""
447
391
        return self._get_user_option('post_commit')
470
414
 
471
415
    def _get_alias(self, value):
472
416
        try:
473
 
            return self._get_parser().get_value("ALIASES",
 
417
            return self._get_parser().get_value("ALIASES", 
474
418
                                                value)
475
419
        except KeyError:
476
420
            pass
478
422
    def _get_nickname(self):
479
423
        return self.get_user_option('nickname')
480
424
 
481
 
    def _write_config_file(self):
482
 
        filename = self._get_filename()
483
 
        atomic_file = atomicfile.AtomicFile(filename)
484
 
        self._get_parser().write(atomic_file)
485
 
        atomic_file.commit()
486
 
        atomic_file.close()
487
 
        osutils.copy_ownership_from_path(filename)
488
 
 
489
425
 
490
426
class GlobalConfig(IniBasedConfig):
491
427
    """The configuration that should be used for a specific location."""
527
463
        self._get_parser().setdefault(section, {})[option] = value
528
464
        self._write_config_file()
529
465
 
 
466
    def _write_config_file(self):
 
467
        f = open(self._get_filename(), 'wb')
 
468
        self._get_parser().write(f)
 
469
        f.close()
 
470
 
530
471
 
531
472
class LocationConfig(IniBasedConfig):
532
473
    """A configuration object that gives the policy for a location."""
666
607
        self._get_parser()[location][option]=value
667
608
        # the allowed values of store match the config policies
668
609
        self._set_option_policy(location, option, store)
669
 
        self._write_config_file()
 
610
        self._get_parser().write(file(self._get_filename(), 'wb'))
670
611
 
671
612
 
672
613
class BranchConfig(Config):
701
642
 
702
643
    def _get_safe_value(self, option_name):
703
644
        """This variant of get_best_value never returns untrusted values.
704
 
 
 
645
        
705
646
        It does not return values from the branch data, because the branch may
706
647
        not be controlled by the user.
707
648
 
716
657
 
717
658
    def _get_user_id(self):
718
659
        """Return the full user id for the branch.
719
 
 
 
660
    
720
661
        e.g. "John Hacker <jhacker@example.com>"
721
662
        This is looked up in the email controlfile for the branch.
722
663
        """
726
667
                    .rstrip("\r\n"))
727
668
        except errors.NoSuchFile, e:
728
669
            pass
729
 
 
 
670
        
730
671
        return self._get_best_value('_get_user_id')
731
672
 
732
 
    def _get_change_editor(self):
733
 
        return self._get_best_value('_get_change_editor')
734
 
 
735
673
    def _get_signature_checking(self):
736
674
        """See Config._get_signature_checking."""
737
675
        return self._get_best_value('_get_signature_checking')
771
709
                        trace.warning('Value "%s" is masked by "%s" from'
772
710
                                      ' branch.conf', value, mask_value)
773
711
 
 
712
 
774
713
    def _gpg_signing_command(self):
775
714
        """See Config.gpg_signing_command."""
776
715
        return self._get_safe_value('_gpg_signing_command')
777
 
 
 
716
        
778
717
    def __init__(self, branch):
779
718
        super(BranchConfig, self).__init__()
780
719
        self._location_config = None
781
720
        self._branch_data_config = None
782
721
        self._global_config = None
783
722
        self.branch = branch
784
 
        self.option_sources = (self._get_location_config,
 
723
        self.option_sources = (self._get_location_config, 
785
724
                               self._get_branch_data_config,
786
725
                               self._get_global_config)
787
726
 
823
762
            os.mkdir(parent_dir)
824
763
        trace.mutter('creating config directory: %r', path)
825
764
        os.mkdir(path)
826
 
        osutils.copy_ownership_from_path(path)
827
765
 
828
766
 
829
767
def config_dir():
830
768
    """Return per-user configuration directory.
831
769
 
832
770
    By default this is ~/.bazaar/
833
 
 
 
771
    
834
772
    TODO: Global option --config-dir to override this.
835
773
    """
836
774
    base = os.environ.get('BZR_HOME', None)
844
782
                                  ' or HOME set')
845
783
        return osutils.pathjoin(base, 'bazaar', '2.0')
846
784
    else:
 
785
        # cygwin, linux, and darwin all have a $HOME directory
847
786
        if base is None:
848
787
            base = os.path.expanduser("~")
849
788
        return osutils.pathjoin(base, ".bazaar")
874
813
    return osutils.pathjoin(config_dir(), 'ignore')
875
814
 
876
815
 
877
 
def crash_dir():
878
 
    """Return the directory name to store crash files.
879
 
 
880
 
    This doesn't implicitly create it.
881
 
 
882
 
    On Windows it's in the config directory; elsewhere it's /var/crash
883
 
    which may be monitored by apport.  It can be overridden by
884
 
    $APPORT_CRASH_DIR.
 
816
def _auto_user_id():
 
817
    """Calculate automatic user identification.
 
818
 
 
819
    Returns (realname, email).
 
820
 
 
821
    Only used when none is set in the environment or the id file.
 
822
 
 
823
    This previously used the FQDN as the default domain, but that can
 
824
    be very slow on machines where DNS is broken.  So now we simply
 
825
    use the hostname.
885
826
    """
 
827
    import socket
 
828
 
886
829
    if sys.platform == 'win32':
887
 
        return osutils.pathjoin(config_dir(), 'Crash')
888
 
    else:
889
 
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
890
 
        # 2010-01-31
891
 
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
892
 
 
893
 
 
894
 
def xdg_cache_dir():
895
 
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
896
 
    # Possibly this should be different on Windows?
897
 
    e = os.environ.get('XDG_CACHE_DIR', None)
898
 
    if e:
899
 
        return e
900
 
    else:
901
 
        return os.path.expanduser('~/.cache')
 
830
        name = win32utils.get_user_name_unicode()
 
831
        if name is None:
 
832
            raise errors.BzrError("Cannot autodetect user name.\n"
 
833
                                  "Please, set your name with command like:\n"
 
834
                                  'bzr whoami "Your Name <name@domain.com>"')
 
835
        host = win32utils.get_host_name_unicode()
 
836
        if host is None:
 
837
            host = socket.gethostname()
 
838
        return name, (name + '@' + host)
 
839
 
 
840
    try:
 
841
        import pwd
 
842
        uid = os.getuid()
 
843
        try:
 
844
            w = pwd.getpwuid(uid)
 
845
        except KeyError:
 
846
            raise errors.BzrCommandError('Unable to determine your name.  '
 
847
                'Please use "bzr whoami" to set it.')
 
848
 
 
849
        # we try utf-8 first, because on many variants (like Linux),
 
850
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
 
851
        # false positives.  (many users will have their user encoding set to
 
852
        # latin-1, which cannot raise UnicodeError.)
 
853
        try:
 
854
            gecos = w.pw_gecos.decode('utf-8')
 
855
            encoding = 'utf-8'
 
856
        except UnicodeError:
 
857
            try:
 
858
                encoding = osutils.get_user_encoding()
 
859
                gecos = w.pw_gecos.decode(encoding)
 
860
            except UnicodeError:
 
861
                raise errors.BzrCommandError('Unable to determine your name.  '
 
862
                   'Use "bzr whoami" to set it.')
 
863
        try:
 
864
            username = w.pw_name.decode(encoding)
 
865
        except UnicodeError:
 
866
            raise errors.BzrCommandError('Unable to determine your name.  '
 
867
                'Use "bzr whoami" to set it.')
 
868
 
 
869
        comma = gecos.find(',')
 
870
        if comma == -1:
 
871
            realname = gecos
 
872
        else:
 
873
            realname = gecos[:comma]
 
874
        if not realname:
 
875
            realname = username
 
876
 
 
877
    except ImportError:
 
878
        import getpass
 
879
        try:
 
880
            user_encoding = osutils.get_user_encoding()
 
881
            realname = username = getpass.getuser().decode(user_encoding)
 
882
        except UnicodeDecodeError:
 
883
            raise errors.BzrError("Can't decode username as %s." % \
 
884
                    user_encoding)
 
885
 
 
886
    return realname, (username + '@' + socket.gethostname())
902
887
 
903
888
 
904
889
def parse_username(username):
913
898
def extract_email_address(e):
914
899
    """Return just the address part of an email string.
915
900
 
916
 
    That is just the user@domain part, nothing else.
 
901
    That is just the user@domain part, nothing else. 
917
902
    This part is required to contain only ascii characters.
918
903
    If it can't be extracted, raises an error.
919
904
 
932
917
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
933
918
 
934
919
    def __init__(self, branch):
935
 
        self._config = branch._get_config()
 
920
        # XXX: Really this should be asking the branch for its configuration
 
921
        # data, rather than relying on a Transport, so that it can work 
 
922
        # more cleanly with a RemoteBranch that has no transport.
 
923
        self._config = TransportConfig(branch._transport, 'branch.conf')
936
924
        self.branch = branch
937
925
 
938
926
    def _get_parser(self, file=None):
946
934
            return self._config.get_option(name, section, default)
947
935
        finally:
948
936
            self.branch.unlock()
 
937
        return result
949
938
 
950
939
    def set_option(self, value, name, section=None):
951
940
        """Set a per-branch configuration option"""
992
981
        """Save the config file, only tests should use it for now."""
993
982
        conf_dir = os.path.dirname(self._filename)
994
983
        ensure_config_dir_exists(conf_dir)
995
 
        f = file(self._filename, 'wb')
996
 
        try:
997
 
            self._get_config().write(f)
998
 
        finally:
999
 
            f.close()
 
984
        self._get_config().write(file(self._filename, 'wb'))
1000
985
 
1001
986
    def _set_option(self, section_name, option_name, value):
1002
987
        """Set an authentication configuration option"""
1008
993
        section[option_name] = value
1009
994
        self._save()
1010
995
 
1011
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
1012
 
                        realm=None):
 
996
    def get_credentials(self, scheme, host, port=None, user=None, path=None):
1013
997
        """Returns the matching credentials from authentication.conf file.
1014
998
 
1015
999
        :param scheme: protocol
1021
1005
        :param user: login (optional)
1022
1006
 
1023
1007
        :param path: the absolute path on the server (optional)
1024
 
        
1025
 
        :param realm: the http authentication realm (optional)
1026
1008
 
1027
1009
        :return: A dict containing the matching credentials or None.
1028
1010
           This includes:
1029
1011
           - name: the section name of the credentials in the
1030
1012
             authentication.conf file,
1031
 
           - user: can't be different from the provided user if any,
1032
 
           - scheme: the server protocol,
1033
 
           - host: the server address,
1034
 
           - port: the server port (can be None),
1035
 
           - path: the absolute server path (can be None),
1036
 
           - realm: the http specific authentication realm (can be None),
 
1013
           - user: can't de different from the provided user if any,
1037
1014
           - password: the decoded password, could be None if the credential
1038
1015
             defines only the user
1039
1016
           - verify_certificates: https specific, True if the server
1080
1057
            if a_user is None:
1081
1058
                # Can't find a user
1082
1059
                continue
1083
 
            # Prepare a credentials dictionary with additional keys
1084
 
            # for the credential providers
1085
1060
            credentials = dict(name=auth_def_name,
1086
1061
                               user=a_user,
1087
 
                               scheme=a_scheme,
1088
 
                               host=host,
1089
 
                               port=port,
1090
 
                               path=path,
1091
 
                               realm=realm,
1092
1062
                               password=auth_def.get('password', None),
1093
1063
                               verify_certificates=a_verify_certificates)
1094
 
            # Decode the password in the credentials (or get one)
1095
1064
            self.decode_password(credentials,
1096
1065
                                 auth_def.get('password_encoding', None))
1097
1066
            if 'auth' in debug.debug_flags:
1098
1067
                trace.mutter("Using authentication section: %r", auth_def_name)
1099
1068
            break
1100
1069
 
1101
 
        if credentials is None:
1102
 
            # No credentials were found in authentication.conf, try the fallback
1103
 
            # credentials stores.
1104
 
            credentials = credential_store_registry.get_fallback_credentials(
1105
 
                scheme, host, port, user, path, realm)
1106
 
 
1107
1070
        return credentials
1108
1071
 
1109
1072
    def set_credentials(self, name, host, user, scheme=None, password=None,
1110
 
                        port=None, path=None, verify_certificates=None,
1111
 
                        realm=None):
 
1073
                        port=None, path=None, verify_certificates=None):
1112
1074
        """Set authentication credentials for a host.
1113
1075
 
1114
1076
        Any existing credentials with matching scheme, host, port and path
1125
1087
            apply to.
1126
1088
        :param verify_certificates: On https, verify server certificates if
1127
1089
            True.
1128
 
        :param realm: The http authentication realm (optional).
1129
1090
        """
1130
1091
        values = {'host': host, 'user': user}
1131
1092
        if password is not None:
1138
1099
            values['path'] = path
1139
1100
        if verify_certificates is not None:
1140
1101
            values['verify_certificates'] = str(verify_certificates)
1141
 
        if realm is not None:
1142
 
            values['realm'] = realm
1143
1102
        config = self._get_config()
1144
1103
        for_deletion = []
1145
1104
        for section, existing_values in config.items():
1146
 
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
 
1105
            for key in ('scheme', 'host', 'port', 'path'):
1147
1106
                if existing_values.get(key) != values.get(key):
1148
1107
                    break
1149
1108
            else:
1151
1110
        config.update({name: values})
1152
1111
        self._save()
1153
1112
 
1154
 
    def get_user(self, scheme, host, port=None, realm=None, path=None,
1155
 
                 prompt=None, ask=False, default=None):
 
1113
    def get_user(self, scheme, host, port=None,
 
1114
                 realm=None, path=None, prompt=None):
1156
1115
        """Get a user from authentication file.
1157
1116
 
1158
1117
        :param scheme: protocol
1165
1124
 
1166
1125
        :param path: the absolute path on the server (optional)
1167
1126
 
1168
 
        :param ask: Ask the user if there is no explicitly configured username 
1169
 
                    (optional)
1170
 
 
1171
 
        :param default: The username returned if none is defined (optional).
1172
 
 
1173
1127
        :return: The found user.
1174
1128
        """
1175
1129
        credentials = self.get_credentials(scheme, host, port, user=None,
1176
 
                                           path=path, realm=realm)
 
1130
                                           path=path)
1177
1131
        if credentials is not None:
1178
1132
            user = credentials['user']
1179
1133
        else:
1180
1134
            user = None
1181
 
        if user is None:
1182
 
            if ask:
1183
 
                if prompt is None:
1184
 
                    # Create a default prompt suitable for most cases
1185
 
                    prompt = scheme.upper() + ' %(host)s username'
1186
 
                # Special handling for optional fields in the prompt
1187
 
                if port is not None:
1188
 
                    prompt_host = '%s:%d' % (host, port)
1189
 
                else:
1190
 
                    prompt_host = host
1191
 
                user = ui.ui_factory.get_username(prompt, host=prompt_host)
1192
 
            else:
1193
 
                user = default
1194
1135
        return user
1195
1136
 
1196
1137
    def get_password(self, scheme, host, user, port=None,
1211
1152
 
1212
1153
        :return: The found password or the one entered by the user.
1213
1154
        """
1214
 
        credentials = self.get_credentials(scheme, host, port, user, path,
1215
 
                                           realm)
 
1155
        credentials = self.get_credentials(scheme, host, port, user, path)
1216
1156
        if credentials is not None:
1217
1157
            password = credentials['password']
1218
1158
            if password is not None and scheme is 'ssh':
1251
1191
    A credential store provides access to credentials via the password_encoding
1252
1192
    field in authentication.conf sections.
1253
1193
 
1254
 
    Except for stores provided by bzr itself, most stores are expected to be
 
1194
    Except for stores provided by bzr itself,most stores are expected to be
1255
1195
    provided by plugins that will therefore use
1256
1196
    register_lazy(password_encoding, module_name, member_name, help=help,
1257
 
    fallback=fallback) to install themselves.
1258
 
 
1259
 
    A fallback credential store is one that is queried if no credentials can be
1260
 
    found via authentication.conf.
 
1197
    info=info) to install themselves.
1261
1198
    """
1262
1199
 
1263
1200
    def get_credential_store(self, encoding=None):
1266
1203
            cs = cs()
1267
1204
        return cs
1268
1205
 
1269
 
    def is_fallback(self, name):
1270
 
        """Check if the named credentials store should be used as fallback."""
1271
 
        return self.get_info(name)
1272
 
 
1273
 
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
1274
 
                                 path=None, realm=None):
1275
 
        """Request credentials from all fallback credentials stores.
1276
 
 
1277
 
        The first credentials store that can provide credentials wins.
1278
 
        """
1279
 
        credentials = None
1280
 
        for name in self.keys():
1281
 
            if not self.is_fallback(name):
1282
 
                continue
1283
 
            cs = self.get_credential_store(name)
1284
 
            credentials = cs.get_credentials(scheme, host, port, user,
1285
 
                                             path, realm)
1286
 
            if credentials is not None:
1287
 
                # We found some credentials
1288
 
                break
1289
 
        return credentials
1290
 
 
1291
 
    def register(self, key, obj, help=None, override_existing=False,
1292
 
                 fallback=False):
1293
 
        """Register a new object to a name.
1294
 
 
1295
 
        :param key: This is the key to use to request the object later.
1296
 
        :param obj: The object to register.
1297
 
        :param help: Help text for this entry. This may be a string or
1298
 
                a callable. If it is a callable, it should take two
1299
 
                parameters (registry, key): this registry and the key that
1300
 
                the help was registered under.
1301
 
        :param override_existing: Raise KeyErorr if False and something has
1302
 
                already been registered for that key. If True, ignore if there
1303
 
                is an existing key (always register the new value).
1304
 
        :param fallback: Whether this credential store should be 
1305
 
                used as fallback.
1306
 
        """
1307
 
        return super(CredentialStoreRegistry,
1308
 
                     self).register(key, obj, help, info=fallback,
1309
 
                                    override_existing=override_existing)
1310
 
 
1311
 
    def register_lazy(self, key, module_name, member_name,
1312
 
                      help=None, override_existing=False,
1313
 
                      fallback=False):
1314
 
        """Register a new credential store to be loaded on request.
1315
 
 
1316
 
        :param module_name: The python path to the module. Such as 'os.path'.
1317
 
        :param member_name: The member of the module to return.  If empty or
1318
 
                None, get() will return the module itself.
1319
 
        :param help: Help text for this entry. This may be a string or
1320
 
                a callable.
1321
 
        :param override_existing: If True, replace the existing object
1322
 
                with the new one. If False, if there is already something
1323
 
                registered with the same key, raise a KeyError
1324
 
        :param fallback: Whether this credential store should be 
1325
 
                used as fallback.
1326
 
        """
1327
 
        return super(CredentialStoreRegistry, self).register_lazy(
1328
 
            key, module_name, member_name, help,
1329
 
            info=fallback, override_existing=override_existing)
1330
 
 
1331
1206
 
1332
1207
credential_store_registry = CredentialStoreRegistry()
1333
1208
 
1336
1211
    """An abstract class to implement storage for credentials"""
1337
1212
 
1338
1213
    def decode_password(self, credentials):
1339
 
        """Returns a clear text password for the provided credentials."""
 
1214
        """Returns a password for the provided credentials in clear text."""
1340
1215
        raise NotImplementedError(self.decode_password)
1341
1216
 
1342
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
1343
 
                        realm=None):
1344
 
        """Return the matching credentials from this credential store.
1345
 
 
1346
 
        This method is only called on fallback credential stores.
1347
 
        """
1348
 
        raise NotImplementedError(self.get_credentials)
1349
 
 
1350
 
 
1351
1217
 
1352
1218
class PlainTextCredentialStore(CredentialStore):
1353
 
    __doc__ = """Plain text credential store for the authentication.conf file"""
 
1219
    """Plain text credential store for the authentication.conf file."""
1354
1220
 
1355
1221
    def decode_password(self, credentials):
1356
1222
        """See CredentialStore.decode_password."""
1364
1230
 
1365
1231
class BzrDirConfig(object):
1366
1232
 
1367
 
    def __init__(self, bzrdir):
1368
 
        self._bzrdir = bzrdir
1369
 
        self._config = bzrdir._get_config()
 
1233
    def __init__(self, transport):
 
1234
        self._config = TransportConfig(transport, 'control.conf')
1370
1235
 
1371
1236
    def set_default_stack_on(self, value):
1372
1237
        """Set the default stacking location.
1376
1241
        This policy affects all branches contained by this bzrdir, except for
1377
1242
        those under repositories.
1378
1243
        """
1379
 
        if self._config is None:
1380
 
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1381
1244
        if value is None:
1382
1245
            self._config.set_option('', 'default_stack_on')
1383
1246
        else:
1391
1254
        This policy affects all branches contained by this bzrdir, except for
1392
1255
        those under repositories.
1393
1256
        """
1394
 
        if self._config is None:
1395
 
            return None
1396
1257
        value = self._config.get_option('default_stack_on')
1397
1258
        if value == '':
1398
1259
            value = None
1443
1304
            configobj.setdefault(section, {})[name] = value
1444
1305
        self._set_configobj(configobj)
1445
1306
 
1446
 
    def _get_config_file(self):
 
1307
    def _get_configobj(self):
1447
1308
        try:
1448
 
            return StringIO(self._transport.get_bytes(self._filename))
 
1309
            return ConfigObj(self._transport.get(self._filename),
 
1310
                             encoding='utf-8')
1449
1311
        except errors.NoSuchFile:
1450
 
            return StringIO()
1451
 
 
1452
 
    def _get_configobj(self):
1453
 
        f = self._get_config_file()
1454
 
        try:
1455
 
            return ConfigObj(f, encoding='utf-8')
1456
 
        finally:
1457
 
            f.close()
 
1312
            return ConfigObj(encoding='utf-8')
1458
1313
 
1459
1314
    def _set_configobj(self, configobj):
1460
1315
        out_file = StringIO()