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