_reqs.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from functools import lru_cache
  2. from typing import Callable, Iterable, Iterator, TypeVar, Union, overload
  3. import setuptools.extern.jaraco.text as text
  4. from setuptools.extern.packaging.requirements import Requirement
  5. _T = TypeVar("_T")
  6. _StrOrIter = Union[str, Iterable[str]]
  7. parse_req: Callable[[str], Requirement] = lru_cache()(Requirement)
  8. # Setuptools parses the same requirement many times
  9. # (e.g. first for validation than for normalisation),
  10. # so it might be worth to cache.
  11. def parse_strings(strs: _StrOrIter) -> Iterator[str]:
  12. """
  13. Yield requirement strings for each specification in `strs`.
  14. `strs` must be a string, or a (possibly-nested) iterable thereof.
  15. """
  16. return text.join_continuation(map(text.drop_comment, text.yield_lines(strs)))
  17. @overload
  18. def parse(strs: _StrOrIter) -> Iterator[Requirement]:
  19. ...
  20. @overload
  21. def parse(strs: _StrOrIter, parser: Callable[[str], _T]) -> Iterator[_T]:
  22. ...
  23. def parse(strs, parser=parse_req):
  24. """
  25. Replacement for ``pkg_resources.parse_requirements`` that uses ``packaging``.
  26. """
  27. return map(parser, parse_strings(strs))