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