req_file.py 17 KB

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