constructors.py 16 KB

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