~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: 2009-10-06 20:45:48 UTC
  • mfrom: (4728.1.2 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20091006204548-bjnc3z4k256ppimz
MutableTree.has_changes() does not require a tree parameter anymore

Show diffs side-by-side

added added

removed removed

Lines of Context:
146
146
class Config(object):
147
147
    """A configuration policy - what username, editor, gpg needs etc."""
148
148
 
 
149
    def __init__(self):
 
150
        super(Config, self).__init__()
 
151
 
149
152
    def get_editor(self):
150
153
        """Get the users pop up editor."""
151
154
        raise NotImplementedError
174
177
        """Get a generic option - no special process, no default."""
175
178
        return self._get_user_option(option_name)
176
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
 
177
189
    def gpg_signing_command(self):
178
190
        """What program should be used to sign signatures?"""
179
191
        result = self._gpg_signing_command()
196
208
        """See log_format()."""
197
209
        return None
198
210
 
199
 
    def __init__(self):
200
 
        super(Config, self).__init__()
201
 
 
202
211
    def post_commit(self):
203
212
        """An ordered list of python functions to call.
204
213
 
299
308
class IniBasedConfig(Config):
300
309
    """A configuration policy that draws from ini files."""
301
310
 
 
311
    def __init__(self, get_filename):
 
312
        super(IniBasedConfig, self).__init__()
 
313
        self._get_filename = get_filename
 
314
        self._parser = None
 
315
 
302
316
    def _get_parser(self, file=None):
303
317
        if self._parser is not None:
304
318
            return self._parser
381
395
        """See Config.log_format."""
382
396
        return self._get_user_option('log_format')
383
397
 
384
 
    def __init__(self, get_filename):
385
 
        super(IniBasedConfig, self).__init__()
386
 
        self._get_filename = get_filename
387
 
        self._parser = None
388
 
 
389
398
    def _post_commit(self):
390
399
        """See Config.post_commit."""
391
400
        return self._get_user_option('post_commit')
709
718
                        trace.warning('Value "%s" is masked by "%s" from'
710
719
                                      ' branch.conf', value, mask_value)
711
720
 
712
 
 
713
721
    def _gpg_signing_command(self):
714
722
        """See Config.gpg_signing_command."""
715
723
        return self._get_safe_value('_gpg_signing_command')
813
821
    return osutils.pathjoin(config_dir(), 'ignore')
814
822
 
815
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
 
816
847
def _auto_user_id():
817
848
    """Calculate automatic user identification.
818
849
 
917
948
    # XXX: Really needs a better name, as this is not part of the tree! -- mbp 20080507
918
949
 
919
950
    def __init__(self, branch):
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')
 
951
        self._config = branch._get_config()
924
952
        self.branch = branch
925
953
 
926
954
    def _get_parser(self, file=None):
934
962
            return self._config.get_option(name, section, default)
935
963
        finally:
936
964
            self.branch.unlock()
937
 
        return result
938
965
 
939
966
    def set_option(self, value, name, section=None):
940
967
        """Set a per-branch configuration option"""
1083
1110
                trace.mutter("Using authentication section: %r", auth_def_name)
1084
1111
            break
1085
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
 
1086
1119
        return credentials
1087
1120
 
1088
1121
    def set_credentials(self, name, host, user, scheme=None, password=None,
1130
1163
        config.update({name: values})
1131
1164
        self._save()
1132
1165
 
1133
 
    def get_user(self, scheme, host, port=None,
1134
 
                 realm=None, path=None, prompt=None):
 
1166
    def get_user(self, scheme, host, port=None, realm=None, path=None,
 
1167
                 prompt=None, ask=False, default=None):
1135
1168
        """Get a user from authentication file.
1136
1169
 
1137
1170
        :param scheme: protocol
1144
1177
 
1145
1178
        :param path: the absolute path on the server (optional)
1146
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
 
1147
1185
        :return: The found user.
1148
1186
        """
1149
1187
        credentials = self.get_credentials(scheme, host, port, user=None,
1152
1190
            user = credentials['user']
1153
1191
        else:
1154
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
1155
1206
        return user
1156
1207
 
1157
1208
    def get_password(self, scheme, host, user, port=None,
1212
1263
    A credential store provides access to credentials via the password_encoding
1213
1264
    field in authentication.conf sections.
1214
1265
 
1215
 
    Except for stores provided by bzr itself,most stores are expected to be
 
1266
    Except for stores provided by bzr itself, most stores are expected to be
1216
1267
    provided by plugins that will therefore use
1217
1268
    register_lazy(password_encoding, module_name, member_name, help=help,
1218
 
    info=info) to install themselves.
 
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.
1219
1273
    """
1220
1274
 
1221
1275
    def get_credential_store(self, encoding=None):
1224
1278
            cs = cs()
1225
1279
        return cs
1226
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
 
1227
1343
 
1228
1344
credential_store_registry = CredentialStoreRegistry()
1229
1345
 
1232
1348
    """An abstract class to implement storage for credentials"""
1233
1349
 
1234
1350
    def decode_password(self, credentials):
1235
 
        """Returns a password for the provided credentials in clear text."""
 
1351
        """Returns a clear text password for the provided credentials."""
1236
1352
        raise NotImplementedError(self.decode_password)
1237
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
 
1238
1363
 
1239
1364
class PlainTextCredentialStore(CredentialStore):
1240
1365
    """Plain text credential store for the authentication.conf file."""
1251
1376
 
1252
1377
class BzrDirConfig(object):
1253
1378
 
1254
 
    def __init__(self, transport):
1255
 
        self._config = TransportConfig(transport, 'control.conf')
 
1379
    def __init__(self, bzrdir):
 
1380
        self._bzrdir = bzrdir
 
1381
        self._config = bzrdir._get_config()
1256
1382
 
1257
1383
    def set_default_stack_on(self, value):
1258
1384
        """Set the default stacking location.
1262
1388
        This policy affects all branches contained by this bzrdir, except for
1263
1389
        those under repositories.
1264
1390
        """
 
1391
        if self._config is None:
 
1392
            raise errors.BzrError("Cannot set configuration in %s" % self._bzrdir)
1265
1393
        if value is None:
1266
1394
            self._config.set_option('', 'default_stack_on')
1267
1395
        else:
1275
1403
        This policy affects all branches contained by this bzrdir, except for
1276
1404
        those under repositories.
1277
1405
        """
 
1406
        if self._config is None:
 
1407
            return None
1278
1408
        value = self._config.get_option('default_stack_on')
1279
1409
        if value == '':
1280
1410
            value = None
1325
1455
            configobj.setdefault(section, {})[name] = value
1326
1456
        self._set_configobj(configobj)
1327
1457
 
 
1458
    def _get_config_file(self):
 
1459
        try:
 
1460
            return self._transport.get(self._filename)
 
1461
        except errors.NoSuchFile:
 
1462
            return StringIO()
 
1463
 
1328
1464
    def _get_configobj(self):
1329
 
        try:
1330
 
            return ConfigObj(self._transport.get(self._filename),
1331
 
                             encoding='utf-8')
1332
 
        except errors.NoSuchFile:
1333
 
            return ConfigObj(encoding='utf-8')
 
1465
        return ConfigObj(self._get_config_file(), encoding='utf-8')
1334
1466
 
1335
1467
    def _set_configobj(self, configobj):
1336
1468
        out_file = StringIO()