req_file.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. """
  2. Requirements file parsing
  3. """
  4. from __future__ import annotations
  5. import codecs
  6. import locale
  7. import logging
  8. import optparse
  9. import os
  10. import re
  11. import shlex
  12. import sys
  13. import urllib.parse
  14. from collections.abc import Generator, Iterable
  15. from dataclasses import dataclass
  16. from optparse import Values
  17. from typing import (
  18. TYPE_CHECKING,
  19. Any,
  20. Callable,
  21. NoReturn,
  22. )
  23. from pip._internal.cli import cmdoptions
  24. from pip._internal.exceptions import InstallationError, RequirementsFileParseError
  25. from pip._internal.models.search_scope import SearchScope
  26. if TYPE_CHECKING:
  27. from pip._internal.index.package_finder import PackageFinder
  28. from pip._internal.network.session import PipSession
  29. __all__ = ["parse_requirements"]
  30. ReqFileLines = Iterable[tuple[int, str]]
  31. LineParser = Callable[[str], tuple[str, Values]]
  32. SCHEME_RE = re.compile(r"^(http|https|file):", re.I)
  33. COMMENT_RE = re.compile(r"(^|\s+)#.*$")
  34. # Matches environment variable-style values in '${MY_VARIABLE_1}' with the
  35. # variable name consisting of only uppercase letters, digits or the '_'
  36. # (underscore). This follows the POSIX standard defined in IEEE Std 1003.1,
  37. # 2013 Edition.
  38. ENV_VAR_RE = re.compile(r"(?P<var>\$\{(?P<name>[A-Z0-9_]+)\})")
  39. SUPPORTED_OPTIONS: list[Callable[..., optparse.Option]] = [
  40. cmdoptions.index_url,
  41. cmdoptions.extra_index_url,
  42. cmdoptions.no_index,
  43. cmdoptions.constraints,
  44. cmdoptions.requirements,
  45. cmdoptions.editable,
  46. cmdoptions.find_links,
  47. cmdoptions.no_binary,
  48. cmdoptions.only_binary,
  49. cmdoptions.prefer_binary,
  50. cmdoptions.require_hashes,
  51. cmdoptions.pre,
  52. cmdoptions.trusted_host,
  53. cmdoptions.use_new_feature,
  54. ]
  55. # options to be passed to requirements
  56. SUPPORTED_OPTIONS_REQ: list[Callable[..., optparse.Option]] = [
  57. cmdoptions.hash,
  58. cmdoptions.config_settings,
  59. ]
  60. SUPPORTED_OPTIONS_EDITABLE_REQ: list[Callable[..., optparse.Option]] = [
  61. cmdoptions.config_settings,
  62. ]
  63. # the 'dest' string values
  64. SUPPORTED_OPTIONS_REQ_DEST = [str(o().dest) for o in SUPPORTED_OPTIONS_REQ]
  65. SUPPORTED_OPTIONS_EDITABLE_REQ_DEST = [
  66. str(o().dest) for o in SUPPORTED_OPTIONS_EDITABLE_REQ
  67. ]
  68. # order of BOMS is important: codecs.BOM_UTF16_LE is a prefix of codecs.BOM_UTF32_LE
  69. # so data.startswith(BOM_UTF16_LE) would be true for UTF32_LE data
  70. BOMS: list[tuple[bytes, str]] = [
  71. (codecs.BOM_UTF8, "utf-8"),
  72. (codecs.BOM_UTF32, "utf-32"),
  73. (codecs.BOM_UTF32_BE, "utf-32-be"),
  74. (codecs.BOM_UTF32_LE, "utf-32-le"),
  75. (codecs.BOM_UTF16, "utf-16"),
  76. (codecs.BOM_UTF16_BE, "utf-16-be"),
  77. (codecs.BOM_UTF16_LE, "utf-16-le"),
  78. ]
  79. PEP263_ENCODING_RE = re.compile(rb"coding[:=]\s*([-\w.]+)")
  80. DEFAULT_ENCODING = "utf-8"
  81. logger = logging.getLogger(__name__)
  82. @dataclass(frozen=True)
  83. class ParsedRequirement:
  84. # TODO: replace this with slots=True when dropping Python 3.9 support.
  85. __slots__ = (
  86. "requirement",
  87. "is_editable",
  88. "comes_from",
  89. "constraint",
  90. "options",
  91. "line_source",
  92. )
  93. requirement: str
  94. is_editable: bool
  95. comes_from: str
  96. constraint: bool
  97. options: dict[str, Any] | None
  98. line_source: str | None
  99. @dataclass(frozen=True)
  100. class ParsedLine:
  101. __slots__ = ("filename", "lineno", "args", "opts", "constraint")
  102. filename: str
  103. lineno: int
  104. args: str
  105. opts: Values
  106. constraint: bool
  107. @property
  108. def is_editable(self) -> bool:
  109. return bool(self.opts.editables)
  110. @property
  111. def requirement(self) -> str | None:
  112. if self.args:
  113. return self.args
  114. elif self.is_editable:
  115. # We don't support multiple -e on one line
  116. return self.opts.editables[0]
  117. return None
  118. def parse_requirements(
  119. filename: str,
  120. session: PipSession,
  121. finder: PackageFinder | None = None,
  122. options: optparse.Values | None = None,
  123. constraint: bool = False,
  124. ) -> Generator[ParsedRequirement, None, None]:
  125. """Parse a requirements file and yield ParsedRequirement instances.
  126. :param filename: Path or url of requirements file.
  127. :param session: PipSession instance.
  128. :param finder: Instance of pip.index.PackageFinder.
  129. :param options: cli options.
  130. :param constraint: If true, parsing a constraint file rather than
  131. requirements file.
  132. """
  133. line_parser = get_line_parser(finder)
  134. parser = RequirementsFileParser(session, line_parser)
  135. for parsed_line in parser.parse(filename, constraint):
  136. parsed_req = handle_line(
  137. parsed_line, options=options, finder=finder, session=session
  138. )
  139. if parsed_req is not None:
  140. yield parsed_req
  141. def preprocess(content: str) -> ReqFileLines:
  142. """Split, filter, and join lines, and return a line iterator
  143. :param content: the content of the requirements file
  144. """
  145. lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1)
  146. lines_enum = join_lines(lines_enum)
  147. lines_enum = ignore_comments(lines_enum)
  148. lines_enum = expand_env_variables(lines_enum)
  149. return lines_enum
  150. def handle_requirement_line(
  151. line: ParsedLine,
  152. options: optparse.Values | None = None,
  153. ) -> ParsedRequirement:
  154. # preserve for the nested code path
  155. line_comes_from = "{} {} (line {})".format(
  156. "-c" if line.constraint else "-r",
  157. line.filename,
  158. line.lineno,
  159. )
  160. assert line.requirement is not None
  161. # get the options that apply to requirements
  162. if line.is_editable:
  163. supported_dest = SUPPORTED_OPTIONS_EDITABLE_REQ_DEST
  164. else:
  165. supported_dest = SUPPORTED_OPTIONS_REQ_DEST
  166. req_options = {}
  167. for dest in supported_dest:
  168. if dest in line.opts.__dict__ and line.opts.__dict__[dest]:
  169. req_options[dest] = line.opts.__dict__[dest]
  170. line_source = f"line {line.lineno} of {line.filename}"
  171. return ParsedRequirement(
  172. requirement=line.requirement,
  173. is_editable=line.is_editable,
  174. comes_from=line_comes_from,
  175. constraint=line.constraint,
  176. options=req_options,
  177. line_source=line_source,
  178. )
  179. def handle_option_line(
  180. opts: Values,
  181. filename: str,
  182. lineno: int,
  183. finder: PackageFinder | None = None,
  184. options: optparse.Values | None = None,
  185. session: PipSession | None = None,
  186. ) -> None:
  187. if opts.hashes:
  188. logger.warning(
  189. "%s line %s has --hash but no requirement, and will be ignored.",
  190. filename,
  191. lineno,
  192. )
  193. if options:
  194. # percolate options upward
  195. if opts.require_hashes:
  196. options.require_hashes = opts.require_hashes
  197. if opts.features_enabled:
  198. options.features_enabled.extend(
  199. f for f in opts.features_enabled if f not in options.features_enabled
  200. )
  201. # set finder options
  202. if finder:
  203. find_links = finder.find_links
  204. index_urls = finder.index_urls
  205. no_index = finder.search_scope.no_index
  206. if opts.no_index is True:
  207. no_index = True
  208. index_urls = []
  209. if opts.index_url and not no_index:
  210. index_urls = [opts.index_url]
  211. if opts.extra_index_urls and not no_index:
  212. index_urls.extend(opts.extra_index_urls)
  213. if opts.find_links:
  214. # FIXME: it would be nice to keep track of the source
  215. # of the find_links: support a find-links local path
  216. # relative to a requirements file.
  217. value = opts.find_links[0]
  218. req_dir = os.path.dirname(os.path.abspath(filename))
  219. relative_to_reqs_file = os.path.join(req_dir, value)
  220. if os.path.exists(relative_to_reqs_file):
  221. value = relative_to_reqs_file
  222. find_links.append(value)
  223. if session:
  224. # We need to update the auth urls in session
  225. session.update_index_urls(index_urls)
  226. search_scope = SearchScope(
  227. find_links=find_links,
  228. index_urls=index_urls,
  229. no_index=no_index,
  230. )
  231. finder.search_scope = search_scope
  232. if opts.pre:
  233. finder.set_allow_all_prereleases()
  234. if opts.prefer_binary:
  235. finder.set_prefer_binary()
  236. if session:
  237. for host in opts.trusted_hosts or []:
  238. source = f"line {lineno} of {filename}"
  239. session.add_trusted_host(host, source=source)
  240. def handle_line(
  241. line: ParsedLine,
  242. options: optparse.Values | None = None,
  243. finder: PackageFinder | None = None,
  244. session: PipSession | None = None,
  245. ) -> ParsedRequirement | None:
  246. """Handle a single parsed requirements line; This can result in
  247. creating/yielding requirements, or updating the finder.
  248. :param line: The parsed line to be processed.
  249. :param options: CLI options.
  250. :param finder: The finder - updated by non-requirement lines.
  251. :param session: The session - updated by non-requirement lines.
  252. Returns a ParsedRequirement object if the line is a requirement line,
  253. otherwise returns None.
  254. For lines that contain requirements, the only options that have an effect
  255. are from SUPPORTED_OPTIONS_REQ, and they are scoped to the
  256. requirement. Other options from SUPPORTED_OPTIONS may be present, but are
  257. ignored.
  258. For lines that do not contain requirements, the only options that have an
  259. effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may
  260. be present, but are ignored. These lines may contain multiple options
  261. (although our docs imply only one is supported), and all our parsed and
  262. affect the finder.
  263. """
  264. if line.requirement is not None:
  265. parsed_req = handle_requirement_line(line, options)
  266. return parsed_req
  267. else:
  268. handle_option_line(
  269. line.opts,
  270. line.filename,
  271. line.lineno,
  272. finder,
  273. options,
  274. session,
  275. )
  276. return None
  277. class RequirementsFileParser:
  278. def __init__(
  279. self,
  280. session: PipSession,
  281. line_parser: LineParser,
  282. ) -> None:
  283. self._session = session
  284. self._line_parser = line_parser
  285. def parse(
  286. self, filename: str, constraint: bool
  287. ) -> Generator[ParsedLine, None, None]:
  288. """Parse a given file, yielding parsed lines."""
  289. yield from self._parse_and_recurse(
  290. filename, constraint, [{os.path.abspath(filename): None}]
  291. )
  292. def _parse_and_recurse(
  293. self,
  294. filename: str,
  295. constraint: bool,
  296. parsed_files_stack: list[dict[str, str | None]],
  297. ) -> Generator[ParsedLine, None, None]:
  298. for line in self._parse_file(filename, constraint):
  299. if line.requirement is None and (
  300. line.opts.requirements or line.opts.constraints
  301. ):
  302. # parse a nested requirements file
  303. if line.opts.requirements:
  304. req_path = line.opts.requirements[0]
  305. nested_constraint = False
  306. else:
  307. req_path = line.opts.constraints[0]
  308. nested_constraint = True
  309. # original file is over http
  310. if SCHEME_RE.search(filename):
  311. # do a url join so relative paths work
  312. req_path = urllib.parse.urljoin(filename, req_path)
  313. # original file and nested file are paths
  314. elif not SCHEME_RE.search(req_path):
  315. # do a join so relative paths work
  316. # and then abspath so that we can identify recursive references
  317. req_path = os.path.abspath(
  318. os.path.join(
  319. os.path.dirname(filename),
  320. req_path,
  321. )
  322. )
  323. parsed_files = parsed_files_stack[0]
  324. if req_path in parsed_files:
  325. initial_file = parsed_files[req_path]
  326. tail = (
  327. f" and again in {initial_file}"
  328. if initial_file is not None
  329. else ""
  330. )
  331. raise RequirementsFileParseError(
  332. f"{req_path} recursively references itself in {filename}{tail}"
  333. )
  334. # Keeping a track where was each file first included in
  335. new_parsed_files = parsed_files.copy()
  336. new_parsed_files[req_path] = filename
  337. yield from self._parse_and_recurse(
  338. req_path, nested_constraint, [new_parsed_files, *parsed_files_stack]
  339. )
  340. else:
  341. yield line
  342. def _parse_file(
  343. self, filename: str, constraint: bool
  344. ) -> Generator[ParsedLine, None, None]:
  345. _, content = get_file_content(filename, self._session)
  346. lines_enum = preprocess(content)
  347. for line_number, line in lines_enum:
  348. try:
  349. args_str, opts = self._line_parser(line)
  350. except OptionParsingError as e:
  351. # add offending line
  352. msg = f"Invalid requirement: {line}\n{e.msg}"
  353. raise RequirementsFileParseError(msg)
  354. yield ParsedLine(
  355. filename,
  356. line_number,
  357. args_str,
  358. opts,
  359. constraint,
  360. )
  361. def get_line_parser(finder: PackageFinder | None) -> LineParser:
  362. def parse_line(line: str) -> tuple[str, Values]:
  363. # Build new parser for each line since it accumulates appendable
  364. # options.
  365. parser = build_parser()
  366. defaults = parser.get_default_values()
  367. defaults.index_url = None
  368. if finder:
  369. defaults.format_control = finder.format_control
  370. args_str, options_str = break_args_options(line)
  371. try:
  372. options = shlex.split(options_str)
  373. except ValueError as e:
  374. raise OptionParsingError(f"Could not split options: {options_str}") from e
  375. opts, _ = parser.parse_args(options, defaults)
  376. return args_str, opts
  377. return parse_line
  378. def break_args_options(line: str) -> tuple[str, str]:
  379. """Break up the line into an args and options string. We only want to shlex
  380. (and then optparse) the options, not the args. args can contain markers
  381. which are corrupted by shlex.
  382. """
  383. tokens = line.split(" ")
  384. args = []
  385. options = tokens[:]
  386. for token in tokens:
  387. if token.startswith(("-", "--")):
  388. break
  389. else:
  390. args.append(token)
  391. options.pop(0)
  392. return " ".join(args), " ".join(options)
  393. class OptionParsingError(Exception):
  394. def __init__(self, msg: str) -> None:
  395. self.msg = msg
  396. def build_parser() -> optparse.OptionParser:
  397. """
  398. Return a parser for parsing requirement lines
  399. """
  400. parser = optparse.OptionParser(add_help_option=False)
  401. option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
  402. for option_factory in option_factories:
  403. option = option_factory()
  404. parser.add_option(option)
  405. # By default optparse sys.exits on parsing errors. We want to wrap
  406. # that in our own exception.
  407. def parser_exit(self: Any, msg: str) -> NoReturn:
  408. raise OptionParsingError(msg)
  409. # NOTE: mypy disallows assigning to a method
  410. # https://github.com/python/mypy/issues/2427
  411. parser.exit = parser_exit # type: ignore
  412. return parser
  413. def join_lines(lines_enum: ReqFileLines) -> ReqFileLines:
  414. """Joins a line ending in '\' with the previous line (except when following
  415. comments). The joined line takes on the index of the first line.
  416. """
  417. primary_line_number = None
  418. new_line: list[str] = []
  419. for line_number, line in lines_enum:
  420. if not line.endswith("\\") or COMMENT_RE.match(line):
  421. if COMMENT_RE.match(line):
  422. # this ensures comments are always matched later
  423. line = " " + line
  424. if new_line:
  425. new_line.append(line)
  426. assert primary_line_number is not None
  427. yield primary_line_number, "".join(new_line)
  428. new_line = []
  429. else:
  430. yield line_number, line
  431. else:
  432. if not new_line:
  433. primary_line_number = line_number
  434. new_line.append(line.strip("\\"))
  435. # last line contains \
  436. if new_line:
  437. assert primary_line_number is not None
  438. yield primary_line_number, "".join(new_line)
  439. # TODO: handle space after '\'.
  440. def ignore_comments(lines_enum: ReqFileLines) -> ReqFileLines:
  441. """
  442. Strips comments and filter empty lines.
  443. """
  444. for line_number, line in lines_enum:
  445. line = COMMENT_RE.sub("", line)
  446. line = line.strip()
  447. if line:
  448. yield line_number, line
  449. def expand_env_variables(lines_enum: ReqFileLines) -> ReqFileLines:
  450. """Replace all environment variables that can be retrieved via `os.getenv`.
  451. The only allowed format for environment variables defined in the
  452. requirement file is `${MY_VARIABLE_1}` to ensure two things:
  453. 1. Strings that contain a `$` aren't accidentally (partially) expanded.
  454. 2. Ensure consistency across platforms for requirement files.
  455. These points are the result of a discussion on the `github pull
  456. request #3514 <https://github.com/pypa/pip/pull/3514>`_.
  457. Valid characters in variable names follow the `POSIX standard
  458. <http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited
  459. to uppercase letter, digits and the `_` (underscore).
  460. """
  461. for line_number, line in lines_enum:
  462. for env_var, var_name in ENV_VAR_RE.findall(line):
  463. value = os.getenv(var_name)
  464. if not value:
  465. continue
  466. line = line.replace(env_var, value)
  467. yield line_number, line
  468. def get_file_content(url: str, session: PipSession) -> tuple[str, str]:
  469. """Gets the content of a file; it may be a filename, file: URL, or
  470. http: URL. Returns (location, content). Content is unicode.
  471. Respects # -*- coding: declarations on the retrieved files.
  472. :param url: File path or url.
  473. :param session: PipSession instance.
  474. """
  475. scheme = urllib.parse.urlsplit(url).scheme
  476. # Pip has special support for file:// URLs (LocalFSAdapter).
  477. if scheme in ["http", "https", "file"]:
  478. # Delay importing heavy network modules until absolutely necessary.
  479. from pip._internal.network.utils import raise_for_status
  480. resp = session.get(url)
  481. raise_for_status(resp)
  482. return resp.url, resp.text
  483. # Assume this is a bare path.
  484. try:
  485. with open(url, "rb") as f:
  486. raw_content = f.read()
  487. except OSError as exc:
  488. raise InstallationError(f"Could not open requirements file: {exc}")
  489. content = _decode_req_file(raw_content, url)
  490. return url, content
  491. def _decode_req_file(data: bytes, url: str) -> str:
  492. for bom, encoding in BOMS:
  493. if data.startswith(bom):
  494. return data[len(bom) :].decode(encoding)
  495. for line in data.split(b"\n")[:2]:
  496. if line[0:1] == b"#":
  497. result = PEP263_ENCODING_RE.search(line)
  498. if result is not None:
  499. encoding = result.groups()[0].decode("ascii")
  500. return data.decode(encoding)
  501. try:
  502. return data.decode(DEFAULT_ENCODING)
  503. except UnicodeDecodeError:
  504. locale_encoding = locale.getpreferredencoding(False) or sys.getdefaultencoding()
  505. logging.warning(
  506. "unable to decode data from %s with default encoding %s, "
  507. "falling back to encoding from locale: %s. "
  508. "If this is intentional you should specify the encoding with a "
  509. "PEP-263 style comment, e.g. '# -*- coding: %s -*-'",
  510. url,
  511. DEFAULT_ENCODING,
  512. locale_encoding,
  513. locale_encoding,
  514. )
  515. return data.decode(locale_encoding)