Debian Codegraph @

debian/patches/use-importlib.patch

raw
1 From: Sijis Aviles <[email protected]>
2 Date: Thu, 5 Jun 2025 21:04:47 -0700
3 Subject: refactor: use importlib instead of pkg_resources (#1669)
4
5 * refactor: use importlib instead of pkg_resources
6
7 * fix: remove try/except import check for importlib
8
9 * fix: workaround to support python 3.9 and older
10
11 * tests: add basic entry_point_plugins tests
12
13 I needed to further adjust the files lookup to ignore distributions that were
14 not found.
15
16 * docs: add info to CHANGES
17
18 Origin: backport, https://github.com/errbotio/errbot/pull/1669
19 Bug-Debian: https://bugs.debian.org/1083380
20 Last-Update: 2026-01-06
21 ---
22 errbot/repo_manager.py | 53 +++++++++++++++++++++-----------------------------
23 errbot/utils.py | 31 +++++++++++++++++++++++++----
24 tests/utils_test.py | 24 ++++++++++++++++++++++-
25 3 files changed, 72 insertions(+), 36 deletions(-)
26
27 diff --git a/errbot/repo_manager.py b/errbot/repo_manager.py
28 index 1651593..ffc1c39 100644
29 --- a/errbot/repo_manager.py
30 +++ b/errbot/repo_manager.py
31 @@ -6,6 +6,7 @@ import shutil
32 import tarfile
33 from collections import namedtuple
34 from datetime import datetime, timedelta
35 +from importlib.metadata import distribution
36 from os import path
37 from pathlib import Path
38 from typing import Dict, Generator, List, Optional, Sequence, Tuple, Union
39 @@ -91,40 +92,30 @@ def check_dependencies(req_path: Path) -> Tuple[Optional[str], Sequence[str]]:
40 Or None, [] if everything is OK.
41 """
42 log.debug("check dependencies of %s", req_path)
43 - # noinspection PyBroadException
44 - try:
45 - from pkg_resources import get_distribution
46 -
47 - missing_pkg = []
48 -
49 - if not req_path.is_file():
50 - log.debug("%s has no requirements.txt file", req_path)
51 - return None, missing_pkg
52 -
53 - with req_path.open() as f:
54 - for line in f:
55 - stripped = line.strip()
56 - # skip empty lines.
57 - if not stripped:
58 - continue
59 -
60 - # noinspection PyBroadException
61 - try:
62 - get_distribution(stripped)
63 - except Exception:
64 - missing_pkg.append(stripped)
65 - if missing_pkg:
66 - return (
67 - f"You need these dependencies for {req_path}: " + ",".join(missing_pkg),
68 - missing_pkg,
69 - )
70 + missing_pkg = []
71 +
72 + if not req_path.is_file():
73 + log.debug("%s has no requirements.txt file", req_path)
74 return None, missing_pkg
75 - except Exception:
76 - log.exception("Problem checking for dependencies.")
77 +
78 + with req_path.open() as f:
79 + for line in f:
80 + stripped = line.strip()
81 + # skip empty lines.
82 + if not stripped:
83 + continue
84 +
85 + # noinspection PyBroadException
86 + try:
87 + distribution(stripped)
88 + except Exception:
89 + missing_pkg.append(stripped)
90 + if missing_pkg:
91 return (
92 - "You need to have setuptools installed for the dependency check of the plugins",
93 - [],
94 + f"You need these dependencies for {req_path}: " + ",".join(missing_pkg),
95 + missing_pkg,
96 )
97 + return None, missing_pkg
98
99
100 class BotRepoManager(StoreMixin):
101 diff --git a/errbot/utils.py b/errbot/utils.py
102 index 68d7d70..658e801 100644
103 --- a/errbot/utils.py
104 +++ b/errbot/utils.py
105 @@ -1,8 +1,10 @@
106 import collections
107 import fnmatch
108 +import importlib.metadata
109 import inspect
110 import logging
111 import os
112 +import pathlib
113 import re
114 import sys
115 import time
116 @@ -10,7 +12,6 @@ from functools import wraps
117 from platform import system
118 from typing import List, Tuple, Union
119
120 -import pkg_resources
121 from dulwich import porcelain
122
123 log = logging.getLogger(__name__)
124 @@ -199,9 +200,31 @@ def collect_roots(base_paths: List, file_sig: str = "*.plug") -> List:
125
126 def entry_point_plugins(group):
127 paths = []
128 - for entry_point in pkg_resources.iter_entry_points(group):
129 - ep = next(pkg_resources.iter_entry_points(group, entry_point.name))
130 - paths.append(f"{ep.dist.module_path}/{entry_point.module_name}")
131 +
132 + eps = importlib.metadata.entry_points()
133 + try:
134 + entry_points = eps.select(group=group)
135 + except AttributeError:
136 + # workaround to support python 3.9 and older
137 + entry_points = eps.get(group, ())
138 +
139 + for entry_point in entry_points:
140 + module_name = entry_point.module
141 + file_name = module_name.replace(".", "/") + ".py"
142 + try:
143 + files = entry_point.dist.files
144 + except AttributeError:
145 + # workaround to support python 3.9 and older
146 + try:
147 + files = importlib.metadata.distribution(entry_point.name).files
148 + except importlib.metadata.PackageNotFoundError:
149 + # entrypoint is not a distribution, so let's skip looking for files
150 + continue
151 +
152 + for f in files:
153 + if file_name == str(f):
154 + parent = str(pathlib.Path(f).resolve().parent)
155 + paths.append(f"{parent}/{module_name}")
156 return paths
157
158
159 diff --git a/tests/utils_test.py b/tests/utils_test.py
160 index 858ee7d..cde8f1d 100644
161 --- a/tests/utils_test.py
162 +++ b/tests/utils_test.py
163 @@ -1,4 +1,7 @@
164 # coding=utf-8
165 +import logging
166 +import sys
167 +
168 from datetime import timedelta
169
170 import pytest
171 @@ -8,7 +11,12 @@ from errbot.backends.test import ShallowConfig
172 from errbot.bootstrap import CORE_STORAGE, bot_config_defaults
173 from errbot.storage import StoreMixin
174 from errbot.storage.base import StoragePluginBase
175 -from errbot.utils import *
176 +from errbot.utils import (
177 + entry_point_plugins,
178 + format_timedelta,
179 + split_string_after,
180 + version2tuple,
181 +)
182
183 log = logging.getLogger(__name__)
184
185 @@ -100,3 +108,17 @@ def test_split_string_after_returns_two_chunks_when_chunksize_equals_half_length
186 splitter = split_string_after(str_, int(len(str_) / 2))
187 split = [chunk for chunk in splitter]
188 assert ["foobar2000", "foobar2000"] == split
189 +
190 +
191 +def test_entry_point_plugins_no_groups():
192 + result = entry_point_plugins("does_not_exist")
193 + assert [] == result
194 +
195 +
196 +def test_entry_point_plugins_valid_groups():
197 + results = entry_point_plugins("console_scripts")
198 + match = False
199 + for result in results:
200 + if result.endswith("errbot/errbot.cli"):
201 + match = True
202 + assert match