httpie-cli/httpie/plugins/manager.py

78 lines
2.4 KiB
Python
Raw Normal View History

from itertools import groupby
2019-08-31 18:33:54 +02:00
from typing import Type, Iterable, List, Dict
2013-09-21 23:46:15 +02:00
from pkg_resources import iter_entry_points
from httpie.plugins import AuthPlugin, FormatterPlugin, ConverterPlugin
2019-08-31 18:33:54 +02:00
from httpie.plugins.base import TransportPlugin, BasePlugin
2013-09-21 23:46:15 +02:00
ENTRY_POINT_NAMES = [
'httpie.plugins.auth.v1',
'httpie.plugins.formatter.v1',
'httpie.plugins.converter.v1',
'httpie.plugins.transport.v1',
2013-09-21 23:46:15 +02:00
]
class PluginManager:
2013-09-21 23:46:15 +02:00
def __init__(self):
self._plugins = []
def __iter__(self):
return iter(self._plugins)
2019-08-31 18:33:54 +02:00
def register(self, *plugins: Type[BasePlugin]):
for plugin in plugins:
self._plugins.append(plugin)
2013-09-21 23:46:15 +02:00
2019-08-31 18:35:24 +02:00
def unregister(self, plugin: Type[BasePlugin]):
self._plugins.remove(plugin)
def load_installed_plugins(self):
for entry_point_name in ENTRY_POINT_NAMES:
for entry_point in iter_entry_points(entry_point_name):
plugin = entry_point.load()
plugin.package_name = entry_point.dist.key
self.register(entry_point.load())
# Auth
2019-08-31 18:33:54 +02:00
def get_auth_plugins(self) -> List[Type[AuthPlugin]]:
return [plugin for plugin in self if issubclass(plugin, AuthPlugin)]
2013-09-21 23:46:15 +02:00
2019-08-31 18:33:54 +02:00
def get_auth_plugin_mapping(self) -> Dict[str, Type[AuthPlugin]]:
return {
plugin.auth_type: plugin for plugin in self.get_auth_plugins()
}
2013-09-21 23:46:15 +02:00
2019-08-31 18:33:54 +02:00
def get_auth_plugin(self, auth_type: str) -> Type[AuthPlugin]:
2013-09-21 23:46:15 +02:00
return self.get_auth_plugin_mapping()[auth_type]
# Output processing
2019-08-31 18:33:54 +02:00
def get_formatters(self) -> List[Type[FormatterPlugin]]:
return [
plugin for plugin in self
if issubclass(plugin, FormatterPlugin)
]
2019-08-31 18:33:54 +02:00
def get_formatters_grouped(self) -> Dict[str, List[Type[FormatterPlugin]]]:
groups = {}
for group_name, group in groupby(
self.get_formatters(),
key=lambda p: getattr(p, 'group_name', 'format')):
groups[group_name] = list(group)
return groups
2019-08-31 18:33:54 +02:00
def get_converters(self) -> List[Type[ConverterPlugin]]:
return [
plugin for plugin in self
if issubclass(plugin, ConverterPlugin)
]
# Adapters
2019-08-31 18:33:54 +02:00
def get_transport_plugins(self) -> List[Type[TransportPlugin]]:
return [
plugin for plugin in self
if issubclass(plugin, TransportPlugin)
]