Пример #1
0
import pluggy

from scenario_player.constants import HOST_NAMESPACE
from scenario_player.services.rpc.blueprints.instances import instances_blueprint
from scenario_player.services.rpc.blueprints.transactions import transactions_blueprint

__all__ = ["transactions_blueprint", "instances_blueprint"]


HOOK_IMPL = pluggy.HookimplMarker(HOST_NAMESPACE)


@HOOK_IMPL
def register_blueprints(app):
    for bp in (transactions_blueprint, instances_blueprint):
        app.register_blueprint(bp)
Пример #2
0
from typing import List, Any, Optional
import pluggy

from ert3.config import ConfigPluginRegistry

_PLUGIN_NAMESPACE = "ert3"

hook_implementation = pluggy.HookimplMarker(_PLUGIN_NAMESPACE)
hook_specification = pluggy.HookspecMarker(_PLUGIN_NAMESPACE)

# Imports below hook_implementation and hook_specification to avoid circular imports
import ert3.plugins.hook_specifications  # pylint: disable=C0413  # noqa: E402
import ert3.config.plugins.implementations  # pylint: disable=C0413  # noqa: E402


# type ignored due to pluggy lacking type information
class ErtPluginManager(pluggy.PluginManager):  # type: ignore
    def __init__(self, plugins: Optional[List[Any]] = None) -> None:
        super().__init__(_PLUGIN_NAMESPACE)
        self.add_hookspecs(ert3.plugins.hook_specifications)
        if plugins is None:
            self.register(ert3.config.plugins.implementations)
            self.load_setuptools_entrypoints(_PLUGIN_NAMESPACE)
        else:
            for plugin in plugins:
                self.register(plugin)

    def collect(self, registry: ConfigPluginRegistry) -> None:
        self.hook.configs(registry=registry)  # pylint: disable=E1101
Пример #3
0
We will emit deprecation warnings for one minor release before making changes to these objects.

If objects are marked experimental they might change between minor versions.

To override/modify tox behaviour via plugins see `tox.hookspec` and its use with pluggy.
"""
import pluggy

from . import exception
from .constants import INFO, PIP, PYTHON
from .hookspecs import hookspec
from .version import __version__

__all__ = (
    "__version__",  # tox version
    "cmdline",  # run tox as part of another program/IDE (same behaviour as called standalone)
    "hookimpl",  # Hook implementation marker to be imported by plugins
    "exception",  # tox specific exceptions
    # EXPERIMENTAL CONSTANTS API
    "PYTHON",
    "INFO",
    "PIP",
    # DEPRECATED - will be removed from API in tox 4
    "hookspec",
)

hookimpl = pluggy.HookimplMarker("tox")

# NOTE: must come last due to circular import
from .session import cmdline  # isort:skip
Пример #4
0
    They might change at any time; use at your own risk.
"""
from __future__ import annotations

from typing import TYPE_CHECKING

import pluggy

from nitpick.constants import PROJECT_NAME

if TYPE_CHECKING:
    from nitpick.plugins.base import NitpickPlugin
    from nitpick.plugins.info import FileInfo

hookspec = pluggy.HookspecMarker(PROJECT_NAME)
hookimpl = pluggy.HookimplMarker(PROJECT_NAME)

__all__ = ("hookimpl", "hookspec")


@hookspec
def plugin_class() -> type[NitpickPlugin]:
    """Return your plugin class here (it should inherit from :py:class:`nitpick.plugins.base.NitpickPlugin`)."""


@hookspec
def can_handle(info: FileInfo) -> type[NitpickPlugin] | None:  # pylint: disable=unused-argument
    """Return a valid :py:class:`nitpick.plugins.base.NitpickPlugin` instance or ``None``.

    :return: A plugin instance if your plugin handles this file info (path or any of its ``identify`` tags).
        Return ``None`` if your plugin doesn't handle this file or file type.
Пример #5
0
# -*- coding: utf-8 -*-
"""A photo booth application in pure Python for the Raspberry Pi."""

__version__ = "2.0.3"

try:

    import pluggy

    # Marker to be imported and used in plugins (and for own implementations)
    hookimpl = pluggy.HookimplMarker('pibooth')

except ImportError:
    pass  # When running the setup.py, pluggy is not yet installed
Пример #6
0
import pluggy
import hashlib
import py
import shutil
import os

try:
    from pip.download import PipSession
    from pip.req import parse_requirements
except ImportError:
    # Support for pip 10 - these have been moved to _internal
    from pip._internal.download import PipSession
    from pip._internal.req.req_file import parse_requirements

hookimpl = pluggy.HookimplMarker('tox')

req_option = '-r'

BOLD = '\033[1m'


@hookimpl
def tox_configure(config):
    set_envdir_for_envconfigs(config.envconfigs)


@hookimpl
def tox_runtest_pre(venv):
    print('{}{} virtualenv: {}{}'.format(BOLD, venv.name, venv.path, BOLD))
    create_virtualenv_symlink(str(venv.envconfig.original_envdir),
                              str(venv.envconfig.envdir))
Пример #7
0
import pluggy
from . import hookspecs

hookimpl = pluggy.HookimplMarker("nixops")
"""Marker to be imported and used in plugins (and for own implementations)"""


def get_plugin_manager():
    pm = pluggy.PluginManager("nixops")
    pm.add_hookspecs(hookspecs)
    pm.load_setuptools_entrypoints("nixops")
    return pm
Пример #8
0
import pluggy

hookimpl = pluggy.HookimplMarker('pyfileconf')
Пример #9
0
"""
`pluggy` plugin and hook management
"""
import pluggy
import contextlib
from . import hookspec

hookimpl = pluggy.HookimplMarker("pysipp")
mng = pluggy.PluginManager("pysipp", implprefix="pysipp")
mng.add_hookspecs(hookspec)


@contextlib.contextmanager
def register(plugins):
    """Temporarily register plugins"""
    try:
        if any(plugins):
            for p in plugins:
                mng.register(p)
        yield
    finally:
        if any(plugins):
            for p in plugins:
                mng.unregister(p)
Пример #10
0
    if not os.path.exists(zvt_env['cache_path']):
        os.makedirs(zvt_env['cache_path'])  

    # create default config.json if not exist
    config_path = os.path.join(zvt_home, 'config.json')
    if not os.path.exists(config_path):
        from shutil import copyfile
        copyfile(os.path.abspath(os.path.join(os.path.dirname(__file__), 'samples', 'config.json')), config_path)

    with open(config_path) as f:
        config_json = json.load(f)
        for k in config_json:
            zvt_env[k] = config_json[k]

    init_log(file_name='analysis.log')

    # import pprint
    # pprint.pprint(zvt_env)


init_env(zvt_home=ZVT_HOME)

import zvt.domain as domain

import pluggy

hookimpl = pluggy.HookimplMarker("zvt")
"""Marker to be imported and used in plugins (and for own implementations)"""

__all__ = ['domain', 'zvt_env', 'init_log', 'init_env']
Пример #11
0
import pluggy

hookimpl = pluggy.HookimplMarker("cdsdashboards")
"""Marker to be imported and used in plugins (and for own implementations)"""


Пример #12
0
from typing import Any, Callable, TypeVar, cast

import pluggy  # type: ignore

F = TypeVar("F", bound=Callable[..., Any])

hookimpl = cast(Callable[[F], F],
                pluggy.HookimplMarker("python_plugin_example"))
Пример #13
0
import os
import pluggy
from coinrat.market_plugins import MarketPluginSpecification
from coinrat.synchronizer_plugins import SynchronizerPluginSpecification
from .synchronizer import BittrexSynchronizer

from .market import bittrex_market_factory, MARKET_NAME, BittrexMarket

get_name_impl = pluggy.HookimplMarker('market_plugins')
get_available_markets_spec = pluggy.HookimplMarker('market_plugins')
get_market_impl = pluggy.HookimplMarker('market_plugins')
get_market_class_impl = pluggy.HookimplMarker('market_plugins')
get_description_impl = pluggy.HookimplMarker('market_plugins')
does_support_market_impl = pluggy.HookimplMarker('market_plugins')

PLUGIN_NAME = 'coinrat_bittrex'
SYNCHRONIZER_NAME = 'bittrex'

bittrex_market = bittrex_market_factory(os.environ.get('BITREX_KEY'),
                                        os.environ.get('BITREX_SECRET'))
get_available_synchronizers_spec = pluggy.HookimplMarker(
    'synchronizer_plugins')
get_synchronizer_impl = pluggy.HookimplMarker('synchronizer_plugins')


class MarketPlugin(MarketPluginSpecification):
    @get_description_impl
    def get_description(self):
        return 'Native implementation of Bittrex using bittrex API 1.1 and 2.0.'

    @get_name_impl
Пример #14
0
"""Plugin Machinery"""
import logging

from pkg_resources import iter_entry_points
import pluggy

_missing = object()
_logger = logging.getLogger('zgres')

hookspec = pluggy.HookspecMarker('zgres')
subscribe = pluggy.HookimplMarker('zgres')


def load(config, section):
    """Gets the plugin factories from the config file.

    Plugins are sorted by the order they are specified in the config file.
    """
    plugin_names = [
        c.strip() for c in config[section].get('plugins', '').split()
        if c.strip()
    ]
    seen = set([])
    for i in plugin_names:
        if i in seen:
            raise AssertionError(
                'Duplicate plugin in config: [{}]{} = {}'.format(
                    config_section, group, i))
        seen.add(i)
    plugins = {}
    available_plugins = []
Пример #15
0
import pluggy

hookspec = pluggy.HookspecMarker('ttt')
hookimpl = pluggy.HookimplMarker('ttt')


class MySpec:
    @hookspec
    def first_hook(self, arg1, arg2, arg3):
        pass

    @hookspec
    def second_hook(self, arg1, arg2, arg3):
        pass

    @hookspec
    def third_hook(self, arg1, arg2, arg3):
        pass


class Plugin1:
    # may be module with hook functions
    @hookimpl
    def first_hook(self, arg1, arg2, arg3):
        print(self.__class__, arg1, arg2, arg3)
        return '1: ' + str(arg1 + arg2 + arg3)

    @hookimpl
    def second_hook(self, arg1, arg2, arg3):
        print(self.__class__, arg1, arg2, arg3)
        return '2: ' + str(arg1 + arg2 + arg3)
Пример #16
0
import logging
from typing import Dict

import pluggy

from ._base import DugElement, DugConcept, Indexable, Parser, FileParser
from .dbgap_parser import DbGaPParser
from .topmed_tag_parser import TOPMedTagParser

logger = logging.getLogger('dug')

hookimpl = pluggy.HookimplMarker("dug")


@hookimpl
def define_parsers(parser_dict: Dict[str, Parser]):
    parser_dict["dbgap"] = DbGaPParser()
    parser_dict["topmedtag"] = TOPMedTagParser()


class ParserNotFoundException(Exception):
    ...


def get_parser(hook, parser_name) -> Parser:
    """Get the parser from all parsers registered via the define_parsers hook"""

    available_parsers = {}
    hook.define_parsers(parser_dict=available_parsers)
    parser = available_parsers.get(parser_name.lower())
    if parser is not None:
Пример #17
0
"""
Example plugin for testing plugin discovery and loading
"""
import pluggy

napari_hook_implementation = pluggy.HookimplMarker("napari")


def reader_function():
    pass


@napari_hook_implementation
def napari_get_reader(path):
    if path.endswith('true'):
        return reader_function
Пример #18
0
# Copyright 2017 Palantir Technologies, Inc.
from future.standard_library import install_aliases
import pluggy
from ._version import get_versions

install_aliases()
__version__ = get_versions()['version']
del get_versions

PYLS = 'pyls'

hookspec = pluggy.HookspecMarker(PYLS)
hookimpl = pluggy.HookimplMarker(PYLS)
Пример #19
0
## Plugins: __init__.py
import pluggy

decoderHookImpl = pluggy.HookimplMarker("decoder")
parserHookImpl = pluggy.HookimplMarker("parser")
Пример #20
0
import subprocess
import sys
from pathlib import Path

# Custom featured needed
import gi
import pluggy
import todotxtio
from alert import Alert
from configurator import Configuration
from gi.repository import Gtk
from hooks import IndicatorSpec

# Decorator for hook. The function that was decorated with this
# will be called from de master source if it in Hookspecks availables
indicatorimpl = pluggy.HookimplMarker("indicator")

try:
    gi.require_version("Gtk", "3.0")
    gi.require_version("Gdk", "3.0")
    gi.require_version("AppIndicator3", "0.1")
except Exception as e:
    print(e)
    exit(-1)


class ExportingHistory(IndicatorSpec):
    def __init__(self, ):
        configuration = Configuration()
        preferences = configuration.get("preferences")
        parent_folder = Path(os.path.expanduser(
Пример #21
0
import pluggy

spec = pluggy.HookspecMarker('addok')
register = pluggy.HookimplMarker('addok')


@spec
def addok_register_api_endpoint(api):
    """Add new endpoints to Addok API."""
    pass


@spec
def addok_register_api_middleware(middlewares):
    """Add new endpoints to Addok API."""
    pass


@spec
def addok_preconfigure(config):
    """Configure addok by patching config object before user local config."""


@spec
def addok_configure(config):
    """Configure addok by patching config object after user local config."""


@spec
def addok_register_command(subparsers):
    """Register command for Addok CLI."""
Пример #22
0
"""Hook specifications and containers."""
import collections
import enum

from typing import Optional, Mapping, Any

import pluggy  # type: ignore

from repobee_plug import log

hookspec = pluggy.HookspecMarker(__package__)
hookimpl = pluggy.HookimplMarker(__package__)


class Status(enum.Enum):
    """Status codes enums for Results.

    Attributes:
        SUCCESS: Signifies a plugin execution without any complications.
        WARNING: Signifies a plugin execution with non-critical failures.
        ERROR: Signifies a critical error during execution.
    """

    SUCCESS = "success"
    WARNING = "warning"
    ERROR = "error"


class Result(
    collections.namedtuple("Result", ("name", "status", "msg", "data"))
):
Пример #23
0
    @hookimpl
    def announce_plugin() -> Union[
        Tuple[str, Type[HTTPBasicAuth], Type[PreparedRequest], Type[Response]], None
    ]:
        return "uberex", UberExAuth, UberExRequest, UberExResponse
"""
# Built-in
from typing import Tuple, Type, Union

# Third-party
import pluggy
from requests import PreparedRequest, Response
from requests.auth import AuthBase, HTTPBasicAuth

hookspec = pluggy.HookspecMarker("bitex")
hookimpl = pluggy.HookimplMarker("bitex")


class AnnouncePluginHookSpec:
    @hookspec
    def announce_plugin(
        self,
    ) -> Union[Tuple[str, Type[AuthBase], Type[PreparedRequest], Type[Response]], None]:
        """Announce plugin classes to :mod:`bitex-framework`.

        The function should return a tuple with the following items:

            * the exchange name this plugin is for
            * the auth class to use when generating authentication signatures for it
            * the prepared request class to use when prepping for transmission
            * the response class to use when generating a response from the exchange.
Пример #24
0
import pluggy

from coinrat.portfolio_snapshot_storage_plugins import PortfolioSnapshotStoragePluginSpecification
from coinrat_influx_db_storage.portfolio_snapshot_storage import PORTFOLIO_SNAPSHOT_STORAGE_NAME
from .di_container_influx_db_storage import DiContainerInfluxDbStorage
from .candle_storage import CANDLE_STORAGE_NAME
from .order_storage import ORDER_STORAGE_NAME, MEASUREMENT_ORDERS_NAMES
from coinrat.candle_storage_plugins import CandleStoragePluginSpecification
from coinrat.order_storage_plugins import OrderStoragePluginSpecification

get_name_impl = pluggy.HookimplMarker('storage_plugins')

get_available_candle_storages_impl = pluggy.HookimplMarker('storage_plugins')
get_candle_storage_impl = pluggy.HookimplMarker('storage_plugins')

get_available_order_storages_impl = pluggy.HookimplMarker('storage_plugins')
get_order_storage_impl = pluggy.HookimplMarker('storage_plugins')

get_available_portfolio_snapshot_storages_impl = pluggy.HookimplMarker(
    'storage_plugins')
get_portfolio_snapshot_storage_impl = pluggy.HookimplMarker('storage_plugins')

PACKAGE_NAME = 'coinrat_influx_db_storage'

di_container = DiContainerInfluxDbStorage()


class CandleStoragePlugin(CandleStoragePluginSpecification):
    @get_name_impl
    def get_name(self):
        return PACKAGE_NAME
Пример #25
0
import os
from pathlib import Path

import pluggy
import todotxtio
from configurator import Configuration

# Custom featured needed
from hooks import ListBoxRowTodoSpec

# Decorator for hook. The function that was decorated with this
# will be called from de master source if it in Hookspecks availables
list_box_todospec = pluggy.HookimplMarker("list_box_todo")


class TrackingHistory(ListBoxRowTodoSpec):
    """A hook implementation namespace.
    """
    def __init__(self):
        configuration = Configuration()
        preferences = configuration.get("preferences")
        self.todo_histoy = (Path(os.path.expanduser(
            preferences["todo-file"])).parent.as_posix() + os.sep +
                            "todo.history.txt")
        todo_histoy_path = Path(self.todo_histoy)
        if not todo_histoy_path.exists():
            todo_histoy_path.touch()

    @list_box_todospec
    def after_track_time(self, todo, before_started_at, after_started_at,
                         total_time, just_now):
Пример #26
0
import pluggy

hookimpl = pluggy.HookimplMarker("eggsample")
"""Marker to be imported and used in plugins (and for own implementations)"""
Пример #27
0
from typing import Any, Callable, TypeVar, cast

import pluggy  # type: ignore

F = TypeVar("F", bound=Callable[..., Any])
hookimpl = cast(Callable[[F], F], pluggy.HookimplMarker("ape"))
hookspec = pluggy.HookspecMarker("ape")

plugin_manager = pluggy.PluginManager("ape")
"""A manager responsible for registering and accessing plugins (singleton)."""


class PluginType:
    """
    The base plugin class in ape. There are several types of plugins available in ape, such
    as the :class:`~ape.plugins.config.Config` or :class:`~ape.plugins.network.EcosystemPlugin`.
    Each one of them subclass this class. It is used to namespace the plugin hooks for the
    registration process, and to ensure overall conformance to type interfaces as much as possible.
    """
Пример #28
0
import importlib
import inspect
import pkgutil
from abc import ABC, abstractmethod

import pluggy

from savedit import plugins

PLUGINS = {}
FAILED_PLUGINS = set()
PluginManager = pluggy.PluginManager('savedit')
hookspec = pluggy.HookspecMarker('savedit')
hookimpl = pluggy.HookimplMarker('savedit')


def import_plugins():
    plugin_path, plugin_name = plugins.__path__, plugins.__name__ + '.'

    for _, name, _ in pkgutil.walk_packages(plugin_path, plugin_name):
        try:
            importlib.import_module(name)
        except ModuleNotFoundError:
            FAILED_PLUGINS.add(name)


def load_plugins(config):
    import_plugins()
    services = []

    for p in config['plugins']:
Пример #29
0
registered with the PluginMagager, the PluginManager gets the Plugin's class object
rather than an instance of that class. Also notice that all of the hooks are
``@staticmethod``\ s. As a result, they can be called directly off of the class object,
and only have access to the state passed into them to perform their function. This is a
deliberate design choice to keep the plugin system simple and to preclude a large class
of potential bugs. At some point it may make sense to revisit this.
"""
from typing import Dict, Union

import pluggy

from armi import pluginManager
from armi.utils import flags

HOOKSPEC = pluggy.HookspecMarker("armi")
HOOKIMPL = pluggy.HookimplMarker("armi")


class ArmiPlugin:
    """
    An ArmiPlugin provides a namespace to collect hook implementations provided by a
    single "plugin". This API is incomplete, unstable, and expected to change
    dramatically!
    """
    @staticmethod
    @HOOKSPEC
    def exposeInterfaces(cs):
        """
        Function for exposing interface(s) to other code.

        Returns
Пример #30
0
import pluggy
import requests

from coinrat.synchronizer_plugins import SynchronizerPluginSpecification
from .synchronizer import CryptocompareSynchronizer, SYNCHRONIZER_NAME

get_name_impl = pluggy.HookimplMarker('synchronizer_plugins')
get_available_synchronizers_spec = pluggy.HookimplMarker('synchronizer_plugins')
get_synchronizer_impl = pluggy.HookimplMarker('synchronizer_plugins')

PACKAGE_NAME = 'coinrat_cryptocompare'


class SynchronizerPlugin(SynchronizerPluginSpecification):
    @get_name_impl
    def get_name(self):
        return PACKAGE_NAME

    @get_available_synchronizers_spec
    def get_available_synchronizers(self):
        return [SYNCHRONIZER_NAME]

    @get_synchronizer_impl
    def get_synchronizer(self, synchronizer_name, storage, event_emitter):
        if synchronizer_name == SYNCHRONIZER_NAME:
            return CryptocompareSynchronizer(storage, event_emitter, requests.session())

        raise ValueError('Synchronizer "{}" not supported by this plugin.'.format(synchronizer_name))


synchronizer_plugin = SynchronizerPlugin()