m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

576 lines
19 KiB

6 months ago
  1. """Backing implementation for InstallRequirement's various constructors
  2. The idea here is that these formed a major chunk of InstallRequirement's size
  3. so, moving them and support code dedicated to them outside of that class
  4. helps creates for better understandability for the rest of the code.
  5. These are meant to be used elsewhere within pip to create instances of
  6. InstallRequirement.
  7. """
  8. import copy
  9. import logging
  10. import os
  11. import re
  12. from typing import Collection, Dict, List, Optional, Set, Tuple, Union
  13. from pip._vendor.packaging.markers import Marker
  14. from pip._vendor.packaging.requirements import InvalidRequirement, Requirement
  15. from pip._vendor.packaging.specifiers import Specifier
  16. from pip._internal.exceptions import InstallationError
  17. from pip._internal.models.index import PyPI, TestPyPI
  18. from pip._internal.models.link import Link
  19. from pip._internal.models.wheel import Wheel
  20. from pip._internal.req.req_file import ParsedRequirement
  21. from pip._internal.req.req_install import InstallRequirement
  22. from pip._internal.utils.filetypes import is_archive_file
  23. from pip._internal.utils.misc import is_installable_dir
  24. from pip._internal.utils.packaging import get_requirement
  25. from pip._internal.utils.urls import path_to_url
  26. from pip._internal.vcs import is_url, vcs
  27. __all__ = [
  28. "install_req_from_editable",
  29. "install_req_from_line",
  30. "parse_editable",
  31. ]
  32. logger = logging.getLogger(__name__)
  33. operators = Specifier._operators.keys()
  34. def _strip_extras(path: str) -> Tuple[str, Optional[str]]:
  35. m = re.match(r"^(.+)(\[[^\]]+\])$", path)
  36. extras = None
  37. if m:
  38. path_no_extras = m.group(1)
  39. extras = m.group(2)
  40. else:
  41. path_no_extras = path
  42. return path_no_extras, extras
  43. def convert_extras(extras: Optional[str]) -> Set[str]:
  44. if not extras:
  45. return set()
  46. return get_requirement("placeholder" + extras.lower()).extras
  47. def _set_requirement_extras(req: Requirement, new_extras: Set[str]) -> Requirement:
  48. """
  49. Returns a new requirement based on the given one, with the supplied extras. If the
  50. given requirement already has extras those are replaced (or dropped if no new extras
  51. are given).
  52. """
  53. match: Optional[re.Match[str]] = re.fullmatch(
  54. # see https://peps.python.org/pep-0508/#complete-grammar
  55. r"([\w\t .-]+)(\[[^\]]*\])?(.*)",
  56. str(req),
  57. flags=re.ASCII,
  58. )
  59. # ireq.req is a valid requirement so the regex should always match
  60. assert (
  61. match is not None
  62. ), f"regex match on requirement {req} failed, this should never happen"
  63. pre: Optional[str] = match.group(1)
  64. post: Optional[str] = match.group(3)
  65. assert (
  66. pre is not None and post is not None
  67. ), f"regex group selection for requirement {req} failed, this should never happen"
  68. extras: str = "[%s]" % ",".join(sorted(new_extras)) if new_extras else ""
  69. return Requirement(f"{pre}{extras}{post}")
  70. def parse_editable(editable_req: str) -> Tuple[Optional[str], str, Set[str]]:
  71. """Parses an editable requirement into:
  72. - a requirement name
  73. - an URL
  74. - extras
  75. - editable options
  76. Accepted requirements:
  77. svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir
  78. .[some_extra]
  79. """
  80. url = editable_req
  81. # If a file path is specified with extras, strip off the extras.
  82. url_no_extras, extras = _strip_extras(url)
  83. if os.path.isdir(url_no_extras):
  84. # Treating it as code that has already been checked out
  85. url_no_extras = path_to_url(url_no_extras)
  86. if url_no_extras.lower().startswith("file:"):
  87. package_name = Link(url_no_extras).egg_fragment
  88. if extras:
  89. return (
  90. package_name,
  91. url_no_extras,
  92. get_requirement("placeholder" + extras.lower()).extras,
  93. )
  94. else:
  95. return package_name, url_no_extras, set()
  96. for version_control in vcs:
  97. if url.lower().startswith(f"{version_control}:"):
  98. url = f"{version_control}+{url}"
  99. break
  100. link = Link(url)
  101. if not link.is_vcs:
  102. backends = ", ".join(vcs.all_schemes)
  103. raise InstallationError(
  104. f"{editable_req} is not a valid editable requirement. "
  105. f"It should either be a path to a local project or a VCS URL "
  106. f"(beginning with {backends})."
  107. )
  108. package_name = link.egg_fragment
  109. if not package_name:
  110. raise InstallationError(
  111. "Could not detect requirement name for '{}', please specify one "
  112. "with #egg=your_package_name".format(editable_req)
  113. )
  114. return package_name, url, set()
  115. def check_first_requirement_in_file(filename: str) -> None:
  116. """Check if file is parsable as a requirements file.
  117. This is heavily based on ``pkg_resources.parse_requirements``, but
  118. simplified to just check the first meaningful line.
  119. :raises InvalidRequirement: If the first meaningful line cannot be parsed
  120. as an requirement.
  121. """
  122. with open(filename, encoding="utf-8", errors="ignore") as f:
  123. # Create a steppable iterator, so we can handle \-continuations.
  124. lines = (
  125. line
  126. for line in (line.strip() for line in f)
  127. if line and not line.startswith("#") # Skip blank lines/comments.
  128. )
  129. for line in lines:
  130. # Drop comments -- a hash without a space may be in a URL.
  131. if " #" in line:
  132. line = line[: line.find(" #")]
  133. # If there is a line continuation, drop it, and append the next line.
  134. if line.endswith("\\"):
  135. line = line[:-2].strip() + next(lines, "")
  136. Requirement(line)
  137. return
  138. def deduce_helpful_msg(req: str) -> str:
  139. """Returns helpful msg in case requirements file does not exist,
  140. or cannot be parsed.
  141. :params req: Requirements file path
  142. """
  143. if not os.path.exists(req):
  144. return f" File '{req}' does not exist."
  145. msg = " The path does exist. "
  146. # Try to parse and check if it is a requirements file.
  147. try:
  148. check_first_requirement_in_file(req)
  149. except InvalidRequirement:
  150. logger.debug("Cannot parse '%s' as requirements file", req)
  151. else:
  152. msg += (
  153. f"The argument you provided "
  154. f"({req}) appears to be a"
  155. f" requirements file. If that is the"
  156. f" case, use the '-r' flag to install"
  157. f" the packages specified within it."
  158. )
  159. return msg
  160. class RequirementParts:
  161. def __init__(
  162. self,
  163. requirement: Optional[Requirement],
  164. link: Optional[Link],
  165. markers: Optional[Marker],
  166. extras: Set[str],
  167. ):
  168. self.requirement = requirement
  169. self.link = link
  170. self.markers = markers
  171. self.extras = extras
  172. def parse_req_from_editable(editable_req: str) -> RequirementParts:
  173. name, url, extras_override = parse_editable(editable_req)
  174. if name is not None:
  175. try:
  176. req: Optional[Requirement] = Requirement(name)
  177. except InvalidRequirement:
  178. raise InstallationError(f"Invalid requirement: '{name}'")
  179. else:
  180. req = None
  181. link = Link(url)
  182. return RequirementParts(req, link, None, extras_override)
  183. # ---- The actual constructors follow ----
  184. def install_req_from_editable(
  185. editable_req: str,
  186. comes_from: Optional[Union[InstallRequirement, str]] = None,
  187. *,
  188. use_pep517: Optional[bool] = None,
  189. isolated: bool = False,
  190. global_options: Optional[List[str]] = None,
  191. hash_options: Optional[Dict[str, List[str]]] = None,
  192. constraint: bool = False,
  193. user_supplied: bool = False,
  194. permit_editable_wheels: bool = False,
  195. config_settings: Optional[Dict[str, Union[str, List[str]]]] = None,
  196. ) -> InstallRequirement:
  197. parts = parse_req_from_editable(editable_req)
  198. return InstallRequirement(
  199. parts.requirement,
  200. comes_from=comes_from,
  201. user_supplied=user_supplied,
  202. editable=True,
  203. permit_editable_wheels=permit_editable_wheels,
  204. link=parts.link,
  205. constraint=constraint,
  206. use_pep517=use_pep517,
  207. isolated=isolated,
  208. global_options=global_options,
  209. hash_options=hash_options,
  210. config_settings=config_settings,
  211. extras=parts.extras,
  212. )
  213. def _looks_like_path(name: str) -> bool:
  214. """Checks whether the string "looks like" a path on the filesystem.
  215. This does not check whether the target actually exists, only judge from the
  216. appearance.
  217. Returns true if any of the following conditions is true:
  218. * a path separator is found (either os.path.sep or os.path.altsep);
  219. * a dot is found (which represents the current directory).
  220. """
  221. if os.path.sep in name:
  222. return True
  223. if os.path.altsep is not None and os.path.altsep in name:
  224. return True
  225. if name.startswith("."):
  226. return True
  227. return False
  228. def _get_url_from_path(path: str, name: str) -> Optional[str]:
  229. """
  230. First, it checks whether a provided path is an installable directory. If it
  231. is, returns the path.
  232. If false, check if the path is an archive file (such as a .whl).
  233. The function checks if the path is a file. If false, if the path has
  234. an @, it will treat it as a PEP 440 URL requirement and return the path.
  235. """
  236. if _looks_like_path(name) and os.path.isdir(path):
  237. if is_installable_dir(path):
  238. return path_to_url(path)
  239. # TODO: The is_installable_dir test here might not be necessary
  240. # now that it is done in load_pyproject_toml too.
  241. raise InstallationError(
  242. f"Directory {name!r} is not installable. Neither 'setup.py' "
  243. "nor 'pyproject.toml' found."
  244. )
  245. if not is_archive_file(path):
  246. return None
  247. if os.path.isfile(path):
  248. return path_to_url(path)
  249. urlreq_parts = name.split("@", 1)
  250. if len(urlreq_parts) >= 2 and not _looks_like_path(urlreq_parts[0]):
  251. # If the path contains '@' and the part before it does not look
  252. # like a path, try to treat it as a PEP 440 URL req instead.
  253. return None
  254. logger.warning(
  255. "Requirement %r looks like a filename, but the file does not exist",
  256. name,
  257. )
  258. return path_to_url(path)
  259. def parse_req_from_line(name: str, line_source: Optional[str]) -> RequirementParts:
  260. if is_url(name):
  261. marker_sep = "; "
  262. else:
  263. marker_sep = ";"
  264. if marker_sep in name:
  265. name, markers_as_string = name.split(marker_sep, 1)
  266. markers_as_string = markers_as_string.strip()
  267. if not markers_as_string:
  268. markers = None
  269. else:
  270. markers = Marker(markers_as_string)
  271. else:
  272. markers = None
  273. name = name.strip()
  274. req_as_string = None
  275. path = os.path.normpath(os.path.abspath(name))
  276. link = None
  277. extras_as_string = None
  278. if is_url(name):
  279. link = Link(name)
  280. else:
  281. p, extras_as_string = _strip_extras(path)
  282. url = _get_url_from_path(p, name)
  283. if url is not None:
  284. link = Link(url)
  285. # it's a local file, dir, or url
  286. if link:
  287. # Handle relative file URLs
  288. if link.scheme == "file" and re.search(r"\.\./", link.url):
  289. link = Link(path_to_url(os.path.normpath(os.path.abspath(link.path))))
  290. # wheel file
  291. if link.is_wheel:
  292. wheel = Wheel(link.filename) # can raise InvalidWheelFilename
  293. req_as_string = f"{wheel.name}=={wheel.version}"
  294. else:
  295. # set the req to the egg fragment. when it's not there, this
  296. # will become an 'unnamed' requirement
  297. req_as_string = link.egg_fragment
  298. # a requirement specifier
  299. else:
  300. req_as_string = name
  301. extras = convert_extras(extras_as_string)
  302. def with_source(text: str) -> str:
  303. if not line_source:
  304. return text
  305. return f"{text} (from {line_source})"
  306. def _parse_req_string(req_as_string: str) -> Requirement:
  307. try:
  308. req = get_requirement(req_as_string)
  309. except InvalidRequirement:
  310. if os.path.sep in req_as_string:
  311. add_msg = "It looks like a path."
  312. add_msg += deduce_helpful_msg(req_as_string)
  313. elif "=" in req_as_string and not any(
  314. op in req_as_string for op in operators
  315. ):
  316. add_msg = "= is not a valid operator. Did you mean == ?"
  317. else:
  318. add_msg = ""
  319. msg = with_source(f"Invalid requirement: {req_as_string!r}")
  320. if add_msg:
  321. msg += f"\nHint: {add_msg}"
  322. raise InstallationError(msg)
  323. else:
  324. # Deprecate extras after specifiers: "name>=1.0[extras]"
  325. # This currently works by accident because _strip_extras() parses
  326. # any extras in the end of the string and those are saved in
  327. # RequirementParts
  328. for spec in req.specifier:
  329. spec_str = str(spec)
  330. if spec_str.endswith("]"):
  331. msg = f"Extras after version '{spec_str}'."
  332. raise InstallationError(msg)
  333. return req
  334. if req_as_string is not None:
  335. req: Optional[Requirement] = _parse_req_string(req_as_string)
  336. else:
  337. req = None
  338. return RequirementParts(req, link, markers, extras)
  339. def install_req_from_line(
  340. name: str,
  341. comes_from: Optional[Union[str, InstallRequirement]] = None,
  342. *,
  343. use_pep517: Optional[bool] = None,
  344. isolated: bool = False,
  345. global_options: Optional[List[str]] = None,
  346. hash_options: Optional[Dict[str, List[str]]] = None,
  347. constraint: bool = False,
  348. line_source: Optional[str] = None,
  349. user_supplied: bool = False,
  350. config_settings: Optional[Dict[str, Union[str, List[str]]]] = None,
  351. ) -> InstallRequirement:
  352. """Creates an InstallRequirement from a name, which might be a
  353. requirement, directory containing 'setup.py', filename, or URL.
  354. :param line_source: An optional string describing where the line is from,
  355. for logging purposes in case of an error.
  356. """
  357. parts = parse_req_from_line(name, line_source)
  358. return InstallRequirement(
  359. parts.requirement,
  360. comes_from,
  361. link=parts.link,
  362. markers=parts.markers,
  363. use_pep517=use_pep517,
  364. isolated=isolated,
  365. global_options=global_options,
  366. hash_options=hash_options,
  367. config_settings=config_settings,
  368. constraint=constraint,
  369. extras=parts.extras,
  370. user_supplied=user_supplied,
  371. )
  372. def install_req_from_req_string(
  373. req_string: str,
  374. comes_from: Optional[InstallRequirement] = None,
  375. isolated: bool = False,
  376. use_pep517: Optional[bool] = None,
  377. user_supplied: bool = False,
  378. ) -> InstallRequirement:
  379. try:
  380. req = get_requirement(req_string)
  381. except InvalidRequirement:
  382. raise InstallationError(f"Invalid requirement: '{req_string}'")
  383. domains_not_allowed = [
  384. PyPI.file_storage_domain,
  385. TestPyPI.file_storage_domain,
  386. ]
  387. if (
  388. req.url
  389. and comes_from
  390. and comes_from.link
  391. and comes_from.link.netloc in domains_not_allowed
  392. ):
  393. # Explicitly disallow pypi packages that depend on external urls
  394. raise InstallationError(
  395. "Packages installed from PyPI cannot depend on packages "
  396. "which are not also hosted on PyPI.\n"
  397. f"{comes_from.name} depends on {req} "
  398. )
  399. return InstallRequirement(
  400. req,
  401. comes_from,
  402. isolated=isolated,
  403. use_pep517=use_pep517,
  404. user_supplied=user_supplied,
  405. )
  406. def install_req_from_parsed_requirement(
  407. parsed_req: ParsedRequirement,
  408. isolated: bool = False,
  409. use_pep517: Optional[bool] = None,
  410. user_supplied: bool = False,
  411. config_settings: Optional[Dict[str, Union[str, List[str]]]] = None,
  412. ) -> InstallRequirement:
  413. if parsed_req.is_editable:
  414. req = install_req_from_editable(
  415. parsed_req.requirement,
  416. comes_from=parsed_req.comes_from,
  417. use_pep517=use_pep517,
  418. constraint=parsed_req.constraint,
  419. isolated=isolated,
  420. user_supplied=user_supplied,
  421. config_settings=config_settings,
  422. )
  423. else:
  424. req = install_req_from_line(
  425. parsed_req.requirement,
  426. comes_from=parsed_req.comes_from,
  427. use_pep517=use_pep517,
  428. isolated=isolated,
  429. global_options=(
  430. parsed_req.options.get("global_options", [])
  431. if parsed_req.options
  432. else []
  433. ),
  434. hash_options=(
  435. parsed_req.options.get("hashes", {}) if parsed_req.options else {}
  436. ),
  437. constraint=parsed_req.constraint,
  438. line_source=parsed_req.line_source,
  439. user_supplied=user_supplied,
  440. config_settings=config_settings,
  441. )
  442. return req
  443. def install_req_from_link_and_ireq(
  444. link: Link, ireq: InstallRequirement
  445. ) -> InstallRequirement:
  446. return InstallRequirement(
  447. req=ireq.req,
  448. comes_from=ireq.comes_from,
  449. editable=ireq.editable,
  450. link=link,
  451. markers=ireq.markers,
  452. use_pep517=ireq.use_pep517,
  453. isolated=ireq.isolated,
  454. global_options=ireq.global_options,
  455. hash_options=ireq.hash_options,
  456. config_settings=ireq.config_settings,
  457. user_supplied=ireq.user_supplied,
  458. )
  459. def install_req_drop_extras(ireq: InstallRequirement) -> InstallRequirement:
  460. """
  461. Creates a new InstallationRequirement using the given template but without
  462. any extras. Sets the original requirement as the new one's parent
  463. (comes_from).
  464. """
  465. return InstallRequirement(
  466. req=(
  467. _set_requirement_extras(ireq.req, set()) if ireq.req is not None else None
  468. ),
  469. comes_from=ireq,
  470. editable=ireq.editable,
  471. link=ireq.link,
  472. markers=ireq.markers,
  473. use_pep517=ireq.use_pep517,
  474. isolated=ireq.isolated,
  475. global_options=ireq.global_options,
  476. hash_options=ireq.hash_options,
  477. constraint=ireq.constraint,
  478. extras=[],
  479. config_settings=ireq.config_settings,
  480. user_supplied=ireq.user_supplied,
  481. permit_editable_wheels=ireq.permit_editable_wheels,
  482. )
  483. def install_req_extend_extras(
  484. ireq: InstallRequirement,
  485. extras: Collection[str],
  486. ) -> InstallRequirement:
  487. """
  488. Returns a copy of an installation requirement with some additional extras.
  489. Makes a shallow copy of the ireq object.
  490. """
  491. result = copy.copy(ireq)
  492. result.extras = {*ireq.extras, *extras}
  493. result.req = (
  494. _set_requirement_extras(ireq.req, result.extras)
  495. if ireq.req is not None
  496. else None
  497. )
  498. return result