class TestSpec: # pylint: disable=too-few-public-methods """A hook specification namespace.""" hookspec = pluggy.HookspecMarker("test") @hookspec(firstresult=True) def visualize_data(self, api): """
class PlcDriverClassLoader: """Hook spec for PLC4PY Driver Loaders""" hookspec = pluggy.HookspecMarker("plc4py") @staticmethod @hookspec def get_driver() -> Type[PlcDriver]: """Returns the PlcConnection class that is used to instantiate the driver""" @staticmethod @hookspec def key() -> str: """Unique key to identify the driver"""
import pluggy hookspec = pluggy.HookspecMarker("threatbus.app") @hookspec def run(config, logging, inq, subscribe_callback, unsubscribe_callback): """Runs / starts a plugin spec with a configuration object @param config A configuration object for the app @param logging A configuration object for the logger @param inq A queue in which this plugin puts incoming messages @param subscribe_callback A callback to use by a plugin to notify about new subscriptions @param unsubscribe_callback A callback to use by a plugin to notify about subscription revocations """ @hookspec def snapshot(snapshot_type, result_q, time_delta): """Requests a snapshot from the implementing plugin. Snapshot are returned up to the requested earliest date. Results are put to the result_q. @param snapshot_type @see threatbus.data.MessageType @param result_q Snapshot results are forwarded to this queue @param time_delta A datetime.timedelta object to mark the snapshot size """
"""Hook specifications for tox - see https://pluggy.readthedocs.io/""" import pluggy hookspec = pluggy.HookspecMarker("tox") @hookspec def tox_addoption(parser): """ add command line options to the argparse-style parser object.""" @hookspec def tox_configure(config): """Called after command line options are parsed and ini-file has been read. Please be aware that the config object layout may change between major tox versions. """ @hookspec(firstresult=True) def tox_package(session, venv): """Return the package to be installed for the given venv. Called once for every environment.""" @hookspec(firstresult=True) def tox_get_python_executable(envconfig): """Return a python executable for the given python base name. The first plugin/hook which returns an executable path will determine it.
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. """
@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
from derex.runner.project import Project from typing import Dict from typing import List from typing import Union import pluggy hookspec = pluggy.HookspecMarker("derex.runner") @hookspec def compose_options() -> Dict[str, Union[str, float, int, List[str]]]: """Return a dict describing how to add this plugin. The dict `name` and `priority` keys will be used to determine ordering. The `variant` key can have values `services` or `openedx`. The `options` key contains a list of strings pointing to docker-compose yml files suitable to be passed as options to docker-compose. Example: .. code-block:: python { "name": "addon", "priority": ">derex-local", "variant": "openedx", "options": ["-f", "/path/to/docker-compose.yml"], } """
""" Standard events for the epydemic models. Event specifications are defined using the pluggy @hookspec decorator. Event implementations are contained in classes and defined using the pluggy @hookimp decorator. """ import pluggy import covidsim.models hookspec = pluggy.HookspecMarker("infectionmodel") @hookspec def track_infection_event(infecting_node, exposed_node, day, results, graph): """ Fires after an infection occurs :param infecting_node: Node that has just spread the infection :param exposed_node: Node that has just become infected :param day: Integer day of infection run :param results: Results collection object :param graph: Optional graph for the model :return: """ @hookspec def track_remove_event(removed_node, day, results, graph): """
import pluggy hookspec = pluggy.HookspecMarker("adapter") class TestSpec(object): @hookspec def testhook(self): """My special little hook that you can customize."""
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']:
''' hookspec defs ''' import pluggy hookspec = pluggy.HookspecMarker('pysipp') # UA factory hooks @hookspec def pysipp_pre_ua_defaults(ua): """Called prior to default ua cmd line arguments being assigned. Only a subset of `pysipp.UserAgent` attributes can be assigned. """ @hookspec def pysipp_post_ua_defaults(ua): """Called just after all default ua cmdline args have been assigned. Any attribute can be overridden on `ua`. """ # Scenario hooks @hookspec def pysipp_load_scendir(path, xmls, confpy): """Called once for every scenario directory that is scanned and loaded by `pysipp.load.iter_scen_dirs`. The `xmls` arg is a list of path strings and `confpy` is the imported conf.py module if one exists or None. A single implementation of this hook must return `True` to include the
import pluggy decoderHookSpec = pluggy.HookspecMarker("decoder") parserHookSpec = pluggy.HookspecMarker("parser") class DecoderSpec(object): @decoderHookSpec def setup(self, arch): pass @decoderHookSpec def decode(self, instrObj_temp): pass class ParserSpec(object): @parserHookSpec def setup(self, trace, arch): pass @parserHookSpec def __iter__(self): pass
"""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")) ):
import pluggy from typing import List, Set, cast from coinrat.event.event_emitter import EventEmitter from .plugins import PluginSpecification, plugins_loader from .domain import MarketStateSynchronizer from .domain.candle import CandleStorage get_name_spec = pluggy.HookspecMarker('coinrat_plugins') get_available_synchronizers_spec = pluggy.HookspecMarker('coinrat_plugins') get_synchronizer_spec = pluggy.HookspecMarker('coinrat_plugins') class SynchronizerPluginSpecification(PluginSpecification): @get_name_spec def get_name(self): raise NotImplementedError() @get_available_synchronizers_spec def get_available_synchronizers(self): raise NotImplementedError() @get_synchronizer_spec def get_synchronizer(self, synchronizer_name, storage, event_emitter): raise NotImplementedError() class SynchronizerNotProvidedByAnyPluginException(Exception): pass
# 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)
Copyright (c) 2019 The Fuel Rats Mischief, All rights reserved. Licensed under the BSD 3-Clause License. See LICENSE.md """ import typing import pluggy from ._constants import _PLUGIN_NAME from .datamodel import ConfigRoot VALIDATOR_SPEC = pluggy.HookspecMarker(_PLUGIN_NAME) REHASH_SPEC = pluggy.HookspecMarker(_PLUGIN_NAME) # noinspection PyUnusedLocal @VALIDATOR_SPEC def validate_config(data: typing.Dict): # pylint: disable=unused-argument """ Validate new configuration data. Args: data (typing.Dict): new configuration data to validate Raises: ValueError: config section failed to validate. KeyError: config section failed to validate.
# -*- coding: utf-8 -*- import pluggy hookspec = pluggy.HookspecMarker('pibooth') #--- Pibooth state-independent hooks ------------------------------------------ @hookspec def pibooth_configure(cfg): """Actions performed after loading of the configuration file. The ``cfg`` object is an instance of :py:class:`ConfigParser` class. :param cfg: loaded configuration """ @hookspec def pibooth_startup(cfg, app): """Actions performed at the startup of pibooth. :param cfg: application cfg :param app: application instance """ @hookspec def pibooth_setup_picture_factory(cfg, opt_index, factory): """Hook used to setup the ``PictureFactory`` instance.
from pathlib import Path from typing import BinaryIO, List, Optional import fastapi import pluggy import quetz from quetz.condainfo import CondaInfo hookspec = pluggy.HookspecMarker("quetz") @hookspec def register_router() -> 'fastapi.APIRouter': """add extra endpoints to the url tree. It should return an :py:class:`fastapi.APIRouter` with new endpoints definitions. By default it will be added to the root of the urlscheme""" @hookspec def post_add_package_version(version: 'quetz.db_models.PackageVersion', condainfo: 'quetz.condainfo.CondaInfo') -> None: """hook for post-processsing after adding a package file. :param quetz.db_models.PackageVersion version: package version model that was added in to the database :param quetz.condainfo.CondaInfo condainfo: metadata extracted from the archive
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."""
# -*- coding: utf-8 -*- # # This file is part of jsonresolver # Copyright (C) 2015 CERN. # # jsonresolver is free software; you can redistribute it and/or # modify it under the terms of the Revised BSD License; see LICENSE # file for more details. """Define hook specification.""" import pluggy hookspec = pluggy.HookspecMarker('jsonresolver') @hookspec def jsonresolver_loader(url_map): """Retrieve JSON document.""" pass # pragma: no cover
The hook specifications and the plugin classes are still experimental and considered as an internal API. 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).
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)
from abc import ABC, abstractmethod, abstractstaticmethod from argparse import ArgumentParser, Namespace from collections import namedtuple from pathlib import Path from typing import TYPE_CHECKING, AbstractSet, List, Optional import pluggy from ocrmypdf.helpers import Resolution if TYPE_CHECKING: from ocrmypdf._jobcontext import PageContext from ocrmypdf.pdfinfo import PdfInfo from PIL import Image hookspec = pluggy.HookspecMarker('ocrmypdf') # pylint: disable=unused-argument @hookspec def add_options(parser: ArgumentParser) -> None: """Allows the plugin to add its own command line and API arguments. OCRmyPDF converts command line arguments to API arguments, so adding arguments here will cause new arguments to be processed for API calls to ``ocrmypdf.ocr``, or when invoked on the command line. Note: This hook will be called from the main process, and may modify global state before child worker processes are forked.
# -*- coding: utf-8 -*- import pluggy hookspec = pluggy.HookspecMarker("zvt") @hookspec def zvt_setup_env(config: dict): pass
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
import weakref from typing import List, Type, TypeVar import pluggy # type: ignore from crib import config, exceptions, plugins from crib.injection import AbstractProvider, Container from crib.repositories import directions as dirrepo from crib.repositories import properties, user from crib.services import directions hookspec = pluggy.HookspecMarker("crib") PR = TypeVar("PR", bound=properties.PropertyRepo) TPR = Type[PR] UR = TypeVar("UR", bound=user.UserRepo) TUR = Type[UR] DR = TypeVar("DR", bound=dirrepo.DirectionsRepo) TDR = Type[DR] DS = TypeVar("DS", bound=directions.DirectionsService) TDS = Type[DS] class CribSpec: @hookspec def crib_add_property_repos(self) -> List[TPR]: # pragma: no cover """Add property repo plugins :return: a list of PropertyRepos """
"""TODO Documentation.""" import pluggy hookspec = pluggy.HookspecMarker("pcli") @hookspec def pcli_get_commands(): """Get a list of commands. :return: List of commands """
import click import networkx as nx import pluggy if TYPE_CHECKING: from _pytask.session import Session from _pytask.nodes import MetaNode from _pytask.nodes import Task from _pytask.outcomes import CollectionOutcome from _pytask.outcomes import TaskOutcome from _pytask.reports import CollectionReport from _pytask.reports import ExecutionReport from _pytask.reports import ResolveDependencyReport hookspec = pluggy.HookspecMarker("pytask") @hookspec def pytask_add_hooks(pm: pluggy.PluginManager) -> None: """Add hook specifications and implementations to the plugin manager. This hook is the first to be called to let plugins register their hook specifications and implementations. If you want to register plugins dynamically depending on the configuration, use :func:`pytask_post_parse` instead. See :mod:`_pytask.debugging` for an example. """
Plugins are currently stateless. They do not have ``__init__()`` methods, and when they are 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.
import pluggy indicatorspec = pluggy.HookspecMarker("indicator") class IndicatorSpec(object): """ Hooks for src/Indicator. In this list you can find all the hook that you can use to get completed your custom features Think that this class is an interface. It only serves to know the list of hooks availables, the parameters and return classes """ @indicatorspec def get_hook_menu(self, ): """Return a Gtk.MenuItem() array to be showed on App indicator (System tray) :return: new Menu Gtk.MenuItem """