Exemple #1
0
def get_plugin(category, name):
    """
    Return an instance of the class registered under the given name and
    for the specified plugin category.

    :param category: the plugin category to load the plugin from, e.g. 'transports'.
    :param name: the name of the plugin
    """
    group = 'aiida.{}'.format(category)

    eps = [ep for ep in epm.iter_entry_points(group=group) if ep.name == name]

    if not eps:
        raise MissingPluginError("No plugin named '{}' found for '{}'".format(
            name, category))

    if len(eps) > 1:
        raise MissingPluginError(
            "Multiple plugins found for '{}' in '{}'".format(name, category))

    entrypoint = eps[0]

    try:
        plugin = entrypoint.load()
    except ImportError as exception:
        import traceback
        raise LoadingPluginFailed("Loading the plugin '{}' failed:\n{}".format(
            name, traceback.format_exc()))

    return plugin
def get_entry_point_from_class(class_module, class_name):
    """
    Given the module and name of a class, attempt to obtain the corresponding entry point if it exists

    :param class_module: module of the class
    :param class_name: name of the class
    :return: a tuple of the corresponding group and entry point or None if not found
    """
    prefix = 'JobProcess_'

    # Curiosity of the dynamically generated JobProcess classes
    if class_name.startswith(prefix):
        class_path = class_name[len(prefix):]
        class_module, class_name = class_path.rsplit('.', 1)

    for group in epm.get_entry_map().keys():
        for entry_point in epm.iter_entry_points(group):

            if entry_point.module_name != class_module:
                continue

            for entry_point_class_name in entry_point.attrs:
                if entry_point_class_name == class_name:
                    return group, entry_point

    return None, None
def get_entry_points(group):
    """
    Return a list of all the entry points within a specific group

    :param group: the entry point group
    :return: a list of entry points
    """
    return [ep for ep in epm.iter_entry_points(group=group)]
Exemple #4
0
def plugin_list(category):
    """
    Get a list of plugins for the given category.

    Passing `example` for the category will list all plugins registered under the
    entry point `aiida.example`.
    """
    group = 'aiida.{}'.format(category)

    return [ep.name for ep in epm.iter_entry_points(group=group)]
Exemple #5
0
def get_db_test_list():
    """
    This function returns the db_test_list for the current backend,
    merged with the 'common' tests.

    :note: This function should be called only after setting the
      backend, and then it returns only the tests for this backend, and the common ones.
    """
    from aiida.backends import settings
    from aiida.common.exceptions import ConfigurationError
    from collections import defaultdict

    current_backend = settings.BACKEND
    try:
        be_tests = db_test_list[current_backend]
    except KeyError:
        raise ConfigurationError("No backend configured yet")

    # Could be undefined, so put to empty dict by default
    try:
        common_tests = db_test_list["common"]
    except KeyError:
        raise ConfigurationError("A 'common' key must always be defined!")

    retdict = defaultdict(list)
    for k, tests in common_tests.iteritems():
        for t in tests:
            retdict[k].append(t)
    for k, tests in be_tests.iteritems():
        for t in tests:
            retdict[k].append(t)

    # This is a temporary solution to be able to run tests in plugins. Once the plugin fixtures
    # have been made working and are released, we can replace this logic with them
    for ep in [ep for ep in epm.iter_entry_points(group='aiida.tests')]:
        retdict[ep.name].append(ep.module_name)

    # Explode the dictionary so that if I have a.b.c,
    # I can run it also just with 'a' or with 'a.b'
    final_retdict = defaultdict(list)
    for k, v in retdict.iteritems():
        final_retdict[k] = v
    for k, v in retdict.iteritems():
        if '.' in k:
            parts = k.split('.')
            for last_idx in range(1, len(parts)):
                parentkey = ".".join(parts[:last_idx])
                final_retdict[parentkey].extend(v)

    return dict(final_retdict)
Exemple #6
0
def main(with_noreg):
    """Test automatic scanning / registering"""
    entry_point_map = manager.get_entry_map(
        groups='reentry_test',
        ep_names=['test-plugin', 'test-noreg', 'builtin'])
    data_file = py_path.local(get_datafile())

    assert entry_point_map, 'The test plugin entry point were not found\nMap:\n{}\n\nData File: {}\n\nContents:\n{}'.format(
        manager.get_entry_map(), data_file.strpath, data_file.read())

    try:
        test_entry_point = entry_point_map['reentry_test']['test-plugin']
        builtin_entry_point = entry_point_map['reentry_test']['builtin']
        if with_noreg:
            noreg_entry_point = entry_point_map['reentry_test']['test-noreg']
    except Exception as err:
        print('datafile: {}'.format(data_file.strpath))
        print('\nCurrent relevant entry point map:\n\n')
        print(manager.format_map(entry_point_map))
        print('\n')
        scan_map = manager.scan(groups=['reentry_test'], nocommit=True)
        print('\nFull entry point map after scan:\n\n')
        print(manager.format_map(scan_map))
        raise err

    plugin_class = test_entry_point.load()
    builtin_class = builtin_entry_point.load()

    assert plugin_class.test_string == 'TEST', 'The test string was incorrect'
    assert builtin_class.test_string == 'TEST', 'The test string was incorrect'
    if with_noreg:
        noreg_class = noreg_entry_point.load()
        assert noreg_class.test_string == 'TEST', 'The test string was incorrect'

    plugin_list = [
        ep.load() for ep in manager.iter_entry_points('reentry_test')
    ]
    assert plugin_class in plugin_list, 'iter_entry_points found differing test entry point from get_entry_map.'
    assert builtin_class in plugin_list, 'iter_entry_points found differing test entry point from get_entry_map.'
    if with_noreg:
        assert noreg_class in plugin_list, 'iter_entry_points found differing test entry point from get_entry_map.'
def get_class_to_entry_point_map(short_group_name=False):
    """
    create a mapping of modules to entry point groups / names

    :param short_group_name: bool, if True the leading 'aiida.' is cut off group names
    :return: dictionary, keys are modules, values are (group, entrypoint-name)
    """
    groups = (g for g in epm.get_entry_map('aiida-core').iterkeys() if g.startswith('aiida'))
    class_ep_map = {}
    for group in groups:
        for ep in epm.iter_entry_points(group):
            for classname in ep.attrs:
                key = '.'.join([ep.module_name, classname])
                if short_group_name:
                    groupname = '.'.join(group.split('.')[1:])
                else:
                    groupname = group
                value = (groupname, ep.name)
                class_ep_map[key] = value
    # ~ module_ep_map = {'.'.join([ep.module_name, ep.attrs]): (group, ep.name) for group in groups for ep in iter_entry_points(group)}
    return class_ep_map
Exemple #8
0
def get_db_test_names():
    retlist = []
    for backend in db_test_list:
        for name in db_test_list[backend]:
            retlist.append(name)

    # This is a temporary solution to be able to run tests in plugins. Once the plugin fixtures
    # have been made working and are released, we can replace this logic with them
    for ep in [ep for ep in epm.iter_entry_points(group='aiida.tests')]:
        retlist.append(ep.name)

    # Explode the list so that if I have a.b.c,
    # I can run it also just with 'a' or with 'a.b'
    final_list = [_ for _ in retlist]
    for k in retlist:
        if '.' in k:
            parts = k.split('.')
            for last_idx in range(1, len(parts)):
                parentkey = ".".join(parts[:last_idx])
                final_list.append(parentkey)

    # return the list of possible names, without duplicates
    return sorted(set(final_list))
Exemple #9
0

def get_config_files(ctx, file_name):
    possible_config_files = [
        '/etc/%s/%s' % (ctx.info_name, file_name),
        '/usr/local/etc/%s/%s' % (ctx.info_name, file_name),
        os.path.join(click.get_app_dir(ctx.info_name), file_name),
    ]
    config_files = []
    for config_file in possible_config_files:
        if os.path.isfile(config_file):
            config_files.append(config_file)
    return config_files


@with_plugins(entry_pt_manager.iter_entry_points('chaos.cli.commands'))
@click.group()
@click.option('--verbose',
              '-v',
              'log_level',
              flag_value='info',
              help='set log level to info',
              envvar='CHAOS_LOG_LEVEL')
@click.option('--debug',
              '-d',
              'log_level',
              flag_value='debug',
              help='set log level to debug',
              envvar='CHAOS_LOG_LEVEL')
@click.option('--config',
              'alternative_config',
Exemple #10
0
def get_plugins(category):
    """
    Get a list of plugins for the given category
    """
    return [ep.name for ep in epm.iter_entry_points(group=category)]