constructors.py 16 KB

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