~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/config.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2010-04-08 06:17:41 UTC
  • mfrom: (4797.33.16 apport)
  • Revision ID: pqm@pqm.ubuntu.com-20100408061741-m7vl6z97vu33riv7
(robertc) Make sure ExecutablePath and InterpreterPath are set in
        Apport. (Martin Pool, James Westby, lp:528114)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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,
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
146
155
 
 
156
    def get_change_editor(self, old_tree, new_tree):
 
157
        from bzrlib import diff
 
158
        cmd = self._get_change_editor()
 
159
        if cmd is None:
 
160
            return None
 
161
        return diff.DiffFromTool.from_string(cmd, old_tree, new_tree,
 
162
                                             sys.stdout)
 
163
 
 
164
 
147
165
    def get_mail_client(self):
148
166
        """Get a mail client to use"""
149
167
        selected_client = self.get_user_option('mail_client')
168
186
        """Get a generic option - no special process, no default."""
169
187
        return self._get_user_option(option_name)
170
188
 
 
189
    def get_user_option_as_bool(self, option_name):
 
190
        """Get a generic option as a boolean - no special process, no default.
 
191
 
 
192
        :return None if the option doesn't exist or its value can't be
 
193
            interpreted as a boolean. Returns True or False otherwise.
 
194
        """
 
195
        s = self._get_user_option(option_name)
 
196
        return ui.bool_from_string(s)
 
197
 
 
198
    def get_user_option_as_list(self, option_name):
 
199
        """Get a generic option as a list - no special process, no default.
 
200
 
 
201
        :return None if the option doesn't exist. Returns the value as a list
 
202
            otherwise.
 
203
        """
 
204
        l = self._get_user_option(option_name)
 
205
        if isinstance(l, (str, unicode)):
 
206
            # A single value, most probably the user forgot the final ','
 
207
            l = [l]
 
208
        return l
 
209
 
171
210
    def gpg_signing_command(self):
172
211
        """What program should be used to sign signatures?"""
173
212
        result = self._gpg_signing_command()
190
229
        """See log_format()."""
191
230
        return None
192
231
 
193
 
    def __init__(self):
194
 
        super(Config, self).__init__()
195
 
 
196
232
    def post_commit(self):
197
233
        """An ordered list of python functions to call.
198
234
 
210
246
 
211
247
    def username(self):
212
248
        """Return email-style username.
213
 
    
 
249
 
214
250
        Something similar to 'Martin Pool <mbp@sourcefrog.net>'
215
 
        
 
251
 
216
252
        $BZR_EMAIL can be set to override this (as well as the
217
253
        deprecated $BZREMAIL), then
218
254
        the concrete policy type is checked, and finally
219
255
        $EMAIL is examined.
220
256
        If none is found, a reasonable default is (hopefully)
221
257
        created.
222
 
    
 
258
 
223
259
        TODO: Check it's reasonably well-formed.
224
260
        """
225
261
        v = os.environ.get('BZR_EMAIL')
226
262
        if v:
227
 
            return v.decode(bzrlib.user_encoding)
 
263
            return v.decode(osutils.get_user_encoding())
228
264
 
229
265
        v = self._get_user_id()
230
266
        if v:
232
268
 
233
269
        v = os.environ.get('EMAIL')
234
270
        if v:
235
 
            return v.decode(bzrlib.user_encoding)
 
271
            return v.decode(osutils.get_user_encoding())
236
272
 
237
273
        name, email = _auto_user_id()
238
274
        if name:
289
325
                path = 'bzr'
290
326
            return path
291
327
 
 
328
    def suppress_warning(self, warning):
 
329
        """Should the warning be suppressed or emitted.
 
330
 
 
331
        :param warning: The name of the warning being tested.
 
332
 
 
333
        :returns: True if the warning should be suppressed, False otherwise.
 
334
        """
 
335
        warnings = self.get_user_option_as_list('suppress_warnings')
 
336
        if warnings is None or warning not in warnings:
 
337
            return False
 
338
        else:
 
339
            return True
 
340
 
292
341
 
293
342
class IniBasedConfig(Config):
294
343
    """A configuration policy that draws from ini files."""
295
344
 
 
345
    def __init__(self, get_filename):
 
346
        super(IniBasedConfig, self).__init__()
 
347
        self._get_filename = get_filename
 
348
        self._parser = None
 
349
 
296
350
    def _get_parser(self, file=None):
297
351
        if self._parser is not None:
298
352
            return self._parser
326
380
        """Return the policy for the given (section, option_name) pair."""
327
381
        return POLICY_NONE
328
382
 
 
383
    def _get_change_editor(self):
 
384
        return self.get_user_option('change_editor')
 
385
 
329
386
    def _get_signature_checking(self):
330
387
        """See Config._get_signature_checking."""
331
388
        policy = self._get_user_option('check_signatures')
375
432
        """See Config.log_format."""
376
433
        return self._get_user_option('log_format')
377
434
 
378
 
    def __init__(self, get_filename):
379
 
        super(IniBasedConfig, self).__init__()
380
 
        self._get_filename = get_filename
381
 
        self._parser = None
382
 
        
383
435
    def _post_commit(self):
384
436
        """See Config.post_commit."""
385
437
        return self._get_user_option('post_commit')
408
460
 
409
461
    def _get_alias(self, value):
410
462
        try:
411
 
            return self._get_parser().get_value("ALIASES", 
 
463
            return self._get_parser().get_value("ALIASES",
412
464
                                                value)
413
465
        except KeyError:
414
466
            pass
458
510
        self._write_config_file()
459
511
 
460
512
    def _write_config_file(self):
461
 
        f = open(self._get_filename(), 'wb')
 
513
        path = self._get_filename()
 
514
        f = osutils.open_with_ownership(path, 'wb')
462
515
        self._get_parser().write(f)
463
516
        f.close()
464
517
 
636
689
 
637
690
    def _get_safe_value(self, option_name):
638
691
        """This variant of get_best_value never returns untrusted values.
639
 
        
 
692
 
640
693
        It does not return values from the branch data, because the branch may
641
694
        not be controlled by the user.
642
695
 
651
704
 
652
705
    def _get_user_id(self):
653
706
        """Return the full user id for the branch.
654
 
    
 
707
 
655
708
        e.g. "John Hacker <jhacker@example.com>"
656
709
        This is looked up in the email controlfile for the branch.
657
710
        """
658
711
        try:
659
712
            return (self.branch._transport.get_bytes("email")
660
 
                    .decode(bzrlib.user_encoding)
 
713
                    .decode(osutils.get_user_encoding())
661
714
                    .rstrip("\r\n"))
662
715
        except errors.NoSuchFile, e:
663
716
            pass
664
 
        
 
717
 
665
718
        return self._get_best_value('_get_user_id')
666
719
 
 
720
    def _get_change_editor(self):
 
721
        return self._get_best_value('_get_change_editor')
 
722
 
667
723
    def _get_signature_checking(self):
668
724
        """See Config._get_signature_checking."""
669
725
        return self._get_best_value('_get_signature_checking')
703
759
                        trace.warning('Value "%s" is masked by "%s" from'
704
760
                                      ' branch.conf', value, mask_value)
705
761
 
706
 
 
707
762
    def _gpg_signing_command(self):
708
763
        """See Config.gpg_signing_command."""
709
764
        return self._get_safe_value('_gpg_signing_command')
710
 
        
 
765
 
711
766
    def __init__(self, branch):
712
767
        super(BranchConfig, self).__init__()
713
768
        self._location_config = None
714
769
        self._branch_data_config = None
715
770
        self._global_config = None
716
771
        self.branch = branch
717
 
        self.option_sources = (self._get_location_config, 
 
772
        self.option_sources = (self._get_location_config,
718
773
                               self._get_branch_data_config,
719
774
                               self._get_global_config)
720
775
 
755
810
                trace.mutter('creating config parent directory: %r', parent_dir)
756
811
            os.mkdir(parent_dir)
757
812
        trace.mutter('creating config directory: %r', path)
758
 
        os.mkdir(path)
 
813
        osutils.mkdir_with_ownership(path)
759
814
 
760
815
 
761
816
def config_dir():
762
817
    """Return per-user configuration directory.
763
818
 
764
819
    By default this is ~/.bazaar/
765
 
    
 
820
 
766
821
    TODO: Global option --config-dir to override this.
767
822
    """
768
823
    base = os.environ.get('BZR_HOME', None)
807
862
    return osutils.pathjoin(config_dir(), 'ignore')
808
863
 
809
864
 
 
865
def crash_dir():
 
866
    """Return the directory name to store crash files.
 
867
 
 
868
    This doesn't implicitly create it.
 
869
 
 
870
    On Windows it's in the config directory; elsewhere it's /var/crash
 
871
    which may be monitored by apport.  It can be overridden by
 
872
    $APPORT_CRASH_DIR.
 
873
    """
 
874
    if sys.platform == 'win32':
 
875
        return osutils.pathjoin(config_dir(), 'Crash')
 
876
    else:
 
877
        # XXX: hardcoded in apport_python_hook.py; therefore here too -- mbp
 
878
        # 2010-01-31
 
879
        return os.environ.get('APPORT_CRASH_DIR', '/var/crash')
 
880
 
 
881
 
 
882
def xdg_cache_dir():
 
883
    # See http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
 
884
    # Possibly this should be different on Windows?
 
885
    e = os.environ.get('XDG_CACHE_DIR', None)
 
886
    if e:
 
887
        return e
 
888
    else:
 
889
        return os.path.expanduser('~/.cache')
 
890
 
 
891
 
810
892
def _auto_user_id():
811
893
    """Calculate automatic user identification.
812
894
 
834
916
    try:
835
917
        import pwd
836
918
        uid = os.getuid()
837
 
        w = pwd.getpwuid(uid)
 
919
        try:
 
920
            w = pwd.getpwuid(uid)
 
921
        except KeyError:
 
922
            raise errors.BzrCommandError('Unable to determine your name.  '
 
923
                'Please use "bzr whoami" to set it.')
838
924
 
839
925
        # we try utf-8 first, because on many variants (like Linux),
840
926
        # /etc/passwd "should" be in utf-8, and because it's unlikely to give
845
931
            encoding = 'utf-8'
846
932
        except UnicodeError:
847
933
            try:
848
 
                gecos = w.pw_gecos.decode(bzrlib.user_encoding)
849
 
                encoding = bzrlib.user_encoding
 
934
                encoding = osutils.get_user_encoding()
 
935
                gecos = w.pw_gecos.decode(encoding)
850
936
            except UnicodeError:
851
937
                raise errors.BzrCommandError('Unable to determine your name.  '
852
938
                   'Use "bzr whoami" to set it.')
867
953
    except ImportError:
868
954
        import getpass
869
955
        try:
870
 
            realname = username = getpass.getuser().decode(bzrlib.user_encoding)
 
956
            user_encoding = osutils.get_user_encoding()
 
957
            realname = username = getpass.getuser().decode(user_encoding)
871
958
        except UnicodeDecodeError:
872
959
            raise errors.BzrError("Can't decode username as %s." % \
873
 
                    bzrlib.user_encoding)
 
960
                    user_encoding)
874
961
 
875
962
    return realname, (username + '@' + socket.gethostname())
876
963
 
887
974
def extract_email_address(e):
888
975
    """Return just the address part of an email string.
889
976
 
890
 
    That is just the user@domain part, nothing else. 
 
977
    That is just the user@domain part, nothing else.
891
978
    This part is required to contain only ascii characters.
892
979
    If it can't be extracted, raises an error.
893
980
 
906
993
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
907
994
 
908
995
    def __init__(self, branch):
909
 
        # XXX: Really this should be asking the branch for its configuration
910
 
        # data, rather than relying on a Transport, so that it can work 
911
 
        # more cleanly with a RemoteBranch that has no transport.
912
 
        self._config = TransportConfig(branch._transport, 'branch.conf')
 
996
        self._config = branch._get_config()
913
997
        self.branch = branch
914
998
 
915
999
    def _get_parser(self, file=None):
923
1007
            return self._config.get_option(name, section, default)
924
1008
        finally:
925
1009
            self.branch.unlock()
926
 
        return result
927
1010
 
928
1011
    def set_option(self, value, name, section=None):
929
1012
        """Set a per-branch configuration option"""
982
1065
        section[option_name] = value
983
1066
        self._save()
984
1067
 
985
 
    def get_credentials(self, scheme, host, port=None, user=None, path=None):
 
1068
    def get_credentials(self, scheme, host, port=None, user=None, path=None, 
 
1069
                        realm=None):
986
1070
        """Returns the matching credentials from authentication.conf file.
987
1071
 
988
1072
        :param scheme: protocol
994
1078
        :param user: login (optional)
995
1079
 
996
1080
        :param path: the absolute path on the server (optional)
 
1081
        
 
1082
        :param realm: the http authentication realm (optional)
997
1083
 
998
1084
        :return: A dict containing the matching credentials or None.
999
1085
           This includes:
1000
1086
           - name: the section name of the credentials in the
1001
1087
             authentication.conf file,
1002
 
           - user: can't de different from the provided user if any,
 
1088
           - user: can't be different from the provided user if any,
 
1089
           - scheme: the server protocol,
 
1090
           - host: the server address,
 
1091
           - port: the server port (can be None),
 
1092
           - path: the absolute server path (can be None),
 
1093
           - realm: the http specific authentication realm (can be None),
1003
1094
           - password: the decoded password, could be None if the credential
1004
1095
             defines only the user
1005
1096
           - verify_certificates: https specific, True if the server
1046
1137
            if a_user is None:
1047
1138
                # Can't find a user
1048
1139
                continue
 
1140
            # Prepare a credentials dictionary with additional keys
 
1141
            # for the credential providers
1049
1142
            credentials = dict(name=auth_def_name,
1050
1143
                               user=a_user,
 
1144
                               scheme=a_scheme,
 
1145
                               host=host,
 
1146
                               port=port,
 
1147
                               path=path,
 
1148
                               realm=realm,
1051
1149
                               password=auth_def.get('password', None),
1052
1150
                               verify_certificates=a_verify_certificates)
 
1151
            # Decode the password in the credentials (or get one)
1053
1152
            self.decode_password(credentials,
1054
1153
                                 auth_def.get('password_encoding', None))
1055
1154
            if 'auth' in debug.debug_flags:
1056
1155
                trace.mutter("Using authentication section: %r", auth_def_name)
1057
1156
            break
1058
1157
 
 
1158
        if credentials is None:
 
1159
            # No credentials were found in authentication.conf, try the fallback
 
1160
            # credentials stores.
 
1161
            credentials = credential_store_registry.get_fallback_credentials(
 
1162
                scheme, host, port, user, path, realm)
 
1163
 
1059
1164
        return credentials
1060
1165
 
1061
 
    def get_user(self, scheme, host, port=None,
1062
 
                 realm=None, path=None, prompt=None):
 
1166
    def set_credentials(self, name, host, user, scheme=None, password=None,
 
1167
                        port=None, path=None, verify_certificates=None,
 
1168
                        realm=None):
 
1169
        """Set authentication credentials for a host.
 
1170
 
 
1171
        Any existing credentials with matching scheme, host, port and path
 
1172
        will be deleted, regardless of name.
 
1173
 
 
1174
        :param name: An arbitrary name to describe this set of credentials.
 
1175
        :param host: Name of the host that accepts these credentials.
 
1176
        :param user: The username portion of these credentials.
 
1177
        :param scheme: The URL scheme (e.g. ssh, http) the credentials apply
 
1178
            to.
 
1179
        :param password: Password portion of these credentials.
 
1180
        :param port: The IP port on the host that these credentials apply to.
 
1181
        :param path: A filesystem path on the host that these credentials
 
1182
            apply to.
 
1183
        :param verify_certificates: On https, verify server certificates if
 
1184
            True.
 
1185
        :param realm: The http authentication realm (optional).
 
1186
        """
 
1187
        values = {'host': host, 'user': user}
 
1188
        if password is not None:
 
1189
            values['password'] = password
 
1190
        if scheme is not None:
 
1191
            values['scheme'] = scheme
 
1192
        if port is not None:
 
1193
            values['port'] = '%d' % port
 
1194
        if path is not None:
 
1195
            values['path'] = path
 
1196
        if verify_certificates is not None:
 
1197
            values['verify_certificates'] = str(verify_certificates)
 
1198
        if realm is not None:
 
1199
            values['realm'] = realm
 
1200
        config = self._get_config()
 
1201
        for_deletion = []
 
1202
        for section, existing_values in config.items():
 
1203
            for key in ('scheme', 'host', 'port', 'path', 'realm'):
 
1204
                if existing_values.get(key) != values.get(key):
 
1205
                    break
 
1206
            else:
 
1207
                del config[section]
 
1208
        config.update({name: values})
 
1209
        self._save()
 
1210
 
 
1211
    def get_user(self, scheme, host, port=None, realm=None, path=None,
 
1212
                 prompt=None, ask=False, default=None):
1063
1213
        """Get a user from authentication file.
1064
1214
 
1065
1215
        :param scheme: protocol
1072
1222
 
1073
1223
        :param path: the absolute path on the server (optional)
1074
1224
 
 
1225
        :param ask: Ask the user if there is no explicitly configured username 
 
1226
                    (optional)
 
1227
 
 
1228
        :param default: The username returned if none is defined (optional).
 
1229
 
1075
1230
        :return: The found user.
1076
1231
        """
1077
1232
        credentials = self.get_credentials(scheme, host, port, user=None,
1078
 
                                           path=path)
 
1233
                                           path=path, realm=realm)
1079
1234
        if credentials is not None:
1080
1235
            user = credentials['user']
1081
1236
        else:
1082
1237
            user = None
 
1238
        if user is None:
 
1239
            if ask:
 
1240
                if prompt is None:
 
1241
                    # Create a default prompt suitable for most cases
 
1242
                    prompt = scheme.upper() + ' %(host)s username'
 
1243
                # Special handling for optional fields in the prompt
 
1244
                if port is not None:
 
1245
                    prompt_host = '%s:%d' % (host, port)
 
1246
                else:
 
1247
                    prompt_host = host
 
1248
                user = ui.ui_factory.get_username(prompt, host=prompt_host)
 
1249
            else:
 
1250
                user = default
1083
1251
        return user
1084
1252
 
1085
1253
    def get_password(self, scheme, host, user, port=None,
1100
1268
 
1101
1269
        :return: The found password or the one entered by the user.
1102
1270
        """
1103
 
        credentials = self.get_credentials(scheme, host, port, user, path)
 
1271
        credentials = self.get_credentials(scheme, host, port, user, path,
 
1272
                                           realm)
1104
1273
        if credentials is not None:
1105
1274
            password = credentials['password']
1106
1275
            if password is not None and scheme is 'ssh':
1125
1294
        return password
1126
1295
 
1127
1296
    def decode_password(self, credentials, encoding):
1128
 
        return credentials
 
1297
        try:
 
1298
            cs = credential_store_registry.get_credential_store(encoding)
 
1299
        except KeyError:
 
1300
            raise ValueError('%r is not a known password_encoding' % encoding)
 
1301
        credentials['password'] = cs.decode_password(credentials)
 
1302
        return credentials
 
1303
 
 
1304
 
 
1305
class CredentialStoreRegistry(registry.Registry):
 
1306
    """A class that registers credential stores.
 
1307
 
 
1308
    A credential store provides access to credentials via the password_encoding
 
1309
    field in authentication.conf sections.
 
1310
 
 
1311
    Except for stores provided by bzr itself, most stores are expected to be
 
1312
    provided by plugins that will therefore use
 
1313
    register_lazy(password_encoding, module_name, member_name, help=help,
 
1314
    fallback=fallback) to install themselves.
 
1315
 
 
1316
    A fallback credential store is one that is queried if no credentials can be
 
1317
    found via authentication.conf.
 
1318
    """
 
1319
 
 
1320
    def get_credential_store(self, encoding=None):
 
1321
        cs = self.get(encoding)
 
1322
        if callable(cs):
 
1323
            cs = cs()
 
1324
        return cs
 
1325
 
 
1326
    def is_fallback(self, name):
 
1327
        """Check if the named credentials store should be used as fallback."""
 
1328
        return self.get_info(name)
 
1329
 
 
1330
    def get_fallback_credentials(self, scheme, host, port=None, user=None,
 
1331
                                 path=None, realm=None):
 
1332
        """Request credentials from all fallback credentials stores.
 
1333
 
 
1334
        The first credentials store that can provide credentials wins.
 
1335
        """
 
1336
        credentials = None
 
1337
        for name in self.keys():
 
1338
            if not self.is_fallback(name):
 
1339
                continue
 
1340
            cs = self.get_credential_store(name)
 
1341
            credentials = cs.get_credentials(scheme, host, port, user,
 
1342
                                             path, realm)
 
1343
            if credentials is not None:
 
1344
                # We found some credentials
 
1345
                break
 
1346
        return credentials
 
1347
 
 
1348
    def register(self, key, obj, help=None, override_existing=False,
 
1349
                 fallback=False):
 
1350
        """Register a new object to a name.
 
1351
 
 
1352
        :param key: This is the key to use to request the object later.
 
1353
        :param obj: The object to register.
 
1354
        :param help: Help text for this entry. This may be a string or
 
1355
                a callable. If it is a callable, it should take two
 
1356
                parameters (registry, key): this registry and the key that
 
1357
                the help was registered under.
 
1358
        :param override_existing: Raise KeyErorr if False and something has
 
1359
                already been registered for that key. If True, ignore if there
 
1360
                is an existing key (always register the new value).
 
1361
        :param fallback: Whether this credential store should be 
 
1362
                used as fallback.
 
1363
        """
 
1364
        return super(CredentialStoreRegistry,
 
1365
                     self).register(key, obj, help, info=fallback,
 
1366
                                    override_existing=override_existing)
 
1367
 
 
1368
    def register_lazy(self, key, module_name, member_name,
 
1369
                      help=None, override_existing=False,
 
1370
                      fallback=False):
 
1371
        """Register a new credential store to be loaded on request.
 
1372
 
 
1373
        :param module_name: The python path to the module. Such as 'os.path'.
 
1374
        :param member_name: The member of the module to return.  If empty or
 
1375
                None, get() will return the module itself.
 
1376
        :param help: Help text for this entry. This may be a string or
 
1377
                a callable.
 
1378
        :param override_existing: If True, replace the existing object
 
1379
                with the new one. If False, if there is already something
 
1380
                registered with the same key, raise a KeyError
 
1381
        :param fallback: Whether this credential store should be 
 
1382
                used as fallback.
 
1383
        """
 
1384
        return super(CredentialStoreRegistry, self).register_lazy(
 
1385
            key, module_name, member_name, help,
 
1386
            info=fallback, override_existing=override_existing)
 
1387
 
 
1388
 
 
1389
credential_store_registry = CredentialStoreRegistry()
 
1390
 
 
1391
 
 
1392
class CredentialStore(object):
 
1393
    """An abstract class to implement storage for credentials"""
 
1394
 
 
1395
    def decode_password(self, credentials):
 
1396
        """Returns a clear text password for the provided credentials."""
 
1397
        raise NotImplementedError(self.decode_password)
 
1398
 
 
1399
    def get_credentials(self, scheme, host, port=None, user=None, path=None,
 
1400
                        realm=None):
 
1401
        """Return the matching credentials from this credential store.
 
1402
 
 
1403
        This method is only called on fallback credential stores.
 
1404
        """
 
1405
        raise NotImplementedError(self.get_credentials)
 
1406
 
 
1407
 
 
1408
 
 
1409
class PlainTextCredentialStore(CredentialStore):
 
1410
    """Plain text credential store for the authentication.conf file."""
 
1411
 
 
1412
    def decode_password(self, credentials):
 
1413
        """See CredentialStore.decode_password."""
 
1414
        return credentials['password']
 
1415
 
 
1416
 
 
1417
credential_store_registry.register('plain', PlainTextCredentialStore,
 
1418
                                   help=PlainTextCredentialStore.__doc__)
 
1419
credential_store_registry.default_key = 'plain'
1129
1420
 
1130
1421
 
1131
1422
class BzrDirConfig(object):
1132
1423
 
1133
 
    def __init__(self, transport):
1134
 
        self._config = TransportConfig(transport, 'control.conf')
 
1424
    def __init__(self, bzrdir):
 
1425
        self._bzrdir = bzrdir
 
1426
        self._config = bzrdir._get_config()
1135
1427
 
1136
1428
    def set_default_stack_on(self, value):
1137
1429
        """Set the default stacking location.
1141
1433
        This policy affects all branches contained by this bzrdir, except for
1142
1434
        those under repositories.
1143
1435
        """
 
1436
        if self._config is None:
 
1437
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1144
1438
        if value is None:
1145
1439
            self._config.set_option('', 'default_stack_on')
1146
1440
        else:
1154
1448
        This policy affects all branches contained by this bzrdir, except for
1155
1449
        those under repositories.
1156
1450
        """
 
1451
        if self._config is None:
 
1452
            return None
1157
1453
        value = self._config.get_option('default_stack_on')
1158
1454
        if value == '':
1159
1455
            value = None
1204
1500
            configobj.setdefault(section, {})[name] = value
1205
1501
        self._set_configobj(configobj)
1206
1502
 
 
1503
    def _get_config_file(self):
 
1504
        try:
 
1505
            return StringIO(self._transport.get_bytes(self._filename))
 
1506
        except errors.NoSuchFile:
 
1507
            return StringIO()
 
1508
 
1207
1509
    def _get_configobj(self):
1208
 
        try:
1209
 
            return ConfigObj(self._transport.get(self._filename),
1210
 
                             encoding='utf-8')
1211
 
        except errors.NoSuchFile:
1212
 
            return ConfigObj(encoding='utf-8')
 
1510
        return ConfigObj(self._get_config_file(), encoding='utf-8')
1213
1511
 
1214
1512
    def _set_configobj(self, configobj):
1215
1513
        out_file = StringIO()