Skip to content

Commit

Permalink
refactor: detecting entry point plugins (errbotio#1630)
Browse files Browse the repository at this point in the history
* refactor: detecting entry point plugins

* fix: deprecation warning on invalid escape sequence

* style: format files

* fix: use entrypoint name object instead of module

* fix: using module instead of name attribute

This seems like the correct attribute to use, as it notes the actual
path of the module.

* refactor: use pkg_resources instead of importlib metadata

* test: clean up entry_point tests

* test: use more common tox variable

* docs: add description to CHANGES

* style: format files
  • Loading branch information
sijis authored and nzlosh committed Feb 4, 2023
1 parent b63c97b commit 073a140
Show file tree
Hide file tree
Showing 20 changed files with 36 additions and 40 deletions.
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ fixes:
- fix: update module versions and build (#1627)
- fix: improve error reporting for plugin activation (#1620)
- chore: update setuptools version (#1628)
- refactor: detecting entry point plugins (#1630)

v6.1.9 (2022-06-11)
-------------------
Expand Down
5 changes: 1 addition & 4 deletions errbot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def botmatch(*args, **kwargs):
"""
Decorator for regex-based message match.
:param \*args: The regular expression a message should match against in order to
:param *args: The regular expression a message should match against in order to
trigger the command.
:param flags: The `flags` parameter which should be passed to :func:`re.compile()`. This
allows the expression's behaviour to be modified, such as making it case-insensitive
Expand Down Expand Up @@ -377,17 +377,14 @@ def repeat_the_value(self, msg, args):
argparse_args = args[1:]

def decorator(func):

if not hasattr(func, "_err_command"):

err_command_parser = ArgumentParser(
prog=name or func.__name__,
description=func.__doc__,
)

@wraps(func)
def wrapper(self, msg, args):

# Attempt to sanitize arguments of bad characters
try:
sanitizer_re = re.compile(
Expand Down
3 changes: 1 addition & 2 deletions errbot/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def invite(self, *args) -> None:
"""
Invite one or more people into the room.
:param \*args:
:param *args:
One or more identifiers to invite into the room.
"""
raise NotImplementedError(
Expand Down Expand Up @@ -592,7 +592,6 @@ def __init__(
reaction_name: str = None,
reacted_to: Mapping = None,
):

if reactor is None:
raise ValueError("Reaction: reactor is None")
if reaction_name is None:
Expand Down
1 change: 0 additions & 1 deletion errbot/backends/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,6 @@ def serve_forever(self) -> None:

try:
while True:

if self._inroom:
frm = TextOccupant(self.user, self.rooms()[0])
to = self.rooms()[0]
Expand Down
1 change: 0 additions & 1 deletion errbot/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ def _read_dict() -> dict:


def main() -> None:

execution_dir = getcwd()

# By default insert the execution path (useful to be able to execute Errbot from
Expand Down
1 change: 0 additions & 1 deletion errbot/core_plugins/chatRoom.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


class ChatRoom(BotPlugin):

connected = False

def callback_connect(self):
Expand Down
10 changes: 5 additions & 5 deletions errbot/core_plugins/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def apropos(self, msg, args):
description = "Available commands:\n"

cls_commands = {}
for (name, command) in self._bot.all_commands.items():
for name, command in self._bot.all_commands.items():
cls = self._bot.get_plugin_class_from_method(command)
cls = str.__module__ + "." + cls.__name__ # makes the fuul qualified name
commands = cls_commands.get(cls, [])
Expand All @@ -60,7 +60,7 @@ def apropos(self, msg, args):
usage = ""
for cls in sorted(cls_commands):
commands = []
for (name, command) in cls_commands[cls]:
for name, command in cls_commands[cls]:
if name == "help":
continue

Expand Down Expand Up @@ -101,7 +101,7 @@ def get_name(named):
description = "### All commands\n"

cls_obj_commands = {}
for (name, command) in self._bot.all_commands.items():
for name, command in self._bot.all_commands.items():
cls = self._bot.get_plugin_class_from_method(command)
obj = command.__self__
_, commands = cls_obj_commands.get(cls, (None, []))
Expand Down Expand Up @@ -158,7 +158,7 @@ def get_name(named):
else:
description += cls.__errdoc__ or "\n\n"
pairs = []
for (name, command) in cmds:
for name, command in cmds:
if self.bot_config.HIDE_RESTRICTED_COMMANDS:
if command._err_command_hidden:
continue
Expand All @@ -169,7 +169,7 @@ def get_name(named):

pairs = sorted(pairs)

for (name, command) in pairs:
for name, command in pairs:
usage += self._cmd_help_line(name, command)

return "".join(filter(None, [description, usage]))
Expand Down
1 change: 0 additions & 1 deletion errbot/core_plugins/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ def repos(self, _, args):
repos = {"repos": []}

for repo_name in all_names:

installed = False

if repo_name in installed_repos:
Expand Down
2 changes: 0 additions & 2 deletions errbot/core_plugins/textcmds.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ class TextModeCmds(BotPlugin):
__errdoc__ = "Added commands for testing purposes"

def activate(self):

# This won't activate the plugin in anything else than text mode.
if self.mode != "text":
return
Expand All @@ -34,7 +33,6 @@ def activate(self):
self._bot._multiline = self[MULTILINE]

def deactivate(self):

# Save the live state.
self[INROOM] = self._bot._inroom
self[USER] = self._bot.user
Expand Down
1 change: 0 additions & 1 deletion errbot/core_plugins/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ def tail(f, window=20):


class Utils(BotPlugin):

# noinspection PyUnusedLocal
@botcmd
def echo(self, _, args):
Expand Down
1 change: 0 additions & 1 deletion errbot/core_plugins/vcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@


class VersionChecker(BotPlugin):

connected = False
activated = False

Expand Down
1 change: 0 additions & 1 deletion errbot/core_plugins/wsview.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ def __init__(self, func, form_param, raw):
)

def dispatch_request(self, *args, **kwargs):

if self.raw: # override and gives the request directly
response = self.func(request, **kwargs)
elif self.form_param:
Expand Down
1 change: 0 additions & 1 deletion errbot/plugin_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,6 @@ def activate_plugin(self, name: str) -> None:
def _activate_plugin_dependencies(
self, name: str, dep_track: Set[str]
) -> List[str]:

plugin_info = self.plugin_infos[name]
dep_track.add(name)

Expand Down
4 changes: 3 additions & 1 deletion errbot/repo_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,9 @@ def install_repo(self, repo: str) -> str:
human_name = human_name or human_name_for_git_url(repo_url)
try:
git_clone(repo_url, os.path.join(self.plugin_dir, human_name))
except Exception as exception: # dulwich errors all base on exceptions.Exception
except (
Exception
) as exception: # dulwich errors all base on exceptions.Exception
raise RepoException(
f"Could not load this plugin: \n\n{repo_url}\n\n---\n\n{exception}"
)
Expand Down
4 changes: 2 additions & 2 deletions errbot/streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ def streamer(index):
log.debug("dispatch %d bytes", len(chunk))
if not chunk:
break
for (_, w) in pipes:
for _, w in pipes:
if w:
w.write(chunk)
log.debug("EOF detected")
for (r, w) in pipes:
for r, w in pipes:
if w:
w.close() # close should flush too
# we want to be sure that if we join on the main thread,
Expand Down
14 changes: 4 additions & 10 deletions errbot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,10 @@
import sys
import time
from functools import wraps
from importlib.util import find_spec

try:
from importlib.metadata import entry_points
except ImportError:
from importlib_metadata import entry_points

from platform import system
from typing import List, Tuple, Union

import pkg_resources
from dulwich import porcelain

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -205,9 +199,9 @@ def collect_roots(base_paths: List, file_sig: str = "*.plug") -> List:

def entry_point_plugins(group):
paths = []
for entry_point in entry_points().get(group, []):
lib_paths = find_spec(entry_point.module).submodule_search_locations
paths.extend(lib_paths)
for entry_point in pkg_resources.iter_entry_points(group):
ep = next(pkg_resources.iter_entry_points(group, entry_point.name))
paths.append(f"{ep.dist.module_path}/{entry_point.module_name}")
return paths


Expand Down
3 changes: 0 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,6 @@
"deepmerge==1.0.1",
]

if py_version < (3, 8):
deps.append("importlib-metadata==4.12.0")

if py_version < (3, 9):
deps.append("graphlib-backport==1.0.3")

Expand Down
2 changes: 0 additions & 2 deletions tests/commands_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ def test_history(testbot):


def test_plugin_cycle(testbot):

plugins = [
"errbotio/err-helloworld",
]
Expand Down Expand Up @@ -155,7 +154,6 @@ def test_plugin_cycle(testbot):


def test_broken_plugin(testbot):

borken_plugin_dir = path.join(
path.dirname(path.realpath(__file__)), "borken_plugin"
)
Expand Down
18 changes: 18 additions & 0 deletions tests/plugin_entrypoint_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from errbot.utils import entry_point_plugins


def test_entrypoint_paths():
plugins = entry_point_plugins("console_scripts")

match = False
for plugin in plugins:
if "errbot/errbot.cli" in plugin:
match = True
assert match


def test_entrypoint_paths_empty():
groups = ["errbot.plugins", "errbot.backend_plugins"]
for entry_point_group in groups:
plugins = entry_point_plugins(entry_point_group)
assert plugins == []
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ deps =
twine
commands =
python setup.py sdist
twine check {tox_root}/dist/*
twine check {toxinidir}/dist/*

[testenv:sort]
deps =
Expand Down

0 comments on commit 073a140

Please sign in to comment.