import pkg_resources


def init_datastore(config):
    """
    Take the config definition and initialize the datastore.

    The config must contain either a 'datastore' parameter, which
    will be simply returned, or
    must contain a 'factory' which is a callable or entry
    point definition. The callable should take the remainder of
    the params in config as kwargs and return a DataStore instance.
    """
    if 'datastore' in config:
        # the datastore has already been initialized, just use it.
        return config['datastore']
    factory = config.pop('factory')
    if isinstance(factory, str):
        """
        factory should be a string defined in the pkg_resources.EntryPoint
        format.
        """
        factory = pkg_resources.EntryPoint.parse('x=' + factory).resolve()
    return factory(**config)