cmdoptions.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. """
  2. shared options and groups
  3. The principle here is to define options once, but *not* instantiate them
  4. globally. One reason being that options with action='append' can carry state
  5. between parses. pip parses general options twice internally, and shouldn't
  6. pass on state. To be consistent, all options will follow this design.
  7. """
  8. # The following comment should be removed at some point in the future.
  9. # mypy: strict-optional=False
  10. import importlib.util
  11. import logging
  12. import os
  13. import textwrap
  14. from functools import partial
  15. from optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values
  16. from textwrap import dedent
  17. from typing import Any, Callable, Dict, Optional, Tuple
  18. from pip._vendor.packaging.utils import canonicalize_name
  19. from pip._internal.cli.parser import ConfigOptionParser
  20. from pip._internal.exceptions import CommandError
  21. from pip._internal.locations import USER_CACHE_DIR, get_src_prefix
  22. from pip._internal.models.format_control import FormatControl
  23. from pip._internal.models.index import PyPI
  24. from pip._internal.models.target_python import TargetPython
  25. from pip._internal.utils.hashes import STRONG_HASHES
  26. from pip._internal.utils.misc import strtobool
  27. logger = logging.getLogger(__name__)
  28. def raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:
  29. """
  30. Raise an option parsing error using parser.error().
  31. Args:
  32. parser: an OptionParser instance.
  33. option: an Option instance.
  34. msg: the error text.
  35. """
  36. msg = f"{option} error: {msg}"
  37. msg = textwrap.fill(" ".join(msg.split()))
  38. parser.error(msg)
  39. def make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:
  40. """
  41. Return an OptionGroup object
  42. group -- assumed to be dict with 'name' and 'options' keys
  43. parser -- an optparse Parser
  44. """
  45. option_group = OptionGroup(parser, group["name"])
  46. for option in group["options"]:
  47. option_group.add_option(option())
  48. return option_group
  49. def check_install_build_global(
  50. options: Values, check_options: Optional[Values] = None
  51. ) -> None:
  52. """Disable wheels if per-setup.py call options are set.
  53. :param options: The OptionParser options to update.
  54. :param check_options: The options to check, if not supplied defaults to
  55. options.
  56. """
  57. if check_options is None:
  58. check_options = options
  59. def getname(n: str) -> Optional[Any]:
  60. return getattr(check_options, n, None)
  61. names = ["build_options", "global_options", "install_options"]
  62. if any(map(getname, names)):
  63. control = options.format_control
  64. control.disallow_binaries()
  65. logger.warning(
  66. "Disabling all use of wheels due to the use of --build-option "
  67. "/ --global-option / --install-option.",
  68. )
  69. def check_dist_restriction(options: Values, check_target: bool = False) -> None:
  70. """Function for determining if custom platform options are allowed.
  71. :param options: The OptionParser options.
  72. :param check_target: Whether or not to check if --target is being used.
  73. """
  74. dist_restriction_set = any(
  75. [
  76. options.python_version,
  77. options.platforms,
  78. options.abis,
  79. options.implementation,
  80. ]
  81. )
  82. binary_only = FormatControl(set(), {":all:"})
  83. sdist_dependencies_allowed = (
  84. options.format_control != binary_only and not options.ignore_dependencies
  85. )
  86. # Installations or downloads using dist restrictions must not combine
  87. # source distributions and dist-specific wheels, as they are not
  88. # guaranteed to be locally compatible.
  89. if dist_restriction_set and sdist_dependencies_allowed:
  90. raise CommandError(
  91. "When restricting platform and interpreter constraints using "
  92. "--python-version, --platform, --abi, or --implementation, "
  93. "either --no-deps must be set, or --only-binary=:all: must be "
  94. "set and --no-binary must not be set (or must be set to "
  95. ":none:)."
  96. )
  97. if check_target:
  98. if dist_restriction_set and not options.target_dir:
  99. raise CommandError(
  100. "Can not use any platform or abi specific options unless "
  101. "installing via '--target'"
  102. )
  103. def _path_option_check(option: Option, opt: str, value: str) -> str:
  104. return os.path.expanduser(value)
  105. def _package_name_option_check(option: Option, opt: str, value: str) -> str:
  106. return canonicalize_name(value)
  107. class PipOption(Option):
  108. TYPES = Option.TYPES + ("path", "package_name")
  109. TYPE_CHECKER = Option.TYPE_CHECKER.copy()
  110. TYPE_CHECKER["package_name"] = _package_name_option_check
  111. TYPE_CHECKER["path"] = _path_option_check
  112. ###########
  113. # options #
  114. ###########
  115. help_: Callable[..., Option] = partial(
  116. Option,
  117. "-h",
  118. "--help",
  119. dest="help",
  120. action="help",
  121. help="Show help.",
  122. )
  123. debug_mode: Callable[..., Option] = partial(
  124. Option,
  125. "--debug",
  126. dest="debug_mode",
  127. action="store_true",
  128. default=False,
  129. help=(
  130. "Let unhandled exceptions propagate outside the main subroutine, "
  131. "instead of logging them to stderr."
  132. ),
  133. )
  134. isolated_mode: Callable[..., Option] = partial(
  135. Option,
  136. "--isolated",
  137. dest="isolated_mode",
  138. action="store_true",
  139. default=False,
  140. help=(
  141. "Run pip in an isolated mode, ignoring environment variables and user "
  142. "configuration."
  143. ),
  144. )
  145. require_virtualenv: Callable[..., Option] = partial(
  146. Option,
  147. "--require-virtualenv",
  148. "--require-venv",
  149. dest="require_venv",
  150. action="store_true",
  151. default=False,
  152. help=(
  153. "Allow pip to only run in a virtual environment; "
  154. "exit with an error otherwise."
  155. ),
  156. )
  157. verbose: Callable[..., Option] = partial(
  158. Option,
  159. "-v",
  160. "--verbose",
  161. dest="verbose",
  162. action="count",
  163. default=0,
  164. help="Give more output. Option is additive, and can be used up to 3 times.",
  165. )
  166. no_color: Callable[..., Option] = partial(
  167. Option,
  168. "--no-color",
  169. dest="no_color",
  170. action="store_true",
  171. default=False,
  172. help="Suppress colored output.",
  173. )
  174. version: Callable[..., Option] = partial(
  175. Option,
  176. "-V",
  177. "--version",
  178. dest="version",
  179. action="store_true",
  180. help="Show version and exit.",
  181. )
  182. quiet: Callable[..., Option] = partial(
  183. Option,
  184. "-q",
  185. "--quiet",
  186. dest="quiet",
  187. action="count",
  188. default=0,
  189. help=(
  190. "Give less output. Option is additive, and can be used up to 3"
  191. " times (corresponding to WARNING, ERROR, and CRITICAL logging"
  192. " levels)."
  193. ),
  194. )
  195. progress_bar: Callable[..., Option] = partial(
  196. Option,
  197. "--progress-bar",
  198. dest="progress_bar",
  199. type="choice",
  200. choices=["on", "off"],
  201. default="on",
  202. help="Specify whether the progress bar should be used [on, off] (default: on)",
  203. )
  204. log: Callable[..., Option] = partial(
  205. PipOption,
  206. "--log",
  207. "--log-file",
  208. "--local-log",
  209. dest="log",
  210. metavar="path",
  211. type="path",
  212. help="Path to a verbose appending log.",
  213. )
  214. no_input: Callable[..., Option] = partial(
  215. Option,
  216. # Don't ask for input
  217. "--no-input",
  218. dest="no_input",
  219. action="store_true",
  220. default=False,
  221. help="Disable prompting for input.",
  222. )
  223. proxy: Callable[..., Option] = partial(
  224. Option,
  225. "--proxy",
  226. dest="proxy",
  227. type="str",
  228. default="",
  229. help="Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.",
  230. )
  231. retries: Callable[..., Option] = partial(
  232. Option,
  233. "--retries",
  234. dest="retries",
  235. type="int",
  236. default=5,
  237. help="Maximum number of retries each connection should attempt "
  238. "(default %default times).",
  239. )
  240. timeout: Callable[..., Option] = partial(
  241. Option,
  242. "--timeout",
  243. "--default-timeout",
  244. metavar="sec",
  245. dest="timeout",
  246. type="float",
  247. default=15,
  248. help="Set the socket timeout (default %default seconds).",
  249. )
  250. def exists_action() -> Option:
  251. return Option(
  252. # Option when path already exist
  253. "--exists-action",
  254. dest="exists_action",
  255. type="choice",
  256. choices=["s", "i", "w", "b", "a"],
  257. default=[],
  258. action="append",
  259. metavar="action",
  260. help="Default action when a path already exists: "
  261. "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.",
  262. )
  263. cert: Callable[..., Option] = partial(
  264. PipOption,
  265. "--cert",
  266. dest="cert",
  267. type="path",
  268. metavar="path",
  269. help=(
  270. "Path to PEM-encoded CA certificate bundle. "
  271. "If provided, overrides the default. "
  272. "See 'SSL Certificate Verification' in pip documentation "
  273. "for more information."
  274. ),
  275. )
  276. client_cert: Callable[..., Option] = partial(
  277. PipOption,
  278. "--client-cert",
  279. dest="client_cert",
  280. type="path",
  281. default=None,
  282. metavar="path",
  283. help="Path to SSL client certificate, a single file containing the "
  284. "private key and the certificate in PEM format.",
  285. )
  286. index_url: Callable[..., Option] = partial(
  287. Option,
  288. "-i",
  289. "--index-url",
  290. "--pypi-url",
  291. dest="index_url",
  292. metavar="URL",
  293. default=PyPI.simple_url,
  294. help="Base URL of the Python Package Index (default %default). "
  295. "This should point to a repository compliant with PEP 503 "
  296. "(the simple repository API) or a local directory laid out "
  297. "in the same format.",
  298. )
  299. def extra_index_url() -> Option:
  300. return Option(
  301. "--extra-index-url",
  302. dest="extra_index_urls",
  303. metavar="URL",
  304. action="append",
  305. default=[],
  306. help="Extra URLs of package indexes to use in addition to "
  307. "--index-url. Should follow the same rules as "
  308. "--index-url.",
  309. )
  310. no_index: Callable[..., Option] = partial(
  311. Option,
  312. "--no-index",
  313. dest="no_index",
  314. action="store_true",
  315. default=False,
  316. help="Ignore package index (only looking at --find-links URLs instead).",
  317. )
  318. def find_links() -> Option:
  319. return Option(
  320. "-f",
  321. "--find-links",
  322. dest="find_links",
  323. action="append",
  324. default=[],
  325. metavar="url",
  326. help="If a URL or path to an html file, then parse for links to "
  327. "archives such as sdist (.tar.gz) or wheel (.whl) files. "
  328. "If a local path or file:// URL that's a directory, "
  329. "then look for archives in the directory listing. "
  330. "Links to VCS project URLs are not supported.",
  331. )
  332. def trusted_host() -> Option:
  333. return Option(
  334. "--trusted-host",
  335. dest="trusted_hosts",
  336. action="append",
  337. metavar="HOSTNAME",
  338. default=[],
  339. help="Mark this host or host:port pair as trusted, even though it "
  340. "does not have valid or any HTTPS.",
  341. )
  342. def constraints() -> Option:
  343. return Option(
  344. "-c",
  345. "--constraint",
  346. dest="constraints",
  347. action="append",
  348. default=[],
  349. metavar="file",
  350. help="Constrain versions using the given constraints file. "
  351. "This option can be used multiple times.",
  352. )
  353. def requirements() -> Option:
  354. return Option(
  355. "-r",
  356. "--requirement",
  357. dest="requirements",
  358. action="append",
  359. default=[],
  360. metavar="file",
  361. help="Install from the given requirements file. "
  362. "This option can be used multiple times.",
  363. )
  364. def editable() -> Option:
  365. return Option(
  366. "-e",
  367. "--editable",
  368. dest="editables",
  369. action="append",
  370. default=[],
  371. metavar="path/url",
  372. help=(
  373. "Install a project in editable mode (i.e. setuptools "
  374. '"develop mode") from a local project path or a VCS url.'
  375. ),
  376. )
  377. def _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:
  378. value = os.path.abspath(value)
  379. setattr(parser.values, option.dest, value)
  380. src: Callable[..., Option] = partial(
  381. PipOption,
  382. "--src",
  383. "--source",
  384. "--source-dir",
  385. "--source-directory",
  386. dest="src_dir",
  387. type="path",
  388. metavar="dir",
  389. default=get_src_prefix(),
  390. action="callback",
  391. callback=_handle_src,
  392. help="Directory to check out editable projects into. "
  393. 'The default in a virtualenv is "<venv path>/src". '
  394. 'The default for global installs is "<current dir>/src".',
  395. )
  396. def _get_format_control(values: Values, option: Option) -> Any:
  397. """Get a format_control object."""
  398. return getattr(values, option.dest)
  399. def _handle_no_binary(
  400. option: Option, opt_str: str, value: str, parser: OptionParser
  401. ) -> None:
  402. existing = _get_format_control(parser.values, option)
  403. FormatControl.handle_mutual_excludes(
  404. value,
  405. existing.no_binary,
  406. existing.only_binary,
  407. )
  408. def _handle_only_binary(
  409. option: Option, opt_str: str, value: str, parser: OptionParser
  410. ) -> None:
  411. existing = _get_format_control(parser.values, option)
  412. FormatControl.handle_mutual_excludes(
  413. value,
  414. existing.only_binary,
  415. existing.no_binary,
  416. )
  417. def no_binary() -> Option:
  418. format_control = FormatControl(set(), set())
  419. return Option(
  420. "--no-binary",
  421. dest="format_control",
  422. action="callback",
  423. callback=_handle_no_binary,
  424. type="str",
  425. default=format_control,
  426. help="Do not use binary packages. Can be supplied multiple times, and "
  427. 'each time adds to the existing value. Accepts either ":all:" to '
  428. 'disable all binary packages, ":none:" to empty the set (notice '
  429. "the colons), or one or more package names with commas between "
  430. "them (no colons). Note that some packages are tricky to compile "
  431. "and may fail to install when this option is used on them.",
  432. )
  433. def only_binary() -> Option:
  434. format_control = FormatControl(set(), set())
  435. return Option(
  436. "--only-binary",
  437. dest="format_control",
  438. action="callback",
  439. callback=_handle_only_binary,
  440. type="str",
  441. default=format_control,
  442. help="Do not use source packages. Can be supplied multiple times, and "
  443. 'each time adds to the existing value. Accepts either ":all:" to '
  444. 'disable all source packages, ":none:" to empty the set, or one '
  445. "or more package names with commas between them. Packages "
  446. "without binary distributions will fail to install when this "
  447. "option is used on them.",
  448. )
  449. platforms: Callable[..., Option] = partial(
  450. Option,
  451. "--platform",
  452. dest="platforms",
  453. metavar="platform",
  454. action="append",
  455. default=None,
  456. help=(
  457. "Only use wheels compatible with <platform>. Defaults to the "
  458. "platform of the running system. Use this option multiple times to "
  459. "specify multiple platforms supported by the target interpreter."
  460. ),
  461. )
  462. # This was made a separate function for unit-testing purposes.
  463. def _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]:
  464. """
  465. Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.
  466. :return: A 2-tuple (version_info, error_msg), where `error_msg` is
  467. non-None if and only if there was a parsing error.
  468. """
  469. if not value:
  470. # The empty string is the same as not providing a value.
  471. return (None, None)
  472. parts = value.split(".")
  473. if len(parts) > 3:
  474. return ((), "at most three version parts are allowed")
  475. if len(parts) == 1:
  476. # Then we are in the case of "3" or "37".
  477. value = parts[0]
  478. if len(value) > 1:
  479. parts = [value[0], value[1:]]
  480. try:
  481. version_info = tuple(int(part) for part in parts)
  482. except ValueError:
  483. return ((), "each version part must be an integer")
  484. return (version_info, None)
  485. def _handle_python_version(
  486. option: Option, opt_str: str, value: str, parser: OptionParser
  487. ) -> None:
  488. """
  489. Handle a provided --python-version value.
  490. """
  491. version_info, error_msg = _convert_python_version(value)
  492. if error_msg is not None:
  493. msg = "invalid --python-version value: {!r}: {}".format(
  494. value,
  495. error_msg,
  496. )
  497. raise_option_error(parser, option=option, msg=msg)
  498. parser.values.python_version = version_info
  499. python_version: Callable[..., Option] = partial(
  500. Option,
  501. "--python-version",
  502. dest="python_version",
  503. metavar="python_version",
  504. action="callback",
  505. callback=_handle_python_version,
  506. type="str",
  507. default=None,
  508. help=dedent(
  509. """\
  510. The Python interpreter version to use for wheel and "Requires-Python"
  511. compatibility checks. Defaults to a version derived from the running
  512. interpreter. The version can be specified using up to three dot-separated
  513. integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor
  514. version can also be given as a string without dots (e.g. "37" for 3.7.0).
  515. """
  516. ),
  517. )
  518. implementation: Callable[..., Option] = partial(
  519. Option,
  520. "--implementation",
  521. dest="implementation",
  522. metavar="implementation",
  523. default=None,
  524. help=(
  525. "Only use wheels compatible with Python "
  526. "implementation <implementation>, e.g. 'pp', 'jy', 'cp', "
  527. " or 'ip'. If not specified, then the current "
  528. "interpreter implementation is used. Use 'py' to force "
  529. "implementation-agnostic wheels."
  530. ),
  531. )
  532. abis: Callable[..., Option] = partial(
  533. Option,
  534. "--abi",
  535. dest="abis",
  536. metavar="abi",
  537. action="append",
  538. default=None,
  539. help=(
  540. "Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. "
  541. "If not specified, then the current interpreter abi tag is used. "
  542. "Use this option multiple times to specify multiple abis supported "
  543. "by the target interpreter. Generally you will need to specify "
  544. "--implementation, --platform, and --python-version when using this "
  545. "option."
  546. ),
  547. )
  548. def add_target_python_options(cmd_opts: OptionGroup) -> None:
  549. cmd_opts.add_option(platforms())
  550. cmd_opts.add_option(python_version())
  551. cmd_opts.add_option(implementation())
  552. cmd_opts.add_option(abis())
  553. def make_target_python(options: Values) -> TargetPython:
  554. target_python = TargetPython(
  555. platforms=options.platforms,
  556. py_version_info=options.python_version,
  557. abis=options.abis,
  558. implementation=options.implementation,
  559. )
  560. return target_python
  561. def prefer_binary() -> Option:
  562. return Option(
  563. "--prefer-binary",
  564. dest="prefer_binary",
  565. action="store_true",
  566. default=False,
  567. help="Prefer older binary packages over newer source packages.",
  568. )
  569. cache_dir: Callable[..., Option] = partial(
  570. PipOption,
  571. "--cache-dir",
  572. dest="cache_dir",
  573. default=USER_CACHE_DIR,
  574. metavar="dir",
  575. type="path",
  576. help="Store the cache data in <dir>.",
  577. )
  578. def _handle_no_cache_dir(
  579. option: Option, opt: str, value: str, parser: OptionParser
  580. ) -> None:
  581. """
  582. Process a value provided for the --no-cache-dir option.
  583. This is an optparse.Option callback for the --no-cache-dir option.
  584. """
  585. # The value argument will be None if --no-cache-dir is passed via the
  586. # command-line, since the option doesn't accept arguments. However,
  587. # the value can be non-None if the option is triggered e.g. by an
  588. # environment variable, like PIP_NO_CACHE_DIR=true.
  589. if value is not None:
  590. # Then parse the string value to get argument error-checking.
  591. try:
  592. strtobool(value)
  593. except ValueError as exc:
  594. raise_option_error(parser, option=option, msg=str(exc))
  595. # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()
  596. # converted to 0 (like "false" or "no") caused cache_dir to be disabled
  597. # rather than enabled (logic would say the latter). Thus, we disable
  598. # the cache directory not just on values that parse to True, but (for
  599. # backwards compatibility reasons) also on values that parse to False.
  600. # In other words, always set it to False if the option is provided in
  601. # some (valid) form.
  602. parser.values.cache_dir = False
  603. no_cache: Callable[..., Option] = partial(
  604. Option,
  605. "--no-cache-dir",
  606. dest="cache_dir",
  607. action="callback",
  608. callback=_handle_no_cache_dir,
  609. help="Disable the cache.",
  610. )
  611. no_deps: Callable[..., Option] = partial(
  612. Option,
  613. "--no-deps",
  614. "--no-dependencies",
  615. dest="ignore_dependencies",
  616. action="store_true",
  617. default=False,
  618. help="Don't install package dependencies.",
  619. )
  620. ignore_requires_python: Callable[..., Option] = partial(
  621. Option,
  622. "--ignore-requires-python",
  623. dest="ignore_requires_python",
  624. action="store_true",
  625. help="Ignore the Requires-Python information.",
  626. )
  627. no_build_isolation: Callable[..., Option] = partial(
  628. Option,
  629. "--no-build-isolation",
  630. dest="build_isolation",
  631. action="store_false",
  632. default=True,
  633. help="Disable isolation when building a modern source distribution. "
  634. "Build dependencies specified by PEP 518 must be already installed "
  635. "if this option is used.",
  636. )
  637. check_build_deps: Callable[..., Option] = partial(
  638. Option,
  639. "--check-build-dependencies",
  640. dest="check_build_deps",
  641. action="store_true",
  642. default=False,
  643. help="Check the build dependencies when PEP517 is used.",
  644. )
  645. def _handle_no_use_pep517(
  646. option: Option, opt: str, value: str, parser: OptionParser
  647. ) -> None:
  648. """
  649. Process a value provided for the --no-use-pep517 option.
  650. This is an optparse.Option callback for the no_use_pep517 option.
  651. """
  652. # Since --no-use-pep517 doesn't accept arguments, the value argument
  653. # will be None if --no-use-pep517 is passed via the command-line.
  654. # However, the value can be non-None if the option is triggered e.g.
  655. # by an environment variable, for example "PIP_NO_USE_PEP517=true".
  656. if value is not None:
  657. msg = """A value was passed for --no-use-pep517,
  658. probably using either the PIP_NO_USE_PEP517 environment variable
  659. or the "no-use-pep517" config file option. Use an appropriate value
  660. of the PIP_USE_PEP517 environment variable or the "use-pep517"
  661. config file option instead.
  662. """
  663. raise_option_error(parser, option=option, msg=msg)
  664. # If user doesn't wish to use pep517, we check if setuptools is installed
  665. # and raise error if it is not.
  666. if not importlib.util.find_spec("setuptools"):
  667. msg = "It is not possible to use --no-use-pep517 without setuptools installed."
  668. raise_option_error(parser, option=option, msg=msg)
  669. # Otherwise, --no-use-pep517 was passed via the command-line.
  670. parser.values.use_pep517 = False
  671. use_pep517: Any = partial(
  672. Option,
  673. "--use-pep517",
  674. dest="use_pep517",
  675. action="store_true",
  676. default=None,
  677. help="Use PEP 517 for building source distributions "
  678. "(use --no-use-pep517 to force legacy behaviour).",
  679. )
  680. no_use_pep517: Any = partial(
  681. Option,
  682. "--no-use-pep517",
  683. dest="use_pep517",
  684. action="callback",
  685. callback=_handle_no_use_pep517,
  686. default=None,
  687. help=SUPPRESS_HELP,
  688. )
  689. def _handle_config_settings(
  690. option: Option, opt_str: str, value: str, parser: OptionParser
  691. ) -> None:
  692. key, sep, val = value.partition("=")
  693. if sep != "=":
  694. parser.error(f"Arguments to {opt_str} must be of the form KEY=VAL") # noqa
  695. dest = getattr(parser.values, option.dest)
  696. if dest is None:
  697. dest = {}
  698. setattr(parser.values, option.dest, dest)
  699. dest[key] = val
  700. config_settings: Callable[..., Option] = partial(
  701. Option,
  702. "--config-settings",
  703. dest="config_settings",
  704. type=str,
  705. action="callback",
  706. callback=_handle_config_settings,
  707. metavar="settings",
  708. help="Configuration settings to be passed to the PEP 517 build backend. "
  709. "Settings take the form KEY=VALUE. Use multiple --config-settings options "
  710. "to pass multiple keys to the backend.",
  711. )
  712. install_options: Callable[..., Option] = partial(
  713. Option,
  714. "--install-option",
  715. dest="install_options",
  716. action="append",
  717. metavar="options",
  718. help="Extra arguments to be supplied to the setup.py install "
  719. 'command (use like --install-option="--install-scripts=/usr/local/'
  720. 'bin"). Use multiple --install-option options to pass multiple '
  721. "options to setup.py install. If you are using an option with a "
  722. "directory path, be sure to use absolute path.",
  723. )
  724. build_options: Callable[..., Option] = partial(
  725. Option,
  726. "--build-option",
  727. dest="build_options",
  728. metavar="options",
  729. action="append",
  730. help="Extra arguments to be supplied to 'setup.py bdist_wheel'.",
  731. )
  732. global_options: Callable[..., Option] = partial(
  733. Option,
  734. "--global-option",
  735. dest="global_options",
  736. action="append",
  737. metavar="options",
  738. help="Extra global options to be supplied to the setup.py "
  739. "call before the install or bdist_wheel command.",
  740. )
  741. no_clean: Callable[..., Option] = partial(
  742. Option,
  743. "--no-clean",
  744. action="store_true",
  745. default=False,
  746. help="Don't clean up build directories.",
  747. )
  748. pre: Callable[..., Option] = partial(
  749. Option,
  750. "--pre",
  751. action="store_true",
  752. default=False,
  753. help="Include pre-release and development versions. By default, "
  754. "pip only finds stable versions.",
  755. )
  756. disable_pip_version_check: Callable[..., Option] = partial(
  757. Option,
  758. "--disable-pip-version-check",
  759. dest="disable_pip_version_check",
  760. action="store_true",
  761. default=False,
  762. help="Don't periodically check PyPI to determine whether a new version "
  763. "of pip is available for download. Implied with --no-index.",
  764. )
  765. root_user_action: Callable[..., Option] = partial(
  766. Option,
  767. "--root-user-action",
  768. dest="root_user_action",
  769. default="warn",
  770. choices=["warn", "ignore"],
  771. help="Action if pip is run as a root user. By default, a warning message is shown.",
  772. )
  773. def _handle_merge_hash(
  774. option: Option, opt_str: str, value: str, parser: OptionParser
  775. ) -> None:
  776. """Given a value spelled "algo:digest", append the digest to a list
  777. pointed to in a dict by the algo name."""
  778. if not parser.values.hashes:
  779. parser.values.hashes = {}
  780. try:
  781. algo, digest = value.split(":", 1)
  782. except ValueError:
  783. parser.error(
  784. "Arguments to {} must be a hash name " # noqa
  785. "followed by a value, like --hash=sha256:"
  786. "abcde...".format(opt_str)
  787. )
  788. if algo not in STRONG_HASHES:
  789. parser.error(
  790. "Allowed hash algorithms for {} are {}.".format( # noqa
  791. opt_str, ", ".join(STRONG_HASHES)
  792. )
  793. )
  794. parser.values.hashes.setdefault(algo, []).append(digest)
  795. hash: Callable[..., Option] = partial(
  796. Option,
  797. "--hash",
  798. # Hash values eventually end up in InstallRequirement.hashes due to
  799. # __dict__ copying in process_line().
  800. dest="hashes",
  801. action="callback",
  802. callback=_handle_merge_hash,
  803. type="string",
  804. help="Verify that the package's archive matches this "
  805. "hash before installing. Example: --hash=sha256:abcdef...",
  806. )
  807. require_hashes: Callable[..., Option] = partial(
  808. Option,
  809. "--require-hashes",
  810. dest="require_hashes",
  811. action="store_true",
  812. default=False,
  813. help="Require a hash to check each requirement against, for "
  814. "repeatable installs. This option is implied when any package in a "
  815. "requirements file has a --hash option.",
  816. )
  817. list_path: Callable[..., Option] = partial(
  818. PipOption,
  819. "--path",
  820. dest="path",
  821. type="path",
  822. action="append",
  823. help="Restrict to the specified installation path for listing "
  824. "packages (can be used multiple times).",
  825. )
  826. def check_list_path_option(options: Values) -> None:
  827. if options.path and (options.user or options.local):
  828. raise CommandError("Cannot combine '--path' with '--user' or '--local'")
  829. list_exclude: Callable[..., Option] = partial(
  830. PipOption,
  831. "--exclude",
  832. dest="excludes",
  833. action="append",
  834. metavar="package",
  835. type="package_name",
  836. help="Exclude specified package from the output",
  837. )
  838. no_python_version_warning: Callable[..., Option] = partial(
  839. Option,
  840. "--no-python-version-warning",
  841. dest="no_python_version_warning",
  842. action="store_true",
  843. default=False,
  844. help="Silence deprecation warnings for upcoming unsupported Pythons.",
  845. )
  846. use_new_feature: Callable[..., Option] = partial(
  847. Option,
  848. "--use-feature",
  849. dest="features_enabled",
  850. metavar="feature",
  851. action="append",
  852. default=[],
  853. choices=["2020-resolver", "fast-deps", "truststore"],
  854. help="Enable new functionality, that may be backward incompatible.",
  855. )
  856. use_deprecated_feature: Callable[..., Option] = partial(
  857. Option,
  858. "--use-deprecated",
  859. dest="deprecated_features_enabled",
  860. metavar="feature",
  861. action="append",
  862. default=[],
  863. choices=[
  864. "legacy-resolver",
  865. ],
  866. help=("Enable deprecated functionality, that will be removed in the future."),
  867. )
  868. ##########
  869. # groups #
  870. ##########
  871. general_group: Dict[str, Any] = {
  872. "name": "General Options",
  873. "options": [
  874. help_,
  875. debug_mode,
  876. isolated_mode,
  877. require_virtualenv,
  878. verbose,
  879. version,
  880. quiet,
  881. log,
  882. no_input,
  883. proxy,
  884. retries,
  885. timeout,
  886. exists_action,
  887. trusted_host,
  888. cert,
  889. client_cert,
  890. cache_dir,
  891. no_cache,
  892. disable_pip_version_check,
  893. no_color,
  894. no_python_version_warning,
  895. use_new_feature,
  896. use_deprecated_feature,
  897. ],
  898. }
  899. index_group: Dict[str, Any] = {
  900. "name": "Package Index Options",
  901. "options": [
  902. index_url,
  903. extra_index_url,
  904. no_index,
  905. find_links,
  906. ],
  907. }