1# Licensed to the Apache Software Foundation (ASF) under one
2# or more contributor license agreements. See the NOTICE file
3# distributed with this work for additional information
4# regarding copyright ownership. The ASF licenses this file
5# to you under the Apache License, Version 2.0 (the
6# "License"); you may not use this file except in compliance
7# with the License. You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing,
12# software distributed under the License is distributed on an
13# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14# KIND, either express or implied. See the License for the
15# specific language governing permissions and limitations
16# under the License.
17from __future__ import annotations
18
19import functools
20import logging
21import sys
22from collections import defaultdict
23from typing import Iterator, Tuple
24
25if sys.version_info >= (3, 12):
26 from importlib import metadata
27else:
28 import importlib_metadata as metadata # type: ignore[no-redef]
29
30log = logging.getLogger(__name__)
31
32EPnD = Tuple[metadata.EntryPoint, metadata.Distribution]
33
34
35@functools.lru_cache(maxsize=None)
36def _get_grouped_entry_points() -> dict[str, list[EPnD]]:
37 mapping: dict[str, list[EPnD]] = defaultdict(list)
38 for dist in metadata.distributions():
39 try:
40 for e in dist.entry_points:
41 mapping[e.group].append((e, dist))
42 except Exception as e:
43 log.warning("Error when retrieving package metadata (skipping it): %s, %s", dist, e)
44 return mapping
45
46
47def entry_points_with_dist(group: str) -> Iterator[EPnD]:
48 """Retrieve entry points of the given group.
49
50 This is like the ``entry_points()`` function from ``importlib.metadata``,
51 except it also returns the distribution the entry point was loaded from.
52
53 Note that this may return multiple distributions to the same package if they
54 are loaded from different ``sys.path`` entries. The caller site should
55 implement appropriate deduplication logic if needed.
56
57 :param group: Filter results to only this entrypoint group
58 :return: Generator of (EntryPoint, Distribution) objects for the specified groups
59 """
60 return iter(_get_grouped_entry_points()[group])