File: entry_points.py

package info (click to toggle)
python-dist-meta 0.9.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,964 kB
  • sloc: python: 2,944; makefile: 9
file content (385 lines) | stat: -rw-r--r-- 10,350 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#!/usr/bin/env python3
#
#  entry_points.py
"""
Parser and emitter for ``entry_points.txt``.

.. note::

	The functions in this module will only parse well-formed ``entry_points.txt`` files,
	and may return unexpected values if passed malformed input.
"""
#
#  Copyright © 2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in all
#  copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
#  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
#  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
#  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
#  OR OTHER DEALINGS IN THE SOFTWARE.
#
#  Parts based on https://github.com/python/importlib_metadata
#  Copyright 2017-2019 Jason R. Coombs, Barry Warsaw
#  Licensed under the Apache License, Version 2.0
#
#  EntryPoint based on https://github.com/takluyver/entrypoints
#  Copyright (c) 2015 Thomas Kluyver and contributors
#  MIT Licensed
#

# stdlib
import importlib
import re
from itertools import groupby
from typing import Dict, Iterable, Iterator, List, Mapping, NamedTuple, Optional, Sequence, Tuple, TypeVar, Union

# 3rd party
from domdf_python_tools.paths import PathPlus
from domdf_python_tools.stringlist import StringList
from domdf_python_tools.typing import PathLike
from domdf_python_tools.utils import divide

# this package
from dist_meta._utils import _cache
from dist_meta.distributions import Distribution

__all__ = (
		"lazy_load",
		"lazy_loads",
		"load",
		"loads",
		"dump",
		"dumps",
		"get_entry_points",
		"get_all_entry_points",
		"EntryPoint",
		)

_EP = TypeVar("_EP", bound="EntryPoint")

#: Type hint for a lazily evaluated iterator of entry points.
EntryPointIterator = Iterator[Tuple[str, Iterator[Tuple[str, str]]]]

#: Type hint for a mapping of entry point groups to mappings of entry point names to entry point objects.
EntryPointMap = Dict[str, Dict[str, str]]


class _Section:

	def __init__(self):
		self.section: Optional[str] = None

	def __call__(self, line: str) -> Optional[str]:
		if line.startswith('[') and line.endswith(']'):
			# new section
			self.section = line.strip("[]")
			return None

		return self.section


def _parse_value(line: str) -> Tuple[str, str]:
	name, obj = divide(line, '=')
	return name.strip(), obj.strip()


def lazy_loads(rawtext: str) -> EntryPointIterator:
	"""
	Parse the entry points from the given text lazily.

	:param rawtext:

	:returns: An iterator over ``(group, entry_point)`` tuples, where ``entry_point``
		is an iterator over ``(name, object)`` tuples.
	"""

	lines = filter(None, map(str.strip, rawtext.splitlines()))

	for section, values in groupby(lines, _Section()):
		if section is not None:
			yield section, map(_parse_value, values)


def lazy_load(filename: PathLike) -> EntryPointIterator:
	"""
	Parse the entry points from the given file lazily.

	:param filename:

	:returns: An iterator over ``(group, entry_point)`` tuples, where ``entry_point``
		is an iterator over ``(name, object)`` tuples.
	"""

	filename = PathPlus(filename)
	return lazy_loads(filename.read_text())


@_cache
def loads(rawtext: str) -> EntryPointMap:
	"""
	Parse the entry points from the given text.

	:param rawtext:

	:returns: A mapping of entry point groups to entry points.

		Entry points in each group are contained in a dictionary mapping entry point names to objects.

		:class:`dist_meta.entry_points.EntryPoint` objects can be constructed as follows:

		.. code-block:: python

			for name, epstr in distro.get_entry_points().get("console_scripts", {}).items():
				EntryPoint(name, epstr)
	"""

	eps = lazy_loads(rawtext)
	return {k: dict(v) for k, v in eps}


def load(filename: PathLike) -> EntryPointMap:
	"""
	Parse the entry points from the given file.

	:param filename:

	:returns: A mapping of entry point groups to entry points.

		Entry points in each group are contained in a dictionary mapping entry point names to objects.

		:class:`dist_meta.entry_points.EntryPoint` objects can be constructed as follows:

		.. code-block:: python

			for name, epstr in distro.get_entry_points().get("console_scripts", {}).items():
				EntryPoint(name, epstr)
	"""

	filename = PathPlus(filename)
	return loads(filename.read_text())


def dumps(entry_points: Union[EntryPointMap, Dict[str, Sequence["EntryPoint"]]]) -> str:
	"""
	Construct an ``entry_points.txt`` file for the given grouped entry points.

	:param entry_points:  A mapping of entry point groups to entry points.

		Entry points in each group are contained in a dictionary mapping entry point names to objects,
		or in a list of :class:`~.EntryPoint` objects.
	"""

	output = StringList()

	for group, group_data in entry_points.items():
		output.append(f"[{group}]")

		for name in group_data:
			if isinstance(name, EntryPoint):
				output.append(f"{name.name} = {name.value}")
			else:
				output.append(f"{name} = {group_data[name]}")  # type: ignore[call-overload]

		output.blankline(ensure_single=True)

	return str(output)


def dump(
		entry_points: Union[EntryPointMap, Dict[str, Sequence["EntryPoint"]]],
		filename: PathLike,
		) -> int:
	"""
	Construct an ``entry_points.txt`` file for the given grouped entry points, and write it to ``filename``.

	:param entry_points:  A mapping of entry point groups to entry points.

		Entry points in each group are contained in a dictionary mapping entry point names to objects,
		or in a list of :class:`~.EntryPoint` objects.

	:param filename:
	"""

	filename = PathPlus(filename)
	return filename.write_text(dumps(entry_points))


def get_entry_points(
		group: str,
		path: Optional[Iterable[PathLike]] = None,
		) -> Iterator["EntryPoint"]:
	"""
	Returns an iterator over :class:`entrypoints.EntryPoint` objects in the given group.

	:param group:
	:param path: The directories entries to search for distributions in.
	:default path: :py:data:`sys.path`
	"""

	# this package
	from dist_meta.distributions import iter_distributions

	for distro in iter_distributions(path=path):

		eps = distro.get_entry_points()

		if group in eps:
			for name, epstr in eps[group].items():
				yield EntryPoint(name, epstr, group=group, distro=distro)


def get_all_entry_points(path: Optional[Iterable[PathLike]] = None, ) -> Dict[str, List["EntryPoint"]]:
	"""
	Returns a mapping of entry point groups to entry points for all installed distributions.

	:param path: The directories entries to search for distributions in.
	:default path: :py:data:`sys.path`
	"""

	# this package
	from dist_meta.distributions import iter_distributions

	grouped_eps: Dict[str, List[EntryPoint]] = {}

	for distro in iter_distributions(path=path):

		eps = distro.get_entry_points()

		for group_name in eps:
			group = grouped_eps.setdefault(group_name, [])

			for name, epstr in eps[group_name].items():  # pylint: disable=use-list-copy
				group.append(EntryPoint(name, epstr, group_name, distro))

	return grouped_eps


_entry_point_pattern = re.compile(
		r"""
(?P<modulename>\w+(\.\w+)*)
(:(?P<objectname>\w+(\.\w+)*))?
\s*
(\[(?P<extras>.+)])?
$
""",
		re.VERBOSE
		)


class EntryPoint(NamedTuple):
	"""
	Represents a single entry point.
	"""

	#: The name of the entry point.
	name: str

	#: The value of the entry point, in the form ``module.submodule:attribute``.
	value: str

	#: The group the entry point belongs to.
	group: Optional[str] = None

	#: The distribution the entry point belongs to.
	distro: Optional["Distribution"] = None

	def load(self) -> object:
		"""
		Load the object referred to by this entry point.

		If only a module is indicated by the value, return that module.
		Otherwise, return the named object.
		"""

		match = _entry_point_pattern.match(self.value)
		if not match:
			raise ValueError(f"Malformed entry point {self.value!r}")

		module_name, object_name = match.group("modulename", "objectname")
		obj = importlib.import_module(module_name)

		if object_name:
			for attr in object_name.split('.'):
				obj = getattr(obj, attr)

		return obj

	@property
	def extras(self) -> List[str]:
		"""
		Returns the list of extras associated with the entry point.
		"""

		match = _entry_point_pattern.match(self.value)
		if not match:
			raise ValueError(f"Malformed entry point {self.value!r}")

		extras = match.group("extras")

		if extras is not None:
			return re.split(r',\s*', extras)

		return []

	@property
	def module(self) -> str:
		"""
		The module component of :class:`self.value <.EntryPoint>`.
		"""

		# TODO: proper xref

		match = _entry_point_pattern.match(self.value)
		if not match:
			raise ValueError(f"Malformed entry point {self.value!r}")

		return match.group("modulename")

	@property
	def attr(self) -> str:
		"""
		The object/attribute component of :class:`self.value <.EntryPoint>`.

		:rtype:

		.. latex:clearpage::
		"""

		# TODO: proper xref

		match = _entry_point_pattern.match(self.value)
		if not match:
			raise ValueError(f"Malformed entry point {self.value!r}")

		return match.group("objectname")

	@classmethod
	def from_mapping(
			cls,
			mapping: Mapping[str, str],
			*,
			group: Optional[str] = None,
			distro: Optional["Distribution"] = None,
			) -> List["EntryPoint"]:
		"""
		Returns a list of :class:`~.EntryPoint` objects constructed from values in ``mapping``.

		:param mapping: A mapping of entry point names to values,
			where values are in the form ``module.submodule:attribute``.
		:param group: The group the entry points belong to.
		:param distro: The distribution the entry points belong to.
		"""

		return [EntryPoint(name, value, group, distro) for name, value in mapping.items()]