Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. Β
See raw diff
- ckpts/hf_ckpt/global_step120/tokenizer.model +3 -0
- ckpts/hf_ckpt/global_step20/tokenizer.model +3 -0
- ckpts/hf_ckpt/global_step60/tokenizer.model +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_233_mp_rank_03_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_28_mp_rank_00_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_47_mp_rank_00_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_5_mp_rank_02_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/bf16_zero_pp_rank_64_mp_rank_00_optim_states.pt +3 -0
- ckpts/llama-3b/global_step100/mp_rank_01_model_states.pt +3 -0
- venv/lib/python3.10/site-packages/__editable__.lm_eval-0.4.2.pth +3 -0
- venv/lib/python3.10/site-packages/click/__init__.py +73 -0
- venv/lib/python3.10/site-packages/click/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/_compat.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/_termui_impl.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/_textwrap.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/_winconsole.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/core.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/decorators.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/exceptions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/formatting.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/globals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/parser.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/shell_completion.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/termui.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/testing.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/__pycache__/utils.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/click/_compat.py +623 -0
- venv/lib/python3.10/site-packages/click/_termui_impl.py +739 -0
- venv/lib/python3.10/site-packages/click/_textwrap.py +49 -0
- venv/lib/python3.10/site-packages/click/_winconsole.py +279 -0
- venv/lib/python3.10/site-packages/click/core.py +0 -0
- venv/lib/python3.10/site-packages/click/decorators.py +561 -0
- venv/lib/python3.10/site-packages/click/exceptions.py +288 -0
- venv/lib/python3.10/site-packages/click/formatting.py +301 -0
- venv/lib/python3.10/site-packages/click/globals.py +68 -0
- venv/lib/python3.10/site-packages/click/parser.py +529 -0
- venv/lib/python3.10/site-packages/click/py.typed +0 -0
- venv/lib/python3.10/site-packages/click/shell_completion.py +596 -0
- venv/lib/python3.10/site-packages/click/termui.py +784 -0
- venv/lib/python3.10/site-packages/click/testing.py +479 -0
- venv/lib/python3.10/site-packages/click/types.py +1089 -0
- venv/lib/python3.10/site-packages/click/utils.py +624 -0
- venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/INSTALLER +1 -0
- venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/METADATA +441 -0
- venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/RECORD +31 -0
- venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/WHEEL +5 -0
- venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt +27 -0
- venv/lib/python3.10/site-packages/dill/__diff.py +234 -0
- venv/lib/python3.10/site-packages/dill/__info__.py +291 -0
ckpts/hf_ckpt/global_step120/tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
3 |
+
size 499723
|
ckpts/hf_ckpt/global_step20/tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
3 |
+
size 499723
|
ckpts/hf_ckpt/global_step60/tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
3 |
+
size 499723
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_233_mp_rank_03_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:62b9abd672566c55c45fa41ef6b9c173a155af32f09a51b6f257e6f91754f208
|
3 |
+
size 41830404
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_28_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7f3f0aff95cfe1870c84a696d21f608e6177574b6bbb2b03dba15a99f983479c
|
3 |
+
size 41830138
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_47_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:752e4007b6d24a6c6f123dc5e4a9983f811549f300d45bab631112c2f8224e6b
|
3 |
+
size 41830138
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_5_mp_rank_02_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c0da16a8691a44fb2c0969783e27dc8b6ce20fbcc3a7b940142c2ba610e33020
|
3 |
+
size 41830320
|
ckpts/llama-3b/global_step100/bf16_zero_pp_rank_64_mp_rank_00_optim_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b7b970fbef76b79a4e778e3da300836067b435b8653b2fcc816813b7798e9850
|
3 |
+
size 41830138
|
ckpts/llama-3b/global_step100/mp_rank_01_model_states.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f7d2d022b3a6a985c60e4a46de39b3cdf3f43d8b16795e8d4278791677fdaccd
|
3 |
+
size 18912452
|
venv/lib/python3.10/site-packages/__editable__.lm_eval-0.4.2.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0b87d24b5f41e9dfa2760bdd38e88bee0db23d5b34659d3ff52d013edad9d5ec
|
3 |
+
size 85
|
venv/lib/python3.10/site-packages/click/__init__.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Click is a simple Python module inspired by the stdlib optparse to make
|
3 |
+
writing command line scripts fun. Unlike other modules, it's based
|
4 |
+
around a simple API that does not come with too much magic and is
|
5 |
+
composable.
|
6 |
+
"""
|
7 |
+
from .core import Argument as Argument
|
8 |
+
from .core import BaseCommand as BaseCommand
|
9 |
+
from .core import Command as Command
|
10 |
+
from .core import CommandCollection as CommandCollection
|
11 |
+
from .core import Context as Context
|
12 |
+
from .core import Group as Group
|
13 |
+
from .core import MultiCommand as MultiCommand
|
14 |
+
from .core import Option as Option
|
15 |
+
from .core import Parameter as Parameter
|
16 |
+
from .decorators import argument as argument
|
17 |
+
from .decorators import command as command
|
18 |
+
from .decorators import confirmation_option as confirmation_option
|
19 |
+
from .decorators import group as group
|
20 |
+
from .decorators import help_option as help_option
|
21 |
+
from .decorators import make_pass_decorator as make_pass_decorator
|
22 |
+
from .decorators import option as option
|
23 |
+
from .decorators import pass_context as pass_context
|
24 |
+
from .decorators import pass_obj as pass_obj
|
25 |
+
from .decorators import password_option as password_option
|
26 |
+
from .decorators import version_option as version_option
|
27 |
+
from .exceptions import Abort as Abort
|
28 |
+
from .exceptions import BadArgumentUsage as BadArgumentUsage
|
29 |
+
from .exceptions import BadOptionUsage as BadOptionUsage
|
30 |
+
from .exceptions import BadParameter as BadParameter
|
31 |
+
from .exceptions import ClickException as ClickException
|
32 |
+
from .exceptions import FileError as FileError
|
33 |
+
from .exceptions import MissingParameter as MissingParameter
|
34 |
+
from .exceptions import NoSuchOption as NoSuchOption
|
35 |
+
from .exceptions import UsageError as UsageError
|
36 |
+
from .formatting import HelpFormatter as HelpFormatter
|
37 |
+
from .formatting import wrap_text as wrap_text
|
38 |
+
from .globals import get_current_context as get_current_context
|
39 |
+
from .parser import OptionParser as OptionParser
|
40 |
+
from .termui import clear as clear
|
41 |
+
from .termui import confirm as confirm
|
42 |
+
from .termui import echo_via_pager as echo_via_pager
|
43 |
+
from .termui import edit as edit
|
44 |
+
from .termui import getchar as getchar
|
45 |
+
from .termui import launch as launch
|
46 |
+
from .termui import pause as pause
|
47 |
+
from .termui import progressbar as progressbar
|
48 |
+
from .termui import prompt as prompt
|
49 |
+
from .termui import secho as secho
|
50 |
+
from .termui import style as style
|
51 |
+
from .termui import unstyle as unstyle
|
52 |
+
from .types import BOOL as BOOL
|
53 |
+
from .types import Choice as Choice
|
54 |
+
from .types import DateTime as DateTime
|
55 |
+
from .types import File as File
|
56 |
+
from .types import FLOAT as FLOAT
|
57 |
+
from .types import FloatRange as FloatRange
|
58 |
+
from .types import INT as INT
|
59 |
+
from .types import IntRange as IntRange
|
60 |
+
from .types import ParamType as ParamType
|
61 |
+
from .types import Path as Path
|
62 |
+
from .types import STRING as STRING
|
63 |
+
from .types import Tuple as Tuple
|
64 |
+
from .types import UNPROCESSED as UNPROCESSED
|
65 |
+
from .types import UUID as UUID
|
66 |
+
from .utils import echo as echo
|
67 |
+
from .utils import format_filename as format_filename
|
68 |
+
from .utils import get_app_dir as get_app_dir
|
69 |
+
from .utils import get_binary_stream as get_binary_stream
|
70 |
+
from .utils import get_text_stream as get_text_stream
|
71 |
+
from .utils import open_file as open_file
|
72 |
+
|
73 |
+
__version__ = "8.1.7"
|
venv/lib/python3.10/site-packages/click/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (2.62 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/_compat.cpython-310.pyc
ADDED
Binary file (15.7 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/_termui_impl.cpython-310.pyc
ADDED
Binary file (16.3 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/_textwrap.cpython-310.pyc
ADDED
Binary file (1.55 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/_winconsole.cpython-310.pyc
ADDED
Binary file (7.67 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/core.cpython-310.pyc
ADDED
Binary file (91.1 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/decorators.cpython-310.pyc
ADDED
Binary file (17.2 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/exceptions.cpython-310.pyc
ADDED
Binary file (10.3 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/formatting.cpython-310.pyc
ADDED
Binary file (9.46 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/globals.cpython-310.pyc
ADDED
Binary file (2.44 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/parser.cpython-310.pyc
ADDED
Binary file (13.7 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/shell_completion.cpython-310.pyc
ADDED
Binary file (16.9 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/termui.cpython-310.pyc
ADDED
Binary file (26.1 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/testing.cpython-310.pyc
ADDED
Binary file (15.2 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/types.cpython-310.pyc
ADDED
Binary file (33.7 kB). View file
|
|
venv/lib/python3.10/site-packages/click/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (18.9 kB). View file
|
|
venv/lib/python3.10/site-packages/click/_compat.py
ADDED
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import codecs
|
2 |
+
import io
|
3 |
+
import os
|
4 |
+
import re
|
5 |
+
import sys
|
6 |
+
import typing as t
|
7 |
+
from weakref import WeakKeyDictionary
|
8 |
+
|
9 |
+
CYGWIN = sys.platform.startswith("cygwin")
|
10 |
+
WIN = sys.platform.startswith("win")
|
11 |
+
auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None
|
12 |
+
_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
|
13 |
+
|
14 |
+
|
15 |
+
def _make_text_stream(
|
16 |
+
stream: t.BinaryIO,
|
17 |
+
encoding: t.Optional[str],
|
18 |
+
errors: t.Optional[str],
|
19 |
+
force_readable: bool = False,
|
20 |
+
force_writable: bool = False,
|
21 |
+
) -> t.TextIO:
|
22 |
+
if encoding is None:
|
23 |
+
encoding = get_best_encoding(stream)
|
24 |
+
if errors is None:
|
25 |
+
errors = "replace"
|
26 |
+
return _NonClosingTextIOWrapper(
|
27 |
+
stream,
|
28 |
+
encoding,
|
29 |
+
errors,
|
30 |
+
line_buffering=True,
|
31 |
+
force_readable=force_readable,
|
32 |
+
force_writable=force_writable,
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
def is_ascii_encoding(encoding: str) -> bool:
|
37 |
+
"""Checks if a given encoding is ascii."""
|
38 |
+
try:
|
39 |
+
return codecs.lookup(encoding).name == "ascii"
|
40 |
+
except LookupError:
|
41 |
+
return False
|
42 |
+
|
43 |
+
|
44 |
+
def get_best_encoding(stream: t.IO[t.Any]) -> str:
|
45 |
+
"""Returns the default stream encoding if not found."""
|
46 |
+
rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()
|
47 |
+
if is_ascii_encoding(rv):
|
48 |
+
return "utf-8"
|
49 |
+
return rv
|
50 |
+
|
51 |
+
|
52 |
+
class _NonClosingTextIOWrapper(io.TextIOWrapper):
|
53 |
+
def __init__(
|
54 |
+
self,
|
55 |
+
stream: t.BinaryIO,
|
56 |
+
encoding: t.Optional[str],
|
57 |
+
errors: t.Optional[str],
|
58 |
+
force_readable: bool = False,
|
59 |
+
force_writable: bool = False,
|
60 |
+
**extra: t.Any,
|
61 |
+
) -> None:
|
62 |
+
self._stream = stream = t.cast(
|
63 |
+
t.BinaryIO, _FixupStream(stream, force_readable, force_writable)
|
64 |
+
)
|
65 |
+
super().__init__(stream, encoding, errors, **extra)
|
66 |
+
|
67 |
+
def __del__(self) -> None:
|
68 |
+
try:
|
69 |
+
self.detach()
|
70 |
+
except Exception:
|
71 |
+
pass
|
72 |
+
|
73 |
+
def isatty(self) -> bool:
|
74 |
+
# https://bitbucket.org/pypy/pypy/issue/1803
|
75 |
+
return self._stream.isatty()
|
76 |
+
|
77 |
+
|
78 |
+
class _FixupStream:
|
79 |
+
"""The new io interface needs more from streams than streams
|
80 |
+
traditionally implement. As such, this fix-up code is necessary in
|
81 |
+
some circumstances.
|
82 |
+
|
83 |
+
The forcing of readable and writable flags are there because some tools
|
84 |
+
put badly patched objects on sys (one such offender are certain version
|
85 |
+
of jupyter notebook).
|
86 |
+
"""
|
87 |
+
|
88 |
+
def __init__(
|
89 |
+
self,
|
90 |
+
stream: t.BinaryIO,
|
91 |
+
force_readable: bool = False,
|
92 |
+
force_writable: bool = False,
|
93 |
+
):
|
94 |
+
self._stream = stream
|
95 |
+
self._force_readable = force_readable
|
96 |
+
self._force_writable = force_writable
|
97 |
+
|
98 |
+
def __getattr__(self, name: str) -> t.Any:
|
99 |
+
return getattr(self._stream, name)
|
100 |
+
|
101 |
+
def read1(self, size: int) -> bytes:
|
102 |
+
f = getattr(self._stream, "read1", None)
|
103 |
+
|
104 |
+
if f is not None:
|
105 |
+
return t.cast(bytes, f(size))
|
106 |
+
|
107 |
+
return self._stream.read(size)
|
108 |
+
|
109 |
+
def readable(self) -> bool:
|
110 |
+
if self._force_readable:
|
111 |
+
return True
|
112 |
+
x = getattr(self._stream, "readable", None)
|
113 |
+
if x is not None:
|
114 |
+
return t.cast(bool, x())
|
115 |
+
try:
|
116 |
+
self._stream.read(0)
|
117 |
+
except Exception:
|
118 |
+
return False
|
119 |
+
return True
|
120 |
+
|
121 |
+
def writable(self) -> bool:
|
122 |
+
if self._force_writable:
|
123 |
+
return True
|
124 |
+
x = getattr(self._stream, "writable", None)
|
125 |
+
if x is not None:
|
126 |
+
return t.cast(bool, x())
|
127 |
+
try:
|
128 |
+
self._stream.write("") # type: ignore
|
129 |
+
except Exception:
|
130 |
+
try:
|
131 |
+
self._stream.write(b"")
|
132 |
+
except Exception:
|
133 |
+
return False
|
134 |
+
return True
|
135 |
+
|
136 |
+
def seekable(self) -> bool:
|
137 |
+
x = getattr(self._stream, "seekable", None)
|
138 |
+
if x is not None:
|
139 |
+
return t.cast(bool, x())
|
140 |
+
try:
|
141 |
+
self._stream.seek(self._stream.tell())
|
142 |
+
except Exception:
|
143 |
+
return False
|
144 |
+
return True
|
145 |
+
|
146 |
+
|
147 |
+
def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool:
|
148 |
+
try:
|
149 |
+
return isinstance(stream.read(0), bytes)
|
150 |
+
except Exception:
|
151 |
+
return default
|
152 |
+
# This happens in some cases where the stream was already
|
153 |
+
# closed. In this case, we assume the default.
|
154 |
+
|
155 |
+
|
156 |
+
def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool:
|
157 |
+
try:
|
158 |
+
stream.write(b"")
|
159 |
+
except Exception:
|
160 |
+
try:
|
161 |
+
stream.write("")
|
162 |
+
return False
|
163 |
+
except Exception:
|
164 |
+
pass
|
165 |
+
return default
|
166 |
+
return True
|
167 |
+
|
168 |
+
|
169 |
+
def _find_binary_reader(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:
|
170 |
+
# We need to figure out if the given stream is already binary.
|
171 |
+
# This can happen because the official docs recommend detaching
|
172 |
+
# the streams to get binary streams. Some code might do this, so
|
173 |
+
# we need to deal with this case explicitly.
|
174 |
+
if _is_binary_reader(stream, False):
|
175 |
+
return t.cast(t.BinaryIO, stream)
|
176 |
+
|
177 |
+
buf = getattr(stream, "buffer", None)
|
178 |
+
|
179 |
+
# Same situation here; this time we assume that the buffer is
|
180 |
+
# actually binary in case it's closed.
|
181 |
+
if buf is not None and _is_binary_reader(buf, True):
|
182 |
+
return t.cast(t.BinaryIO, buf)
|
183 |
+
|
184 |
+
return None
|
185 |
+
|
186 |
+
|
187 |
+
def _find_binary_writer(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:
|
188 |
+
# We need to figure out if the given stream is already binary.
|
189 |
+
# This can happen because the official docs recommend detaching
|
190 |
+
# the streams to get binary streams. Some code might do this, so
|
191 |
+
# we need to deal with this case explicitly.
|
192 |
+
if _is_binary_writer(stream, False):
|
193 |
+
return t.cast(t.BinaryIO, stream)
|
194 |
+
|
195 |
+
buf = getattr(stream, "buffer", None)
|
196 |
+
|
197 |
+
# Same situation here; this time we assume that the buffer is
|
198 |
+
# actually binary in case it's closed.
|
199 |
+
if buf is not None and _is_binary_writer(buf, True):
|
200 |
+
return t.cast(t.BinaryIO, buf)
|
201 |
+
|
202 |
+
return None
|
203 |
+
|
204 |
+
|
205 |
+
def _stream_is_misconfigured(stream: t.TextIO) -> bool:
|
206 |
+
"""A stream is misconfigured if its encoding is ASCII."""
|
207 |
+
# If the stream does not have an encoding set, we assume it's set
|
208 |
+
# to ASCII. This appears to happen in certain unittest
|
209 |
+
# environments. It's not quite clear what the correct behavior is
|
210 |
+
# but this at least will force Click to recover somehow.
|
211 |
+
return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")
|
212 |
+
|
213 |
+
|
214 |
+
def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: t.Optional[str]) -> bool:
|
215 |
+
"""A stream attribute is compatible if it is equal to the
|
216 |
+
desired value or the desired value is unset and the attribute
|
217 |
+
has a value.
|
218 |
+
"""
|
219 |
+
stream_value = getattr(stream, attr, None)
|
220 |
+
return stream_value == value or (value is None and stream_value is not None)
|
221 |
+
|
222 |
+
|
223 |
+
def _is_compatible_text_stream(
|
224 |
+
stream: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]
|
225 |
+
) -> bool:
|
226 |
+
"""Check if a stream's encoding and errors attributes are
|
227 |
+
compatible with the desired values.
|
228 |
+
"""
|
229 |
+
return _is_compat_stream_attr(
|
230 |
+
stream, "encoding", encoding
|
231 |
+
) and _is_compat_stream_attr(stream, "errors", errors)
|
232 |
+
|
233 |
+
|
234 |
+
def _force_correct_text_stream(
|
235 |
+
text_stream: t.IO[t.Any],
|
236 |
+
encoding: t.Optional[str],
|
237 |
+
errors: t.Optional[str],
|
238 |
+
is_binary: t.Callable[[t.IO[t.Any], bool], bool],
|
239 |
+
find_binary: t.Callable[[t.IO[t.Any]], t.Optional[t.BinaryIO]],
|
240 |
+
force_readable: bool = False,
|
241 |
+
force_writable: bool = False,
|
242 |
+
) -> t.TextIO:
|
243 |
+
if is_binary(text_stream, False):
|
244 |
+
binary_reader = t.cast(t.BinaryIO, text_stream)
|
245 |
+
else:
|
246 |
+
text_stream = t.cast(t.TextIO, text_stream)
|
247 |
+
# If the stream looks compatible, and won't default to a
|
248 |
+
# misconfigured ascii encoding, return it as-is.
|
249 |
+
if _is_compatible_text_stream(text_stream, encoding, errors) and not (
|
250 |
+
encoding is None and _stream_is_misconfigured(text_stream)
|
251 |
+
):
|
252 |
+
return text_stream
|
253 |
+
|
254 |
+
# Otherwise, get the underlying binary reader.
|
255 |
+
possible_binary_reader = find_binary(text_stream)
|
256 |
+
|
257 |
+
# If that's not possible, silently use the original reader
|
258 |
+
# and get mojibake instead of exceptions.
|
259 |
+
if possible_binary_reader is None:
|
260 |
+
return text_stream
|
261 |
+
|
262 |
+
binary_reader = possible_binary_reader
|
263 |
+
|
264 |
+
# Default errors to replace instead of strict in order to get
|
265 |
+
# something that works.
|
266 |
+
if errors is None:
|
267 |
+
errors = "replace"
|
268 |
+
|
269 |
+
# Wrap the binary stream in a text stream with the correct
|
270 |
+
# encoding parameters.
|
271 |
+
return _make_text_stream(
|
272 |
+
binary_reader,
|
273 |
+
encoding,
|
274 |
+
errors,
|
275 |
+
force_readable=force_readable,
|
276 |
+
force_writable=force_writable,
|
277 |
+
)
|
278 |
+
|
279 |
+
|
280 |
+
def _force_correct_text_reader(
|
281 |
+
text_reader: t.IO[t.Any],
|
282 |
+
encoding: t.Optional[str],
|
283 |
+
errors: t.Optional[str],
|
284 |
+
force_readable: bool = False,
|
285 |
+
) -> t.TextIO:
|
286 |
+
return _force_correct_text_stream(
|
287 |
+
text_reader,
|
288 |
+
encoding,
|
289 |
+
errors,
|
290 |
+
_is_binary_reader,
|
291 |
+
_find_binary_reader,
|
292 |
+
force_readable=force_readable,
|
293 |
+
)
|
294 |
+
|
295 |
+
|
296 |
+
def _force_correct_text_writer(
|
297 |
+
text_writer: t.IO[t.Any],
|
298 |
+
encoding: t.Optional[str],
|
299 |
+
errors: t.Optional[str],
|
300 |
+
force_writable: bool = False,
|
301 |
+
) -> t.TextIO:
|
302 |
+
return _force_correct_text_stream(
|
303 |
+
text_writer,
|
304 |
+
encoding,
|
305 |
+
errors,
|
306 |
+
_is_binary_writer,
|
307 |
+
_find_binary_writer,
|
308 |
+
force_writable=force_writable,
|
309 |
+
)
|
310 |
+
|
311 |
+
|
312 |
+
def get_binary_stdin() -> t.BinaryIO:
|
313 |
+
reader = _find_binary_reader(sys.stdin)
|
314 |
+
if reader is None:
|
315 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stdin.")
|
316 |
+
return reader
|
317 |
+
|
318 |
+
|
319 |
+
def get_binary_stdout() -> t.BinaryIO:
|
320 |
+
writer = _find_binary_writer(sys.stdout)
|
321 |
+
if writer is None:
|
322 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stdout.")
|
323 |
+
return writer
|
324 |
+
|
325 |
+
|
326 |
+
def get_binary_stderr() -> t.BinaryIO:
|
327 |
+
writer = _find_binary_writer(sys.stderr)
|
328 |
+
if writer is None:
|
329 |
+
raise RuntimeError("Was not able to determine binary stream for sys.stderr.")
|
330 |
+
return writer
|
331 |
+
|
332 |
+
|
333 |
+
def get_text_stdin(
|
334 |
+
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
|
335 |
+
) -> t.TextIO:
|
336 |
+
rv = _get_windows_console_stream(sys.stdin, encoding, errors)
|
337 |
+
if rv is not None:
|
338 |
+
return rv
|
339 |
+
return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)
|
340 |
+
|
341 |
+
|
342 |
+
def get_text_stdout(
|
343 |
+
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
|
344 |
+
) -> t.TextIO:
|
345 |
+
rv = _get_windows_console_stream(sys.stdout, encoding, errors)
|
346 |
+
if rv is not None:
|
347 |
+
return rv
|
348 |
+
return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)
|
349 |
+
|
350 |
+
|
351 |
+
def get_text_stderr(
|
352 |
+
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
|
353 |
+
) -> t.TextIO:
|
354 |
+
rv = _get_windows_console_stream(sys.stderr, encoding, errors)
|
355 |
+
if rv is not None:
|
356 |
+
return rv
|
357 |
+
return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)
|
358 |
+
|
359 |
+
|
360 |
+
def _wrap_io_open(
|
361 |
+
file: t.Union[str, "os.PathLike[str]", int],
|
362 |
+
mode: str,
|
363 |
+
encoding: t.Optional[str],
|
364 |
+
errors: t.Optional[str],
|
365 |
+
) -> t.IO[t.Any]:
|
366 |
+
"""Handles not passing ``encoding`` and ``errors`` in binary mode."""
|
367 |
+
if "b" in mode:
|
368 |
+
return open(file, mode)
|
369 |
+
|
370 |
+
return open(file, mode, encoding=encoding, errors=errors)
|
371 |
+
|
372 |
+
|
373 |
+
def open_stream(
|
374 |
+
filename: "t.Union[str, os.PathLike[str]]",
|
375 |
+
mode: str = "r",
|
376 |
+
encoding: t.Optional[str] = None,
|
377 |
+
errors: t.Optional[str] = "strict",
|
378 |
+
atomic: bool = False,
|
379 |
+
) -> t.Tuple[t.IO[t.Any], bool]:
|
380 |
+
binary = "b" in mode
|
381 |
+
filename = os.fspath(filename)
|
382 |
+
|
383 |
+
# Standard streams first. These are simple because they ignore the
|
384 |
+
# atomic flag. Use fsdecode to handle Path("-").
|
385 |
+
if os.fsdecode(filename) == "-":
|
386 |
+
if any(m in mode for m in ["w", "a", "x"]):
|
387 |
+
if binary:
|
388 |
+
return get_binary_stdout(), False
|
389 |
+
return get_text_stdout(encoding=encoding, errors=errors), False
|
390 |
+
if binary:
|
391 |
+
return get_binary_stdin(), False
|
392 |
+
return get_text_stdin(encoding=encoding, errors=errors), False
|
393 |
+
|
394 |
+
# Non-atomic writes directly go out through the regular open functions.
|
395 |
+
if not atomic:
|
396 |
+
return _wrap_io_open(filename, mode, encoding, errors), True
|
397 |
+
|
398 |
+
# Some usability stuff for atomic writes
|
399 |
+
if "a" in mode:
|
400 |
+
raise ValueError(
|
401 |
+
"Appending to an existing file is not supported, because that"
|
402 |
+
" would involve an expensive `copy`-operation to a temporary"
|
403 |
+
" file. Open the file in normal `w`-mode and copy explicitly"
|
404 |
+
" if that's what you're after."
|
405 |
+
)
|
406 |
+
if "x" in mode:
|
407 |
+
raise ValueError("Use the `overwrite`-parameter instead.")
|
408 |
+
if "w" not in mode:
|
409 |
+
raise ValueError("Atomic writes only make sense with `w`-mode.")
|
410 |
+
|
411 |
+
# Atomic writes are more complicated. They work by opening a file
|
412 |
+
# as a proxy in the same folder and then using the fdopen
|
413 |
+
# functionality to wrap it in a Python file. Then we wrap it in an
|
414 |
+
# atomic file that moves the file over on close.
|
415 |
+
import errno
|
416 |
+
import random
|
417 |
+
|
418 |
+
try:
|
419 |
+
perm: t.Optional[int] = os.stat(filename).st_mode
|
420 |
+
except OSError:
|
421 |
+
perm = None
|
422 |
+
|
423 |
+
flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
|
424 |
+
|
425 |
+
if binary:
|
426 |
+
flags |= getattr(os, "O_BINARY", 0)
|
427 |
+
|
428 |
+
while True:
|
429 |
+
tmp_filename = os.path.join(
|
430 |
+
os.path.dirname(filename),
|
431 |
+
f".__atomic-write{random.randrange(1 << 32):08x}",
|
432 |
+
)
|
433 |
+
try:
|
434 |
+
fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)
|
435 |
+
break
|
436 |
+
except OSError as e:
|
437 |
+
if e.errno == errno.EEXIST or (
|
438 |
+
os.name == "nt"
|
439 |
+
and e.errno == errno.EACCES
|
440 |
+
and os.path.isdir(e.filename)
|
441 |
+
and os.access(e.filename, os.W_OK)
|
442 |
+
):
|
443 |
+
continue
|
444 |
+
raise
|
445 |
+
|
446 |
+
if perm is not None:
|
447 |
+
os.chmod(tmp_filename, perm) # in case perm includes bits in umask
|
448 |
+
|
449 |
+
f = _wrap_io_open(fd, mode, encoding, errors)
|
450 |
+
af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))
|
451 |
+
return t.cast(t.IO[t.Any], af), True
|
452 |
+
|
453 |
+
|
454 |
+
class _AtomicFile:
|
455 |
+
def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None:
|
456 |
+
self._f = f
|
457 |
+
self._tmp_filename = tmp_filename
|
458 |
+
self._real_filename = real_filename
|
459 |
+
self.closed = False
|
460 |
+
|
461 |
+
@property
|
462 |
+
def name(self) -> str:
|
463 |
+
return self._real_filename
|
464 |
+
|
465 |
+
def close(self, delete: bool = False) -> None:
|
466 |
+
if self.closed:
|
467 |
+
return
|
468 |
+
self._f.close()
|
469 |
+
os.replace(self._tmp_filename, self._real_filename)
|
470 |
+
self.closed = True
|
471 |
+
|
472 |
+
def __getattr__(self, name: str) -> t.Any:
|
473 |
+
return getattr(self._f, name)
|
474 |
+
|
475 |
+
def __enter__(self) -> "_AtomicFile":
|
476 |
+
return self
|
477 |
+
|
478 |
+
def __exit__(self, exc_type: t.Optional[t.Type[BaseException]], *_: t.Any) -> None:
|
479 |
+
self.close(delete=exc_type is not None)
|
480 |
+
|
481 |
+
def __repr__(self) -> str:
|
482 |
+
return repr(self._f)
|
483 |
+
|
484 |
+
|
485 |
+
def strip_ansi(value: str) -> str:
|
486 |
+
return _ansi_re.sub("", value)
|
487 |
+
|
488 |
+
|
489 |
+
def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:
|
490 |
+
while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):
|
491 |
+
stream = stream._stream
|
492 |
+
|
493 |
+
return stream.__class__.__module__.startswith("ipykernel.")
|
494 |
+
|
495 |
+
|
496 |
+
def should_strip_ansi(
|
497 |
+
stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None
|
498 |
+
) -> bool:
|
499 |
+
if color is None:
|
500 |
+
if stream is None:
|
501 |
+
stream = sys.stdin
|
502 |
+
return not isatty(stream) and not _is_jupyter_kernel_output(stream)
|
503 |
+
return not color
|
504 |
+
|
505 |
+
|
506 |
+
# On Windows, wrap the output streams with colorama to support ANSI
|
507 |
+
# color codes.
|
508 |
+
# NOTE: double check is needed so mypy does not analyze this on Linux
|
509 |
+
if sys.platform.startswith("win") and WIN:
|
510 |
+
from ._winconsole import _get_windows_console_stream
|
511 |
+
|
512 |
+
def _get_argv_encoding() -> str:
|
513 |
+
import locale
|
514 |
+
|
515 |
+
return locale.getpreferredencoding()
|
516 |
+
|
517 |
+
_ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
|
518 |
+
|
519 |
+
def auto_wrap_for_ansi( # noqa: F811
|
520 |
+
stream: t.TextIO, color: t.Optional[bool] = None
|
521 |
+
) -> t.TextIO:
|
522 |
+
"""Support ANSI color and style codes on Windows by wrapping a
|
523 |
+
stream with colorama.
|
524 |
+
"""
|
525 |
+
try:
|
526 |
+
cached = _ansi_stream_wrappers.get(stream)
|
527 |
+
except Exception:
|
528 |
+
cached = None
|
529 |
+
|
530 |
+
if cached is not None:
|
531 |
+
return cached
|
532 |
+
|
533 |
+
import colorama
|
534 |
+
|
535 |
+
strip = should_strip_ansi(stream, color)
|
536 |
+
ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
|
537 |
+
rv = t.cast(t.TextIO, ansi_wrapper.stream)
|
538 |
+
_write = rv.write
|
539 |
+
|
540 |
+
def _safe_write(s):
|
541 |
+
try:
|
542 |
+
return _write(s)
|
543 |
+
except BaseException:
|
544 |
+
ansi_wrapper.reset_all()
|
545 |
+
raise
|
546 |
+
|
547 |
+
rv.write = _safe_write
|
548 |
+
|
549 |
+
try:
|
550 |
+
_ansi_stream_wrappers[stream] = rv
|
551 |
+
except Exception:
|
552 |
+
pass
|
553 |
+
|
554 |
+
return rv
|
555 |
+
|
556 |
+
else:
|
557 |
+
|
558 |
+
def _get_argv_encoding() -> str:
|
559 |
+
return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()
|
560 |
+
|
561 |
+
def _get_windows_console_stream(
|
562 |
+
f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]
|
563 |
+
) -> t.Optional[t.TextIO]:
|
564 |
+
return None
|
565 |
+
|
566 |
+
|
567 |
+
def term_len(x: str) -> int:
|
568 |
+
return len(strip_ansi(x))
|
569 |
+
|
570 |
+
|
571 |
+
def isatty(stream: t.IO[t.Any]) -> bool:
|
572 |
+
try:
|
573 |
+
return stream.isatty()
|
574 |
+
except Exception:
|
575 |
+
return False
|
576 |
+
|
577 |
+
|
578 |
+
def _make_cached_stream_func(
|
579 |
+
src_func: t.Callable[[], t.Optional[t.TextIO]],
|
580 |
+
wrapper_func: t.Callable[[], t.TextIO],
|
581 |
+
) -> t.Callable[[], t.Optional[t.TextIO]]:
|
582 |
+
cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
|
583 |
+
|
584 |
+
def func() -> t.Optional[t.TextIO]:
|
585 |
+
stream = src_func()
|
586 |
+
|
587 |
+
if stream is None:
|
588 |
+
return None
|
589 |
+
|
590 |
+
try:
|
591 |
+
rv = cache.get(stream)
|
592 |
+
except Exception:
|
593 |
+
rv = None
|
594 |
+
if rv is not None:
|
595 |
+
return rv
|
596 |
+
rv = wrapper_func()
|
597 |
+
try:
|
598 |
+
cache[stream] = rv
|
599 |
+
except Exception:
|
600 |
+
pass
|
601 |
+
return rv
|
602 |
+
|
603 |
+
return func
|
604 |
+
|
605 |
+
|
606 |
+
_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)
|
607 |
+
_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)
|
608 |
+
_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)
|
609 |
+
|
610 |
+
|
611 |
+
binary_streams: t.Mapping[str, t.Callable[[], t.BinaryIO]] = {
|
612 |
+
"stdin": get_binary_stdin,
|
613 |
+
"stdout": get_binary_stdout,
|
614 |
+
"stderr": get_binary_stderr,
|
615 |
+
}
|
616 |
+
|
617 |
+
text_streams: t.Mapping[
|
618 |
+
str, t.Callable[[t.Optional[str], t.Optional[str]], t.TextIO]
|
619 |
+
] = {
|
620 |
+
"stdin": get_text_stdin,
|
621 |
+
"stdout": get_text_stdout,
|
622 |
+
"stderr": get_text_stderr,
|
623 |
+
}
|
venv/lib/python3.10/site-packages/click/_termui_impl.py
ADDED
@@ -0,0 +1,739 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module contains implementations for the termui module. To keep the
|
3 |
+
import time of Click down, some infrequently used functionality is
|
4 |
+
placed in this module and only imported as needed.
|
5 |
+
"""
|
6 |
+
import contextlib
|
7 |
+
import math
|
8 |
+
import os
|
9 |
+
import sys
|
10 |
+
import time
|
11 |
+
import typing as t
|
12 |
+
from gettext import gettext as _
|
13 |
+
from io import StringIO
|
14 |
+
from types import TracebackType
|
15 |
+
|
16 |
+
from ._compat import _default_text_stdout
|
17 |
+
from ._compat import CYGWIN
|
18 |
+
from ._compat import get_best_encoding
|
19 |
+
from ._compat import isatty
|
20 |
+
from ._compat import open_stream
|
21 |
+
from ._compat import strip_ansi
|
22 |
+
from ._compat import term_len
|
23 |
+
from ._compat import WIN
|
24 |
+
from .exceptions import ClickException
|
25 |
+
from .utils import echo
|
26 |
+
|
27 |
+
V = t.TypeVar("V")
|
28 |
+
|
29 |
+
if os.name == "nt":
|
30 |
+
BEFORE_BAR = "\r"
|
31 |
+
AFTER_BAR = "\n"
|
32 |
+
else:
|
33 |
+
BEFORE_BAR = "\r\033[?25l"
|
34 |
+
AFTER_BAR = "\033[?25h\n"
|
35 |
+
|
36 |
+
|
37 |
+
class ProgressBar(t.Generic[V]):
|
38 |
+
def __init__(
|
39 |
+
self,
|
40 |
+
iterable: t.Optional[t.Iterable[V]],
|
41 |
+
length: t.Optional[int] = None,
|
42 |
+
fill_char: str = "#",
|
43 |
+
empty_char: str = " ",
|
44 |
+
bar_template: str = "%(bar)s",
|
45 |
+
info_sep: str = " ",
|
46 |
+
show_eta: bool = True,
|
47 |
+
show_percent: t.Optional[bool] = None,
|
48 |
+
show_pos: bool = False,
|
49 |
+
item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,
|
50 |
+
label: t.Optional[str] = None,
|
51 |
+
file: t.Optional[t.TextIO] = None,
|
52 |
+
color: t.Optional[bool] = None,
|
53 |
+
update_min_steps: int = 1,
|
54 |
+
width: int = 30,
|
55 |
+
) -> None:
|
56 |
+
self.fill_char = fill_char
|
57 |
+
self.empty_char = empty_char
|
58 |
+
self.bar_template = bar_template
|
59 |
+
self.info_sep = info_sep
|
60 |
+
self.show_eta = show_eta
|
61 |
+
self.show_percent = show_percent
|
62 |
+
self.show_pos = show_pos
|
63 |
+
self.item_show_func = item_show_func
|
64 |
+
self.label: str = label or ""
|
65 |
+
|
66 |
+
if file is None:
|
67 |
+
file = _default_text_stdout()
|
68 |
+
|
69 |
+
# There are no standard streams attached to write to. For example,
|
70 |
+
# pythonw on Windows.
|
71 |
+
if file is None:
|
72 |
+
file = StringIO()
|
73 |
+
|
74 |
+
self.file = file
|
75 |
+
self.color = color
|
76 |
+
self.update_min_steps = update_min_steps
|
77 |
+
self._completed_intervals = 0
|
78 |
+
self.width: int = width
|
79 |
+
self.autowidth: bool = width == 0
|
80 |
+
|
81 |
+
if length is None:
|
82 |
+
from operator import length_hint
|
83 |
+
|
84 |
+
length = length_hint(iterable, -1)
|
85 |
+
|
86 |
+
if length == -1:
|
87 |
+
length = None
|
88 |
+
if iterable is None:
|
89 |
+
if length is None:
|
90 |
+
raise TypeError("iterable or length is required")
|
91 |
+
iterable = t.cast(t.Iterable[V], range(length))
|
92 |
+
self.iter: t.Iterable[V] = iter(iterable)
|
93 |
+
self.length = length
|
94 |
+
self.pos = 0
|
95 |
+
self.avg: t.List[float] = []
|
96 |
+
self.last_eta: float
|
97 |
+
self.start: float
|
98 |
+
self.start = self.last_eta = time.time()
|
99 |
+
self.eta_known: bool = False
|
100 |
+
self.finished: bool = False
|
101 |
+
self.max_width: t.Optional[int] = None
|
102 |
+
self.entered: bool = False
|
103 |
+
self.current_item: t.Optional[V] = None
|
104 |
+
self.is_hidden: bool = not isatty(self.file)
|
105 |
+
self._last_line: t.Optional[str] = None
|
106 |
+
|
107 |
+
def __enter__(self) -> "ProgressBar[V]":
|
108 |
+
self.entered = True
|
109 |
+
self.render_progress()
|
110 |
+
return self
|
111 |
+
|
112 |
+
def __exit__(
|
113 |
+
self,
|
114 |
+
exc_type: t.Optional[t.Type[BaseException]],
|
115 |
+
exc_value: t.Optional[BaseException],
|
116 |
+
tb: t.Optional[TracebackType],
|
117 |
+
) -> None:
|
118 |
+
self.render_finish()
|
119 |
+
|
120 |
+
def __iter__(self) -> t.Iterator[V]:
|
121 |
+
if not self.entered:
|
122 |
+
raise RuntimeError("You need to use progress bars in a with block.")
|
123 |
+
self.render_progress()
|
124 |
+
return self.generator()
|
125 |
+
|
126 |
+
def __next__(self) -> V:
|
127 |
+
# Iteration is defined in terms of a generator function,
|
128 |
+
# returned by iter(self); use that to define next(). This works
|
129 |
+
# because `self.iter` is an iterable consumed by that generator,
|
130 |
+
# so it is re-entry safe. Calling `next(self.generator())`
|
131 |
+
# twice works and does "what you want".
|
132 |
+
return next(iter(self))
|
133 |
+
|
134 |
+
def render_finish(self) -> None:
|
135 |
+
if self.is_hidden:
|
136 |
+
return
|
137 |
+
self.file.write(AFTER_BAR)
|
138 |
+
self.file.flush()
|
139 |
+
|
140 |
+
@property
|
141 |
+
def pct(self) -> float:
|
142 |
+
if self.finished:
|
143 |
+
return 1.0
|
144 |
+
return min(self.pos / (float(self.length or 1) or 1), 1.0)
|
145 |
+
|
146 |
+
@property
|
147 |
+
def time_per_iteration(self) -> float:
|
148 |
+
if not self.avg:
|
149 |
+
return 0.0
|
150 |
+
return sum(self.avg) / float(len(self.avg))
|
151 |
+
|
152 |
+
@property
|
153 |
+
def eta(self) -> float:
|
154 |
+
if self.length is not None and not self.finished:
|
155 |
+
return self.time_per_iteration * (self.length - self.pos)
|
156 |
+
return 0.0
|
157 |
+
|
158 |
+
def format_eta(self) -> str:
|
159 |
+
if self.eta_known:
|
160 |
+
t = int(self.eta)
|
161 |
+
seconds = t % 60
|
162 |
+
t //= 60
|
163 |
+
minutes = t % 60
|
164 |
+
t //= 60
|
165 |
+
hours = t % 24
|
166 |
+
t //= 24
|
167 |
+
if t > 0:
|
168 |
+
return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"
|
169 |
+
else:
|
170 |
+
return f"{hours:02}:{minutes:02}:{seconds:02}"
|
171 |
+
return ""
|
172 |
+
|
173 |
+
def format_pos(self) -> str:
|
174 |
+
pos = str(self.pos)
|
175 |
+
if self.length is not None:
|
176 |
+
pos += f"/{self.length}"
|
177 |
+
return pos
|
178 |
+
|
179 |
+
def format_pct(self) -> str:
|
180 |
+
return f"{int(self.pct * 100): 4}%"[1:]
|
181 |
+
|
182 |
+
def format_bar(self) -> str:
|
183 |
+
if self.length is not None:
|
184 |
+
bar_length = int(self.pct * self.width)
|
185 |
+
bar = self.fill_char * bar_length
|
186 |
+
bar += self.empty_char * (self.width - bar_length)
|
187 |
+
elif self.finished:
|
188 |
+
bar = self.fill_char * self.width
|
189 |
+
else:
|
190 |
+
chars = list(self.empty_char * (self.width or 1))
|
191 |
+
if self.time_per_iteration != 0:
|
192 |
+
chars[
|
193 |
+
int(
|
194 |
+
(math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)
|
195 |
+
* self.width
|
196 |
+
)
|
197 |
+
] = self.fill_char
|
198 |
+
bar = "".join(chars)
|
199 |
+
return bar
|
200 |
+
|
201 |
+
def format_progress_line(self) -> str:
|
202 |
+
show_percent = self.show_percent
|
203 |
+
|
204 |
+
info_bits = []
|
205 |
+
if self.length is not None and show_percent is None:
|
206 |
+
show_percent = not self.show_pos
|
207 |
+
|
208 |
+
if self.show_pos:
|
209 |
+
info_bits.append(self.format_pos())
|
210 |
+
if show_percent:
|
211 |
+
info_bits.append(self.format_pct())
|
212 |
+
if self.show_eta and self.eta_known and not self.finished:
|
213 |
+
info_bits.append(self.format_eta())
|
214 |
+
if self.item_show_func is not None:
|
215 |
+
item_info = self.item_show_func(self.current_item)
|
216 |
+
if item_info is not None:
|
217 |
+
info_bits.append(item_info)
|
218 |
+
|
219 |
+
return (
|
220 |
+
self.bar_template
|
221 |
+
% {
|
222 |
+
"label": self.label,
|
223 |
+
"bar": self.format_bar(),
|
224 |
+
"info": self.info_sep.join(info_bits),
|
225 |
+
}
|
226 |
+
).rstrip()
|
227 |
+
|
228 |
+
def render_progress(self) -> None:
|
229 |
+
import shutil
|
230 |
+
|
231 |
+
if self.is_hidden:
|
232 |
+
# Only output the label as it changes if the output is not a
|
233 |
+
# TTY. Use file=stderr if you expect to be piping stdout.
|
234 |
+
if self._last_line != self.label:
|
235 |
+
self._last_line = self.label
|
236 |
+
echo(self.label, file=self.file, color=self.color)
|
237 |
+
|
238 |
+
return
|
239 |
+
|
240 |
+
buf = []
|
241 |
+
# Update width in case the terminal has been resized
|
242 |
+
if self.autowidth:
|
243 |
+
old_width = self.width
|
244 |
+
self.width = 0
|
245 |
+
clutter_length = term_len(self.format_progress_line())
|
246 |
+
new_width = max(0, shutil.get_terminal_size().columns - clutter_length)
|
247 |
+
if new_width < old_width:
|
248 |
+
buf.append(BEFORE_BAR)
|
249 |
+
buf.append(" " * self.max_width) # type: ignore
|
250 |
+
self.max_width = new_width
|
251 |
+
self.width = new_width
|
252 |
+
|
253 |
+
clear_width = self.width
|
254 |
+
if self.max_width is not None:
|
255 |
+
clear_width = self.max_width
|
256 |
+
|
257 |
+
buf.append(BEFORE_BAR)
|
258 |
+
line = self.format_progress_line()
|
259 |
+
line_len = term_len(line)
|
260 |
+
if self.max_width is None or self.max_width < line_len:
|
261 |
+
self.max_width = line_len
|
262 |
+
|
263 |
+
buf.append(line)
|
264 |
+
buf.append(" " * (clear_width - line_len))
|
265 |
+
line = "".join(buf)
|
266 |
+
# Render the line only if it changed.
|
267 |
+
|
268 |
+
if line != self._last_line:
|
269 |
+
self._last_line = line
|
270 |
+
echo(line, file=self.file, color=self.color, nl=False)
|
271 |
+
self.file.flush()
|
272 |
+
|
273 |
+
def make_step(self, n_steps: int) -> None:
|
274 |
+
self.pos += n_steps
|
275 |
+
if self.length is not None and self.pos >= self.length:
|
276 |
+
self.finished = True
|
277 |
+
|
278 |
+
if (time.time() - self.last_eta) < 1.0:
|
279 |
+
return
|
280 |
+
|
281 |
+
self.last_eta = time.time()
|
282 |
+
|
283 |
+
# self.avg is a rolling list of length <= 7 of steps where steps are
|
284 |
+
# defined as time elapsed divided by the total progress through
|
285 |
+
# self.length.
|
286 |
+
if self.pos:
|
287 |
+
step = (time.time() - self.start) / self.pos
|
288 |
+
else:
|
289 |
+
step = time.time() - self.start
|
290 |
+
|
291 |
+
self.avg = self.avg[-6:] + [step]
|
292 |
+
|
293 |
+
self.eta_known = self.length is not None
|
294 |
+
|
295 |
+
def update(self, n_steps: int, current_item: t.Optional[V] = None) -> None:
|
296 |
+
"""Update the progress bar by advancing a specified number of
|
297 |
+
steps, and optionally set the ``current_item`` for this new
|
298 |
+
position.
|
299 |
+
|
300 |
+
:param n_steps: Number of steps to advance.
|
301 |
+
:param current_item: Optional item to set as ``current_item``
|
302 |
+
for the updated position.
|
303 |
+
|
304 |
+
.. versionchanged:: 8.0
|
305 |
+
Added the ``current_item`` optional parameter.
|
306 |
+
|
307 |
+
.. versionchanged:: 8.0
|
308 |
+
Only render when the number of steps meets the
|
309 |
+
``update_min_steps`` threshold.
|
310 |
+
"""
|
311 |
+
if current_item is not None:
|
312 |
+
self.current_item = current_item
|
313 |
+
|
314 |
+
self._completed_intervals += n_steps
|
315 |
+
|
316 |
+
if self._completed_intervals >= self.update_min_steps:
|
317 |
+
self.make_step(self._completed_intervals)
|
318 |
+
self.render_progress()
|
319 |
+
self._completed_intervals = 0
|
320 |
+
|
321 |
+
def finish(self) -> None:
|
322 |
+
self.eta_known = False
|
323 |
+
self.current_item = None
|
324 |
+
self.finished = True
|
325 |
+
|
326 |
+
def generator(self) -> t.Iterator[V]:
|
327 |
+
"""Return a generator which yields the items added to the bar
|
328 |
+
during construction, and updates the progress bar *after* the
|
329 |
+
yielded block returns.
|
330 |
+
"""
|
331 |
+
# WARNING: the iterator interface for `ProgressBar` relies on
|
332 |
+
# this and only works because this is a simple generator which
|
333 |
+
# doesn't create or manage additional state. If this function
|
334 |
+
# changes, the impact should be evaluated both against
|
335 |
+
# `iter(bar)` and `next(bar)`. `next()` in particular may call
|
336 |
+
# `self.generator()` repeatedly, and this must remain safe in
|
337 |
+
# order for that interface to work.
|
338 |
+
if not self.entered:
|
339 |
+
raise RuntimeError("You need to use progress bars in a with block.")
|
340 |
+
|
341 |
+
if self.is_hidden:
|
342 |
+
yield from self.iter
|
343 |
+
else:
|
344 |
+
for rv in self.iter:
|
345 |
+
self.current_item = rv
|
346 |
+
|
347 |
+
# This allows show_item_func to be updated before the
|
348 |
+
# item is processed. Only trigger at the beginning of
|
349 |
+
# the update interval.
|
350 |
+
if self._completed_intervals == 0:
|
351 |
+
self.render_progress()
|
352 |
+
|
353 |
+
yield rv
|
354 |
+
self.update(1)
|
355 |
+
|
356 |
+
self.finish()
|
357 |
+
self.render_progress()
|
358 |
+
|
359 |
+
|
360 |
+
def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:
|
361 |
+
"""Decide what method to use for paging through text."""
|
362 |
+
stdout = _default_text_stdout()
|
363 |
+
|
364 |
+
# There are no standard streams attached to write to. For example,
|
365 |
+
# pythonw on Windows.
|
366 |
+
if stdout is None:
|
367 |
+
stdout = StringIO()
|
368 |
+
|
369 |
+
if not isatty(sys.stdin) or not isatty(stdout):
|
370 |
+
return _nullpager(stdout, generator, color)
|
371 |
+
pager_cmd = (os.environ.get("PAGER", None) or "").strip()
|
372 |
+
if pager_cmd:
|
373 |
+
if WIN:
|
374 |
+
return _tempfilepager(generator, pager_cmd, color)
|
375 |
+
return _pipepager(generator, pager_cmd, color)
|
376 |
+
if os.environ.get("TERM") in ("dumb", "emacs"):
|
377 |
+
return _nullpager(stdout, generator, color)
|
378 |
+
if WIN or sys.platform.startswith("os2"):
|
379 |
+
return _tempfilepager(generator, "more <", color)
|
380 |
+
if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:
|
381 |
+
return _pipepager(generator, "less", color)
|
382 |
+
|
383 |
+
import tempfile
|
384 |
+
|
385 |
+
fd, filename = tempfile.mkstemp()
|
386 |
+
os.close(fd)
|
387 |
+
try:
|
388 |
+
if hasattr(os, "system") and os.system(f'more "{filename}"') == 0:
|
389 |
+
return _pipepager(generator, "more", color)
|
390 |
+
return _nullpager(stdout, generator, color)
|
391 |
+
finally:
|
392 |
+
os.unlink(filename)
|
393 |
+
|
394 |
+
|
395 |
+
def _pipepager(generator: t.Iterable[str], cmd: str, color: t.Optional[bool]) -> None:
|
396 |
+
"""Page through text by feeding it to another program. Invoking a
|
397 |
+
pager through this might support colors.
|
398 |
+
"""
|
399 |
+
import subprocess
|
400 |
+
|
401 |
+
env = dict(os.environ)
|
402 |
+
|
403 |
+
# If we're piping to less we might support colors under the
|
404 |
+
# condition that
|
405 |
+
cmd_detail = cmd.rsplit("/", 1)[-1].split()
|
406 |
+
if color is None and cmd_detail[0] == "less":
|
407 |
+
less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"
|
408 |
+
if not less_flags:
|
409 |
+
env["LESS"] = "-R"
|
410 |
+
color = True
|
411 |
+
elif "r" in less_flags or "R" in less_flags:
|
412 |
+
color = True
|
413 |
+
|
414 |
+
c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)
|
415 |
+
stdin = t.cast(t.BinaryIO, c.stdin)
|
416 |
+
encoding = get_best_encoding(stdin)
|
417 |
+
try:
|
418 |
+
for text in generator:
|
419 |
+
if not color:
|
420 |
+
text = strip_ansi(text)
|
421 |
+
|
422 |
+
stdin.write(text.encode(encoding, "replace"))
|
423 |
+
except (OSError, KeyboardInterrupt):
|
424 |
+
pass
|
425 |
+
else:
|
426 |
+
stdin.close()
|
427 |
+
|
428 |
+
# Less doesn't respect ^C, but catches it for its own UI purposes (aborting
|
429 |
+
# search or other commands inside less).
|
430 |
+
#
|
431 |
+
# That means when the user hits ^C, the parent process (click) terminates,
|
432 |
+
# but less is still alive, paging the output and messing up the terminal.
|
433 |
+
#
|
434 |
+
# If the user wants to make the pager exit on ^C, they should set
|
435 |
+
# `LESS='-K'`. It's not our decision to make.
|
436 |
+
while True:
|
437 |
+
try:
|
438 |
+
c.wait()
|
439 |
+
except KeyboardInterrupt:
|
440 |
+
pass
|
441 |
+
else:
|
442 |
+
break
|
443 |
+
|
444 |
+
|
445 |
+
def _tempfilepager(
|
446 |
+
generator: t.Iterable[str], cmd: str, color: t.Optional[bool]
|
447 |
+
) -> None:
|
448 |
+
"""Page through text by invoking a program on a temporary file."""
|
449 |
+
import tempfile
|
450 |
+
|
451 |
+
fd, filename = tempfile.mkstemp()
|
452 |
+
# TODO: This never terminates if the passed generator never terminates.
|
453 |
+
text = "".join(generator)
|
454 |
+
if not color:
|
455 |
+
text = strip_ansi(text)
|
456 |
+
encoding = get_best_encoding(sys.stdout)
|
457 |
+
with open_stream(filename, "wb")[0] as f:
|
458 |
+
f.write(text.encode(encoding))
|
459 |
+
try:
|
460 |
+
os.system(f'{cmd} "{filename}"')
|
461 |
+
finally:
|
462 |
+
os.close(fd)
|
463 |
+
os.unlink(filename)
|
464 |
+
|
465 |
+
|
466 |
+
def _nullpager(
|
467 |
+
stream: t.TextIO, generator: t.Iterable[str], color: t.Optional[bool]
|
468 |
+
) -> None:
|
469 |
+
"""Simply print unformatted text. This is the ultimate fallback."""
|
470 |
+
for text in generator:
|
471 |
+
if not color:
|
472 |
+
text = strip_ansi(text)
|
473 |
+
stream.write(text)
|
474 |
+
|
475 |
+
|
476 |
+
class Editor:
|
477 |
+
def __init__(
|
478 |
+
self,
|
479 |
+
editor: t.Optional[str] = None,
|
480 |
+
env: t.Optional[t.Mapping[str, str]] = None,
|
481 |
+
require_save: bool = True,
|
482 |
+
extension: str = ".txt",
|
483 |
+
) -> None:
|
484 |
+
self.editor = editor
|
485 |
+
self.env = env
|
486 |
+
self.require_save = require_save
|
487 |
+
self.extension = extension
|
488 |
+
|
489 |
+
def get_editor(self) -> str:
|
490 |
+
if self.editor is not None:
|
491 |
+
return self.editor
|
492 |
+
for key in "VISUAL", "EDITOR":
|
493 |
+
rv = os.environ.get(key)
|
494 |
+
if rv:
|
495 |
+
return rv
|
496 |
+
if WIN:
|
497 |
+
return "notepad"
|
498 |
+
for editor in "sensible-editor", "vim", "nano":
|
499 |
+
if os.system(f"which {editor} >/dev/null 2>&1") == 0:
|
500 |
+
return editor
|
501 |
+
return "vi"
|
502 |
+
|
503 |
+
def edit_file(self, filename: str) -> None:
|
504 |
+
import subprocess
|
505 |
+
|
506 |
+
editor = self.get_editor()
|
507 |
+
environ: t.Optional[t.Dict[str, str]] = None
|
508 |
+
|
509 |
+
if self.env:
|
510 |
+
environ = os.environ.copy()
|
511 |
+
environ.update(self.env)
|
512 |
+
|
513 |
+
try:
|
514 |
+
c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True)
|
515 |
+
exit_code = c.wait()
|
516 |
+
if exit_code != 0:
|
517 |
+
raise ClickException(
|
518 |
+
_("{editor}: Editing failed").format(editor=editor)
|
519 |
+
)
|
520 |
+
except OSError as e:
|
521 |
+
raise ClickException(
|
522 |
+
_("{editor}: Editing failed: {e}").format(editor=editor, e=e)
|
523 |
+
) from e
|
524 |
+
|
525 |
+
def edit(self, text: t.Optional[t.AnyStr]) -> t.Optional[t.AnyStr]:
|
526 |
+
import tempfile
|
527 |
+
|
528 |
+
if not text:
|
529 |
+
data = b""
|
530 |
+
elif isinstance(text, (bytes, bytearray)):
|
531 |
+
data = text
|
532 |
+
else:
|
533 |
+
if text and not text.endswith("\n"):
|
534 |
+
text += "\n"
|
535 |
+
|
536 |
+
if WIN:
|
537 |
+
data = text.replace("\n", "\r\n").encode("utf-8-sig")
|
538 |
+
else:
|
539 |
+
data = text.encode("utf-8")
|
540 |
+
|
541 |
+
fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)
|
542 |
+
f: t.BinaryIO
|
543 |
+
|
544 |
+
try:
|
545 |
+
with os.fdopen(fd, "wb") as f:
|
546 |
+
f.write(data)
|
547 |
+
|
548 |
+
# If the filesystem resolution is 1 second, like Mac OS
|
549 |
+
# 10.12 Extended, or 2 seconds, like FAT32, and the editor
|
550 |
+
# closes very fast, require_save can fail. Set the modified
|
551 |
+
# time to be 2 seconds in the past to work around this.
|
552 |
+
os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))
|
553 |
+
# Depending on the resolution, the exact value might not be
|
554 |
+
# recorded, so get the new recorded value.
|
555 |
+
timestamp = os.path.getmtime(name)
|
556 |
+
|
557 |
+
self.edit_file(name)
|
558 |
+
|
559 |
+
if self.require_save and os.path.getmtime(name) == timestamp:
|
560 |
+
return None
|
561 |
+
|
562 |
+
with open(name, "rb") as f:
|
563 |
+
rv = f.read()
|
564 |
+
|
565 |
+
if isinstance(text, (bytes, bytearray)):
|
566 |
+
return rv
|
567 |
+
|
568 |
+
return rv.decode("utf-8-sig").replace("\r\n", "\n") # type: ignore
|
569 |
+
finally:
|
570 |
+
os.unlink(name)
|
571 |
+
|
572 |
+
|
573 |
+
def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
|
574 |
+
import subprocess
|
575 |
+
|
576 |
+
def _unquote_file(url: str) -> str:
|
577 |
+
from urllib.parse import unquote
|
578 |
+
|
579 |
+
if url.startswith("file://"):
|
580 |
+
url = unquote(url[7:])
|
581 |
+
|
582 |
+
return url
|
583 |
+
|
584 |
+
if sys.platform == "darwin":
|
585 |
+
args = ["open"]
|
586 |
+
if wait:
|
587 |
+
args.append("-W")
|
588 |
+
if locate:
|
589 |
+
args.append("-R")
|
590 |
+
args.append(_unquote_file(url))
|
591 |
+
null = open("/dev/null", "w")
|
592 |
+
try:
|
593 |
+
return subprocess.Popen(args, stderr=null).wait()
|
594 |
+
finally:
|
595 |
+
null.close()
|
596 |
+
elif WIN:
|
597 |
+
if locate:
|
598 |
+
url = _unquote_file(url.replace('"', ""))
|
599 |
+
args = f'explorer /select,"{url}"'
|
600 |
+
else:
|
601 |
+
url = url.replace('"', "")
|
602 |
+
wait_str = "/WAIT" if wait else ""
|
603 |
+
args = f'start {wait_str} "" "{url}"'
|
604 |
+
return os.system(args)
|
605 |
+
elif CYGWIN:
|
606 |
+
if locate:
|
607 |
+
url = os.path.dirname(_unquote_file(url).replace('"', ""))
|
608 |
+
args = f'cygstart "{url}"'
|
609 |
+
else:
|
610 |
+
url = url.replace('"', "")
|
611 |
+
wait_str = "-w" if wait else ""
|
612 |
+
args = f'cygstart {wait_str} "{url}"'
|
613 |
+
return os.system(args)
|
614 |
+
|
615 |
+
try:
|
616 |
+
if locate:
|
617 |
+
url = os.path.dirname(_unquote_file(url)) or "."
|
618 |
+
else:
|
619 |
+
url = _unquote_file(url)
|
620 |
+
c = subprocess.Popen(["xdg-open", url])
|
621 |
+
if wait:
|
622 |
+
return c.wait()
|
623 |
+
return 0
|
624 |
+
except OSError:
|
625 |
+
if url.startswith(("http://", "https://")) and not locate and not wait:
|
626 |
+
import webbrowser
|
627 |
+
|
628 |
+
webbrowser.open(url)
|
629 |
+
return 0
|
630 |
+
return 1
|
631 |
+
|
632 |
+
|
633 |
+
def _translate_ch_to_exc(ch: str) -> t.Optional[BaseException]:
|
634 |
+
if ch == "\x03":
|
635 |
+
raise KeyboardInterrupt()
|
636 |
+
|
637 |
+
if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
|
638 |
+
raise EOFError()
|
639 |
+
|
640 |
+
if ch == "\x1a" and WIN: # Windows, Ctrl+Z
|
641 |
+
raise EOFError()
|
642 |
+
|
643 |
+
return None
|
644 |
+
|
645 |
+
|
646 |
+
if WIN:
|
647 |
+
import msvcrt
|
648 |
+
|
649 |
+
@contextlib.contextmanager
|
650 |
+
def raw_terminal() -> t.Iterator[int]:
|
651 |
+
yield -1
|
652 |
+
|
653 |
+
def getchar(echo: bool) -> str:
|
654 |
+
# The function `getch` will return a bytes object corresponding to
|
655 |
+
# the pressed character. Since Windows 10 build 1803, it will also
|
656 |
+
# return \x00 when called a second time after pressing a regular key.
|
657 |
+
#
|
658 |
+
# `getwch` does not share this probably-bugged behavior. Moreover, it
|
659 |
+
# returns a Unicode object by default, which is what we want.
|
660 |
+
#
|
661 |
+
# Either of these functions will return \x00 or \xe0 to indicate
|
662 |
+
# a special key, and you need to call the same function again to get
|
663 |
+
# the "rest" of the code. The fun part is that \u00e0 is
|
664 |
+
# "latin small letter a with grave", so if you type that on a French
|
665 |
+
# keyboard, you _also_ get a \xe0.
|
666 |
+
# E.g., consider the Up arrow. This returns \xe0 and then \x48. The
|
667 |
+
# resulting Unicode string reads as "a with grave" + "capital H".
|
668 |
+
# This is indistinguishable from when the user actually types
|
669 |
+
# "a with grave" and then "capital H".
|
670 |
+
#
|
671 |
+
# When \xe0 is returned, we assume it's part of a special-key sequence
|
672 |
+
# and call `getwch` again, but that means that when the user types
|
673 |
+
# the \u00e0 character, `getchar` doesn't return until a second
|
674 |
+
# character is typed.
|
675 |
+
# The alternative is returning immediately, but that would mess up
|
676 |
+
# cross-platform handling of arrow keys and others that start with
|
677 |
+
# \xe0. Another option is using `getch`, but then we can't reliably
|
678 |
+
# read non-ASCII characters, because return values of `getch` are
|
679 |
+
# limited to the current 8-bit codepage.
|
680 |
+
#
|
681 |
+
# Anyway, Click doesn't claim to do this Right(tm), and using `getwch`
|
682 |
+
# is doing the right thing in more situations than with `getch`.
|
683 |
+
func: t.Callable[[], str]
|
684 |
+
|
685 |
+
if echo:
|
686 |
+
func = msvcrt.getwche # type: ignore
|
687 |
+
else:
|
688 |
+
func = msvcrt.getwch # type: ignore
|
689 |
+
|
690 |
+
rv = func()
|
691 |
+
|
692 |
+
if rv in ("\x00", "\xe0"):
|
693 |
+
# \x00 and \xe0 are control characters that indicate special key,
|
694 |
+
# see above.
|
695 |
+
rv += func()
|
696 |
+
|
697 |
+
_translate_ch_to_exc(rv)
|
698 |
+
return rv
|
699 |
+
|
700 |
+
else:
|
701 |
+
import tty
|
702 |
+
import termios
|
703 |
+
|
704 |
+
@contextlib.contextmanager
|
705 |
+
def raw_terminal() -> t.Iterator[int]:
|
706 |
+
f: t.Optional[t.TextIO]
|
707 |
+
fd: int
|
708 |
+
|
709 |
+
if not isatty(sys.stdin):
|
710 |
+
f = open("/dev/tty")
|
711 |
+
fd = f.fileno()
|
712 |
+
else:
|
713 |
+
fd = sys.stdin.fileno()
|
714 |
+
f = None
|
715 |
+
|
716 |
+
try:
|
717 |
+
old_settings = termios.tcgetattr(fd)
|
718 |
+
|
719 |
+
try:
|
720 |
+
tty.setraw(fd)
|
721 |
+
yield fd
|
722 |
+
finally:
|
723 |
+
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
|
724 |
+
sys.stdout.flush()
|
725 |
+
|
726 |
+
if f is not None:
|
727 |
+
f.close()
|
728 |
+
except termios.error:
|
729 |
+
pass
|
730 |
+
|
731 |
+
def getchar(echo: bool) -> str:
|
732 |
+
with raw_terminal() as fd:
|
733 |
+
ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
|
734 |
+
|
735 |
+
if echo and isatty(sys.stdout):
|
736 |
+
sys.stdout.write(ch)
|
737 |
+
|
738 |
+
_translate_ch_to_exc(ch)
|
739 |
+
return ch
|
venv/lib/python3.10/site-packages/click/_textwrap.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import textwrap
|
2 |
+
import typing as t
|
3 |
+
from contextlib import contextmanager
|
4 |
+
|
5 |
+
|
6 |
+
class TextWrapper(textwrap.TextWrapper):
|
7 |
+
def _handle_long_word(
|
8 |
+
self,
|
9 |
+
reversed_chunks: t.List[str],
|
10 |
+
cur_line: t.List[str],
|
11 |
+
cur_len: int,
|
12 |
+
width: int,
|
13 |
+
) -> None:
|
14 |
+
space_left = max(width - cur_len, 1)
|
15 |
+
|
16 |
+
if self.break_long_words:
|
17 |
+
last = reversed_chunks[-1]
|
18 |
+
cut = last[:space_left]
|
19 |
+
res = last[space_left:]
|
20 |
+
cur_line.append(cut)
|
21 |
+
reversed_chunks[-1] = res
|
22 |
+
elif not cur_line:
|
23 |
+
cur_line.append(reversed_chunks.pop())
|
24 |
+
|
25 |
+
@contextmanager
|
26 |
+
def extra_indent(self, indent: str) -> t.Iterator[None]:
|
27 |
+
old_initial_indent = self.initial_indent
|
28 |
+
old_subsequent_indent = self.subsequent_indent
|
29 |
+
self.initial_indent += indent
|
30 |
+
self.subsequent_indent += indent
|
31 |
+
|
32 |
+
try:
|
33 |
+
yield
|
34 |
+
finally:
|
35 |
+
self.initial_indent = old_initial_indent
|
36 |
+
self.subsequent_indent = old_subsequent_indent
|
37 |
+
|
38 |
+
def indent_only(self, text: str) -> str:
|
39 |
+
rv = []
|
40 |
+
|
41 |
+
for idx, line in enumerate(text.splitlines()):
|
42 |
+
indent = self.initial_indent
|
43 |
+
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This module is based on the excellent work by Adam BartoΕ‘ who
|
2 |
+
# provided a lot of what went into the implementation here in
|
3 |
+
# the discussion to issue1602 in the Python bug tracker.
|
4 |
+
#
|
5 |
+
# There are some general differences in regards to how this works
|
6 |
+
# compared to the original patches as we do not need to patch
|
7 |
+
# the entire interpreter but just work in our little world of
|
8 |
+
# echo and prompt.
|
9 |
+
import io
|
10 |
+
import sys
|
11 |
+
import time
|
12 |
+
import typing as t
|
13 |
+
from ctypes import byref
|
14 |
+
from ctypes import c_char
|
15 |
+
from ctypes import c_char_p
|
16 |
+
from ctypes import c_int
|
17 |
+
from ctypes import c_ssize_t
|
18 |
+
from ctypes import c_ulong
|
19 |
+
from ctypes import c_void_p
|
20 |
+
from ctypes import POINTER
|
21 |
+
from ctypes import py_object
|
22 |
+
from ctypes import Structure
|
23 |
+
from ctypes.wintypes import DWORD
|
24 |
+
from ctypes.wintypes import HANDLE
|
25 |
+
from ctypes.wintypes import LPCWSTR
|
26 |
+
from ctypes.wintypes import LPWSTR
|
27 |
+
|
28 |
+
from ._compat import _NonClosingTextIOWrapper
|
29 |
+
|
30 |
+
assert sys.platform == "win32"
|
31 |
+
import msvcrt # noqa: E402
|
32 |
+
from ctypes import windll # noqa: E402
|
33 |
+
from ctypes import WINFUNCTYPE # noqa: E402
|
34 |
+
|
35 |
+
c_ssize_p = POINTER(c_ssize_t)
|
36 |
+
|
37 |
+
kernel32 = windll.kernel32
|
38 |
+
GetStdHandle = kernel32.GetStdHandle
|
39 |
+
ReadConsoleW = kernel32.ReadConsoleW
|
40 |
+
WriteConsoleW = kernel32.WriteConsoleW
|
41 |
+
GetConsoleMode = kernel32.GetConsoleMode
|
42 |
+
GetLastError = kernel32.GetLastError
|
43 |
+
GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
|
44 |
+
CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
|
45 |
+
("CommandLineToArgvW", windll.shell32)
|
46 |
+
)
|
47 |
+
LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))
|
48 |
+
|
49 |
+
STDIN_HANDLE = GetStdHandle(-10)
|
50 |
+
STDOUT_HANDLE = GetStdHandle(-11)
|
51 |
+
STDERR_HANDLE = GetStdHandle(-12)
|
52 |
+
|
53 |
+
PyBUF_SIMPLE = 0
|
54 |
+
PyBUF_WRITABLE = 1
|
55 |
+
|
56 |
+
ERROR_SUCCESS = 0
|
57 |
+
ERROR_NOT_ENOUGH_MEMORY = 8
|
58 |
+
ERROR_OPERATION_ABORTED = 995
|
59 |
+
|
60 |
+
STDIN_FILENO = 0
|
61 |
+
STDOUT_FILENO = 1
|
62 |
+
STDERR_FILENO = 2
|
63 |
+
|
64 |
+
EOF = b"\x1a"
|
65 |
+
MAX_BYTES_WRITTEN = 32767
|
66 |
+
|
67 |
+
try:
|
68 |
+
from ctypes import pythonapi
|
69 |
+
except ImportError:
|
70 |
+
# On PyPy we cannot get buffers so our ability to operate here is
|
71 |
+
# severely limited.
|
72 |
+
get_buffer = None
|
73 |
+
else:
|
74 |
+
|
75 |
+
class Py_buffer(Structure):
|
76 |
+
_fields_ = [
|
77 |
+
("buf", c_void_p),
|
78 |
+
("obj", py_object),
|
79 |
+
("len", c_ssize_t),
|
80 |
+
("itemsize", c_ssize_t),
|
81 |
+
("readonly", c_int),
|
82 |
+
("ndim", c_int),
|
83 |
+
("format", c_char_p),
|
84 |
+
("shape", c_ssize_p),
|
85 |
+
("strides", c_ssize_p),
|
86 |
+
("suboffsets", c_ssize_p),
|
87 |
+
("internal", c_void_p),
|
88 |
+
]
|
89 |
+
|
90 |
+
PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
|
91 |
+
PyBuffer_Release = pythonapi.PyBuffer_Release
|
92 |
+
|
93 |
+
def get_buffer(obj, writable=False):
|
94 |
+
buf = Py_buffer()
|
95 |
+
flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE
|
96 |
+
PyObject_GetBuffer(py_object(obj), byref(buf), flags)
|
97 |
+
|
98 |
+
try:
|
99 |
+
buffer_type = c_char * buf.len
|
100 |
+
return buffer_type.from_address(buf.buf)
|
101 |
+
finally:
|
102 |
+
PyBuffer_Release(byref(buf))
|
103 |
+
|
104 |
+
|
105 |
+
class _WindowsConsoleRawIOBase(io.RawIOBase):
|
106 |
+
def __init__(self, handle):
|
107 |
+
self.handle = handle
|
108 |
+
|
109 |
+
def isatty(self):
|
110 |
+
super().isatty()
|
111 |
+
return True
|
112 |
+
|
113 |
+
|
114 |
+
class _WindowsConsoleReader(_WindowsConsoleRawIOBase):
|
115 |
+
def readable(self):
|
116 |
+
return True
|
117 |
+
|
118 |
+
def readinto(self, b):
|
119 |
+
bytes_to_be_read = len(b)
|
120 |
+
if not bytes_to_be_read:
|
121 |
+
return 0
|
122 |
+
elif bytes_to_be_read % 2:
|
123 |
+
raise ValueError(
|
124 |
+
"cannot read odd number of bytes from UTF-16-LE encoded console"
|
125 |
+
)
|
126 |
+
|
127 |
+
buffer = get_buffer(b, writable=True)
|
128 |
+
code_units_to_be_read = bytes_to_be_read // 2
|
129 |
+
code_units_read = c_ulong()
|
130 |
+
|
131 |
+
rv = ReadConsoleW(
|
132 |
+
HANDLE(self.handle),
|
133 |
+
buffer,
|
134 |
+
code_units_to_be_read,
|
135 |
+
byref(code_units_read),
|
136 |
+
None,
|
137 |
+
)
|
138 |
+
if GetLastError() == ERROR_OPERATION_ABORTED:
|
139 |
+
# wait for KeyboardInterrupt
|
140 |
+
time.sleep(0.1)
|
141 |
+
if not rv:
|
142 |
+
raise OSError(f"Windows error: {GetLastError()}")
|
143 |
+
|
144 |
+
if buffer[0] == EOF:
|
145 |
+
return 0
|
146 |
+
return 2 * code_units_read.value
|
147 |
+
|
148 |
+
|
149 |
+
class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):
|
150 |
+
def writable(self):
|
151 |
+
return True
|
152 |
+
|
153 |
+
@staticmethod
|
154 |
+
def _get_error_message(errno):
|
155 |
+
if errno == ERROR_SUCCESS:
|
156 |
+
return "ERROR_SUCCESS"
|
157 |
+
elif errno == ERROR_NOT_ENOUGH_MEMORY:
|
158 |
+
return "ERROR_NOT_ENOUGH_MEMORY"
|
159 |
+
return f"Windows error {errno}"
|
160 |
+
|
161 |
+
def write(self, b):
|
162 |
+
bytes_to_be_written = len(b)
|
163 |
+
buf = get_buffer(b)
|
164 |
+
code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2
|
165 |
+
code_units_written = c_ulong()
|
166 |
+
|
167 |
+
WriteConsoleW(
|
168 |
+
HANDLE(self.handle),
|
169 |
+
buf,
|
170 |
+
code_units_to_be_written,
|
171 |
+
byref(code_units_written),
|
172 |
+
None,
|
173 |
+
)
|
174 |
+
bytes_written = 2 * code_units_written.value
|
175 |
+
|
176 |
+
if bytes_written == 0 and bytes_to_be_written > 0:
|
177 |
+
raise OSError(self._get_error_message(GetLastError()))
|
178 |
+
return bytes_written
|
179 |
+
|
180 |
+
|
181 |
+
class ConsoleStream:
|
182 |
+
def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:
|
183 |
+
self._text_stream = text_stream
|
184 |
+
self.buffer = byte_stream
|
185 |
+
|
186 |
+
@property
|
187 |
+
def name(self) -> str:
|
188 |
+
return self.buffer.name
|
189 |
+
|
190 |
+
def write(self, x: t.AnyStr) -> int:
|
191 |
+
if isinstance(x, str):
|
192 |
+
return self._text_stream.write(x)
|
193 |
+
try:
|
194 |
+
self.flush()
|
195 |
+
except Exception:
|
196 |
+
pass
|
197 |
+
return self.buffer.write(x)
|
198 |
+
|
199 |
+
def writelines(self, lines: t.Iterable[t.AnyStr]) -> None:
|
200 |
+
for line in lines:
|
201 |
+
self.write(line)
|
202 |
+
|
203 |
+
def __getattr__(self, name: str) -> t.Any:
|
204 |
+
return getattr(self._text_stream, name)
|
205 |
+
|
206 |
+
def isatty(self) -> bool:
|
207 |
+
return self.buffer.isatty()
|
208 |
+
|
209 |
+
def __repr__(self):
|
210 |
+
return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"
|
211 |
+
|
212 |
+
|
213 |
+
def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:
|
214 |
+
text_stream = _NonClosingTextIOWrapper(
|
215 |
+
io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
|
216 |
+
"utf-16-le",
|
217 |
+
"strict",
|
218 |
+
line_buffering=True,
|
219 |
+
)
|
220 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
221 |
+
|
222 |
+
|
223 |
+
def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:
|
224 |
+
text_stream = _NonClosingTextIOWrapper(
|
225 |
+
io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
|
226 |
+
"utf-16-le",
|
227 |
+
"strict",
|
228 |
+
line_buffering=True,
|
229 |
+
)
|
230 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
231 |
+
|
232 |
+
|
233 |
+
def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:
|
234 |
+
text_stream = _NonClosingTextIOWrapper(
|
235 |
+
io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
|
236 |
+
"utf-16-le",
|
237 |
+
"strict",
|
238 |
+
line_buffering=True,
|
239 |
+
)
|
240 |
+
return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
|
241 |
+
|
242 |
+
|
243 |
+
_stream_factories: t.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {
|
244 |
+
0: _get_text_stdin,
|
245 |
+
1: _get_text_stdout,
|
246 |
+
2: _get_text_stderr,
|
247 |
+
}
|
248 |
+
|
249 |
+
|
250 |
+
def _is_console(f: t.TextIO) -> bool:
|
251 |
+
if not hasattr(f, "fileno"):
|
252 |
+
return False
|
253 |
+
|
254 |
+
try:
|
255 |
+
fileno = f.fileno()
|
256 |
+
except (OSError, io.UnsupportedOperation):
|
257 |
+
return False
|
258 |
+
|
259 |
+
handle = msvcrt.get_osfhandle(fileno)
|
260 |
+
return bool(GetConsoleMode(handle, byref(DWORD())))
|
261 |
+
|
262 |
+
|
263 |
+
def _get_windows_console_stream(
|
264 |
+
f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]
|
265 |
+
) -> t.Optional[t.TextIO]:
|
266 |
+
if (
|
267 |
+
get_buffer is not None
|
268 |
+
and encoding in {"utf-16-le", None}
|
269 |
+
and errors in {"strict", None}
|
270 |
+
and _is_console(f)
|
271 |
+
):
|
272 |
+
func = _stream_factories.get(f.fileno())
|
273 |
+
if func is not None:
|
274 |
+
b = getattr(f, "buffer", None)
|
275 |
+
|
276 |
+
if b is None:
|
277 |
+
return None
|
278 |
+
|
279 |
+
return func(b)
|
venv/lib/python3.10/site-packages/click/core.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/click/decorators.py
ADDED
@@ -0,0 +1,561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
from gettext import gettext as _
|
6 |
+
|
7 |
+
from .core import Argument
|
8 |
+
from .core import Command
|
9 |
+
from .core import Context
|
10 |
+
from .core import Group
|
11 |
+
from .core import Option
|
12 |
+
from .core import Parameter
|
13 |
+
from .globals import get_current_context
|
14 |
+
from .utils import echo
|
15 |
+
|
16 |
+
if t.TYPE_CHECKING:
|
17 |
+
import typing_extensions as te
|
18 |
+
|
19 |
+
P = te.ParamSpec("P")
|
20 |
+
|
21 |
+
R = t.TypeVar("R")
|
22 |
+
T = t.TypeVar("T")
|
23 |
+
_AnyCallable = t.Callable[..., t.Any]
|
24 |
+
FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])
|
25 |
+
|
26 |
+
|
27 |
+
def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":
|
28 |
+
"""Marks a callback as wanting to receive the current context
|
29 |
+
object as first argument.
|
30 |
+
"""
|
31 |
+
|
32 |
+
def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":
|
33 |
+
return f(get_current_context(), *args, **kwargs)
|
34 |
+
|
35 |
+
return update_wrapper(new_func, f)
|
36 |
+
|
37 |
+
|
38 |
+
def pass_obj(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":
|
39 |
+
"""Similar to :func:`pass_context`, but only pass the object on the
|
40 |
+
context onwards (:attr:`Context.obj`). This is useful if that object
|
41 |
+
represents the state of a nested system.
|
42 |
+
"""
|
43 |
+
|
44 |
+
def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":
|
45 |
+
return f(get_current_context().obj, *args, **kwargs)
|
46 |
+
|
47 |
+
return update_wrapper(new_func, f)
|
48 |
+
|
49 |
+
|
50 |
+
def make_pass_decorator(
|
51 |
+
object_type: t.Type[T], ensure: bool = False
|
52 |
+
) -> t.Callable[["t.Callable[te.Concatenate[T, P], R]"], "t.Callable[P, R]"]:
|
53 |
+
"""Given an object type this creates a decorator that will work
|
54 |
+
similar to :func:`pass_obj` but instead of passing the object of the
|
55 |
+
current context, it will find the innermost context of type
|
56 |
+
:func:`object_type`.
|
57 |
+
|
58 |
+
This generates a decorator that works roughly like this::
|
59 |
+
|
60 |
+
from functools import update_wrapper
|
61 |
+
|
62 |
+
def decorator(f):
|
63 |
+
@pass_context
|
64 |
+
def new_func(ctx, *args, **kwargs):
|
65 |
+
obj = ctx.find_object(object_type)
|
66 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
67 |
+
return update_wrapper(new_func, f)
|
68 |
+
return decorator
|
69 |
+
|
70 |
+
:param object_type: the type of the object to pass.
|
71 |
+
:param ensure: if set to `True`, a new object will be created and
|
72 |
+
remembered on the context if it's not there yet.
|
73 |
+
"""
|
74 |
+
|
75 |
+
def decorator(f: "t.Callable[te.Concatenate[T, P], R]") -> "t.Callable[P, R]":
|
76 |
+
def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":
|
77 |
+
ctx = get_current_context()
|
78 |
+
|
79 |
+
obj: t.Optional[T]
|
80 |
+
if ensure:
|
81 |
+
obj = ctx.ensure_object(object_type)
|
82 |
+
else:
|
83 |
+
obj = ctx.find_object(object_type)
|
84 |
+
|
85 |
+
if obj is None:
|
86 |
+
raise RuntimeError(
|
87 |
+
"Managed to invoke callback without a context"
|
88 |
+
f" object of type {object_type.__name__!r}"
|
89 |
+
" existing."
|
90 |
+
)
|
91 |
+
|
92 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
93 |
+
|
94 |
+
return update_wrapper(new_func, f)
|
95 |
+
|
96 |
+
return decorator # type: ignore[return-value]
|
97 |
+
|
98 |
+
|
99 |
+
def pass_meta_key(
|
100 |
+
key: str, *, doc_description: t.Optional[str] = None
|
101 |
+
) -> "t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]":
|
102 |
+
"""Create a decorator that passes a key from
|
103 |
+
:attr:`click.Context.meta` as the first argument to the decorated
|
104 |
+
function.
|
105 |
+
|
106 |
+
:param key: Key in ``Context.meta`` to pass.
|
107 |
+
:param doc_description: Description of the object being passed,
|
108 |
+
inserted into the decorator's docstring. Defaults to "the 'key'
|
109 |
+
key from Context.meta".
|
110 |
+
|
111 |
+
.. versionadded:: 8.0
|
112 |
+
"""
|
113 |
+
|
114 |
+
def decorator(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":
|
115 |
+
def new_func(*args: "P.args", **kwargs: "P.kwargs") -> R:
|
116 |
+
ctx = get_current_context()
|
117 |
+
obj = ctx.meta[key]
|
118 |
+
return ctx.invoke(f, obj, *args, **kwargs)
|
119 |
+
|
120 |
+
return update_wrapper(new_func, f)
|
121 |
+
|
122 |
+
if doc_description is None:
|
123 |
+
doc_description = f"the {key!r} key from :attr:`click.Context.meta`"
|
124 |
+
|
125 |
+
decorator.__doc__ = (
|
126 |
+
f"Decorator that passes {doc_description} as the first argument"
|
127 |
+
" to the decorated function."
|
128 |
+
)
|
129 |
+
return decorator # type: ignore[return-value]
|
130 |
+
|
131 |
+
|
132 |
+
CmdType = t.TypeVar("CmdType", bound=Command)
|
133 |
+
|
134 |
+
|
135 |
+
# variant: no call, directly as decorator for a function.
|
136 |
+
@t.overload
|
137 |
+
def command(name: _AnyCallable) -> Command:
|
138 |
+
...
|
139 |
+
|
140 |
+
|
141 |
+
# variant: with positional name and with positional or keyword cls argument:
|
142 |
+
# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)
|
143 |
+
@t.overload
|
144 |
+
def command(
|
145 |
+
name: t.Optional[str],
|
146 |
+
cls: t.Type[CmdType],
|
147 |
+
**attrs: t.Any,
|
148 |
+
) -> t.Callable[[_AnyCallable], CmdType]:
|
149 |
+
...
|
150 |
+
|
151 |
+
|
152 |
+
# variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)
|
153 |
+
@t.overload
|
154 |
+
def command(
|
155 |
+
name: None = None,
|
156 |
+
*,
|
157 |
+
cls: t.Type[CmdType],
|
158 |
+
**attrs: t.Any,
|
159 |
+
) -> t.Callable[[_AnyCallable], CmdType]:
|
160 |
+
...
|
161 |
+
|
162 |
+
|
163 |
+
# variant: with optional string name, no cls argument provided.
|
164 |
+
@t.overload
|
165 |
+
def command(
|
166 |
+
name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any
|
167 |
+
) -> t.Callable[[_AnyCallable], Command]:
|
168 |
+
...
|
169 |
+
|
170 |
+
|
171 |
+
def command(
|
172 |
+
name: t.Union[t.Optional[str], _AnyCallable] = None,
|
173 |
+
cls: t.Optional[t.Type[CmdType]] = None,
|
174 |
+
**attrs: t.Any,
|
175 |
+
) -> t.Union[Command, t.Callable[[_AnyCallable], t.Union[Command, CmdType]]]:
|
176 |
+
r"""Creates a new :class:`Command` and uses the decorated function as
|
177 |
+
callback. This will also automatically attach all decorated
|
178 |
+
:func:`option`\s and :func:`argument`\s as parameters to the command.
|
179 |
+
|
180 |
+
The name of the command defaults to the name of the function with
|
181 |
+
underscores replaced by dashes. If you want to change that, you can
|
182 |
+
pass the intended name as the first argument.
|
183 |
+
|
184 |
+
All keyword arguments are forwarded to the underlying command class.
|
185 |
+
For the ``params`` argument, any decorated params are appended to
|
186 |
+
the end of the list.
|
187 |
+
|
188 |
+
Once decorated the function turns into a :class:`Command` instance
|
189 |
+
that can be invoked as a command line utility or be attached to a
|
190 |
+
command :class:`Group`.
|
191 |
+
|
192 |
+
:param name: the name of the command. This defaults to the function
|
193 |
+
name with underscores replaced by dashes.
|
194 |
+
:param cls: the command class to instantiate. This defaults to
|
195 |
+
:class:`Command`.
|
196 |
+
|
197 |
+
.. versionchanged:: 8.1
|
198 |
+
This decorator can be applied without parentheses.
|
199 |
+
|
200 |
+
.. versionchanged:: 8.1
|
201 |
+
The ``params`` argument can be used. Decorated params are
|
202 |
+
appended to the end of the list.
|
203 |
+
"""
|
204 |
+
|
205 |
+
func: t.Optional[t.Callable[[_AnyCallable], t.Any]] = None
|
206 |
+
|
207 |
+
if callable(name):
|
208 |
+
func = name
|
209 |
+
name = None
|
210 |
+
assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
|
211 |
+
assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
|
212 |
+
|
213 |
+
if cls is None:
|
214 |
+
cls = t.cast(t.Type[CmdType], Command)
|
215 |
+
|
216 |
+
def decorator(f: _AnyCallable) -> CmdType:
|
217 |
+
if isinstance(f, Command):
|
218 |
+
raise TypeError("Attempted to convert a callback into a command twice.")
|
219 |
+
|
220 |
+
attr_params = attrs.pop("params", None)
|
221 |
+
params = attr_params if attr_params is not None else []
|
222 |
+
|
223 |
+
try:
|
224 |
+
decorator_params = f.__click_params__ # type: ignore
|
225 |
+
except AttributeError:
|
226 |
+
pass
|
227 |
+
else:
|
228 |
+
del f.__click_params__ # type: ignore
|
229 |
+
params.extend(reversed(decorator_params))
|
230 |
+
|
231 |
+
if attrs.get("help") is None:
|
232 |
+
attrs["help"] = f.__doc__
|
233 |
+
|
234 |
+
if t.TYPE_CHECKING:
|
235 |
+
assert cls is not None
|
236 |
+
assert not callable(name)
|
237 |
+
|
238 |
+
cmd = cls(
|
239 |
+
name=name or f.__name__.lower().replace("_", "-"),
|
240 |
+
callback=f,
|
241 |
+
params=params,
|
242 |
+
**attrs,
|
243 |
+
)
|
244 |
+
cmd.__doc__ = f.__doc__
|
245 |
+
return cmd
|
246 |
+
|
247 |
+
if func is not None:
|
248 |
+
return decorator(func)
|
249 |
+
|
250 |
+
return decorator
|
251 |
+
|
252 |
+
|
253 |
+
GrpType = t.TypeVar("GrpType", bound=Group)
|
254 |
+
|
255 |
+
|
256 |
+
# variant: no call, directly as decorator for a function.
|
257 |
+
@t.overload
|
258 |
+
def group(name: _AnyCallable) -> Group:
|
259 |
+
...
|
260 |
+
|
261 |
+
|
262 |
+
# variant: with positional name and with positional or keyword cls argument:
|
263 |
+
# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)
|
264 |
+
@t.overload
|
265 |
+
def group(
|
266 |
+
name: t.Optional[str],
|
267 |
+
cls: t.Type[GrpType],
|
268 |
+
**attrs: t.Any,
|
269 |
+
) -> t.Callable[[_AnyCallable], GrpType]:
|
270 |
+
...
|
271 |
+
|
272 |
+
|
273 |
+
# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)
|
274 |
+
@t.overload
|
275 |
+
def group(
|
276 |
+
name: None = None,
|
277 |
+
*,
|
278 |
+
cls: t.Type[GrpType],
|
279 |
+
**attrs: t.Any,
|
280 |
+
) -> t.Callable[[_AnyCallable], GrpType]:
|
281 |
+
...
|
282 |
+
|
283 |
+
|
284 |
+
# variant: with optional string name, no cls argument provided.
|
285 |
+
@t.overload
|
286 |
+
def group(
|
287 |
+
name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any
|
288 |
+
) -> t.Callable[[_AnyCallable], Group]:
|
289 |
+
...
|
290 |
+
|
291 |
+
|
292 |
+
def group(
|
293 |
+
name: t.Union[str, _AnyCallable, None] = None,
|
294 |
+
cls: t.Optional[t.Type[GrpType]] = None,
|
295 |
+
**attrs: t.Any,
|
296 |
+
) -> t.Union[Group, t.Callable[[_AnyCallable], t.Union[Group, GrpType]]]:
|
297 |
+
"""Creates a new :class:`Group` with a function as callback. This
|
298 |
+
works otherwise the same as :func:`command` just that the `cls`
|
299 |
+
parameter is set to :class:`Group`.
|
300 |
+
|
301 |
+
.. versionchanged:: 8.1
|
302 |
+
This decorator can be applied without parentheses.
|
303 |
+
"""
|
304 |
+
if cls is None:
|
305 |
+
cls = t.cast(t.Type[GrpType], Group)
|
306 |
+
|
307 |
+
if callable(name):
|
308 |
+
return command(cls=cls, **attrs)(name)
|
309 |
+
|
310 |
+
return command(name, cls, **attrs)
|
311 |
+
|
312 |
+
|
313 |
+
def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None:
|
314 |
+
if isinstance(f, Command):
|
315 |
+
f.params.append(param)
|
316 |
+
else:
|
317 |
+
if not hasattr(f, "__click_params__"):
|
318 |
+
f.__click_params__ = [] # type: ignore
|
319 |
+
|
320 |
+
f.__click_params__.append(param) # type: ignore
|
321 |
+
|
322 |
+
|
323 |
+
def argument(
|
324 |
+
*param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any
|
325 |
+
) -> t.Callable[[FC], FC]:
|
326 |
+
"""Attaches an argument to the command. All positional arguments are
|
327 |
+
passed as parameter declarations to :class:`Argument`; all keyword
|
328 |
+
arguments are forwarded unchanged (except ``cls``).
|
329 |
+
This is equivalent to creating an :class:`Argument` instance manually
|
330 |
+
and attaching it to the :attr:`Command.params` list.
|
331 |
+
|
332 |
+
For the default argument class, refer to :class:`Argument` and
|
333 |
+
:class:`Parameter` for descriptions of parameters.
|
334 |
+
|
335 |
+
:param cls: the argument class to instantiate. This defaults to
|
336 |
+
:class:`Argument`.
|
337 |
+
:param param_decls: Passed as positional arguments to the constructor of
|
338 |
+
``cls``.
|
339 |
+
:param attrs: Passed as keyword arguments to the constructor of ``cls``.
|
340 |
+
"""
|
341 |
+
if cls is None:
|
342 |
+
cls = Argument
|
343 |
+
|
344 |
+
def decorator(f: FC) -> FC:
|
345 |
+
_param_memo(f, cls(param_decls, **attrs))
|
346 |
+
return f
|
347 |
+
|
348 |
+
return decorator
|
349 |
+
|
350 |
+
|
351 |
+
def option(
|
352 |
+
*param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any
|
353 |
+
) -> t.Callable[[FC], FC]:
|
354 |
+
"""Attaches an option to the command. All positional arguments are
|
355 |
+
passed as parameter declarations to :class:`Option`; all keyword
|
356 |
+
arguments are forwarded unchanged (except ``cls``).
|
357 |
+
This is equivalent to creating an :class:`Option` instance manually
|
358 |
+
and attaching it to the :attr:`Command.params` list.
|
359 |
+
|
360 |
+
For the default option class, refer to :class:`Option` and
|
361 |
+
:class:`Parameter` for descriptions of parameters.
|
362 |
+
|
363 |
+
:param cls: the option class to instantiate. This defaults to
|
364 |
+
:class:`Option`.
|
365 |
+
:param param_decls: Passed as positional arguments to the constructor of
|
366 |
+
``cls``.
|
367 |
+
:param attrs: Passed as keyword arguments to the constructor of ``cls``.
|
368 |
+
"""
|
369 |
+
if cls is None:
|
370 |
+
cls = Option
|
371 |
+
|
372 |
+
def decorator(f: FC) -> FC:
|
373 |
+
_param_memo(f, cls(param_decls, **attrs))
|
374 |
+
return f
|
375 |
+
|
376 |
+
return decorator
|
377 |
+
|
378 |
+
|
379 |
+
def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
380 |
+
"""Add a ``--yes`` option which shows a prompt before continuing if
|
381 |
+
not passed. If the prompt is declined, the program will exit.
|
382 |
+
|
383 |
+
:param param_decls: One or more option names. Defaults to the single
|
384 |
+
value ``"--yes"``.
|
385 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
386 |
+
"""
|
387 |
+
|
388 |
+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
|
389 |
+
if not value:
|
390 |
+
ctx.abort()
|
391 |
+
|
392 |
+
if not param_decls:
|
393 |
+
param_decls = ("--yes",)
|
394 |
+
|
395 |
+
kwargs.setdefault("is_flag", True)
|
396 |
+
kwargs.setdefault("callback", callback)
|
397 |
+
kwargs.setdefault("expose_value", False)
|
398 |
+
kwargs.setdefault("prompt", "Do you want to continue?")
|
399 |
+
kwargs.setdefault("help", "Confirm the action without prompting.")
|
400 |
+
return option(*param_decls, **kwargs)
|
401 |
+
|
402 |
+
|
403 |
+
def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
404 |
+
"""Add a ``--password`` option which prompts for a password, hiding
|
405 |
+
input and asking to enter the value again for confirmation.
|
406 |
+
|
407 |
+
:param param_decls: One or more option names. Defaults to the single
|
408 |
+
value ``"--password"``.
|
409 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
410 |
+
"""
|
411 |
+
if not param_decls:
|
412 |
+
param_decls = ("--password",)
|
413 |
+
|
414 |
+
kwargs.setdefault("prompt", True)
|
415 |
+
kwargs.setdefault("confirmation_prompt", True)
|
416 |
+
kwargs.setdefault("hide_input", True)
|
417 |
+
return option(*param_decls, **kwargs)
|
418 |
+
|
419 |
+
|
420 |
+
def version_option(
|
421 |
+
version: t.Optional[str] = None,
|
422 |
+
*param_decls: str,
|
423 |
+
package_name: t.Optional[str] = None,
|
424 |
+
prog_name: t.Optional[str] = None,
|
425 |
+
message: t.Optional[str] = None,
|
426 |
+
**kwargs: t.Any,
|
427 |
+
) -> t.Callable[[FC], FC]:
|
428 |
+
"""Add a ``--version`` option which immediately prints the version
|
429 |
+
number and exits the program.
|
430 |
+
|
431 |
+
If ``version`` is not provided, Click will try to detect it using
|
432 |
+
:func:`importlib.metadata.version` to get the version for the
|
433 |
+
``package_name``. On Python < 3.8, the ``importlib_metadata``
|
434 |
+
backport must be installed.
|
435 |
+
|
436 |
+
If ``package_name`` is not provided, Click will try to detect it by
|
437 |
+
inspecting the stack frames. This will be used to detect the
|
438 |
+
version, so it must match the name of the installed package.
|
439 |
+
|
440 |
+
:param version: The version number to show. If not provided, Click
|
441 |
+
will try to detect it.
|
442 |
+
:param param_decls: One or more option names. Defaults to the single
|
443 |
+
value ``"--version"``.
|
444 |
+
:param package_name: The package name to detect the version from. If
|
445 |
+
not provided, Click will try to detect it.
|
446 |
+
:param prog_name: The name of the CLI to show in the message. If not
|
447 |
+
provided, it will be detected from the command.
|
448 |
+
:param message: The message to show. The values ``%(prog)s``,
|
449 |
+
``%(package)s``, and ``%(version)s`` are available. Defaults to
|
450 |
+
``"%(prog)s, version %(version)s"``.
|
451 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
452 |
+
:raise RuntimeError: ``version`` could not be detected.
|
453 |
+
|
454 |
+
.. versionchanged:: 8.0
|
455 |
+
Add the ``package_name`` parameter, and the ``%(package)s``
|
456 |
+
value for messages.
|
457 |
+
|
458 |
+
.. versionchanged:: 8.0
|
459 |
+
Use :mod:`importlib.metadata` instead of ``pkg_resources``. The
|
460 |
+
version is detected based on the package name, not the entry
|
461 |
+
point name. The Python package name must match the installed
|
462 |
+
package name, or be passed with ``package_name=``.
|
463 |
+
"""
|
464 |
+
if message is None:
|
465 |
+
message = _("%(prog)s, version %(version)s")
|
466 |
+
|
467 |
+
if version is None and package_name is None:
|
468 |
+
frame = inspect.currentframe()
|
469 |
+
f_back = frame.f_back if frame is not None else None
|
470 |
+
f_globals = f_back.f_globals if f_back is not None else None
|
471 |
+
# break reference cycle
|
472 |
+
# https://docs.python.org/3/library/inspect.html#the-interpreter-stack
|
473 |
+
del frame
|
474 |
+
|
475 |
+
if f_globals is not None:
|
476 |
+
package_name = f_globals.get("__name__")
|
477 |
+
|
478 |
+
if package_name == "__main__":
|
479 |
+
package_name = f_globals.get("__package__")
|
480 |
+
|
481 |
+
if package_name:
|
482 |
+
package_name = package_name.partition(".")[0]
|
483 |
+
|
484 |
+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
|
485 |
+
if not value or ctx.resilient_parsing:
|
486 |
+
return
|
487 |
+
|
488 |
+
nonlocal prog_name
|
489 |
+
nonlocal version
|
490 |
+
|
491 |
+
if prog_name is None:
|
492 |
+
prog_name = ctx.find_root().info_name
|
493 |
+
|
494 |
+
if version is None and package_name is not None:
|
495 |
+
metadata: t.Optional[types.ModuleType]
|
496 |
+
|
497 |
+
try:
|
498 |
+
from importlib import metadata # type: ignore
|
499 |
+
except ImportError:
|
500 |
+
# Python < 3.8
|
501 |
+
import importlib_metadata as metadata # type: ignore
|
502 |
+
|
503 |
+
try:
|
504 |
+
version = metadata.version(package_name) # type: ignore
|
505 |
+
except metadata.PackageNotFoundError: # type: ignore
|
506 |
+
raise RuntimeError(
|
507 |
+
f"{package_name!r} is not installed. Try passing"
|
508 |
+
" 'package_name' instead."
|
509 |
+
) from None
|
510 |
+
|
511 |
+
if version is None:
|
512 |
+
raise RuntimeError(
|
513 |
+
f"Could not determine the version for {package_name!r} automatically."
|
514 |
+
)
|
515 |
+
|
516 |
+
echo(
|
517 |
+
message % {"prog": prog_name, "package": package_name, "version": version},
|
518 |
+
color=ctx.color,
|
519 |
+
)
|
520 |
+
ctx.exit()
|
521 |
+
|
522 |
+
if not param_decls:
|
523 |
+
param_decls = ("--version",)
|
524 |
+
|
525 |
+
kwargs.setdefault("is_flag", True)
|
526 |
+
kwargs.setdefault("expose_value", False)
|
527 |
+
kwargs.setdefault("is_eager", True)
|
528 |
+
kwargs.setdefault("help", _("Show the version and exit."))
|
529 |
+
kwargs["callback"] = callback
|
530 |
+
return option(*param_decls, **kwargs)
|
531 |
+
|
532 |
+
|
533 |
+
def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
|
534 |
+
"""Add a ``--help`` option which immediately prints the help page
|
535 |
+
and exits the program.
|
536 |
+
|
537 |
+
This is usually unnecessary, as the ``--help`` option is added to
|
538 |
+
each command automatically unless ``add_help_option=False`` is
|
539 |
+
passed.
|
540 |
+
|
541 |
+
:param param_decls: One or more option names. Defaults to the single
|
542 |
+
value ``"--help"``.
|
543 |
+
:param kwargs: Extra arguments are passed to :func:`option`.
|
544 |
+
"""
|
545 |
+
|
546 |
+
def callback(ctx: Context, param: Parameter, value: bool) -> None:
|
547 |
+
if not value or ctx.resilient_parsing:
|
548 |
+
return
|
549 |
+
|
550 |
+
echo(ctx.get_help(), color=ctx.color)
|
551 |
+
ctx.exit()
|
552 |
+
|
553 |
+
if not param_decls:
|
554 |
+
param_decls = ("--help",)
|
555 |
+
|
556 |
+
kwargs.setdefault("is_flag", True)
|
557 |
+
kwargs.setdefault("expose_value", False)
|
558 |
+
kwargs.setdefault("is_eager", True)
|
559 |
+
kwargs.setdefault("help", _("Show this message and exit."))
|
560 |
+
kwargs["callback"] = callback
|
561 |
+
return option(*param_decls, **kwargs)
|
venv/lib/python3.10/site-packages/click/exceptions.py
ADDED
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
from gettext import gettext as _
|
3 |
+
from gettext import ngettext
|
4 |
+
|
5 |
+
from ._compat import get_text_stderr
|
6 |
+
from .utils import echo
|
7 |
+
from .utils import format_filename
|
8 |
+
|
9 |
+
if t.TYPE_CHECKING:
|
10 |
+
from .core import Command
|
11 |
+
from .core import Context
|
12 |
+
from .core import Parameter
|
13 |
+
|
14 |
+
|
15 |
+
def _join_param_hints(
|
16 |
+
param_hint: t.Optional[t.Union[t.Sequence[str], str]]
|
17 |
+
) -> t.Optional[str]:
|
18 |
+
if param_hint is not None and not isinstance(param_hint, str):
|
19 |
+
return " / ".join(repr(x) for x in param_hint)
|
20 |
+
|
21 |
+
return param_hint
|
22 |
+
|
23 |
+
|
24 |
+
class ClickException(Exception):
|
25 |
+
"""An exception that Click can handle and show to the user."""
|
26 |
+
|
27 |
+
#: The exit code for this exception.
|
28 |
+
exit_code = 1
|
29 |
+
|
30 |
+
def __init__(self, message: str) -> None:
|
31 |
+
super().__init__(message)
|
32 |
+
self.message = message
|
33 |
+
|
34 |
+
def format_message(self) -> str:
|
35 |
+
return self.message
|
36 |
+
|
37 |
+
def __str__(self) -> str:
|
38 |
+
return self.message
|
39 |
+
|
40 |
+
def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:
|
41 |
+
if file is None:
|
42 |
+
file = get_text_stderr()
|
43 |
+
|
44 |
+
echo(_("Error: {message}").format(message=self.format_message()), file=file)
|
45 |
+
|
46 |
+
|
47 |
+
class UsageError(ClickException):
|
48 |
+
"""An internal exception that signals a usage error. This typically
|
49 |
+
aborts any further handling.
|
50 |
+
|
51 |
+
:param message: the error message to display.
|
52 |
+
:param ctx: optionally the context that caused this error. Click will
|
53 |
+
fill in the context automatically in some situations.
|
54 |
+
"""
|
55 |
+
|
56 |
+
exit_code = 2
|
57 |
+
|
58 |
+
def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:
|
59 |
+
super().__init__(message)
|
60 |
+
self.ctx = ctx
|
61 |
+
self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None
|
62 |
+
|
63 |
+
def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:
|
64 |
+
if file is None:
|
65 |
+
file = get_text_stderr()
|
66 |
+
color = None
|
67 |
+
hint = ""
|
68 |
+
if (
|
69 |
+
self.ctx is not None
|
70 |
+
and self.ctx.command.get_help_option(self.ctx) is not None
|
71 |
+
):
|
72 |
+
hint = _("Try '{command} {option}' for help.").format(
|
73 |
+
command=self.ctx.command_path, option=self.ctx.help_option_names[0]
|
74 |
+
)
|
75 |
+
hint = f"{hint}\n"
|
76 |
+
if self.ctx is not None:
|
77 |
+
color = self.ctx.color
|
78 |
+
echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)
|
79 |
+
echo(
|
80 |
+
_("Error: {message}").format(message=self.format_message()),
|
81 |
+
file=file,
|
82 |
+
color=color,
|
83 |
+
)
|
84 |
+
|
85 |
+
|
86 |
+
class BadParameter(UsageError):
|
87 |
+
"""An exception that formats out a standardized error message for a
|
88 |
+
bad parameter. This is useful when thrown from a callback or type as
|
89 |
+
Click will attach contextual information to it (for instance, which
|
90 |
+
parameter it is).
|
91 |
+
|
92 |
+
.. versionadded:: 2.0
|
93 |
+
|
94 |
+
:param param: the parameter object that caused this error. This can
|
95 |
+
be left out, and Click will attach this info itself
|
96 |
+
if possible.
|
97 |
+
:param param_hint: a string that shows up as parameter name. This
|
98 |
+
can be used as alternative to `param` in cases
|
99 |
+
where custom validation should happen. If it is
|
100 |
+
a string it's used as such, if it's a list then
|
101 |
+
each item is quoted and separated.
|
102 |
+
"""
|
103 |
+
|
104 |
+
def __init__(
|
105 |
+
self,
|
106 |
+
message: str,
|
107 |
+
ctx: t.Optional["Context"] = None,
|
108 |
+
param: t.Optional["Parameter"] = None,
|
109 |
+
param_hint: t.Optional[str] = None,
|
110 |
+
) -> None:
|
111 |
+
super().__init__(message, ctx)
|
112 |
+
self.param = param
|
113 |
+
self.param_hint = param_hint
|
114 |
+
|
115 |
+
def format_message(self) -> str:
|
116 |
+
if self.param_hint is not None:
|
117 |
+
param_hint = self.param_hint
|
118 |
+
elif self.param is not None:
|
119 |
+
param_hint = self.param.get_error_hint(self.ctx) # type: ignore
|
120 |
+
else:
|
121 |
+
return _("Invalid value: {message}").format(message=self.message)
|
122 |
+
|
123 |
+
return _("Invalid value for {param_hint}: {message}").format(
|
124 |
+
param_hint=_join_param_hints(param_hint), message=self.message
|
125 |
+
)
|
126 |
+
|
127 |
+
|
128 |
+
class MissingParameter(BadParameter):
|
129 |
+
"""Raised if click required an option or argument but it was not
|
130 |
+
provided when invoking the script.
|
131 |
+
|
132 |
+
.. versionadded:: 4.0
|
133 |
+
|
134 |
+
:param param_type: a string that indicates the type of the parameter.
|
135 |
+
The default is to inherit the parameter type from
|
136 |
+
the given `param`. Valid values are ``'parameter'``,
|
137 |
+
``'option'`` or ``'argument'``.
|
138 |
+
"""
|
139 |
+
|
140 |
+
def __init__(
|
141 |
+
self,
|
142 |
+
message: t.Optional[str] = None,
|
143 |
+
ctx: t.Optional["Context"] = None,
|
144 |
+
param: t.Optional["Parameter"] = None,
|
145 |
+
param_hint: t.Optional[str] = None,
|
146 |
+
param_type: t.Optional[str] = None,
|
147 |
+
) -> None:
|
148 |
+
super().__init__(message or "", ctx, param, param_hint)
|
149 |
+
self.param_type = param_type
|
150 |
+
|
151 |
+
def format_message(self) -> str:
|
152 |
+
if self.param_hint is not None:
|
153 |
+
param_hint: t.Optional[str] = self.param_hint
|
154 |
+
elif self.param is not None:
|
155 |
+
param_hint = self.param.get_error_hint(self.ctx) # type: ignore
|
156 |
+
else:
|
157 |
+
param_hint = None
|
158 |
+
|
159 |
+
param_hint = _join_param_hints(param_hint)
|
160 |
+
param_hint = f" {param_hint}" if param_hint else ""
|
161 |
+
|
162 |
+
param_type = self.param_type
|
163 |
+
if param_type is None and self.param is not None:
|
164 |
+
param_type = self.param.param_type_name
|
165 |
+
|
166 |
+
msg = self.message
|
167 |
+
if self.param is not None:
|
168 |
+
msg_extra = self.param.type.get_missing_message(self.param)
|
169 |
+
if msg_extra:
|
170 |
+
if msg:
|
171 |
+
msg += f". {msg_extra}"
|
172 |
+
else:
|
173 |
+
msg = msg_extra
|
174 |
+
|
175 |
+
msg = f" {msg}" if msg else ""
|
176 |
+
|
177 |
+
# Translate param_type for known types.
|
178 |
+
if param_type == "argument":
|
179 |
+
missing = _("Missing argument")
|
180 |
+
elif param_type == "option":
|
181 |
+
missing = _("Missing option")
|
182 |
+
elif param_type == "parameter":
|
183 |
+
missing = _("Missing parameter")
|
184 |
+
else:
|
185 |
+
missing = _("Missing {param_type}").format(param_type=param_type)
|
186 |
+
|
187 |
+
return f"{missing}{param_hint}.{msg}"
|
188 |
+
|
189 |
+
def __str__(self) -> str:
|
190 |
+
if not self.message:
|
191 |
+
param_name = self.param.name if self.param else None
|
192 |
+
return _("Missing parameter: {param_name}").format(param_name=param_name)
|
193 |
+
else:
|
194 |
+
return self.message
|
195 |
+
|
196 |
+
|
197 |
+
class NoSuchOption(UsageError):
|
198 |
+
"""Raised if click attempted to handle an option that does not
|
199 |
+
exist.
|
200 |
+
|
201 |
+
.. versionadded:: 4.0
|
202 |
+
"""
|
203 |
+
|
204 |
+
def __init__(
|
205 |
+
self,
|
206 |
+
option_name: str,
|
207 |
+
message: t.Optional[str] = None,
|
208 |
+
possibilities: t.Optional[t.Sequence[str]] = None,
|
209 |
+
ctx: t.Optional["Context"] = None,
|
210 |
+
) -> None:
|
211 |
+
if message is None:
|
212 |
+
message = _("No such option: {name}").format(name=option_name)
|
213 |
+
|
214 |
+
super().__init__(message, ctx)
|
215 |
+
self.option_name = option_name
|
216 |
+
self.possibilities = possibilities
|
217 |
+
|
218 |
+
def format_message(self) -> str:
|
219 |
+
if not self.possibilities:
|
220 |
+
return self.message
|
221 |
+
|
222 |
+
possibility_str = ", ".join(sorted(self.possibilities))
|
223 |
+
suggest = ngettext(
|
224 |
+
"Did you mean {possibility}?",
|
225 |
+
"(Possible options: {possibilities})",
|
226 |
+
len(self.possibilities),
|
227 |
+
).format(possibility=possibility_str, possibilities=possibility_str)
|
228 |
+
return f"{self.message} {suggest}"
|
229 |
+
|
230 |
+
|
231 |
+
class BadOptionUsage(UsageError):
|
232 |
+
"""Raised if an option is generally supplied but the use of the option
|
233 |
+
was incorrect. This is for instance raised if the number of arguments
|
234 |
+
for an option is not correct.
|
235 |
+
|
236 |
+
.. versionadded:: 4.0
|
237 |
+
|
238 |
+
:param option_name: the name of the option being used incorrectly.
|
239 |
+
"""
|
240 |
+
|
241 |
+
def __init__(
|
242 |
+
self, option_name: str, message: str, ctx: t.Optional["Context"] = None
|
243 |
+
) -> None:
|
244 |
+
super().__init__(message, ctx)
|
245 |
+
self.option_name = option_name
|
246 |
+
|
247 |
+
|
248 |
+
class BadArgumentUsage(UsageError):
|
249 |
+
"""Raised if an argument is generally supplied but the use of the argument
|
250 |
+
was incorrect. This is for instance raised if the number of values
|
251 |
+
for an argument is not correct.
|
252 |
+
|
253 |
+
.. versionadded:: 6.0
|
254 |
+
"""
|
255 |
+
|
256 |
+
|
257 |
+
class FileError(ClickException):
|
258 |
+
"""Raised if a file cannot be opened."""
|
259 |
+
|
260 |
+
def __init__(self, filename: str, hint: t.Optional[str] = None) -> None:
|
261 |
+
if hint is None:
|
262 |
+
hint = _("unknown error")
|
263 |
+
|
264 |
+
super().__init__(hint)
|
265 |
+
self.ui_filename: str = format_filename(filename)
|
266 |
+
self.filename = filename
|
267 |
+
|
268 |
+
def format_message(self) -> str:
|
269 |
+
return _("Could not open file {filename!r}: {message}").format(
|
270 |
+
filename=self.ui_filename, message=self.message
|
271 |
+
)
|
272 |
+
|
273 |
+
|
274 |
+
class Abort(RuntimeError):
|
275 |
+
"""An internal signalling exception that signals Click to abort."""
|
276 |
+
|
277 |
+
|
278 |
+
class Exit(RuntimeError):
|
279 |
+
"""An exception that indicates that the application should exit with some
|
280 |
+
status code.
|
281 |
+
|
282 |
+
:param code: the status code to exit with.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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
from contextlib import contextmanager
|
3 |
+
from gettext import gettext as _
|
4 |
+
|
5 |
+
from ._compat import term_len
|
6 |
+
from .parser import split_opt
|
7 |
+
|
8 |
+
# Can force a width. This is used by the test system
|
9 |
+
FORCED_WIDTH: t.Optional[int] = None
|
10 |
+
|
11 |
+
|
12 |
+
def measure_table(rows: t.Iterable[t.Tuple[str, str]]) -> t.Tuple[int, ...]:
|
13 |
+
widths: t.Dict[int, int] = {}
|
14 |
+
|
15 |
+
for row in rows:
|
16 |
+
for idx, col in enumerate(row):
|
17 |
+
widths[idx] = max(widths.get(idx, 0), term_len(col))
|
18 |
+
|
19 |
+
return tuple(y for x, y in sorted(widths.items()))
|
20 |
+
|
21 |
+
|
22 |
+
def iter_rows(
|
23 |
+
rows: t.Iterable[t.Tuple[str, str]], col_count: int
|
24 |
+
) -> t.Iterator[t.Tuple[str, ...]]:
|
25 |
+
for row in rows:
|
26 |
+
yield row + ("",) * (col_count - len(row))
|
27 |
+
|
28 |
+
|
29 |
+
def wrap_text(
|
30 |
+
text: str,
|
31 |
+
width: int = 78,
|
32 |
+
initial_indent: str = "",
|
33 |
+
subsequent_indent: str = "",
|
34 |
+
preserve_paragraphs: bool = False,
|
35 |
+
) -> str:
|
36 |
+
"""A helper function that intelligently wraps text. By default, it
|
37 |
+
assumes that it operates on a single paragraph of text but if the
|
38 |
+
`preserve_paragraphs` parameter is provided it will intelligently
|
39 |
+
handle paragraphs (defined by two empty lines).
|
40 |
+
|
41 |
+
If paragraphs are handled, a paragraph can be prefixed with an empty
|
42 |
+
line containing the ``\\b`` character (``\\x08``) to indicate that
|
43 |
+
no rewrapping should happen in that block.
|
44 |
+
|
45 |
+
:param text: the text that should be rewrapped.
|
46 |
+
:param width: the maximum width for the text.
|
47 |
+
:param initial_indent: the initial indent that should be placed on the
|
48 |
+
first line as a string.
|
49 |
+
:param subsequent_indent: the indent string that should be placed on
|
50 |
+
each consecutive line.
|
51 |
+
:param preserve_paragraphs: if this flag is set then the wrapping will
|
52 |
+
intelligently handle paragraphs.
|
53 |
+
"""
|
54 |
+
from ._textwrap import TextWrapper
|
55 |
+
|
56 |
+
text = text.expandtabs()
|
57 |
+
wrapper = TextWrapper(
|
58 |
+
width,
|
59 |
+
initial_indent=initial_indent,
|
60 |
+
subsequent_indent=subsequent_indent,
|
61 |
+
replace_whitespace=False,
|
62 |
+
)
|
63 |
+
if not preserve_paragraphs:
|
64 |
+
return wrapper.fill(text)
|
65 |
+
|
66 |
+
p: t.List[t.Tuple[int, bool, str]] = []
|
67 |
+
buf: t.List[str] = []
|
68 |
+
indent = None
|
69 |
+
|
70 |
+
def _flush_par() -> None:
|
71 |
+
if not buf:
|
72 |
+
return
|
73 |
+
if buf[0].strip() == "\b":
|
74 |
+
p.append((indent or 0, True, "\n".join(buf[1:])))
|
75 |
+
else:
|
76 |
+
p.append((indent or 0, False, " ".join(buf)))
|
77 |
+
del buf[:]
|
78 |
+
|
79 |
+
for line in text.splitlines():
|
80 |
+
if not line:
|
81 |
+
_flush_par()
|
82 |
+
indent = None
|
83 |
+
else:
|
84 |
+
if indent is None:
|
85 |
+
orig_len = term_len(line)
|
86 |
+
line = line.lstrip()
|
87 |
+
indent = orig_len - term_len(line)
|
88 |
+
buf.append(line)
|
89 |
+
_flush_par()
|
90 |
+
|
91 |
+
rv = []
|
92 |
+
for indent, raw, text in p:
|
93 |
+
with wrapper.extra_indent(" " * indent):
|
94 |
+
if raw:
|
95 |
+
rv.append(wrapper.indent_only(text))
|
96 |
+
else:
|
97 |
+
rv.append(wrapper.fill(text))
|
98 |
+
|
99 |
+
return "\n\n".join(rv)
|
100 |
+
|
101 |
+
|
102 |
+
class HelpFormatter:
|
103 |
+
"""This class helps with formatting text-based help pages. It's
|
104 |
+
usually just needed for very special internal cases, but it's also
|
105 |
+
exposed so that developers can write their own fancy outputs.
|
106 |
+
|
107 |
+
At present, it always writes into memory.
|
108 |
+
|
109 |
+
:param indent_increment: the additional increment for each level.
|
110 |
+
:param width: the width for the text. This defaults to the terminal
|
111 |
+
width clamped to a maximum of 78.
|
112 |
+
"""
|
113 |
+
|
114 |
+
def __init__(
|
115 |
+
self,
|
116 |
+
indent_increment: int = 2,
|
117 |
+
width: t.Optional[int] = None,
|
118 |
+
max_width: t.Optional[int] = None,
|
119 |
+
) -> None:
|
120 |
+
import shutil
|
121 |
+
|
122 |
+
self.indent_increment = indent_increment
|
123 |
+
if max_width is None:
|
124 |
+
max_width = 80
|
125 |
+
if width is None:
|
126 |
+
width = FORCED_WIDTH
|
127 |
+
if width is None:
|
128 |
+
width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)
|
129 |
+
self.width = width
|
130 |
+
self.current_indent = 0
|
131 |
+
self.buffer: t.List[str] = []
|
132 |
+
|
133 |
+
def write(self, string: str) -> None:
|
134 |
+
"""Writes a unicode string into the internal buffer."""
|
135 |
+
self.buffer.append(string)
|
136 |
+
|
137 |
+
def indent(self) -> None:
|
138 |
+
"""Increases the indentation."""
|
139 |
+
self.current_indent += self.indent_increment
|
140 |
+
|
141 |
+
def dedent(self) -> None:
|
142 |
+
"""Decreases the indentation."""
|
143 |
+
self.current_indent -= self.indent_increment
|
144 |
+
|
145 |
+
def write_usage(
|
146 |
+
self, prog: str, args: str = "", prefix: t.Optional[str] = None
|
147 |
+
) -> None:
|
148 |
+
"""Writes a usage line into the buffer.
|
149 |
+
|
150 |
+
:param prog: the program name.
|
151 |
+
:param args: whitespace separated list of arguments.
|
152 |
+
:param prefix: The prefix for the first line. Defaults to
|
153 |
+
``"Usage: "``.
|
154 |
+
"""
|
155 |
+
if prefix is None:
|
156 |
+
prefix = f"{_('Usage:')} "
|
157 |
+
|
158 |
+
usage_prefix = f"{prefix:>{self.current_indent}}{prog} "
|
159 |
+
text_width = self.width - self.current_indent
|
160 |
+
|
161 |
+
if text_width >= (term_len(usage_prefix) + 20):
|
162 |
+
# The arguments will fit to the right of the prefix.
|
163 |
+
indent = " " * term_len(usage_prefix)
|
164 |
+
self.write(
|
165 |
+
wrap_text(
|
166 |
+
args,
|
167 |
+
text_width,
|
168 |
+
initial_indent=usage_prefix,
|
169 |
+
subsequent_indent=indent,
|
170 |
+
)
|
171 |
+
)
|
172 |
+
else:
|
173 |
+
# The prefix is too long, put the arguments on the next line.
|
174 |
+
self.write(usage_prefix)
|
175 |
+
self.write("\n")
|
176 |
+
indent = " " * (max(self.current_indent, term_len(prefix)) + 4)
|
177 |
+
self.write(
|
178 |
+
wrap_text(
|
179 |
+
args, text_width, initial_indent=indent, subsequent_indent=indent
|
180 |
+
)
|
181 |
+
)
|
182 |
+
|
183 |
+
self.write("\n")
|
184 |
+
|
185 |
+
def write_heading(self, heading: str) -> None:
|
186 |
+
"""Writes a heading into the buffer."""
|
187 |
+
self.write(f"{'':>{self.current_indent}}{heading}:\n")
|
188 |
+
|
189 |
+
def write_paragraph(self) -> None:
|
190 |
+
"""Writes a paragraph into the buffer."""
|
191 |
+
if self.buffer:
|
192 |
+
self.write("\n")
|
193 |
+
|
194 |
+
def write_text(self, text: str) -> None:
|
195 |
+
"""Writes re-indented text into the buffer. This rewraps and
|
196 |
+
preserves paragraphs.
|
197 |
+
"""
|
198 |
+
indent = " " * self.current_indent
|
199 |
+
self.write(
|
200 |
+
wrap_text(
|
201 |
+
text,
|
202 |
+
self.width,
|
203 |
+
initial_indent=indent,
|
204 |
+
subsequent_indent=indent,
|
205 |
+
preserve_paragraphs=True,
|
206 |
+
)
|
207 |
+
)
|
208 |
+
self.write("\n")
|
209 |
+
|
210 |
+
def write_dl(
|
211 |
+
self,
|
212 |
+
rows: t.Sequence[t.Tuple[str, str]],
|
213 |
+
col_max: int = 30,
|
214 |
+
col_spacing: int = 2,
|
215 |
+
) -> None:
|
216 |
+
"""Writes a definition list into the buffer. This is how options
|
217 |
+
and commands are usually formatted.
|
218 |
+
|
219 |
+
:param rows: a list of two item tuples for the terms and values.
|
220 |
+
:param col_max: the maximum width of the first column.
|
221 |
+
:param col_spacing: the number of spaces between the first and
|
222 |
+
second column.
|
223 |
+
"""
|
224 |
+
rows = list(rows)
|
225 |
+
widths = measure_table(rows)
|
226 |
+
if len(widths) != 2:
|
227 |
+
raise TypeError("Expected two columns for definition list")
|
228 |
+
|
229 |
+
first_col = min(widths[0], col_max) + col_spacing
|
230 |
+
|
231 |
+
for first, second in iter_rows(rows, len(widths)):
|
232 |
+
self.write(f"{'':>{self.current_indent}}{first}")
|
233 |
+
if not second:
|
234 |
+
self.write("\n")
|
235 |
+
continue
|
236 |
+
if term_len(first) <= first_col - col_spacing:
|
237 |
+
self.write(" " * (first_col - term_len(first)))
|
238 |
+
else:
|
239 |
+
self.write("\n")
|
240 |
+
self.write(" " * (first_col + self.current_indent))
|
241 |
+
|
242 |
+
text_width = max(self.width - first_col - 2, 10)
|
243 |
+
wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)
|
244 |
+
lines = wrapped_text.splitlines()
|
245 |
+
|
246 |
+
if lines:
|
247 |
+
self.write(f"{lines[0]}\n")
|
248 |
+
|
249 |
+
for line in lines[1:]:
|
250 |
+
self.write(f"{'':>{first_col + self.current_indent}}{line}\n")
|
251 |
+
else:
|
252 |
+
self.write("\n")
|
253 |
+
|
254 |
+
@contextmanager
|
255 |
+
def section(self, name: str) -> t.Iterator[None]:
|
256 |
+
"""Helpful context manager that writes a paragraph, a heading,
|
257 |
+
and the indents.
|
258 |
+
|
259 |
+
:param name: the section name that is written as heading.
|
260 |
+
"""
|
261 |
+
self.write_paragraph()
|
262 |
+
self.write_heading(name)
|
263 |
+
self.indent()
|
264 |
+
try:
|
265 |
+
yield
|
266 |
+
finally:
|
267 |
+
self.dedent()
|
268 |
+
|
269 |
+
@contextmanager
|
270 |
+
def indentation(self) -> t.Iterator[None]:
|
271 |
+
"""A context manager that increases the indentation."""
|
272 |
+
self.indent()
|
273 |
+
try:
|
274 |
+
yield
|
275 |
+
finally:
|
276 |
+
self.dedent()
|
277 |
+
|
278 |
+
def getvalue(self) -> str:
|
279 |
+
"""Returns the buffer contents."""
|
280 |
+
return "".join(self.buffer)
|
281 |
+
|
282 |
+
|
283 |
+
def join_options(options: t.Sequence[str]) -> t.Tuple[str, bool]:
|
284 |
+
"""Given a list of option strings this joins them in the most appropriate
|
285 |
+
way and returns them in the form ``(formatted_string,
|
286 |
+
any_prefix_is_slash)`` where the second item in the tuple is a flag that
|
287 |
+
indicates if any of the option prefixes was a slash.
|
288 |
+
"""
|
289 |
+
rv = []
|
290 |
+
any_prefix_is_slash = False
|
291 |
+
|
292 |
+
for opt in options:
|
293 |
+
prefix = split_opt(opt)[0]
|
294 |
+
|
295 |
+
if prefix == "/":
|
296 |
+
any_prefix_is_slash = True
|
297 |
+
|
298 |
+
rv.append((len(prefix), opt))
|
299 |
+
|
300 |
+
rv.sort(key=lambda x: x[0])
|
301 |
+
return ", ".join(x[1] for x in rv), any_prefix_is_slash
|
venv/lib/python3.10/site-packages/click/globals.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import typing as t
|
2 |
+
from threading import local
|
3 |
+
|
4 |
+
if t.TYPE_CHECKING:
|
5 |
+
import typing_extensions as te
|
6 |
+
from .core import Context
|
7 |
+
|
8 |
+
_local = local()
|
9 |
+
|
10 |
+
|
11 |
+
@t.overload
|
12 |
+
def get_current_context(silent: "te.Literal[False]" = False) -> "Context":
|
13 |
+
...
|
14 |
+
|
15 |
+
|
16 |
+
@t.overload
|
17 |
+
def get_current_context(silent: bool = ...) -> t.Optional["Context"]:
|
18 |
+
...
|
19 |
+
|
20 |
+
|
21 |
+
def get_current_context(silent: bool = False) -> t.Optional["Context"]:
|
22 |
+
"""Returns the current click context. This can be used as a way to
|
23 |
+
access the current context object from anywhere. This is a more implicit
|
24 |
+
alternative to the :func:`pass_context` decorator. This function is
|
25 |
+
primarily useful for helpers such as :func:`echo` which might be
|
26 |
+
interested in changing its behavior based on the current context.
|
27 |
+
|
28 |
+
To push the current context, :meth:`Context.scope` can be used.
|
29 |
+
|
30 |
+
.. versionadded:: 5.0
|
31 |
+
|
32 |
+
:param silent: if set to `True` the return value is `None` if no context
|
33 |
+
is available. The default behavior is to raise a
|
34 |
+
:exc:`RuntimeError`.
|
35 |
+
"""
|
36 |
+
try:
|
37 |
+
return t.cast("Context", _local.stack[-1])
|
38 |
+
except (AttributeError, IndexError) as e:
|
39 |
+
if not silent:
|
40 |
+
raise RuntimeError("There is no active click context.") from e
|
41 |
+
|
42 |
+
return None
|
43 |
+
|
44 |
+
|
45 |
+
def push_context(ctx: "Context") -> None:
|
46 |
+
"""Pushes a new context to the current stack."""
|
47 |
+
_local.__dict__.setdefault("stack", []).append(ctx)
|
48 |
+
|
49 |
+
|
50 |
+
def pop_context() -> None:
|
51 |
+
"""Removes the top level from the stack."""
|
52 |
+
_local.stack.pop()
|
53 |
+
|
54 |
+
|
55 |
+
def resolve_color_default(color: t.Optional[bool] = None) -> t.Optional[bool]:
|
56 |
+
"""Internal helper to get the default value of the color flag. If a
|
57 |
+
value is passed it's returned unchanged, otherwise it's looked up from
|
58 |
+
the current context.
|
59 |
+
"""
|
60 |
+
if color is not None:
|
61 |
+
return color
|
62 |
+
|
63 |
+
ctx = get_current_context(silent=True)
|
64 |
+
|
65 |
+
if ctx is not None:
|
66 |
+
return ctx.color
|
67 |
+
|
68 |
+
return None
|
venv/lib/python3.10/site-packages/click/parser.py
ADDED
@@ -0,0 +1,529 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module started out as largely a copy paste from the stdlib's
|
3 |
+
optparse module with the features removed that we do not need from
|
4 |
+
optparse because we implement them in Click on a higher level (for
|
5 |
+
instance type handling, help formatting and a lot more).
|
6 |
+
|
7 |
+
The plan is to remove more and more from here over time.
|
8 |
+
|
9 |
+
The reason this is a different module and not optparse from the stdlib
|
10 |
+
is that there are differences in 2.x and 3.x about the error messages
|
11 |
+
generated and optparse in the stdlib uses gettext for no good reason
|
12 |
+
and might cause us issues.
|
13 |
+
|
14 |
+
Click uses parts of optparse written by Gregory P. Ward and maintained
|
15 |
+
by the Python Software Foundation. This is limited to code in parser.py.
|
16 |
+
|
17 |
+
Copyright 2001-2006 Gregory P. Ward. All rights reserved.
|
18 |
+
Copyright 2002-2006 Python Software Foundation. All rights reserved.
|
19 |
+
"""
|
20 |
+
# This code uses parts of optparse written by Gregory P. Ward and
|
21 |
+
# maintained by the Python Software Foundation.
|
22 |
+
# Copyright 2001-2006 Gregory P. Ward
|
23 |
+
# Copyright 2002-2006 Python Software Foundation
|
24 |
+
import typing as t
|
25 |
+
from collections import deque
|
26 |
+
from gettext import gettext as _
|
27 |
+
from gettext import ngettext
|
28 |
+
|
29 |
+
from .exceptions import BadArgumentUsage
|
30 |
+
from .exceptions import BadOptionUsage
|
31 |
+
from .exceptions import NoSuchOption
|
32 |
+
from .exceptions import UsageError
|
33 |
+
|
34 |
+
if t.TYPE_CHECKING:
|
35 |
+
import typing_extensions as te
|
36 |
+
from .core import Argument as CoreArgument
|
37 |
+
from .core import Context
|
38 |
+
from .core import Option as CoreOption
|
39 |
+
from .core import Parameter as CoreParameter
|
40 |
+
|
41 |
+
V = t.TypeVar("V")
|
42 |
+
|
43 |
+
# Sentinel value that indicates an option was passed as a flag without a
|
44 |
+
# value but is not a flag option. Option.consume_value uses this to
|
45 |
+
# prompt or use the flag_value.
|
46 |
+
_flag_needs_value = object()
|
47 |
+
|
48 |
+
|
49 |
+
def _unpack_args(
|
50 |
+
args: t.Sequence[str], nargs_spec: t.Sequence[int]
|
51 |
+
) -> t.Tuple[t.Sequence[t.Union[str, t.Sequence[t.Optional[str]], None]], t.List[str]]:
|
52 |
+
"""Given an iterable of arguments and an iterable of nargs specifications,
|
53 |
+
it returns a tuple with all the unpacked arguments at the first index
|
54 |
+
and all remaining arguments as the second.
|
55 |
+
|
56 |
+
The nargs specification is the number of arguments that should be consumed
|
57 |
+
or `-1` to indicate that this position should eat up all the remainders.
|
58 |
+
|
59 |
+
Missing items are filled with `None`.
|
60 |
+
"""
|
61 |
+
args = deque(args)
|
62 |
+
nargs_spec = deque(nargs_spec)
|
63 |
+
rv: t.List[t.Union[str, t.Tuple[t.Optional[str], ...], None]] = []
|
64 |
+
spos: t.Optional[int] = None
|
65 |
+
|
66 |
+
def _fetch(c: "te.Deque[V]") -> t.Optional[V]:
|
67 |
+
try:
|
68 |
+
if spos is None:
|
69 |
+
return c.popleft()
|
70 |
+
else:
|
71 |
+
return c.pop()
|
72 |
+
except IndexError:
|
73 |
+
return None
|
74 |
+
|
75 |
+
while nargs_spec:
|
76 |
+
nargs = _fetch(nargs_spec)
|
77 |
+
|
78 |
+
if nargs is None:
|
79 |
+
continue
|
80 |
+
|
81 |
+
if nargs == 1:
|
82 |
+
rv.append(_fetch(args))
|
83 |
+
elif nargs > 1:
|
84 |
+
x = [_fetch(args) for _ in range(nargs)]
|
85 |
+
|
86 |
+
# If we're reversed, we're pulling in the arguments in reverse,
|
87 |
+
# so we need to turn them around.
|
88 |
+
if spos is not None:
|
89 |
+
x.reverse()
|
90 |
+
|
91 |
+
rv.append(tuple(x))
|
92 |
+
elif nargs < 0:
|
93 |
+
if spos is not None:
|
94 |
+
raise TypeError("Cannot have two nargs < 0")
|
95 |
+
|
96 |
+
spos = len(rv)
|
97 |
+
rv.append(None)
|
98 |
+
|
99 |
+
# spos is the position of the wildcard (star). If it's not `None`,
|
100 |
+
# we fill it with the remainder.
|
101 |
+
if spos is not None:
|
102 |
+
rv[spos] = tuple(args)
|
103 |
+
args = []
|
104 |
+
rv[spos + 1 :] = reversed(rv[spos + 1 :])
|
105 |
+
|
106 |
+
return tuple(rv), list(args)
|
107 |
+
|
108 |
+
|
109 |
+
def split_opt(opt: str) -> t.Tuple[str, str]:
|
110 |
+
first = opt[:1]
|
111 |
+
if first.isalnum():
|
112 |
+
return "", opt
|
113 |
+
if opt[1:2] == first:
|
114 |
+
return opt[:2], opt[2:]
|
115 |
+
return first, opt[1:]
|
116 |
+
|
117 |
+
|
118 |
+
def normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:
|
119 |
+
if ctx is None or ctx.token_normalize_func is None:
|
120 |
+
return opt
|
121 |
+
prefix, opt = split_opt(opt)
|
122 |
+
return f"{prefix}{ctx.token_normalize_func(opt)}"
|
123 |
+
|
124 |
+
|
125 |
+
def split_arg_string(string: str) -> t.List[str]:
|
126 |
+
"""Split an argument string as with :func:`shlex.split`, but don't
|
127 |
+
fail if the string is incomplete. Ignores a missing closing quote or
|
128 |
+
incomplete escape sequence and uses the partial token as-is.
|
129 |
+
|
130 |
+
.. code-block:: python
|
131 |
+
|
132 |
+
split_arg_string("example 'my file")
|
133 |
+
["example", "my file"]
|
134 |
+
|
135 |
+
split_arg_string("example my\\")
|
136 |
+
["example", "my"]
|
137 |
+
|
138 |
+
:param string: String to split.
|
139 |
+
"""
|
140 |
+
import shlex
|
141 |
+
|
142 |
+
lex = shlex.shlex(string, posix=True)
|
143 |
+
lex.whitespace_split = True
|
144 |
+
lex.commenters = ""
|
145 |
+
out = []
|
146 |
+
|
147 |
+
try:
|
148 |
+
for token in lex:
|
149 |
+
out.append(token)
|
150 |
+
except ValueError:
|
151 |
+
# Raised when end-of-string is reached in an invalid state. Use
|
152 |
+
# the partial token as-is. The quote or escape character is in
|
153 |
+
# lex.state, not lex.token.
|
154 |
+
out.append(lex.token)
|
155 |
+
|
156 |
+
return out
|
157 |
+
|
158 |
+
|
159 |
+
class Option:
|
160 |
+
def __init__(
|
161 |
+
self,
|
162 |
+
obj: "CoreOption",
|
163 |
+
opts: t.Sequence[str],
|
164 |
+
dest: t.Optional[str],
|
165 |
+
action: t.Optional[str] = None,
|
166 |
+
nargs: int = 1,
|
167 |
+
const: t.Optional[t.Any] = None,
|
168 |
+
):
|
169 |
+
self._short_opts = []
|
170 |
+
self._long_opts = []
|
171 |
+
self.prefixes: t.Set[str] = set()
|
172 |
+
|
173 |
+
for opt in opts:
|
174 |
+
prefix, value = split_opt(opt)
|
175 |
+
if not prefix:
|
176 |
+
raise ValueError(f"Invalid start character for option ({opt})")
|
177 |
+
self.prefixes.add(prefix[0])
|
178 |
+
if len(prefix) == 1 and len(value) == 1:
|
179 |
+
self._short_opts.append(opt)
|
180 |
+
else:
|
181 |
+
self._long_opts.append(opt)
|
182 |
+
self.prefixes.add(prefix)
|
183 |
+
|
184 |
+
if action is None:
|
185 |
+
action = "store"
|
186 |
+
|
187 |
+
self.dest = dest
|
188 |
+
self.action = action
|
189 |
+
self.nargs = nargs
|
190 |
+
self.const = const
|
191 |
+
self.obj = obj
|
192 |
+
|
193 |
+
@property
|
194 |
+
def takes_value(self) -> bool:
|
195 |
+
return self.action in ("store", "append")
|
196 |
+
|
197 |
+
def process(self, value: t.Any, state: "ParsingState") -> None:
|
198 |
+
if self.action == "store":
|
199 |
+
state.opts[self.dest] = value # type: ignore
|
200 |
+
elif self.action == "store_const":
|
201 |
+
state.opts[self.dest] = self.const # type: ignore
|
202 |
+
elif self.action == "append":
|
203 |
+
state.opts.setdefault(self.dest, []).append(value) # type: ignore
|
204 |
+
elif self.action == "append_const":
|
205 |
+
state.opts.setdefault(self.dest, []).append(self.const) # type: ignore
|
206 |
+
elif self.action == "count":
|
207 |
+
state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore
|
208 |
+
else:
|
209 |
+
raise ValueError(f"unknown action '{self.action}'")
|
210 |
+
state.order.append(self.obj)
|
211 |
+
|
212 |
+
|
213 |
+
class Argument:
|
214 |
+
def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):
|
215 |
+
self.dest = dest
|
216 |
+
self.nargs = nargs
|
217 |
+
self.obj = obj
|
218 |
+
|
219 |
+
def process(
|
220 |
+
self,
|
221 |
+
value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],
|
222 |
+
state: "ParsingState",
|
223 |
+
) -> None:
|
224 |
+
if self.nargs > 1:
|
225 |
+
assert value is not None
|
226 |
+
holes = sum(1 for x in value if x is None)
|
227 |
+
if holes == len(value):
|
228 |
+
value = None
|
229 |
+
elif holes != 0:
|
230 |
+
raise BadArgumentUsage(
|
231 |
+
_("Argument {name!r} takes {nargs} values.").format(
|
232 |
+
name=self.dest, nargs=self.nargs
|
233 |
+
)
|
234 |
+
)
|
235 |
+
|
236 |
+
if self.nargs == -1 and self.obj.envvar is not None and value == ():
|
237 |
+
# Replace empty tuple with None so that a value from the
|
238 |
+
# environment may be tried.
|
239 |
+
value = None
|
240 |
+
|
241 |
+
state.opts[self.dest] = value # type: ignore
|
242 |
+
state.order.append(self.obj)
|
243 |
+
|
244 |
+
|
245 |
+
class ParsingState:
|
246 |
+
def __init__(self, rargs: t.List[str]) -> None:
|
247 |
+
self.opts: t.Dict[str, t.Any] = {}
|
248 |
+
self.largs: t.List[str] = []
|
249 |
+
self.rargs = rargs
|
250 |
+
self.order: t.List["CoreParameter"] = []
|
251 |
+
|
252 |
+
|
253 |
+
class OptionParser:
|
254 |
+
"""The option parser is an internal class that is ultimately used to
|
255 |
+
parse options and arguments. It's modelled after optparse and brings
|
256 |
+
a similar but vastly simplified API. It should generally not be used
|
257 |
+
directly as the high level Click classes wrap it for you.
|
258 |
+
|
259 |
+
It's not nearly as extensible as optparse or argparse as it does not
|
260 |
+
implement features that are implemented on a higher level (such as
|
261 |
+
types or defaults).
|
262 |
+
|
263 |
+
:param ctx: optionally the :class:`~click.Context` where this parser
|
264 |
+
should go with.
|
265 |
+
"""
|
266 |
+
|
267 |
+
def __init__(self, ctx: t.Optional["Context"] = None) -> None:
|
268 |
+
#: The :class:`~click.Context` for this parser. This might be
|
269 |
+
#: `None` for some advanced use cases.
|
270 |
+
self.ctx = ctx
|
271 |
+
#: This controls how the parser deals with interspersed arguments.
|
272 |
+
#: If this is set to `False`, the parser will stop on the first
|
273 |
+
#: non-option. Click uses this to implement nested subcommands
|
274 |
+
#: safely.
|
275 |
+
self.allow_interspersed_args: bool = True
|
276 |
+
#: This tells the parser how to deal with unknown options. By
|
277 |
+
#: default it will error out (which is sensible), but there is a
|
278 |
+
#: second mode where it will ignore it and continue processing
|
279 |
+
#: after shifting all the unknown options into the resulting args.
|
280 |
+
self.ignore_unknown_options: bool = False
|
281 |
+
|
282 |
+
if ctx is not None:
|
283 |
+
self.allow_interspersed_args = ctx.allow_interspersed_args
|
284 |
+
self.ignore_unknown_options = ctx.ignore_unknown_options
|
285 |
+
|
286 |
+
self._short_opt: t.Dict[str, Option] = {}
|
287 |
+
self._long_opt: t.Dict[str, Option] = {}
|
288 |
+
self._opt_prefixes = {"-", "--"}
|
289 |
+
self._args: t.List[Argument] = []
|
290 |
+
|
291 |
+
def add_option(
|
292 |
+
self,
|
293 |
+
obj: "CoreOption",
|
294 |
+
opts: t.Sequence[str],
|
295 |
+
dest: t.Optional[str],
|
296 |
+
action: t.Optional[str] = None,
|
297 |
+
nargs: int = 1,
|
298 |
+
const: t.Optional[t.Any] = None,
|
299 |
+
) -> None:
|
300 |
+
"""Adds a new option named `dest` to the parser. The destination
|
301 |
+
is not inferred (unlike with optparse) and needs to be explicitly
|
302 |
+
provided. Action can be any of ``store``, ``store_const``,
|
303 |
+
``append``, ``append_const`` or ``count``.
|
304 |
+
|
305 |
+
The `obj` can be used to identify the option in the order list
|
306 |
+
that is returned from the parser.
|
307 |
+
"""
|
308 |
+
opts = [normalize_opt(opt, self.ctx) for opt in opts]
|
309 |
+
option = Option(obj, opts, dest, action=action, nargs=nargs, const=const)
|
310 |
+
self._opt_prefixes.update(option.prefixes)
|
311 |
+
for opt in option._short_opts:
|
312 |
+
self._short_opt[opt] = option
|
313 |
+
for opt in option._long_opts:
|
314 |
+
self._long_opt[opt] = option
|
315 |
+
|
316 |
+
def add_argument(
|
317 |
+
self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1
|
318 |
+
) -> None:
|
319 |
+
"""Adds a positional argument named `dest` to the parser.
|
320 |
+
|
321 |
+
The `obj` can be used to identify the option in the order list
|
322 |
+
that is returned from the parser.
|
323 |
+
"""
|
324 |
+
self._args.append(Argument(obj, dest=dest, nargs=nargs))
|
325 |
+
|
326 |
+
def parse_args(
|
327 |
+
self, args: t.List[str]
|
328 |
+
) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]:
|
329 |
+
"""Parses positional arguments and returns ``(values, args, order)``
|
330 |
+
for the parsed options and arguments as well as the leftover
|
331 |
+
arguments if there are any. The order is a list of objects as they
|
332 |
+
appear on the command line. If arguments appear multiple times they
|
333 |
+
will be memorized multiple times as well.
|
334 |
+
"""
|
335 |
+
state = ParsingState(args)
|
336 |
+
try:
|
337 |
+
self._process_args_for_options(state)
|
338 |
+
self._process_args_for_args(state)
|
339 |
+
except UsageError:
|
340 |
+
if self.ctx is None or not self.ctx.resilient_parsing:
|
341 |
+
raise
|
342 |
+
return state.opts, state.largs, state.order
|
343 |
+
|
344 |
+
def _process_args_for_args(self, state: ParsingState) -> None:
|
345 |
+
pargs, args = _unpack_args(
|
346 |
+
state.largs + state.rargs, [x.nargs for x in self._args]
|
347 |
+
)
|
348 |
+
|
349 |
+
for idx, arg in enumerate(self._args):
|
350 |
+
arg.process(pargs[idx], state)
|
351 |
+
|
352 |
+
state.largs = args
|
353 |
+
state.rargs = []
|
354 |
+
|
355 |
+
def _process_args_for_options(self, state: ParsingState) -> None:
|
356 |
+
while state.rargs:
|
357 |
+
arg = state.rargs.pop(0)
|
358 |
+
arglen = len(arg)
|
359 |
+
# Double dashes always handled explicitly regardless of what
|
360 |
+
# prefixes are valid.
|
361 |
+
if arg == "--":
|
362 |
+
return
|
363 |
+
elif arg[:1] in self._opt_prefixes and arglen > 1:
|
364 |
+
self._process_opts(arg, state)
|
365 |
+
elif self.allow_interspersed_args:
|
366 |
+
state.largs.append(arg)
|
367 |
+
else:
|
368 |
+
state.rargs.insert(0, arg)
|
369 |
+
return
|
370 |
+
|
371 |
+
# Say this is the original argument list:
|
372 |
+
# [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
|
373 |
+
# ^
|
374 |
+
# (we are about to process arg(i)).
|
375 |
+
#
|
376 |
+
# Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
|
377 |
+
# [arg0, ..., arg(i-1)] (any options and their arguments will have
|
378 |
+
# been removed from largs).
|
379 |
+
#
|
380 |
+
# The while loop will usually consume 1 or more arguments per pass.
|
381 |
+
# If it consumes 1 (eg. arg is an option that takes no arguments),
|
382 |
+
# then after _process_arg() is done the situation is:
|
383 |
+
#
|
384 |
+
# largs = subset of [arg0, ..., arg(i)]
|
385 |
+
# rargs = [arg(i+1), ..., arg(N-1)]
|
386 |
+
#
|
387 |
+
# If allow_interspersed_args is false, largs will always be
|
388 |
+
# *empty* -- still a subset of [arg0, ..., arg(i-1)], but
|
389 |
+
# not a very interesting subset!
|
390 |
+
|
391 |
+
def _match_long_opt(
|
392 |
+
self, opt: str, explicit_value: t.Optional[str], state: ParsingState
|
393 |
+
) -> None:
|
394 |
+
if opt not in self._long_opt:
|
395 |
+
from difflib import get_close_matches
|
396 |
+
|
397 |
+
possibilities = get_close_matches(opt, self._long_opt)
|
398 |
+
raise NoSuchOption(opt, possibilities=possibilities, ctx=self.ctx)
|
399 |
+
|
400 |
+
option = self._long_opt[opt]
|
401 |
+
if option.takes_value:
|
402 |
+
# At this point it's safe to modify rargs by injecting the
|
403 |
+
# explicit value, because no exception is raised in this
|
404 |
+
# branch. This means that the inserted value will be fully
|
405 |
+
# consumed.
|
406 |
+
if explicit_value is not None:
|
407 |
+
state.rargs.insert(0, explicit_value)
|
408 |
+
|
409 |
+
value = self._get_value_from_state(opt, option, state)
|
410 |
+
|
411 |
+
elif explicit_value is not None:
|
412 |
+
raise BadOptionUsage(
|
413 |
+
opt, _("Option {name!r} does not take a value.").format(name=opt)
|
414 |
+
)
|
415 |
+
|
416 |
+
else:
|
417 |
+
value = None
|
418 |
+
|
419 |
+
option.process(value, state)
|
420 |
+
|
421 |
+
def _match_short_opt(self, arg: str, state: ParsingState) -> None:
|
422 |
+
stop = False
|
423 |
+
i = 1
|
424 |
+
prefix = arg[0]
|
425 |
+
unknown_options = []
|
426 |
+
|
427 |
+
for ch in arg[1:]:
|
428 |
+
opt = normalize_opt(f"{prefix}{ch}", self.ctx)
|
429 |
+
option = self._short_opt.get(opt)
|
430 |
+
i += 1
|
431 |
+
|
432 |
+
if not option:
|
433 |
+
if self.ignore_unknown_options:
|
434 |
+
unknown_options.append(ch)
|
435 |
+
continue
|
436 |
+
raise NoSuchOption(opt, ctx=self.ctx)
|
437 |
+
if option.takes_value:
|
438 |
+
# Any characters left in arg? Pretend they're the
|
439 |
+
# next arg, and stop consuming characters of arg.
|
440 |
+
if i < len(arg):
|
441 |
+
state.rargs.insert(0, arg[i:])
|
442 |
+
stop = True
|
443 |
+
|
444 |
+
value = self._get_value_from_state(opt, option, state)
|
445 |
+
|
446 |
+
else:
|
447 |
+
value = None
|
448 |
+
|
449 |
+
option.process(value, state)
|
450 |
+
|
451 |
+
if stop:
|
452 |
+
break
|
453 |
+
|
454 |
+
# If we got any unknown options we recombine the string of the
|
455 |
+
# remaining options and re-attach the prefix, then report that
|
456 |
+
# to the state as new larg. This way there is basic combinatorics
|
457 |
+
# that can be achieved while still ignoring unknown arguments.
|
458 |
+
if self.ignore_unknown_options and unknown_options:
|
459 |
+
state.largs.append(f"{prefix}{''.join(unknown_options)}")
|
460 |
+
|
461 |
+
def _get_value_from_state(
|
462 |
+
self, option_name: str, option: Option, state: ParsingState
|
463 |
+
) -> t.Any:
|
464 |
+
nargs = option.nargs
|
465 |
+
|
466 |
+
if len(state.rargs) < nargs:
|
467 |
+
if option.obj._flag_needs_value:
|
468 |
+
# Option allows omitting the value.
|
469 |
+
value = _flag_needs_value
|
470 |
+
else:
|
471 |
+
raise BadOptionUsage(
|
472 |
+
option_name,
|
473 |
+
ngettext(
|
474 |
+
"Option {name!r} requires an argument.",
|
475 |
+
"Option {name!r} requires {nargs} arguments.",
|
476 |
+
nargs,
|
477 |
+
).format(name=option_name, nargs=nargs),
|
478 |
+
)
|
479 |
+
elif nargs == 1:
|
480 |
+
next_rarg = state.rargs[0]
|
481 |
+
|
482 |
+
if (
|
483 |
+
option.obj._flag_needs_value
|
484 |
+
and isinstance(next_rarg, str)
|
485 |
+
and next_rarg[:1] in self._opt_prefixes
|
486 |
+
and len(next_rarg) > 1
|
487 |
+
):
|
488 |
+
# The next arg looks like the start of an option, don't
|
489 |
+
# use it as the value if omitting the value is allowed.
|
490 |
+
value = _flag_needs_value
|
491 |
+
else:
|
492 |
+
value = state.rargs.pop(0)
|
493 |
+
else:
|
494 |
+
value = tuple(state.rargs[:nargs])
|
495 |
+
del state.rargs[:nargs]
|
496 |
+
|
497 |
+
return value
|
498 |
+
|
499 |
+
def _process_opts(self, arg: str, state: ParsingState) -> None:
|
500 |
+
explicit_value = None
|
501 |
+
# Long option handling happens in two parts. The first part is
|
502 |
+
# supporting explicitly attached values. In any case, we will try
|
503 |
+
# to long match the option first.
|
504 |
+
if "=" in arg:
|
505 |
+
long_opt, explicit_value = arg.split("=", 1)
|
506 |
+
else:
|
507 |
+
long_opt = arg
|
508 |
+
norm_long_opt = normalize_opt(long_opt, self.ctx)
|
509 |
+
|
510 |
+
# At this point we will match the (assumed) long option through
|
511 |
+
# the long option matching code. Note that this allows options
|
512 |
+
# like "-foo" to be matched as long options.
|
513 |
+
try:
|
514 |
+
self._match_long_opt(norm_long_opt, explicit_value, state)
|
515 |
+
except NoSuchOption:
|
516 |
+
# At this point the long option matching failed, and we need
|
517 |
+
# to try with short options. However there is a special rule
|
518 |
+
# which says, that if we have a two character options prefix
|
519 |
+
# (applies to "--foo" for instance), we do not dispatch to the
|
520 |
+
# short option code and will instead raise the no option
|
521 |
+
# error.
|
522 |
+
if arg[:2] not in self._opt_prefixes:
|
523 |
+
self._match_short_opt(arg, state)
|
524 |
+
return
|
525 |
+
|
526 |
+
if not self.ignore_unknown_options:
|
527 |
+
raise
|
528 |
+
|
529 |
+
state.largs.append(arg)
|
venv/lib/python3.10/site-packages/click/py.typed
ADDED
File without changes
|
venv/lib/python3.10/site-packages/click/shell_completion.py
ADDED
@@ -0,0 +1,596 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
5 |
+
|
6 |
+
from .core import Argument
|
7 |
+
from .core import BaseCommand
|
8 |
+
from .core import Context
|
9 |
+
from .core import MultiCommand
|
10 |
+
from .core import Option
|
11 |
+
from .core import Parameter
|
12 |
+
from .core import ParameterSource
|
13 |
+
from .parser import split_arg_string
|
14 |
+
from .utils import echo
|
15 |
+
|
16 |
+
|
17 |
+
def shell_complete(
|
18 |
+
cli: BaseCommand,
|
19 |
+
ctx_args: t.MutableMapping[str, t.Any],
|
20 |
+
prog_name: str,
|
21 |
+
complete_var: str,
|
22 |
+
instruction: str,
|
23 |
+
) -> int:
|
24 |
+
"""Perform shell completion for the given CLI program.
|
25 |
+
|
26 |
+
:param cli: Command being called.
|
27 |
+
:param ctx_args: Extra arguments to pass to
|
28 |
+
``cli.make_context``.
|
29 |
+
:param prog_name: Name of the executable in the shell.
|
30 |
+
:param complete_var: Name of the environment variable that holds
|
31 |
+
the completion instruction.
|
32 |
+
:param instruction: Value of ``complete_var`` with the completion
|
33 |
+
instruction and shell, in the form ``instruction_shell``.
|
34 |
+
:return: Status code to exit with.
|
35 |
+
"""
|
36 |
+
shell, _, instruction = instruction.partition("_")
|
37 |
+
comp_cls = get_completion_class(shell)
|
38 |
+
|
39 |
+
if comp_cls is None:
|
40 |
+
return 1
|
41 |
+
|
42 |
+
comp = comp_cls(cli, ctx_args, prog_name, complete_var)
|
43 |
+
|
44 |
+
if instruction == "source":
|
45 |
+
echo(comp.source())
|
46 |
+
return 0
|
47 |
+
|
48 |
+
if instruction == "complete":
|
49 |
+
echo(comp.complete())
|
50 |
+
return 0
|
51 |
+
|
52 |
+
return 1
|
53 |
+
|
54 |
+
|
55 |
+
class CompletionItem:
|
56 |
+
"""Represents a completion value and metadata about the value. The
|
57 |
+
default metadata is ``type`` to indicate special shell handling,
|
58 |
+
and ``help`` if a shell supports showing a help string next to the
|
59 |
+
value.
|
60 |
+
|
61 |
+
Arbitrary parameters can be passed when creating the object, and
|
62 |
+
accessed using ``item.attr``. If an attribute wasn't passed,
|
63 |
+
accessing it returns ``None``.
|
64 |
+
|
65 |
+
:param value: The completion suggestion.
|
66 |
+
:param type: Tells the shell script to provide special completion
|
67 |
+
support for the type. Click uses ``"dir"`` and ``"file"``.
|
68 |
+
:param help: String shown next to the value if supported.
|
69 |
+
:param kwargs: Arbitrary metadata. The built-in implementations
|
70 |
+
don't use this, but custom type completions paired with custom
|
71 |
+
shell support could use it.
|
72 |
+
"""
|
73 |
+
|
74 |
+
__slots__ = ("value", "type", "help", "_info")
|
75 |
+
|
76 |
+
def __init__(
|
77 |
+
self,
|
78 |
+
value: t.Any,
|
79 |
+
type: str = "plain",
|
80 |
+
help: t.Optional[str] = None,
|
81 |
+
**kwargs: t.Any,
|
82 |
+
) -> None:
|
83 |
+
self.value: t.Any = value
|
84 |
+
self.type: str = type
|
85 |
+
self.help: t.Optional[str] = help
|
86 |
+
self._info = kwargs
|
87 |
+
|
88 |
+
def __getattr__(self, name: str) -> t.Any:
|
89 |
+
return self._info.get(name)
|
90 |
+
|
91 |
+
|
92 |
+
# Only Bash >= 4.4 has the nosort option.
|
93 |
+
_SOURCE_BASH = """\
|
94 |
+
%(complete_func)s() {
|
95 |
+
local IFS=$'\\n'
|
96 |
+
local response
|
97 |
+
|
98 |
+
response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
|
99 |
+
%(complete_var)s=bash_complete $1)
|
100 |
+
|
101 |
+
for completion in $response; do
|
102 |
+
IFS=',' read type value <<< "$completion"
|
103 |
+
|
104 |
+
if [[ $type == 'dir' ]]; then
|
105 |
+
COMPREPLY=()
|
106 |
+
compopt -o dirnames
|
107 |
+
elif [[ $type == 'file' ]]; then
|
108 |
+
COMPREPLY=()
|
109 |
+
compopt -o default
|
110 |
+
elif [[ $type == 'plain' ]]; then
|
111 |
+
COMPREPLY+=($value)
|
112 |
+
fi
|
113 |
+
done
|
114 |
+
|
115 |
+
return 0
|
116 |
+
}
|
117 |
+
|
118 |
+
%(complete_func)s_setup() {
|
119 |
+
complete -o nosort -F %(complete_func)s %(prog_name)s
|
120 |
+
}
|
121 |
+
|
122 |
+
%(complete_func)s_setup;
|
123 |
+
"""
|
124 |
+
|
125 |
+
_SOURCE_ZSH = """\
|
126 |
+
#compdef %(prog_name)s
|
127 |
+
|
128 |
+
%(complete_func)s() {
|
129 |
+
local -a completions
|
130 |
+
local -a completions_with_descriptions
|
131 |
+
local -a response
|
132 |
+
(( ! $+commands[%(prog_name)s] )) && return 1
|
133 |
+
|
134 |
+
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \
|
135 |
+
%(complete_var)s=zsh_complete %(prog_name)s)}")
|
136 |
+
|
137 |
+
for type key descr in ${response}; do
|
138 |
+
if [[ "$type" == "plain" ]]; then
|
139 |
+
if [[ "$descr" == "_" ]]; then
|
140 |
+
completions+=("$key")
|
141 |
+
else
|
142 |
+
completions_with_descriptions+=("$key":"$descr")
|
143 |
+
fi
|
144 |
+
elif [[ "$type" == "dir" ]]; then
|
145 |
+
_path_files -/
|
146 |
+
elif [[ "$type" == "file" ]]; then
|
147 |
+
_path_files -f
|
148 |
+
fi
|
149 |
+
done
|
150 |
+
|
151 |
+
if [ -n "$completions_with_descriptions" ]; then
|
152 |
+
_describe -V unsorted completions_with_descriptions -U
|
153 |
+
fi
|
154 |
+
|
155 |
+
if [ -n "$completions" ]; then
|
156 |
+
compadd -U -V unsorted -a completions
|
157 |
+
fi
|
158 |
+
}
|
159 |
+
|
160 |
+
if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
|
161 |
+
# autoload from fpath, call function directly
|
162 |
+
%(complete_func)s "$@"
|
163 |
+
else
|
164 |
+
# eval/source/. command, register function for later
|
165 |
+
compdef %(complete_func)s %(prog_name)s
|
166 |
+
fi
|
167 |
+
"""
|
168 |
+
|
169 |
+
_SOURCE_FISH = """\
|
170 |
+
function %(complete_func)s;
|
171 |
+
set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \
|
172 |
+
COMP_CWORD=(commandline -t) %(prog_name)s);
|
173 |
+
|
174 |
+
for completion in $response;
|
175 |
+
set -l metadata (string split "," $completion);
|
176 |
+
|
177 |
+
if test $metadata[1] = "dir";
|
178 |
+
__fish_complete_directories $metadata[2];
|
179 |
+
else if test $metadata[1] = "file";
|
180 |
+
__fish_complete_path $metadata[2];
|
181 |
+
else if test $metadata[1] = "plain";
|
182 |
+
echo $metadata[2];
|
183 |
+
end;
|
184 |
+
end;
|
185 |
+
end;
|
186 |
+
|
187 |
+
complete --no-files --command %(prog_name)s --arguments \
|
188 |
+
"(%(complete_func)s)";
|
189 |
+
"""
|
190 |
+
|
191 |
+
|
192 |
+
class ShellComplete:
|
193 |
+
"""Base class for providing shell completion support. A subclass for
|
194 |
+
a given shell will override attributes and methods to implement the
|
195 |
+
completion instructions (``source`` and ``complete``).
|
196 |
+
|
197 |
+
:param cli: Command being called.
|
198 |
+
:param prog_name: Name of the executable in the shell.
|
199 |
+
:param complete_var: Name of the environment variable that holds
|
200 |
+
the completion instruction.
|
201 |
+
|
202 |
+
.. versionadded:: 8.0
|
203 |
+
"""
|
204 |
+
|
205 |
+
name: t.ClassVar[str]
|
206 |
+
"""Name to register the shell as with :func:`add_completion_class`.
|
207 |
+
This is used in completion instructions (``{name}_source`` and
|
208 |
+
``{name}_complete``).
|
209 |
+
"""
|
210 |
+
|
211 |
+
source_template: t.ClassVar[str]
|
212 |
+
"""Completion script template formatted by :meth:`source`. This must
|
213 |
+
be provided by subclasses.
|
214 |
+
"""
|
215 |
+
|
216 |
+
def __init__(
|
217 |
+
self,
|
218 |
+
cli: BaseCommand,
|
219 |
+
ctx_args: t.MutableMapping[str, t.Any],
|
220 |
+
prog_name: str,
|
221 |
+
complete_var: str,
|
222 |
+
) -> None:
|
223 |
+
self.cli = cli
|
224 |
+
self.ctx_args = ctx_args
|
225 |
+
self.prog_name = prog_name
|
226 |
+
self.complete_var = complete_var
|
227 |
+
|
228 |
+
@property
|
229 |
+
def func_name(self) -> str:
|
230 |
+
"""The name of the shell function defined by the completion
|
231 |
+
script.
|
232 |
+
"""
|
233 |
+
safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)
|
234 |
+
return f"_{safe_name}_completion"
|
235 |
+
|
236 |
+
def source_vars(self) -> t.Dict[str, t.Any]:
|
237 |
+
"""Vars for formatting :attr:`source_template`.
|
238 |
+
|
239 |
+
By default this provides ``complete_func``, ``complete_var``,
|
240 |
+
and ``prog_name``.
|
241 |
+
"""
|
242 |
+
return {
|
243 |
+
"complete_func": self.func_name,
|
244 |
+
"complete_var": self.complete_var,
|
245 |
+
"prog_name": self.prog_name,
|
246 |
+
}
|
247 |
+
|
248 |
+
def source(self) -> str:
|
249 |
+
"""Produce the shell script that defines the completion
|
250 |
+
function. By default this ``%``-style formats
|
251 |
+
:attr:`source_template` with the dict returned by
|
252 |
+
:meth:`source_vars`.
|
253 |
+
"""
|
254 |
+
return self.source_template % self.source_vars()
|
255 |
+
|
256 |
+
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
|
257 |
+
"""Use the env vars defined by the shell script to return a
|
258 |
+
tuple of ``args, incomplete``. This must be implemented by
|
259 |
+
subclasses.
|
260 |
+
"""
|
261 |
+
raise NotImplementedError
|
262 |
+
|
263 |
+
def get_completions(
|
264 |
+
self, args: t.List[str], incomplete: str
|
265 |
+
) -> t.List[CompletionItem]:
|
266 |
+
"""Determine the context and last complete command or parameter
|
267 |
+
from the complete args. Call that object's ``shell_complete``
|
268 |
+
method to get the completions for the incomplete value.
|
269 |
+
|
270 |
+
:param args: List of complete args before the incomplete value.
|
271 |
+
:param incomplete: Value being completed. May be empty.
|
272 |
+
"""
|
273 |
+
ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)
|
274 |
+
obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
|
275 |
+
return obj.shell_complete(ctx, incomplete)
|
276 |
+
|
277 |
+
def format_completion(self, item: CompletionItem) -> str:
|
278 |
+
"""Format a completion item into the form recognized by the
|
279 |
+
shell script. This must be implemented by subclasses.
|
280 |
+
|
281 |
+
:param item: Completion item to format.
|
282 |
+
"""
|
283 |
+
raise NotImplementedError
|
284 |
+
|
285 |
+
def complete(self) -> str:
|
286 |
+
"""Produce the completion data to send back to the shell.
|
287 |
+
|
288 |
+
By default this calls :meth:`get_completion_args`, gets the
|
289 |
+
completions, then calls :meth:`format_completion` for each
|
290 |
+
completion.
|
291 |
+
"""
|
292 |
+
args, incomplete = self.get_completion_args()
|
293 |
+
completions = self.get_completions(args, incomplete)
|
294 |
+
out = [self.format_completion(item) for item in completions]
|
295 |
+
return "\n".join(out)
|
296 |
+
|
297 |
+
|
298 |
+
class BashComplete(ShellComplete):
|
299 |
+
"""Shell completion for Bash."""
|
300 |
+
|
301 |
+
name = "bash"
|
302 |
+
source_template = _SOURCE_BASH
|
303 |
+
|
304 |
+
@staticmethod
|
305 |
+
def _check_version() -> None:
|
306 |
+
import subprocess
|
307 |
+
|
308 |
+
output = subprocess.run(
|
309 |
+
["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE
|
310 |
+
)
|
311 |
+
match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
|
312 |
+
|
313 |
+
if match is not None:
|
314 |
+
major, minor = match.groups()
|
315 |
+
|
316 |
+
if major < "4" or major == "4" and minor < "4":
|
317 |
+
echo(
|
318 |
+
_(
|
319 |
+
"Shell completion is not supported for Bash"
|
320 |
+
" versions older than 4.4."
|
321 |
+
),
|
322 |
+
err=True,
|
323 |
+
)
|
324 |
+
else:
|
325 |
+
echo(
|
326 |
+
_("Couldn't detect Bash version, shell completion is not supported."),
|
327 |
+
err=True,
|
328 |
+
)
|
329 |
+
|
330 |
+
def source(self) -> str:
|
331 |
+
self._check_version()
|
332 |
+
return super().source()
|
333 |
+
|
334 |
+
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
|
335 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
336 |
+
cword = int(os.environ["COMP_CWORD"])
|
337 |
+
args = cwords[1:cword]
|
338 |
+
|
339 |
+
try:
|
340 |
+
incomplete = cwords[cword]
|
341 |
+
except IndexError:
|
342 |
+
incomplete = ""
|
343 |
+
|
344 |
+
return args, incomplete
|
345 |
+
|
346 |
+
def format_completion(self, item: CompletionItem) -> str:
|
347 |
+
return f"{item.type},{item.value}"
|
348 |
+
|
349 |
+
|
350 |
+
class ZshComplete(ShellComplete):
|
351 |
+
"""Shell completion for Zsh."""
|
352 |
+
|
353 |
+
name = "zsh"
|
354 |
+
source_template = _SOURCE_ZSH
|
355 |
+
|
356 |
+
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
|
357 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
358 |
+
cword = int(os.environ["COMP_CWORD"])
|
359 |
+
args = cwords[1:cword]
|
360 |
+
|
361 |
+
try:
|
362 |
+
incomplete = cwords[cword]
|
363 |
+
except IndexError:
|
364 |
+
incomplete = ""
|
365 |
+
|
366 |
+
return args, incomplete
|
367 |
+
|
368 |
+
def format_completion(self, item: CompletionItem) -> str:
|
369 |
+
return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"
|
370 |
+
|
371 |
+
|
372 |
+
class FishComplete(ShellComplete):
|
373 |
+
"""Shell completion for Fish."""
|
374 |
+
|
375 |
+
name = "fish"
|
376 |
+
source_template = _SOURCE_FISH
|
377 |
+
|
378 |
+
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
|
379 |
+
cwords = split_arg_string(os.environ["COMP_WORDS"])
|
380 |
+
incomplete = os.environ["COMP_CWORD"]
|
381 |
+
args = cwords[1:]
|
382 |
+
|
383 |
+
# Fish stores the partial word in both COMP_WORDS and
|
384 |
+
# COMP_CWORD, remove it from complete args.
|
385 |
+
if incomplete and args and args[-1] == incomplete:
|
386 |
+
args.pop()
|
387 |
+
|
388 |
+
return args, incomplete
|
389 |
+
|
390 |
+
def format_completion(self, item: CompletionItem) -> str:
|
391 |
+
if item.help:
|
392 |
+
return f"{item.type},{item.value}\t{item.help}"
|
393 |
+
|
394 |
+
return f"{item.type},{item.value}"
|
395 |
+
|
396 |
+
|
397 |
+
ShellCompleteType = t.TypeVar("ShellCompleteType", bound=t.Type[ShellComplete])
|
398 |
+
|
399 |
+
|
400 |
+
_available_shells: t.Dict[str, t.Type[ShellComplete]] = {
|
401 |
+
"bash": BashComplete,
|
402 |
+
"fish": FishComplete,
|
403 |
+
"zsh": ZshComplete,
|
404 |
+
}
|
405 |
+
|
406 |
+
|
407 |
+
def add_completion_class(
|
408 |
+
cls: ShellCompleteType, name: t.Optional[str] = None
|
409 |
+
) -> ShellCompleteType:
|
410 |
+
"""Register a :class:`ShellComplete` subclass under the given name.
|
411 |
+
The name will be provided by the completion instruction environment
|
412 |
+
variable during completion.
|
413 |
+
|
414 |
+
:param cls: The completion class that will handle completion for the
|
415 |
+
shell.
|
416 |
+
:param name: Name to register the class under. Defaults to the
|
417 |
+
class's ``name`` attribute.
|
418 |
+
"""
|
419 |
+
if name is None:
|
420 |
+
name = cls.name
|
421 |
+
|
422 |
+
_available_shells[name] = cls
|
423 |
+
|
424 |
+
return cls
|
425 |
+
|
426 |
+
|
427 |
+
def get_completion_class(shell: str) -> t.Optional[t.Type[ShellComplete]]:
|
428 |
+
"""Look up a registered :class:`ShellComplete` subclass by the name
|
429 |
+
provided by the completion instruction environment variable. If the
|
430 |
+
name isn't registered, returns ``None``.
|
431 |
+
|
432 |
+
:param shell: Name the class is registered under.
|
433 |
+
"""
|
434 |
+
return _available_shells.get(shell)
|
435 |
+
|
436 |
+
|
437 |
+
def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:
|
438 |
+
"""Determine if the given parameter is an argument that can still
|
439 |
+
accept values.
|
440 |
+
|
441 |
+
:param ctx: Invocation context for the command represented by the
|
442 |
+
parsed complete args.
|
443 |
+
:param param: Argument object being checked.
|
444 |
+
"""
|
445 |
+
if not isinstance(param, Argument):
|
446 |
+
return False
|
447 |
+
|
448 |
+
assert param.name is not None
|
449 |
+
# Will be None if expose_value is False.
|
450 |
+
value = ctx.params.get(param.name)
|
451 |
+
return (
|
452 |
+
param.nargs == -1
|
453 |
+
or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE
|
454 |
+
or (
|
455 |
+
param.nargs > 1
|
456 |
+
and isinstance(value, (tuple, list))
|
457 |
+
and len(value) < param.nargs
|
458 |
+
)
|
459 |
+
)
|
460 |
+
|
461 |
+
|
462 |
+
def _start_of_option(ctx: Context, value: str) -> bool:
|
463 |
+
"""Check if the value looks like the start of an option."""
|
464 |
+
if not value:
|
465 |
+
return False
|
466 |
+
|
467 |
+
c = value[0]
|
468 |
+
return c in ctx._opt_prefixes
|
469 |
+
|
470 |
+
|
471 |
+
def _is_incomplete_option(ctx: Context, args: t.List[str], param: Parameter) -> bool:
|
472 |
+
"""Determine if the given parameter is an option that needs a value.
|
473 |
+
|
474 |
+
:param args: List of complete args before the incomplete value.
|
475 |
+
:param param: Option object being checked.
|
476 |
+
"""
|
477 |
+
if not isinstance(param, Option):
|
478 |
+
return False
|
479 |
+
|
480 |
+
if param.is_flag or param.count:
|
481 |
+
return False
|
482 |
+
|
483 |
+
last_option = None
|
484 |
+
|
485 |
+
for index, arg in enumerate(reversed(args)):
|
486 |
+
if index + 1 > param.nargs:
|
487 |
+
break
|
488 |
+
|
489 |
+
if _start_of_option(ctx, arg):
|
490 |
+
last_option = arg
|
491 |
+
|
492 |
+
return last_option is not None and last_option in param.opts
|
493 |
+
|
494 |
+
|
495 |
+
def _resolve_context(
|
496 |
+
cli: BaseCommand,
|
497 |
+
ctx_args: t.MutableMapping[str, t.Any],
|
498 |
+
prog_name: str,
|
499 |
+
args: t.List[str],
|
500 |
+
) -> Context:
|
501 |
+
"""Produce the context hierarchy starting with the command and
|
502 |
+
traversing the complete arguments. This only follows the commands,
|
503 |
+
it doesn't trigger input prompts or callbacks.
|
504 |
+
|
505 |
+
:param cli: Command being called.
|
506 |
+
:param prog_name: Name of the executable in the shell.
|
507 |
+
:param args: List of complete args before the incomplete value.
|
508 |
+
"""
|
509 |
+
ctx_args["resilient_parsing"] = True
|
510 |
+
ctx = cli.make_context(prog_name, args.copy(), **ctx_args)
|
511 |
+
args = ctx.protected_args + ctx.args
|
512 |
+
|
513 |
+
while args:
|
514 |
+
command = ctx.command
|
515 |
+
|
516 |
+
if isinstance(command, MultiCommand):
|
517 |
+
if not command.chain:
|
518 |
+
name, cmd, args = command.resolve_command(ctx, args)
|
519 |
+
|
520 |
+
if cmd is None:
|
521 |
+
return ctx
|
522 |
+
|
523 |
+
ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)
|
524 |
+
args = ctx.protected_args + ctx.args
|
525 |
+
else:
|
526 |
+
sub_ctx = ctx
|
527 |
+
|
528 |
+
while args:
|
529 |
+
name, cmd, args = command.resolve_command(ctx, args)
|
530 |
+
|
531 |
+
if cmd is None:
|
532 |
+
return ctx
|
533 |
+
|
534 |
+
sub_ctx = cmd.make_context(
|
535 |
+
name,
|
536 |
+
args,
|
537 |
+
parent=ctx,
|
538 |
+
allow_extra_args=True,
|
539 |
+
allow_interspersed_args=False,
|
540 |
+
resilient_parsing=True,
|
541 |
+
)
|
542 |
+
args = sub_ctx.args
|
543 |
+
|
544 |
+
ctx = sub_ctx
|
545 |
+
args = [*sub_ctx.protected_args, *sub_ctx.args]
|
546 |
+
else:
|
547 |
+
break
|
548 |
+
|
549 |
+
return ctx
|
550 |
+
|
551 |
+
|
552 |
+
def _resolve_incomplete(
|
553 |
+
ctx: Context, args: t.List[str], incomplete: str
|
554 |
+
) -> t.Tuple[t.Union[BaseCommand, Parameter], str]:
|
555 |
+
"""Find the Click object that will handle the completion of the
|
556 |
+
incomplete value. Return the object and the incomplete value.
|
557 |
+
|
558 |
+
:param ctx: Invocation context for the command represented by
|
559 |
+
the parsed complete args.
|
560 |
+
:param args: List of complete args before the incomplete value.
|
561 |
+
:param incomplete: Value being completed. May be empty.
|
562 |
+
"""
|
563 |
+
# Different shells treat an "=" between a long option name and
|
564 |
+
# value differently. Might keep the value joined, return the "="
|
565 |
+
# as a separate item, or return the split name and value. Always
|
566 |
+
# split and discard the "=" to make completion easier.
|
567 |
+
if incomplete == "=":
|
568 |
+
incomplete = ""
|
569 |
+
elif "=" in incomplete and _start_of_option(ctx, incomplete):
|
570 |
+
name, _, incomplete = incomplete.partition("=")
|
571 |
+
args.append(name)
|
572 |
+
|
573 |
+
# The "--" marker tells Click to stop treating values as options
|
574 |
+
# even if they start with the option character. If it hasn't been
|
575 |
+
# given and the incomplete arg looks like an option, the current
|
576 |
+
# command will provide option name completions.
|
577 |
+
if "--" not in args and _start_of_option(ctx, incomplete):
|
578 |
+
return ctx.command, incomplete
|
579 |
+
|
580 |
+
params = ctx.command.get_params(ctx)
|
581 |
+
|
582 |
+
# If the last complete arg is an option name with an incomplete
|
583 |
+
# value, the option will provide value completions.
|
584 |
+
for param in params:
|
585 |
+
if _is_incomplete_option(ctx, args, param):
|
586 |
+
return param, incomplete
|
587 |
+
|
588 |
+
# It's not an option name or value. The first argument without a
|
589 |
+
# parsed value will provide value completions.
|
590 |
+
for param in params:
|
591 |
+
if _is_incomplete_argument(ctx, param):
|
592 |
+
return param, incomplete
|
593 |
+
|
594 |
+
# There were no unparsed arguments, the command may be a group that
|
595 |
+
# will provide command name completions.
|
596 |
+
return ctx.command, incomplete
|
venv/lib/python3.10/site-packages/click/termui.py
ADDED
@@ -0,0 +1,784 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
import io
|
3 |
+
import itertools
|
4 |
+
import sys
|
5 |
+
import typing as t
|
6 |
+
from gettext import gettext as _
|
7 |
+
|
8 |
+
from ._compat import isatty
|
9 |
+
from ._compat import strip_ansi
|
10 |
+
from .exceptions import Abort
|
11 |
+
from .exceptions import UsageError
|
12 |
+
from .globals import resolve_color_default
|
13 |
+
from .types import Choice
|
14 |
+
from .types import convert_type
|
15 |
+
from .types import ParamType
|
16 |
+
from .utils import echo
|
17 |
+
from .utils import LazyFile
|
18 |
+
|
19 |
+
if t.TYPE_CHECKING:
|
20 |
+
from ._termui_impl import ProgressBar
|
21 |
+
|
22 |
+
V = t.TypeVar("V")
|
23 |
+
|
24 |
+
# The prompt functions to use. The doc tools currently override these
|
25 |
+
# functions to customize how they work.
|
26 |
+
visible_prompt_func: t.Callable[[str], str] = input
|
27 |
+
|
28 |
+
_ansi_colors = {
|
29 |
+
"black": 30,
|
30 |
+
"red": 31,
|
31 |
+
"green": 32,
|
32 |
+
"yellow": 33,
|
33 |
+
"blue": 34,
|
34 |
+
"magenta": 35,
|
35 |
+
"cyan": 36,
|
36 |
+
"white": 37,
|
37 |
+
"reset": 39,
|
38 |
+
"bright_black": 90,
|
39 |
+
"bright_red": 91,
|
40 |
+
"bright_green": 92,
|
41 |
+
"bright_yellow": 93,
|
42 |
+
"bright_blue": 94,
|
43 |
+
"bright_magenta": 95,
|
44 |
+
"bright_cyan": 96,
|
45 |
+
"bright_white": 97,
|
46 |
+
}
|
47 |
+
_ansi_reset_all = "\033[0m"
|
48 |
+
|
49 |
+
|
50 |
+
def hidden_prompt_func(prompt: str) -> str:
|
51 |
+
import getpass
|
52 |
+
|
53 |
+
return getpass.getpass(prompt)
|
54 |
+
|
55 |
+
|
56 |
+
def _build_prompt(
|
57 |
+
text: str,
|
58 |
+
suffix: str,
|
59 |
+
show_default: bool = False,
|
60 |
+
default: t.Optional[t.Any] = None,
|
61 |
+
show_choices: bool = True,
|
62 |
+
type: t.Optional[ParamType] = None,
|
63 |
+
) -> str:
|
64 |
+
prompt = text
|
65 |
+
if type is not None and show_choices and isinstance(type, Choice):
|
66 |
+
prompt += f" ({', '.join(map(str, type.choices))})"
|
67 |
+
if default is not None and show_default:
|
68 |
+
prompt = f"{prompt} [{_format_default(default)}]"
|
69 |
+
return f"{prompt}{suffix}"
|
70 |
+
|
71 |
+
|
72 |
+
def _format_default(default: t.Any) -> t.Any:
|
73 |
+
if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
|
74 |
+
return default.name
|
75 |
+
|
76 |
+
return default
|
77 |
+
|
78 |
+
|
79 |
+
def prompt(
|
80 |
+
text: str,
|
81 |
+
default: t.Optional[t.Any] = None,
|
82 |
+
hide_input: bool = False,
|
83 |
+
confirmation_prompt: t.Union[bool, str] = False,
|
84 |
+
type: t.Optional[t.Union[ParamType, t.Any]] = None,
|
85 |
+
value_proc: t.Optional[t.Callable[[str], t.Any]] = None,
|
86 |
+
prompt_suffix: str = ": ",
|
87 |
+
show_default: bool = True,
|
88 |
+
err: bool = False,
|
89 |
+
show_choices: bool = True,
|
90 |
+
) -> t.Any:
|
91 |
+
"""Prompts a user for input. This is a convenience function that can
|
92 |
+
be used to prompt a user for input later.
|
93 |
+
|
94 |
+
If the user aborts the input by sending an interrupt signal, this
|
95 |
+
function will catch it and raise a :exc:`Abort` exception.
|
96 |
+
|
97 |
+
:param text: the text to show for the prompt.
|
98 |
+
:param default: the default value to use if no input happens. If this
|
99 |
+
is not given it will prompt until it's aborted.
|
100 |
+
:param hide_input: if this is set to true then the input value will
|
101 |
+
be hidden.
|
102 |
+
:param confirmation_prompt: Prompt a second time to confirm the
|
103 |
+
value. Can be set to a string instead of ``True`` to customize
|
104 |
+
the message.
|
105 |
+
:param type: the type to use to check the value against.
|
106 |
+
:param value_proc: if this parameter is provided it's a function that
|
107 |
+
is invoked instead of the type conversion to
|
108 |
+
convert a value.
|
109 |
+
:param prompt_suffix: a suffix that should be added to the prompt.
|
110 |
+
:param show_default: shows or hides the default value in the prompt.
|
111 |
+
:param err: if set to true the file defaults to ``stderr`` instead of
|
112 |
+
``stdout``, the same as with echo.
|
113 |
+
:param show_choices: Show or hide choices if the passed type is a Choice.
|
114 |
+
For example if type is a Choice of either day or week,
|
115 |
+
show_choices is true and text is "Group by" then the
|
116 |
+
prompt will be "Group by (day, week): ".
|
117 |
+
|
118 |
+
.. versionadded:: 8.0
|
119 |
+
``confirmation_prompt`` can be a custom string.
|
120 |
+
|
121 |
+
.. versionadded:: 7.0
|
122 |
+
Added the ``show_choices`` parameter.
|
123 |
+
|
124 |
+
.. versionadded:: 6.0
|
125 |
+
Added unicode support for cmd.exe on Windows.
|
126 |
+
|
127 |
+
.. versionadded:: 4.0
|
128 |
+
Added the `err` parameter.
|
129 |
+
|
130 |
+
"""
|
131 |
+
|
132 |
+
def prompt_func(text: str) -> str:
|
133 |
+
f = hidden_prompt_func if hide_input else visible_prompt_func
|
134 |
+
try:
|
135 |
+
# Write the prompt separately so that we get nice
|
136 |
+
# coloring through colorama on Windows
|
137 |
+
echo(text.rstrip(" "), nl=False, err=err)
|
138 |
+
# Echo a space to stdout to work around an issue where
|
139 |
+
# readline causes backspace to clear the whole line.
|
140 |
+
return f(" ")
|
141 |
+
except (KeyboardInterrupt, EOFError):
|
142 |
+
# getpass doesn't print a newline if the user aborts input with ^C.
|
143 |
+
# Allegedly this behavior is inherited from getpass(3).
|
144 |
+
# A doc bug has been filed at https://bugs.python.org/issue24711
|
145 |
+
if hide_input:
|
146 |
+
echo(None, err=err)
|
147 |
+
raise Abort() from None
|
148 |
+
|
149 |
+
if value_proc is None:
|
150 |
+
value_proc = convert_type(type, default)
|
151 |
+
|
152 |
+
prompt = _build_prompt(
|
153 |
+
text, prompt_suffix, show_default, default, show_choices, type
|
154 |
+
)
|
155 |
+
|
156 |
+
if confirmation_prompt:
|
157 |
+
if confirmation_prompt is True:
|
158 |
+
confirmation_prompt = _("Repeat for confirmation")
|
159 |
+
|
160 |
+
confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
|
161 |
+
|
162 |
+
while True:
|
163 |
+
while True:
|
164 |
+
value = prompt_func(prompt)
|
165 |
+
if value:
|
166 |
+
break
|
167 |
+
elif default is not None:
|
168 |
+
value = default
|
169 |
+
break
|
170 |
+
try:
|
171 |
+
result = value_proc(value)
|
172 |
+
except UsageError as e:
|
173 |
+
if hide_input:
|
174 |
+
echo(_("Error: The value you entered was invalid."), err=err)
|
175 |
+
else:
|
176 |
+
echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306
|
177 |
+
continue
|
178 |
+
if not confirmation_prompt:
|
179 |
+
return result
|
180 |
+
while True:
|
181 |
+
value2 = prompt_func(confirmation_prompt)
|
182 |
+
is_empty = not value and not value2
|
183 |
+
if value2 or is_empty:
|
184 |
+
break
|
185 |
+
if value == value2:
|
186 |
+
return result
|
187 |
+
echo(_("Error: The two entered values do not match."), err=err)
|
188 |
+
|
189 |
+
|
190 |
+
def confirm(
|
191 |
+
text: str,
|
192 |
+
default: t.Optional[bool] = False,
|
193 |
+
abort: bool = False,
|
194 |
+
prompt_suffix: str = ": ",
|
195 |
+
show_default: bool = True,
|
196 |
+
err: bool = False,
|
197 |
+
) -> bool:
|
198 |
+
"""Prompts for confirmation (yes/no question).
|
199 |
+
|
200 |
+
If the user aborts the input by sending a interrupt signal this
|
201 |
+
function will catch it and raise a :exc:`Abort` exception.
|
202 |
+
|
203 |
+
:param text: the question to ask.
|
204 |
+
:param default: The default value to use when no input is given. If
|
205 |
+
``None``, repeat until input is given.
|
206 |
+
:param abort: if this is set to `True` a negative answer aborts the
|
207 |
+
exception by raising :exc:`Abort`.
|
208 |
+
:param prompt_suffix: a suffix that should be added to the prompt.
|
209 |
+
:param show_default: shows or hides the default value in the prompt.
|
210 |
+
:param err: if set to true the file defaults to ``stderr`` instead of
|
211 |
+
``stdout``, the same as with echo.
|
212 |
+
|
213 |
+
.. versionchanged:: 8.0
|
214 |
+
Repeat until input is given if ``default`` is ``None``.
|
215 |
+
|
216 |
+
.. versionadded:: 4.0
|
217 |
+
Added the ``err`` parameter.
|
218 |
+
"""
|
219 |
+
prompt = _build_prompt(
|
220 |
+
text,
|
221 |
+
prompt_suffix,
|
222 |
+
show_default,
|
223 |
+
"y/n" if default is None else ("Y/n" if default else "y/N"),
|
224 |
+
)
|
225 |
+
|
226 |
+
while True:
|
227 |
+
try:
|
228 |
+
# Write the prompt separately so that we get nice
|
229 |
+
# coloring through colorama on Windows
|
230 |
+
echo(prompt.rstrip(" "), nl=False, err=err)
|
231 |
+
# Echo a space to stdout to work around an issue where
|
232 |
+
# readline causes backspace to clear the whole line.
|
233 |
+
value = visible_prompt_func(" ").lower().strip()
|
234 |
+
except (KeyboardInterrupt, EOFError):
|
235 |
+
raise Abort() from None
|
236 |
+
if value in ("y", "yes"):
|
237 |
+
rv = True
|
238 |
+
elif value in ("n", "no"):
|
239 |
+
rv = False
|
240 |
+
elif default is not None and value == "":
|
241 |
+
rv = default
|
242 |
+
else:
|
243 |
+
echo(_("Error: invalid input"), err=err)
|
244 |
+
continue
|
245 |
+
break
|
246 |
+
if abort and not rv:
|
247 |
+
raise Abort()
|
248 |
+
return rv
|
249 |
+
|
250 |
+
|
251 |
+
def echo_via_pager(
|
252 |
+
text_or_generator: t.Union[t.Iterable[str], t.Callable[[], t.Iterable[str]], str],
|
253 |
+
color: t.Optional[bool] = None,
|
254 |
+
) -> None:
|
255 |
+
"""This function takes a text and shows it via an environment specific
|
256 |
+
pager on stdout.
|
257 |
+
|
258 |
+
.. versionchanged:: 3.0
|
259 |
+
Added the `color` flag.
|
260 |
+
|
261 |
+
:param text_or_generator: the text to page, or alternatively, a
|
262 |
+
generator emitting the text to page.
|
263 |
+
:param color: controls if the pager supports ANSI colors or not. The
|
264 |
+
default is autodetection.
|
265 |
+
"""
|
266 |
+
color = resolve_color_default(color)
|
267 |
+
|
268 |
+
if inspect.isgeneratorfunction(text_or_generator):
|
269 |
+
i = t.cast(t.Callable[[], t.Iterable[str]], text_or_generator)()
|
270 |
+
elif isinstance(text_or_generator, str):
|
271 |
+
i = [text_or_generator]
|
272 |
+
else:
|
273 |
+
i = iter(t.cast(t.Iterable[str], text_or_generator))
|
274 |
+
|
275 |
+
# convert every element of i to a text type if necessary
|
276 |
+
text_generator = (el if isinstance(el, str) else str(el) for el in i)
|
277 |
+
|
278 |
+
from ._termui_impl import pager
|
279 |
+
|
280 |
+
return pager(itertools.chain(text_generator, "\n"), color)
|
281 |
+
|
282 |
+
|
283 |
+
def progressbar(
|
284 |
+
iterable: t.Optional[t.Iterable[V]] = None,
|
285 |
+
length: t.Optional[int] = None,
|
286 |
+
label: t.Optional[str] = None,
|
287 |
+
show_eta: bool = True,
|
288 |
+
show_percent: t.Optional[bool] = None,
|
289 |
+
show_pos: bool = False,
|
290 |
+
item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,
|
291 |
+
fill_char: str = "#",
|
292 |
+
empty_char: str = "-",
|
293 |
+
bar_template: str = "%(label)s [%(bar)s] %(info)s",
|
294 |
+
info_sep: str = " ",
|
295 |
+
width: int = 36,
|
296 |
+
file: t.Optional[t.TextIO] = None,
|
297 |
+
color: t.Optional[bool] = None,
|
298 |
+
update_min_steps: int = 1,
|
299 |
+
) -> "ProgressBar[V]":
|
300 |
+
"""This function creates an iterable context manager that can be used
|
301 |
+
to iterate over something while showing a progress bar. It will
|
302 |
+
either iterate over the `iterable` or `length` items (that are counted
|
303 |
+
up). While iteration happens, this function will print a rendered
|
304 |
+
progress bar to the given `file` (defaults to stdout) and will attempt
|
305 |
+
to calculate remaining time and more. By default, this progress bar
|
306 |
+
will not be rendered if the file is not a terminal.
|
307 |
+
|
308 |
+
The context manager creates the progress bar. When the context
|
309 |
+
manager is entered the progress bar is already created. With every
|
310 |
+
iteration over the progress bar, the iterable passed to the bar is
|
311 |
+
advanced and the bar is updated. When the context manager exits,
|
312 |
+
a newline is printed and the progress bar is finalized on screen.
|
313 |
+
|
314 |
+
Note: The progress bar is currently designed for use cases where the
|
315 |
+
total progress can be expected to take at least several seconds.
|
316 |
+
Because of this, the ProgressBar class object won't display
|
317 |
+
progress that is considered too fast, and progress where the time
|
318 |
+
between steps is less than a second.
|
319 |
+
|
320 |
+
No printing must happen or the progress bar will be unintentionally
|
321 |
+
destroyed.
|
322 |
+
|
323 |
+
Example usage::
|
324 |
+
|
325 |
+
with progressbar(items) as bar:
|
326 |
+
for item in bar:
|
327 |
+
do_something_with(item)
|
328 |
+
|
329 |
+
Alternatively, if no iterable is specified, one can manually update the
|
330 |
+
progress bar through the `update()` method instead of directly
|
331 |
+
iterating over the progress bar. The update method accepts the number
|
332 |
+
of steps to increment the bar with::
|
333 |
+
|
334 |
+
with progressbar(length=chunks.total_bytes) as bar:
|
335 |
+
for chunk in chunks:
|
336 |
+
process_chunk(chunk)
|
337 |
+
bar.update(chunks.bytes)
|
338 |
+
|
339 |
+
The ``update()`` method also takes an optional value specifying the
|
340 |
+
``current_item`` at the new position. This is useful when used
|
341 |
+
together with ``item_show_func`` to customize the output for each
|
342 |
+
manual step::
|
343 |
+
|
344 |
+
with click.progressbar(
|
345 |
+
length=total_size,
|
346 |
+
label='Unzipping archive',
|
347 |
+
item_show_func=lambda a: a.filename
|
348 |
+
) as bar:
|
349 |
+
for archive in zip_file:
|
350 |
+
archive.extract()
|
351 |
+
bar.update(archive.size, archive)
|
352 |
+
|
353 |
+
:param iterable: an iterable to iterate over. If not provided the length
|
354 |
+
is required.
|
355 |
+
:param length: the number of items to iterate over. By default the
|
356 |
+
progressbar will attempt to ask the iterator about its
|
357 |
+
length, which might or might not work. If an iterable is
|
358 |
+
also provided this parameter can be used to override the
|
359 |
+
length. If an iterable is not provided the progress bar
|
360 |
+
will iterate over a range of that length.
|
361 |
+
:param label: the label to show next to the progress bar.
|
362 |
+
:param show_eta: enables or disables the estimated time display. This is
|
363 |
+
automatically disabled if the length cannot be
|
364 |
+
determined.
|
365 |
+
:param show_percent: enables or disables the percentage display. The
|
366 |
+
default is `True` if the iterable has a length or
|
367 |
+
`False` if not.
|
368 |
+
:param show_pos: enables or disables the absolute position display. The
|
369 |
+
default is `False`.
|
370 |
+
:param item_show_func: A function called with the current item which
|
371 |
+
can return a string to show next to the progress bar. If the
|
372 |
+
function returns ``None`` nothing is shown. The current item can
|
373 |
+
be ``None``, such as when entering and exiting the bar.
|
374 |
+
:param fill_char: the character to use to show the filled part of the
|
375 |
+
progress bar.
|
376 |
+
:param empty_char: the character to use to show the non-filled part of
|
377 |
+
the progress bar.
|
378 |
+
:param bar_template: the format string to use as template for the bar.
|
379 |
+
The parameters in it are ``label`` for the label,
|
380 |
+
``bar`` for the progress bar and ``info`` for the
|
381 |
+
info section.
|
382 |
+
:param info_sep: the separator between multiple info items (eta etc.)
|
383 |
+
:param width: the width of the progress bar in characters, 0 means full
|
384 |
+
terminal width
|
385 |
+
:param file: The file to write to. If this is not a terminal then
|
386 |
+
only the label is printed.
|
387 |
+
:param color: controls if the terminal supports ANSI colors or not. The
|
388 |
+
default is autodetection. This is only needed if ANSI
|
389 |
+
codes are included anywhere in the progress bar output
|
390 |
+
which is not the case by default.
|
391 |
+
:param update_min_steps: Render only when this many updates have
|
392 |
+
completed. This allows tuning for very fast iterators.
|
393 |
+
|
394 |
+
.. versionchanged:: 8.0
|
395 |
+
Output is shown even if execution time is less than 0.5 seconds.
|
396 |
+
|
397 |
+
.. versionchanged:: 8.0
|
398 |
+
``item_show_func`` shows the current item, not the previous one.
|
399 |
+
|
400 |
+
.. versionchanged:: 8.0
|
401 |
+
Labels are echoed if the output is not a TTY. Reverts a change
|
402 |
+
in 7.0 that removed all output.
|
403 |
+
|
404 |
+
.. versionadded:: 8.0
|
405 |
+
Added the ``update_min_steps`` parameter.
|
406 |
+
|
407 |
+
.. versionchanged:: 4.0
|
408 |
+
Added the ``color`` parameter. Added the ``update`` method to
|
409 |
+
the object.
|
410 |
+
|
411 |
+
.. versionadded:: 2.0
|
412 |
+
"""
|
413 |
+
from ._termui_impl import ProgressBar
|
414 |
+
|
415 |
+
color = resolve_color_default(color)
|
416 |
+
return ProgressBar(
|
417 |
+
iterable=iterable,
|
418 |
+
length=length,
|
419 |
+
show_eta=show_eta,
|
420 |
+
show_percent=show_percent,
|
421 |
+
show_pos=show_pos,
|
422 |
+
item_show_func=item_show_func,
|
423 |
+
fill_char=fill_char,
|
424 |
+
empty_char=empty_char,
|
425 |
+
bar_template=bar_template,
|
426 |
+
info_sep=info_sep,
|
427 |
+
file=file,
|
428 |
+
label=label,
|
429 |
+
width=width,
|
430 |
+
color=color,
|
431 |
+
update_min_steps=update_min_steps,
|
432 |
+
)
|
433 |
+
|
434 |
+
|
435 |
+
def clear() -> None:
|
436 |
+
"""Clears the terminal screen. This will have the effect of clearing
|
437 |
+
the whole visible space of the terminal and moving the cursor to the
|
438 |
+
top left. This does not do anything if not connected to a terminal.
|
439 |
+
|
440 |
+
.. versionadded:: 2.0
|
441 |
+
"""
|
442 |
+
if not isatty(sys.stdout):
|
443 |
+
return
|
444 |
+
|
445 |
+
# ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
|
446 |
+
echo("\033[2J\033[1;1H", nl=False)
|
447 |
+
|
448 |
+
|
449 |
+
def _interpret_color(
|
450 |
+
color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0
|
451 |
+
) -> str:
|
452 |
+
if isinstance(color, int):
|
453 |
+
return f"{38 + offset};5;{color:d}"
|
454 |
+
|
455 |
+
if isinstance(color, (tuple, list)):
|
456 |
+
r, g, b = color
|
457 |
+
return f"{38 + offset};2;{r:d};{g:d};{b:d}"
|
458 |
+
|
459 |
+
return str(_ansi_colors[color] + offset)
|
460 |
+
|
461 |
+
|
462 |
+
def style(
|
463 |
+
text: t.Any,
|
464 |
+
fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,
|
465 |
+
bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,
|
466 |
+
bold: t.Optional[bool] = None,
|
467 |
+
dim: t.Optional[bool] = None,
|
468 |
+
underline: t.Optional[bool] = None,
|
469 |
+
overline: t.Optional[bool] = None,
|
470 |
+
italic: t.Optional[bool] = None,
|
471 |
+
blink: t.Optional[bool] = None,
|
472 |
+
reverse: t.Optional[bool] = None,
|
473 |
+
strikethrough: t.Optional[bool] = None,
|
474 |
+
reset: bool = True,
|
475 |
+
) -> str:
|
476 |
+
"""Styles a text with ANSI styles and returns the new string. By
|
477 |
+
default the styling is self contained which means that at the end
|
478 |
+
of the string a reset code is issued. This can be prevented by
|
479 |
+
passing ``reset=False``.
|
480 |
+
|
481 |
+
Examples::
|
482 |
+
|
483 |
+
click.echo(click.style('Hello World!', fg='green'))
|
484 |
+
click.echo(click.style('ATTENTION!', blink=True))
|
485 |
+
click.echo(click.style('Some things', reverse=True, fg='cyan'))
|
486 |
+
click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
|
487 |
+
|
488 |
+
Supported color names:
|
489 |
+
|
490 |
+
* ``black`` (might be a gray)
|
491 |
+
* ``red``
|
492 |
+
* ``green``
|
493 |
+
* ``yellow`` (might be an orange)
|
494 |
+
* ``blue``
|
495 |
+
* ``magenta``
|
496 |
+
* ``cyan``
|
497 |
+
* ``white`` (might be light gray)
|
498 |
+
* ``bright_black``
|
499 |
+
* ``bright_red``
|
500 |
+
* ``bright_green``
|
501 |
+
* ``bright_yellow``
|
502 |
+
* ``bright_blue``
|
503 |
+
* ``bright_magenta``
|
504 |
+
* ``bright_cyan``
|
505 |
+
* ``bright_white``
|
506 |
+
* ``reset`` (reset the color code only)
|
507 |
+
|
508 |
+
If the terminal supports it, color may also be specified as:
|
509 |
+
|
510 |
+
- An integer in the interval [0, 255]. The terminal must support
|
511 |
+
8-bit/256-color mode.
|
512 |
+
- An RGB tuple of three integers in [0, 255]. The terminal must
|
513 |
+
support 24-bit/true-color mode.
|
514 |
+
|
515 |
+
See https://en.wikipedia.org/wiki/ANSI_color and
|
516 |
+
https://gist.github.com/XVilka/8346728 for more information.
|
517 |
+
|
518 |
+
:param text: the string to style with ansi codes.
|
519 |
+
:param fg: if provided this will become the foreground color.
|
520 |
+
:param bg: if provided this will become the background color.
|
521 |
+
:param bold: if provided this will enable or disable bold mode.
|
522 |
+
:param dim: if provided this will enable or disable dim mode. This is
|
523 |
+
badly supported.
|
524 |
+
:param underline: if provided this will enable or disable underline.
|
525 |
+
:param overline: if provided this will enable or disable overline.
|
526 |
+
:param italic: if provided this will enable or disable italic.
|
527 |
+
:param blink: if provided this will enable or disable blinking.
|
528 |
+
:param reverse: if provided this will enable or disable inverse
|
529 |
+
rendering (foreground becomes background and the
|
530 |
+
other way round).
|
531 |
+
:param strikethrough: if provided this will enable or disable
|
532 |
+
striking through text.
|
533 |
+
:param reset: by default a reset-all code is added at the end of the
|
534 |
+
string which means that styles do not carry over. This
|
535 |
+
can be disabled to compose styles.
|
536 |
+
|
537 |
+
.. versionchanged:: 8.0
|
538 |
+
A non-string ``message`` is converted to a string.
|
539 |
+
|
540 |
+
.. versionchanged:: 8.0
|
541 |
+
Added support for 256 and RGB color codes.
|
542 |
+
|
543 |
+
.. versionchanged:: 8.0
|
544 |
+
Added the ``strikethrough``, ``italic``, and ``overline``
|
545 |
+
parameters.
|
546 |
+
|
547 |
+
.. versionchanged:: 7.0
|
548 |
+
Added support for bright colors.
|
549 |
+
|
550 |
+
.. versionadded:: 2.0
|
551 |
+
"""
|
552 |
+
if not isinstance(text, str):
|
553 |
+
text = str(text)
|
554 |
+
|
555 |
+
bits = []
|
556 |
+
|
557 |
+
if fg:
|
558 |
+
try:
|
559 |
+
bits.append(f"\033[{_interpret_color(fg)}m")
|
560 |
+
except KeyError:
|
561 |
+
raise TypeError(f"Unknown color {fg!r}") from None
|
562 |
+
|
563 |
+
if bg:
|
564 |
+
try:
|
565 |
+
bits.append(f"\033[{_interpret_color(bg, 10)}m")
|
566 |
+
except KeyError:
|
567 |
+
raise TypeError(f"Unknown color {bg!r}") from None
|
568 |
+
|
569 |
+
if bold is not None:
|
570 |
+
bits.append(f"\033[{1 if bold else 22}m")
|
571 |
+
if dim is not None:
|
572 |
+
bits.append(f"\033[{2 if dim else 22}m")
|
573 |
+
if underline is not None:
|
574 |
+
bits.append(f"\033[{4 if underline else 24}m")
|
575 |
+
if overline is not None:
|
576 |
+
bits.append(f"\033[{53 if overline else 55}m")
|
577 |
+
if italic is not None:
|
578 |
+
bits.append(f"\033[{3 if italic else 23}m")
|
579 |
+
if blink is not None:
|
580 |
+
bits.append(f"\033[{5 if blink else 25}m")
|
581 |
+
if reverse is not None:
|
582 |
+
bits.append(f"\033[{7 if reverse else 27}m")
|
583 |
+
if strikethrough is not None:
|
584 |
+
bits.append(f"\033[{9 if strikethrough else 29}m")
|
585 |
+
bits.append(text)
|
586 |
+
if reset:
|
587 |
+
bits.append(_ansi_reset_all)
|
588 |
+
return "".join(bits)
|
589 |
+
|
590 |
+
|
591 |
+
def unstyle(text: str) -> str:
|
592 |
+
"""Removes ANSI styling information from a string. Usually it's not
|
593 |
+
necessary to use this function as Click's echo function will
|
594 |
+
automatically remove styling if necessary.
|
595 |
+
|
596 |
+
.. versionadded:: 2.0
|
597 |
+
|
598 |
+
:param text: the text to remove style information from.
|
599 |
+
"""
|
600 |
+
return strip_ansi(text)
|
601 |
+
|
602 |
+
|
603 |
+
def secho(
|
604 |
+
message: t.Optional[t.Any] = None,
|
605 |
+
file: t.Optional[t.IO[t.AnyStr]] = None,
|
606 |
+
nl: bool = True,
|
607 |
+
err: bool = False,
|
608 |
+
color: t.Optional[bool] = None,
|
609 |
+
**styles: t.Any,
|
610 |
+
) -> None:
|
611 |
+
"""This function combines :func:`echo` and :func:`style` into one
|
612 |
+
call. As such the following two calls are the same::
|
613 |
+
|
614 |
+
click.secho('Hello World!', fg='green')
|
615 |
+
click.echo(click.style('Hello World!', fg='green'))
|
616 |
+
|
617 |
+
All keyword arguments are forwarded to the underlying functions
|
618 |
+
depending on which one they go with.
|
619 |
+
|
620 |
+
Non-string types will be converted to :class:`str`. However,
|
621 |
+
:class:`bytes` are passed directly to :meth:`echo` without applying
|
622 |
+
style. If you want to style bytes that represent text, call
|
623 |
+
:meth:`bytes.decode` first.
|
624 |
+
|
625 |
+
.. versionchanged:: 8.0
|
626 |
+
A non-string ``message`` is converted to a string. Bytes are
|
627 |
+
passed through without style applied.
|
628 |
+
|
629 |
+
.. versionadded:: 2.0
|
630 |
+
"""
|
631 |
+
if message is not None and not isinstance(message, (bytes, bytearray)):
|
632 |
+
message = style(message, **styles)
|
633 |
+
|
634 |
+
return echo(message, file=file, nl=nl, err=err, color=color)
|
635 |
+
|
636 |
+
|
637 |
+
def edit(
|
638 |
+
text: t.Optional[t.AnyStr] = None,
|
639 |
+
editor: t.Optional[str] = None,
|
640 |
+
env: t.Optional[t.Mapping[str, str]] = None,
|
641 |
+
require_save: bool = True,
|
642 |
+
extension: str = ".txt",
|
643 |
+
filename: t.Optional[str] = None,
|
644 |
+
) -> t.Optional[t.AnyStr]:
|
645 |
+
r"""Edits the given text in the defined editor. If an editor is given
|
646 |
+
(should be the full path to the executable but the regular operating
|
647 |
+
system search path is used for finding the executable) it overrides
|
648 |
+
the detected editor. Optionally, some environment variables can be
|
649 |
+
used. If the editor is closed without changes, `None` is returned. In
|
650 |
+
case a file is edited directly the return value is always `None` and
|
651 |
+
`require_save` and `extension` are ignored.
|
652 |
+
|
653 |
+
If the editor cannot be opened a :exc:`UsageError` is raised.
|
654 |
+
|
655 |
+
Note for Windows: to simplify cross-platform usage, the newlines are
|
656 |
+
automatically converted from POSIX to Windows and vice versa. As such,
|
657 |
+
the message here will have ``\n`` as newline markers.
|
658 |
+
|
659 |
+
:param text: the text to edit.
|
660 |
+
:param editor: optionally the editor to use. Defaults to automatic
|
661 |
+
detection.
|
662 |
+
:param env: environment variables to forward to the editor.
|
663 |
+
:param require_save: if this is true, then not saving in the editor
|
664 |
+
will make the return value become `None`.
|
665 |
+
:param extension: the extension to tell the editor about. This defaults
|
666 |
+
to `.txt` but changing this might change syntax
|
667 |
+
highlighting.
|
668 |
+
:param filename: if provided it will edit this file instead of the
|
669 |
+
provided text contents. It will not use a temporary
|
670 |
+
file as an indirection in that case.
|
671 |
+
"""
|
672 |
+
from ._termui_impl import Editor
|
673 |
+
|
674 |
+
ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
|
675 |
+
|
676 |
+
if filename is None:
|
677 |
+
return ed.edit(text)
|
678 |
+
|
679 |
+
ed.edit_file(filename)
|
680 |
+
return None
|
681 |
+
|
682 |
+
|
683 |
+
def launch(url: str, wait: bool = False, locate: bool = False) -> int:
|
684 |
+
"""This function launches the given URL (or filename) in the default
|
685 |
+
viewer application for this file type. If this is an executable, it
|
686 |
+
might launch the executable in a new session. The return value is
|
687 |
+
the exit code of the launched application. Usually, ``0`` indicates
|
688 |
+
success.
|
689 |
+
|
690 |
+
Examples::
|
691 |
+
|
692 |
+
click.launch('https://click.palletsprojects.com/')
|
693 |
+
click.launch('/my/downloaded/file', locate=True)
|
694 |
+
|
695 |
+
.. versionadded:: 2.0
|
696 |
+
|
697 |
+
:param url: URL or filename of the thing to launch.
|
698 |
+
:param wait: Wait for the program to exit before returning. This
|
699 |
+
only works if the launched program blocks. In particular,
|
700 |
+
``xdg-open`` on Linux does not block.
|
701 |
+
:param locate: if this is set to `True` then instead of launching the
|
702 |
+
application associated with the URL it will attempt to
|
703 |
+
launch a file manager with the file located. This
|
704 |
+
might have weird effects if the URL does not point to
|
705 |
+
the filesystem.
|
706 |
+
"""
|
707 |
+
from ._termui_impl import open_url
|
708 |
+
|
709 |
+
return open_url(url, wait=wait, locate=locate)
|
710 |
+
|
711 |
+
|
712 |
+
# If this is provided, getchar() calls into this instead. This is used
|
713 |
+
# for unittesting purposes.
|
714 |
+
_getchar: t.Optional[t.Callable[[bool], str]] = None
|
715 |
+
|
716 |
+
|
717 |
+
def getchar(echo: bool = False) -> str:
|
718 |
+
"""Fetches a single character from the terminal and returns it. This
|
719 |
+
will always return a unicode character and under certain rare
|
720 |
+
circumstances this might return more than one character. The
|
721 |
+
situations which more than one character is returned is when for
|
722 |
+
whatever reason multiple characters end up in the terminal buffer or
|
723 |
+
standard input was not actually a terminal.
|
724 |
+
|
725 |
+
Note that this will always read from the terminal, even if something
|
726 |
+
is piped into the standard input.
|
727 |
+
|
728 |
+
Note for Windows: in rare cases when typing non-ASCII characters, this
|
729 |
+
function might wait for a second character and then return both at once.
|
730 |
+
This is because certain Unicode characters look like special-key markers.
|
731 |
+
|
732 |
+
.. versionadded:: 2.0
|
733 |
+
|
734 |
+
:param echo: if set to `True`, the character read will also show up on
|
735 |
+
the terminal. The default is to not show it.
|
736 |
+
"""
|
737 |
+
global _getchar
|
738 |
+
|
739 |
+
if _getchar is None:
|
740 |
+
from ._termui_impl import getchar as f
|
741 |
+
|
742 |
+
_getchar = f
|
743 |
+
|
744 |
+
return _getchar(echo)
|
745 |
+
|
746 |
+
|
747 |
+
def raw_terminal() -> t.ContextManager[int]:
|
748 |
+
from ._termui_impl import raw_terminal as f
|
749 |
+
|
750 |
+
return f()
|
751 |
+
|
752 |
+
|
753 |
+
def pause(info: t.Optional[str] = None, err: bool = False) -> None:
|
754 |
+
"""This command stops execution and waits for the user to press any
|
755 |
+
key to continue. This is similar to the Windows batch "pause"
|
756 |
+
command. If the program is not run through a terminal, this command
|
757 |
+
will instead do nothing.
|
758 |
+
|
759 |
+
.. versionadded:: 2.0
|
760 |
+
|
761 |
+
.. versionadded:: 4.0
|
762 |
+
Added the `err` parameter.
|
763 |
+
|
764 |
+
:param info: The message to print before pausing. Defaults to
|
765 |
+
``"Press any key to continue..."``.
|
766 |
+
:param err: if set to message goes to ``stderr`` instead of
|
767 |
+
``stdout``, the same as with echo.
|
768 |
+
"""
|
769 |
+
if not isatty(sys.stdin) or not isatty(sys.stdout):
|
770 |
+
return
|
771 |
+
|
772 |
+
if info is None:
|
773 |
+
info = _("Press any key to continue...")
|
774 |
+
|
775 |
+
try:
|
776 |
+
if info:
|
777 |
+
echo(info, nl=False, err=err)
|
778 |
+
try:
|
779 |
+
getchar()
|
780 |
+
except (KeyboardInterrupt, EOFError):
|
781 |
+
pass
|
782 |
+
finally:
|
783 |
+
if info:
|
784 |
+
echo(err=err)
|
venv/lib/python3.10/site-packages/click/testing.py
ADDED
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import contextlib
|
2 |
+
import io
|
3 |
+
import os
|
4 |
+
import shlex
|
5 |
+
import shutil
|
6 |
+
import sys
|
7 |
+
import tempfile
|
8 |
+
import typing as t
|
9 |
+
from types import TracebackType
|
10 |
+
|
11 |
+
from . import formatting
|
12 |
+
from . import termui
|
13 |
+
from . import utils
|
14 |
+
from ._compat import _find_binary_reader
|
15 |
+
|
16 |
+
if t.TYPE_CHECKING:
|
17 |
+
from .core import BaseCommand
|
18 |
+
|
19 |
+
|
20 |
+
class EchoingStdin:
|
21 |
+
def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:
|
22 |
+
self._input = input
|
23 |
+
self._output = output
|
24 |
+
self._paused = False
|
25 |
+
|
26 |
+
def __getattr__(self, x: str) -> t.Any:
|
27 |
+
return getattr(self._input, x)
|
28 |
+
|
29 |
+
def _echo(self, rv: bytes) -> bytes:
|
30 |
+
if not self._paused:
|
31 |
+
self._output.write(rv)
|
32 |
+
|
33 |
+
return rv
|
34 |
+
|
35 |
+
def read(self, n: int = -1) -> bytes:
|
36 |
+
return self._echo(self._input.read(n))
|
37 |
+
|
38 |
+
def read1(self, n: int = -1) -> bytes:
|
39 |
+
return self._echo(self._input.read1(n)) # type: ignore
|
40 |
+
|
41 |
+
def readline(self, n: int = -1) -> bytes:
|
42 |
+
return self._echo(self._input.readline(n))
|
43 |
+
|
44 |
+
def readlines(self) -> t.List[bytes]:
|
45 |
+
return [self._echo(x) for x in self._input.readlines()]
|
46 |
+
|
47 |
+
def __iter__(self) -> t.Iterator[bytes]:
|
48 |
+
return iter(self._echo(x) for x in self._input)
|
49 |
+
|
50 |
+
def __repr__(self) -> str:
|
51 |
+
return repr(self._input)
|
52 |
+
|
53 |
+
|
54 |
+
@contextlib.contextmanager
|
55 |
+
def _pause_echo(stream: t.Optional[EchoingStdin]) -> t.Iterator[None]:
|
56 |
+
if stream is None:
|
57 |
+
yield
|
58 |
+
else:
|
59 |
+
stream._paused = True
|
60 |
+
yield
|
61 |
+
stream._paused = False
|
62 |
+
|
63 |
+
|
64 |
+
class _NamedTextIOWrapper(io.TextIOWrapper):
|
65 |
+
def __init__(
|
66 |
+
self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any
|
67 |
+
) -> None:
|
68 |
+
super().__init__(buffer, **kwargs)
|
69 |
+
self._name = name
|
70 |
+
self._mode = mode
|
71 |
+
|
72 |
+
@property
|
73 |
+
def name(self) -> str:
|
74 |
+
return self._name
|
75 |
+
|
76 |
+
@property
|
77 |
+
def mode(self) -> str:
|
78 |
+
return self._mode
|
79 |
+
|
80 |
+
|
81 |
+
def make_input_stream(
|
82 |
+
input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]], charset: str
|
83 |
+
) -> t.BinaryIO:
|
84 |
+
# Is already an input stream.
|
85 |
+
if hasattr(input, "read"):
|
86 |
+
rv = _find_binary_reader(t.cast(t.IO[t.Any], input))
|
87 |
+
|
88 |
+
if rv is not None:
|
89 |
+
return rv
|
90 |
+
|
91 |
+
raise TypeError("Could not find binary reader for input stream.")
|
92 |
+
|
93 |
+
if input is None:
|
94 |
+
input = b""
|
95 |
+
elif isinstance(input, str):
|
96 |
+
input = input.encode(charset)
|
97 |
+
|
98 |
+
return io.BytesIO(input)
|
99 |
+
|
100 |
+
|
101 |
+
class Result:
|
102 |
+
"""Holds the captured result of an invoked CLI script."""
|
103 |
+
|
104 |
+
def __init__(
|
105 |
+
self,
|
106 |
+
runner: "CliRunner",
|
107 |
+
stdout_bytes: bytes,
|
108 |
+
stderr_bytes: t.Optional[bytes],
|
109 |
+
return_value: t.Any,
|
110 |
+
exit_code: int,
|
111 |
+
exception: t.Optional[BaseException],
|
112 |
+
exc_info: t.Optional[
|
113 |
+
t.Tuple[t.Type[BaseException], BaseException, TracebackType]
|
114 |
+
] = None,
|
115 |
+
):
|
116 |
+
#: The runner that created the result
|
117 |
+
self.runner = runner
|
118 |
+
#: The standard output as bytes.
|
119 |
+
self.stdout_bytes = stdout_bytes
|
120 |
+
#: The standard error as bytes, or None if not available
|
121 |
+
self.stderr_bytes = stderr_bytes
|
122 |
+
#: The value returned from the invoked command.
|
123 |
+
#:
|
124 |
+
#: .. versionadded:: 8.0
|
125 |
+
self.return_value = return_value
|
126 |
+
#: The exit code as integer.
|
127 |
+
self.exit_code = exit_code
|
128 |
+
#: The exception that happened if one did.
|
129 |
+
self.exception = exception
|
130 |
+
#: The traceback
|
131 |
+
self.exc_info = exc_info
|
132 |
+
|
133 |
+
@property
|
134 |
+
def output(self) -> str:
|
135 |
+
"""The (standard) output as unicode string."""
|
136 |
+
return self.stdout
|
137 |
+
|
138 |
+
@property
|
139 |
+
def stdout(self) -> str:
|
140 |
+
"""The standard output as unicode string."""
|
141 |
+
return self.stdout_bytes.decode(self.runner.charset, "replace").replace(
|
142 |
+
"\r\n", "\n"
|
143 |
+
)
|
144 |
+
|
145 |
+
@property
|
146 |
+
def stderr(self) -> str:
|
147 |
+
"""The standard error as unicode string."""
|
148 |
+
if self.stderr_bytes is None:
|
149 |
+
raise ValueError("stderr not separately captured")
|
150 |
+
return self.stderr_bytes.decode(self.runner.charset, "replace").replace(
|
151 |
+
"\r\n", "\n"
|
152 |
+
)
|
153 |
+
|
154 |
+
def __repr__(self) -> str:
|
155 |
+
exc_str = repr(self.exception) if self.exception else "okay"
|
156 |
+
return f"<{type(self).__name__} {exc_str}>"
|
157 |
+
|
158 |
+
|
159 |
+
class CliRunner:
|
160 |
+
"""The CLI runner provides functionality to invoke a Click command line
|
161 |
+
script for unittesting purposes in a isolated environment. This only
|
162 |
+
works in single-threaded systems without any concurrency as it changes the
|
163 |
+
global interpreter state.
|
164 |
+
|
165 |
+
:param charset: the character set for the input and output data.
|
166 |
+
:param env: a dictionary with environment variables for overriding.
|
167 |
+
:param echo_stdin: if this is set to `True`, then reading from stdin writes
|
168 |
+
to stdout. This is useful for showing examples in
|
169 |
+
some circumstances. Note that regular prompts
|
170 |
+
will automatically echo the input.
|
171 |
+
:param mix_stderr: if this is set to `False`, then stdout and stderr are
|
172 |
+
preserved as independent streams. This is useful for
|
173 |
+
Unix-philosophy apps that have predictable stdout and
|
174 |
+
noisy stderr, such that each may be measured
|
175 |
+
independently
|
176 |
+
"""
|
177 |
+
|
178 |
+
def __init__(
|
179 |
+
self,
|
180 |
+
charset: str = "utf-8",
|
181 |
+
env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,
|
182 |
+
echo_stdin: bool = False,
|
183 |
+
mix_stderr: bool = True,
|
184 |
+
) -> None:
|
185 |
+
self.charset = charset
|
186 |
+
self.env: t.Mapping[str, t.Optional[str]] = env or {}
|
187 |
+
self.echo_stdin = echo_stdin
|
188 |
+
self.mix_stderr = mix_stderr
|
189 |
+
|
190 |
+
def get_default_prog_name(self, cli: "BaseCommand") -> str:
|
191 |
+
"""Given a command object it will return the default program name
|
192 |
+
for it. The default is the `name` attribute or ``"root"`` if not
|
193 |
+
set.
|
194 |
+
"""
|
195 |
+
return cli.name or "root"
|
196 |
+
|
197 |
+
def make_env(
|
198 |
+
self, overrides: t.Optional[t.Mapping[str, t.Optional[str]]] = None
|
199 |
+
) -> t.Mapping[str, t.Optional[str]]:
|
200 |
+
"""Returns the environment overrides for invoking a script."""
|
201 |
+
rv = dict(self.env)
|
202 |
+
if overrides:
|
203 |
+
rv.update(overrides)
|
204 |
+
return rv
|
205 |
+
|
206 |
+
@contextlib.contextmanager
|
207 |
+
def isolation(
|
208 |
+
self,
|
209 |
+
input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,
|
210 |
+
env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,
|
211 |
+
color: bool = False,
|
212 |
+
) -> t.Iterator[t.Tuple[io.BytesIO, t.Optional[io.BytesIO]]]:
|
213 |
+
"""A context manager that sets up the isolation for invoking of a
|
214 |
+
command line tool. This sets up stdin with the given input data
|
215 |
+
and `os.environ` with the overrides from the given dictionary.
|
216 |
+
This also rebinds some internals in Click to be mocked (like the
|
217 |
+
prompt functionality).
|
218 |
+
|
219 |
+
This is automatically done in the :meth:`invoke` method.
|
220 |
+
|
221 |
+
:param input: the input stream to put into sys.stdin.
|
222 |
+
:param env: the environment overrides as dictionary.
|
223 |
+
:param color: whether the output should contain color codes. The
|
224 |
+
application can still override this explicitly.
|
225 |
+
|
226 |
+
.. versionchanged:: 8.0
|
227 |
+
``stderr`` is opened with ``errors="backslashreplace"``
|
228 |
+
instead of the default ``"strict"``.
|
229 |
+
|
230 |
+
.. versionchanged:: 4.0
|
231 |
+
Added the ``color`` parameter.
|
232 |
+
"""
|
233 |
+
bytes_input = make_input_stream(input, self.charset)
|
234 |
+
echo_input = None
|
235 |
+
|
236 |
+
old_stdin = sys.stdin
|
237 |
+
old_stdout = sys.stdout
|
238 |
+
old_stderr = sys.stderr
|
239 |
+
old_forced_width = formatting.FORCED_WIDTH
|
240 |
+
formatting.FORCED_WIDTH = 80
|
241 |
+
|
242 |
+
env = self.make_env(env)
|
243 |
+
|
244 |
+
bytes_output = io.BytesIO()
|
245 |
+
|
246 |
+
if self.echo_stdin:
|
247 |
+
bytes_input = echo_input = t.cast(
|
248 |
+
t.BinaryIO, EchoingStdin(bytes_input, bytes_output)
|
249 |
+
)
|
250 |
+
|
251 |
+
sys.stdin = text_input = _NamedTextIOWrapper(
|
252 |
+
bytes_input, encoding=self.charset, name="<stdin>", mode="r"
|
253 |
+
)
|
254 |
+
|
255 |
+
if self.echo_stdin:
|
256 |
+
# Force unbuffered reads, otherwise TextIOWrapper reads a
|
257 |
+
# large chunk which is echoed early.
|
258 |
+
text_input._CHUNK_SIZE = 1 # type: ignore
|
259 |
+
|
260 |
+
sys.stdout = _NamedTextIOWrapper(
|
261 |
+
bytes_output, encoding=self.charset, name="<stdout>", mode="w"
|
262 |
+
)
|
263 |
+
|
264 |
+
bytes_error = None
|
265 |
+
if self.mix_stderr:
|
266 |
+
sys.stderr = sys.stdout
|
267 |
+
else:
|
268 |
+
bytes_error = io.BytesIO()
|
269 |
+
sys.stderr = _NamedTextIOWrapper(
|
270 |
+
bytes_error,
|
271 |
+
encoding=self.charset,
|
272 |
+
name="<stderr>",
|
273 |
+
mode="w",
|
274 |
+
errors="backslashreplace",
|
275 |
+
)
|
276 |
+
|
277 |
+
@_pause_echo(echo_input) # type: ignore
|
278 |
+
def visible_input(prompt: t.Optional[str] = None) -> str:
|
279 |
+
sys.stdout.write(prompt or "")
|
280 |
+
val = text_input.readline().rstrip("\r\n")
|
281 |
+
sys.stdout.write(f"{val}\n")
|
282 |
+
sys.stdout.flush()
|
283 |
+
return val
|
284 |
+
|
285 |
+
@_pause_echo(echo_input) # type: ignore
|
286 |
+
def hidden_input(prompt: t.Optional[str] = None) -> str:
|
287 |
+
sys.stdout.write(f"{prompt or ''}\n")
|
288 |
+
sys.stdout.flush()
|
289 |
+
return text_input.readline().rstrip("\r\n")
|
290 |
+
|
291 |
+
@_pause_echo(echo_input) # type: ignore
|
292 |
+
def _getchar(echo: bool) -> str:
|
293 |
+
char = sys.stdin.read(1)
|
294 |
+
|
295 |
+
if echo:
|
296 |
+
sys.stdout.write(char)
|
297 |
+
|
298 |
+
sys.stdout.flush()
|
299 |
+
return char
|
300 |
+
|
301 |
+
default_color = color
|
302 |
+
|
303 |
+
def should_strip_ansi(
|
304 |
+
stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None
|
305 |
+
) -> bool:
|
306 |
+
if color is None:
|
307 |
+
return not default_color
|
308 |
+
return not color
|
309 |
+
|
310 |
+
old_visible_prompt_func = termui.visible_prompt_func
|
311 |
+
old_hidden_prompt_func = termui.hidden_prompt_func
|
312 |
+
old__getchar_func = termui._getchar
|
313 |
+
old_should_strip_ansi = utils.should_strip_ansi # type: ignore
|
314 |
+
termui.visible_prompt_func = visible_input
|
315 |
+
termui.hidden_prompt_func = hidden_input
|
316 |
+
termui._getchar = _getchar
|
317 |
+
utils.should_strip_ansi = should_strip_ansi # type: ignore
|
318 |
+
|
319 |
+
old_env = {}
|
320 |
+
try:
|
321 |
+
for key, value in env.items():
|
322 |
+
old_env[key] = os.environ.get(key)
|
323 |
+
if value is None:
|
324 |
+
try:
|
325 |
+
del os.environ[key]
|
326 |
+
except Exception:
|
327 |
+
pass
|
328 |
+
else:
|
329 |
+
os.environ[key] = value
|
330 |
+
yield (bytes_output, bytes_error)
|
331 |
+
finally:
|
332 |
+
for key, value in old_env.items():
|
333 |
+
if value is None:
|
334 |
+
try:
|
335 |
+
del os.environ[key]
|
336 |
+
except Exception:
|
337 |
+
pass
|
338 |
+
else:
|
339 |
+
os.environ[key] = value
|
340 |
+
sys.stdout = old_stdout
|
341 |
+
sys.stderr = old_stderr
|
342 |
+
sys.stdin = old_stdin
|
343 |
+
termui.visible_prompt_func = old_visible_prompt_func
|
344 |
+
termui.hidden_prompt_func = old_hidden_prompt_func
|
345 |
+
termui._getchar = old__getchar_func
|
346 |
+
utils.should_strip_ansi = old_should_strip_ansi # type: ignore
|
347 |
+
formatting.FORCED_WIDTH = old_forced_width
|
348 |
+
|
349 |
+
def invoke(
|
350 |
+
self,
|
351 |
+
cli: "BaseCommand",
|
352 |
+
args: t.Optional[t.Union[str, t.Sequence[str]]] = None,
|
353 |
+
input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,
|
354 |
+
env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,
|
355 |
+
catch_exceptions: bool = True,
|
356 |
+
color: bool = False,
|
357 |
+
**extra: t.Any,
|
358 |
+
) -> Result:
|
359 |
+
"""Invokes a command in an isolated environment. The arguments are
|
360 |
+
forwarded directly to the command line script, the `extra` keyword
|
361 |
+
arguments are passed to the :meth:`~clickpkg.Command.main` function of
|
362 |
+
the command.
|
363 |
+
|
364 |
+
This returns a :class:`Result` object.
|
365 |
+
|
366 |
+
:param cli: the command to invoke
|
367 |
+
:param args: the arguments to invoke. It may be given as an iterable
|
368 |
+
or a string. When given as string it will be interpreted
|
369 |
+
as a Unix shell command. More details at
|
370 |
+
:func:`shlex.split`.
|
371 |
+
:param input: the input data for `sys.stdin`.
|
372 |
+
:param env: the environment overrides.
|
373 |
+
:param catch_exceptions: Whether to catch any other exceptions than
|
374 |
+
``SystemExit``.
|
375 |
+
:param extra: the keyword arguments to pass to :meth:`main`.
|
376 |
+
:param color: whether the output should contain color codes. The
|
377 |
+
application can still override this explicitly.
|
378 |
+
|
379 |
+
.. versionchanged:: 8.0
|
380 |
+
The result object has the ``return_value`` attribute with
|
381 |
+
the value returned from the invoked command.
|
382 |
+
|
383 |
+
.. versionchanged:: 4.0
|
384 |
+
Added the ``color`` parameter.
|
385 |
+
|
386 |
+
.. versionchanged:: 3.0
|
387 |
+
Added the ``catch_exceptions`` parameter.
|
388 |
+
|
389 |
+
.. versionchanged:: 3.0
|
390 |
+
The result object has the ``exc_info`` attribute with the
|
391 |
+
traceback if available.
|
392 |
+
"""
|
393 |
+
exc_info = None
|
394 |
+
with self.isolation(input=input, env=env, color=color) as outstreams:
|
395 |
+
return_value = None
|
396 |
+
exception: t.Optional[BaseException] = None
|
397 |
+
exit_code = 0
|
398 |
+
|
399 |
+
if isinstance(args, str):
|
400 |
+
args = shlex.split(args)
|
401 |
+
|
402 |
+
try:
|
403 |
+
prog_name = extra.pop("prog_name")
|
404 |
+
except KeyError:
|
405 |
+
prog_name = self.get_default_prog_name(cli)
|
406 |
+
|
407 |
+
try:
|
408 |
+
return_value = cli.main(args=args or (), prog_name=prog_name, **extra)
|
409 |
+
except SystemExit as e:
|
410 |
+
exc_info = sys.exc_info()
|
411 |
+
e_code = t.cast(t.Optional[t.Union[int, t.Any]], e.code)
|
412 |
+
|
413 |
+
if e_code is None:
|
414 |
+
e_code = 0
|
415 |
+
|
416 |
+
if e_code != 0:
|
417 |
+
exception = e
|
418 |
+
|
419 |
+
if not isinstance(e_code, int):
|
420 |
+
sys.stdout.write(str(e_code))
|
421 |
+
sys.stdout.write("\n")
|
422 |
+
e_code = 1
|
423 |
+
|
424 |
+
exit_code = e_code
|
425 |
+
|
426 |
+
except Exception as e:
|
427 |
+
if not catch_exceptions:
|
428 |
+
raise
|
429 |
+
exception = e
|
430 |
+
exit_code = 1
|
431 |
+
exc_info = sys.exc_info()
|
432 |
+
finally:
|
433 |
+
sys.stdout.flush()
|
434 |
+
stdout = outstreams[0].getvalue()
|
435 |
+
if self.mix_stderr:
|
436 |
+
stderr = None
|
437 |
+
else:
|
438 |
+
stderr = outstreams[1].getvalue() # type: ignore
|
439 |
+
|
440 |
+
return Result(
|
441 |
+
runner=self,
|
442 |
+
stdout_bytes=stdout,
|
443 |
+
stderr_bytes=stderr,
|
444 |
+
return_value=return_value,
|
445 |
+
exit_code=exit_code,
|
446 |
+
exception=exception,
|
447 |
+
exc_info=exc_info, # type: ignore
|
448 |
+
)
|
449 |
+
|
450 |
+
@contextlib.contextmanager
|
451 |
+
def isolated_filesystem(
|
452 |
+
self, temp_dir: t.Optional[t.Union[str, "os.PathLike[str]"]] = None
|
453 |
+
) -> t.Iterator[str]:
|
454 |
+
"""A context manager that creates a temporary directory and
|
455 |
+
changes the current working directory to it. This isolates tests
|
456 |
+
that affect the contents of the CWD to prevent them from
|
457 |
+
interfering with each other.
|
458 |
+
|
459 |
+
:param temp_dir: Create the temporary directory under this
|
460 |
+
directory. If given, the created directory is not removed
|
461 |
+
when exiting.
|
462 |
+
|
463 |
+
.. versionchanged:: 8.0
|
464 |
+
Added the ``temp_dir`` parameter.
|
465 |
+
"""
|
466 |
+
cwd = os.getcwd()
|
467 |
+
dt = tempfile.mkdtemp(dir=temp_dir)
|
468 |
+
os.chdir(dt)
|
469 |
+
|
470 |
+
try:
|
471 |
+
yield dt
|
472 |
+
finally:
|
473 |
+
os.chdir(cwd)
|
474 |
+
|
475 |
+
if temp_dir is None:
|
476 |
+
try:
|
477 |
+
shutil.rmtree(dt)
|
478 |
+
except OSError: # noqa: B014
|
479 |
+
pass
|
venv/lib/python3.10/site-packages/click/types.py
ADDED
@@ -0,0 +1,1089 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
import typing as t
|
5 |
+
from datetime import datetime
|
6 |
+
from gettext import gettext as _
|
7 |
+
from gettext import ngettext
|
8 |
+
|
9 |
+
from ._compat import _get_argv_encoding
|
10 |
+
from ._compat import open_stream
|
11 |
+
from .exceptions import BadParameter
|
12 |
+
from .utils import format_filename
|
13 |
+
from .utils import LazyFile
|
14 |
+
from .utils import safecall
|
15 |
+
|
16 |
+
if t.TYPE_CHECKING:
|
17 |
+
import typing_extensions as te
|
18 |
+
from .core import Context
|
19 |
+
from .core import Parameter
|
20 |
+
from .shell_completion import CompletionItem
|
21 |
+
|
22 |
+
|
23 |
+
class ParamType:
|
24 |
+
"""Represents the type of a parameter. Validates and converts values
|
25 |
+
from the command line or Python into the correct type.
|
26 |
+
|
27 |
+
To implement a custom type, subclass and implement at least the
|
28 |
+
following:
|
29 |
+
|
30 |
+
- The :attr:`name` class attribute must be set.
|
31 |
+
- Calling an instance of the type with ``None`` must return
|
32 |
+
``None``. This is already implemented by default.
|
33 |
+
- :meth:`convert` must convert string values to the correct type.
|
34 |
+
- :meth:`convert` must accept values that are already the correct
|
35 |
+
type.
|
36 |
+
- It must be able to convert a value if the ``ctx`` and ``param``
|
37 |
+
arguments are ``None``. This can occur when converting prompt
|
38 |
+
input.
|
39 |
+
"""
|
40 |
+
|
41 |
+
is_composite: t.ClassVar[bool] = False
|
42 |
+
arity: t.ClassVar[int] = 1
|
43 |
+
|
44 |
+
#: the descriptive name of this type
|
45 |
+
name: str
|
46 |
+
|
47 |
+
#: if a list of this type is expected and the value is pulled from a
|
48 |
+
#: string environment variable, this is what splits it up. `None`
|
49 |
+
#: means any whitespace. For all parameters the general rule is that
|
50 |
+
#: whitespace splits them up. The exception are paths and files which
|
51 |
+
#: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on
|
52 |
+
#: Windows).
|
53 |
+
envvar_list_splitter: t.ClassVar[t.Optional[str]] = None
|
54 |
+
|
55 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
56 |
+
"""Gather information that could be useful for a tool generating
|
57 |
+
user-facing documentation.
|
58 |
+
|
59 |
+
Use :meth:`click.Context.to_info_dict` to traverse the entire
|
60 |
+
CLI structure.
|
61 |
+
|
62 |
+
.. versionadded:: 8.0
|
63 |
+
"""
|
64 |
+
# The class name without the "ParamType" suffix.
|
65 |
+
param_type = type(self).__name__.partition("ParamType")[0]
|
66 |
+
param_type = param_type.partition("ParameterType")[0]
|
67 |
+
|
68 |
+
# Custom subclasses might not remember to set a name.
|
69 |
+
if hasattr(self, "name"):
|
70 |
+
name = self.name
|
71 |
+
else:
|
72 |
+
name = param_type
|
73 |
+
|
74 |
+
return {"param_type": param_type, "name": name}
|
75 |
+
|
76 |
+
def __call__(
|
77 |
+
self,
|
78 |
+
value: t.Any,
|
79 |
+
param: t.Optional["Parameter"] = None,
|
80 |
+
ctx: t.Optional["Context"] = None,
|
81 |
+
) -> t.Any:
|
82 |
+
if value is not None:
|
83 |
+
return self.convert(value, param, ctx)
|
84 |
+
|
85 |
+
def get_metavar(self, param: "Parameter") -> t.Optional[str]:
|
86 |
+
"""Returns the metavar default for this param if it provides one."""
|
87 |
+
|
88 |
+
def get_missing_message(self, param: "Parameter") -> t.Optional[str]:
|
89 |
+
"""Optionally might return extra information about a missing
|
90 |
+
parameter.
|
91 |
+
|
92 |
+
.. versionadded:: 2.0
|
93 |
+
"""
|
94 |
+
|
95 |
+
def convert(
|
96 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
97 |
+
) -> t.Any:
|
98 |
+
"""Convert the value to the correct type. This is not called if
|
99 |
+
the value is ``None`` (the missing value).
|
100 |
+
|
101 |
+
This must accept string values from the command line, as well as
|
102 |
+
values that are already the correct type. It may also convert
|
103 |
+
other compatible types.
|
104 |
+
|
105 |
+
The ``param`` and ``ctx`` arguments may be ``None`` in certain
|
106 |
+
situations, such as when converting prompt input.
|
107 |
+
|
108 |
+
If the value cannot be converted, call :meth:`fail` with a
|
109 |
+
descriptive message.
|
110 |
+
|
111 |
+
:param value: The value to convert.
|
112 |
+
:param param: The parameter that is using this type to convert
|
113 |
+
its value. May be ``None``.
|
114 |
+
:param ctx: The current context that arrived at this value. May
|
115 |
+
be ``None``.
|
116 |
+
"""
|
117 |
+
return value
|
118 |
+
|
119 |
+
def split_envvar_value(self, rv: str) -> t.Sequence[str]:
|
120 |
+
"""Given a value from an environment variable this splits it up
|
121 |
+
into small chunks depending on the defined envvar list splitter.
|
122 |
+
|
123 |
+
If the splitter is set to `None`, which means that whitespace splits,
|
124 |
+
then leading and trailing whitespace is ignored. Otherwise, leading
|
125 |
+
and trailing splitters usually lead to empty items being included.
|
126 |
+
"""
|
127 |
+
return (rv or "").split(self.envvar_list_splitter)
|
128 |
+
|
129 |
+
def fail(
|
130 |
+
self,
|
131 |
+
message: str,
|
132 |
+
param: t.Optional["Parameter"] = None,
|
133 |
+
ctx: t.Optional["Context"] = None,
|
134 |
+
) -> "t.NoReturn":
|
135 |
+
"""Helper method to fail with an invalid value message."""
|
136 |
+
raise BadParameter(message, ctx=ctx, param=param)
|
137 |
+
|
138 |
+
def shell_complete(
|
139 |
+
self, ctx: "Context", param: "Parameter", incomplete: str
|
140 |
+
) -> t.List["CompletionItem"]:
|
141 |
+
"""Return a list of
|
142 |
+
:class:`~click.shell_completion.CompletionItem` objects for the
|
143 |
+
incomplete value. Most types do not provide completions, but
|
144 |
+
some do, and this allows custom types to provide custom
|
145 |
+
completions as well.
|
146 |
+
|
147 |
+
:param ctx: Invocation context for this command.
|
148 |
+
:param param: The parameter that is requesting completion.
|
149 |
+
:param incomplete: Value being completed. May be empty.
|
150 |
+
|
151 |
+
.. versionadded:: 8.0
|
152 |
+
"""
|
153 |
+
return []
|
154 |
+
|
155 |
+
|
156 |
+
class CompositeParamType(ParamType):
|
157 |
+
is_composite = True
|
158 |
+
|
159 |
+
@property
|
160 |
+
def arity(self) -> int: # type: ignore
|
161 |
+
raise NotImplementedError()
|
162 |
+
|
163 |
+
|
164 |
+
class FuncParamType(ParamType):
|
165 |
+
def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:
|
166 |
+
self.name: str = func.__name__
|
167 |
+
self.func = func
|
168 |
+
|
169 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
170 |
+
info_dict = super().to_info_dict()
|
171 |
+
info_dict["func"] = self.func
|
172 |
+
return info_dict
|
173 |
+
|
174 |
+
def convert(
|
175 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
176 |
+
) -> t.Any:
|
177 |
+
try:
|
178 |
+
return self.func(value)
|
179 |
+
except ValueError:
|
180 |
+
try:
|
181 |
+
value = str(value)
|
182 |
+
except UnicodeError:
|
183 |
+
value = value.decode("utf-8", "replace")
|
184 |
+
|
185 |
+
self.fail(value, param, ctx)
|
186 |
+
|
187 |
+
|
188 |
+
class UnprocessedParamType(ParamType):
|
189 |
+
name = "text"
|
190 |
+
|
191 |
+
def convert(
|
192 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
193 |
+
) -> t.Any:
|
194 |
+
return value
|
195 |
+
|
196 |
+
def __repr__(self) -> str:
|
197 |
+
return "UNPROCESSED"
|
198 |
+
|
199 |
+
|
200 |
+
class StringParamType(ParamType):
|
201 |
+
name = "text"
|
202 |
+
|
203 |
+
def convert(
|
204 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
205 |
+
) -> t.Any:
|
206 |
+
if isinstance(value, bytes):
|
207 |
+
enc = _get_argv_encoding()
|
208 |
+
try:
|
209 |
+
value = value.decode(enc)
|
210 |
+
except UnicodeError:
|
211 |
+
fs_enc = sys.getfilesystemencoding()
|
212 |
+
if fs_enc != enc:
|
213 |
+
try:
|
214 |
+
value = value.decode(fs_enc)
|
215 |
+
except UnicodeError:
|
216 |
+
value = value.decode("utf-8", "replace")
|
217 |
+
else:
|
218 |
+
value = value.decode("utf-8", "replace")
|
219 |
+
return value
|
220 |
+
return str(value)
|
221 |
+
|
222 |
+
def __repr__(self) -> str:
|
223 |
+
return "STRING"
|
224 |
+
|
225 |
+
|
226 |
+
class Choice(ParamType):
|
227 |
+
"""The choice type allows a value to be checked against a fixed set
|
228 |
+
of supported values. All of these values have to be strings.
|
229 |
+
|
230 |
+
You should only pass a list or tuple of choices. Other iterables
|
231 |
+
(like generators) may lead to surprising results.
|
232 |
+
|
233 |
+
The resulting value will always be one of the originally passed choices
|
234 |
+
regardless of ``case_sensitive`` or any ``ctx.token_normalize_func``
|
235 |
+
being specified.
|
236 |
+
|
237 |
+
See :ref:`choice-opts` for an example.
|
238 |
+
|
239 |
+
:param case_sensitive: Set to false to make choices case
|
240 |
+
insensitive. Defaults to true.
|
241 |
+
"""
|
242 |
+
|
243 |
+
name = "choice"
|
244 |
+
|
245 |
+
def __init__(self, choices: t.Sequence[str], case_sensitive: bool = True) -> None:
|
246 |
+
self.choices = choices
|
247 |
+
self.case_sensitive = case_sensitive
|
248 |
+
|
249 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
250 |
+
info_dict = super().to_info_dict()
|
251 |
+
info_dict["choices"] = self.choices
|
252 |
+
info_dict["case_sensitive"] = self.case_sensitive
|
253 |
+
return info_dict
|
254 |
+
|
255 |
+
def get_metavar(self, param: "Parameter") -> str:
|
256 |
+
choices_str = "|".join(self.choices)
|
257 |
+
|
258 |
+
# Use curly braces to indicate a required argument.
|
259 |
+
if param.required and param.param_type_name == "argument":
|
260 |
+
return f"{{{choices_str}}}"
|
261 |
+
|
262 |
+
# Use square braces to indicate an option or optional argument.
|
263 |
+
return f"[{choices_str}]"
|
264 |
+
|
265 |
+
def get_missing_message(self, param: "Parameter") -> str:
|
266 |
+
return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))
|
267 |
+
|
268 |
+
def convert(
|
269 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
270 |
+
) -> t.Any:
|
271 |
+
# Match through normalization and case sensitivity
|
272 |
+
# first do token_normalize_func, then lowercase
|
273 |
+
# preserve original `value` to produce an accurate message in
|
274 |
+
# `self.fail`
|
275 |
+
normed_value = value
|
276 |
+
normed_choices = {choice: choice for choice in self.choices}
|
277 |
+
|
278 |
+
if ctx is not None and ctx.token_normalize_func is not None:
|
279 |
+
normed_value = ctx.token_normalize_func(value)
|
280 |
+
normed_choices = {
|
281 |
+
ctx.token_normalize_func(normed_choice): original
|
282 |
+
for normed_choice, original in normed_choices.items()
|
283 |
+
}
|
284 |
+
|
285 |
+
if not self.case_sensitive:
|
286 |
+
normed_value = normed_value.casefold()
|
287 |
+
normed_choices = {
|
288 |
+
normed_choice.casefold(): original
|
289 |
+
for normed_choice, original in normed_choices.items()
|
290 |
+
}
|
291 |
+
|
292 |
+
if normed_value in normed_choices:
|
293 |
+
return normed_choices[normed_value]
|
294 |
+
|
295 |
+
choices_str = ", ".join(map(repr, self.choices))
|
296 |
+
self.fail(
|
297 |
+
ngettext(
|
298 |
+
"{value!r} is not {choice}.",
|
299 |
+
"{value!r} is not one of {choices}.",
|
300 |
+
len(self.choices),
|
301 |
+
).format(value=value, choice=choices_str, choices=choices_str),
|
302 |
+
param,
|
303 |
+
ctx,
|
304 |
+
)
|
305 |
+
|
306 |
+
def __repr__(self) -> str:
|
307 |
+
return f"Choice({list(self.choices)})"
|
308 |
+
|
309 |
+
def shell_complete(
|
310 |
+
self, ctx: "Context", param: "Parameter", incomplete: str
|
311 |
+
) -> t.List["CompletionItem"]:
|
312 |
+
"""Complete choices that start with the incomplete value.
|
313 |
+
|
314 |
+
:param ctx: Invocation context for this command.
|
315 |
+
:param param: The parameter that is requesting completion.
|
316 |
+
:param incomplete: Value being completed. May be empty.
|
317 |
+
|
318 |
+
.. versionadded:: 8.0
|
319 |
+
"""
|
320 |
+
from click.shell_completion import CompletionItem
|
321 |
+
|
322 |
+
str_choices = map(str, self.choices)
|
323 |
+
|
324 |
+
if self.case_sensitive:
|
325 |
+
matched = (c for c in str_choices if c.startswith(incomplete))
|
326 |
+
else:
|
327 |
+
incomplete = incomplete.lower()
|
328 |
+
matched = (c for c in str_choices if c.lower().startswith(incomplete))
|
329 |
+
|
330 |
+
return [CompletionItem(c) for c in matched]
|
331 |
+
|
332 |
+
|
333 |
+
class DateTime(ParamType):
|
334 |
+
"""The DateTime type converts date strings into `datetime` objects.
|
335 |
+
|
336 |
+
The format strings which are checked are configurable, but default to some
|
337 |
+
common (non-timezone aware) ISO 8601 formats.
|
338 |
+
|
339 |
+
When specifying *DateTime* formats, you should only pass a list or a tuple.
|
340 |
+
Other iterables, like generators, may lead to surprising results.
|
341 |
+
|
342 |
+
The format strings are processed using ``datetime.strptime``, and this
|
343 |
+
consequently defines the format strings which are allowed.
|
344 |
+
|
345 |
+
Parsing is tried using each format, in order, and the first format which
|
346 |
+
parses successfully is used.
|
347 |
+
|
348 |
+
:param formats: A list or tuple of date format strings, in the order in
|
349 |
+
which they should be tried. Defaults to
|
350 |
+
``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,
|
351 |
+
``'%Y-%m-%d %H:%M:%S'``.
|
352 |
+
"""
|
353 |
+
|
354 |
+
name = "datetime"
|
355 |
+
|
356 |
+
def __init__(self, formats: t.Optional[t.Sequence[str]] = None):
|
357 |
+
self.formats: t.Sequence[str] = formats or [
|
358 |
+
"%Y-%m-%d",
|
359 |
+
"%Y-%m-%dT%H:%M:%S",
|
360 |
+
"%Y-%m-%d %H:%M:%S",
|
361 |
+
]
|
362 |
+
|
363 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
364 |
+
info_dict = super().to_info_dict()
|
365 |
+
info_dict["formats"] = self.formats
|
366 |
+
return info_dict
|
367 |
+
|
368 |
+
def get_metavar(self, param: "Parameter") -> str:
|
369 |
+
return f"[{'|'.join(self.formats)}]"
|
370 |
+
|
371 |
+
def _try_to_convert_date(self, value: t.Any, format: str) -> t.Optional[datetime]:
|
372 |
+
try:
|
373 |
+
return datetime.strptime(value, format)
|
374 |
+
except ValueError:
|
375 |
+
return None
|
376 |
+
|
377 |
+
def convert(
|
378 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
379 |
+
) -> t.Any:
|
380 |
+
if isinstance(value, datetime):
|
381 |
+
return value
|
382 |
+
|
383 |
+
for format in self.formats:
|
384 |
+
converted = self._try_to_convert_date(value, format)
|
385 |
+
|
386 |
+
if converted is not None:
|
387 |
+
return converted
|
388 |
+
|
389 |
+
formats_str = ", ".join(map(repr, self.formats))
|
390 |
+
self.fail(
|
391 |
+
ngettext(
|
392 |
+
"{value!r} does not match the format {format}.",
|
393 |
+
"{value!r} does not match the formats {formats}.",
|
394 |
+
len(self.formats),
|
395 |
+
).format(value=value, format=formats_str, formats=formats_str),
|
396 |
+
param,
|
397 |
+
ctx,
|
398 |
+
)
|
399 |
+
|
400 |
+
def __repr__(self) -> str:
|
401 |
+
return "DateTime"
|
402 |
+
|
403 |
+
|
404 |
+
class _NumberParamTypeBase(ParamType):
|
405 |
+
_number_class: t.ClassVar[t.Type[t.Any]]
|
406 |
+
|
407 |
+
def convert(
|
408 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
409 |
+
) -> t.Any:
|
410 |
+
try:
|
411 |
+
return self._number_class(value)
|
412 |
+
except ValueError:
|
413 |
+
self.fail(
|
414 |
+
_("{value!r} is not a valid {number_type}.").format(
|
415 |
+
value=value, number_type=self.name
|
416 |
+
),
|
417 |
+
param,
|
418 |
+
ctx,
|
419 |
+
)
|
420 |
+
|
421 |
+
|
422 |
+
class _NumberRangeBase(_NumberParamTypeBase):
|
423 |
+
def __init__(
|
424 |
+
self,
|
425 |
+
min: t.Optional[float] = None,
|
426 |
+
max: t.Optional[float] = None,
|
427 |
+
min_open: bool = False,
|
428 |
+
max_open: bool = False,
|
429 |
+
clamp: bool = False,
|
430 |
+
) -> None:
|
431 |
+
self.min = min
|
432 |
+
self.max = max
|
433 |
+
self.min_open = min_open
|
434 |
+
self.max_open = max_open
|
435 |
+
self.clamp = clamp
|
436 |
+
|
437 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
438 |
+
info_dict = super().to_info_dict()
|
439 |
+
info_dict.update(
|
440 |
+
min=self.min,
|
441 |
+
max=self.max,
|
442 |
+
min_open=self.min_open,
|
443 |
+
max_open=self.max_open,
|
444 |
+
clamp=self.clamp,
|
445 |
+
)
|
446 |
+
return info_dict
|
447 |
+
|
448 |
+
def convert(
|
449 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
450 |
+
) -> t.Any:
|
451 |
+
import operator
|
452 |
+
|
453 |
+
rv = super().convert(value, param, ctx)
|
454 |
+
lt_min: bool = self.min is not None and (
|
455 |
+
operator.le if self.min_open else operator.lt
|
456 |
+
)(rv, self.min)
|
457 |
+
gt_max: bool = self.max is not None and (
|
458 |
+
operator.ge if self.max_open else operator.gt
|
459 |
+
)(rv, self.max)
|
460 |
+
|
461 |
+
if self.clamp:
|
462 |
+
if lt_min:
|
463 |
+
return self._clamp(self.min, 1, self.min_open) # type: ignore
|
464 |
+
|
465 |
+
if gt_max:
|
466 |
+
return self._clamp(self.max, -1, self.max_open) # type: ignore
|
467 |
+
|
468 |
+
if lt_min or gt_max:
|
469 |
+
self.fail(
|
470 |
+
_("{value} is not in the range {range}.").format(
|
471 |
+
value=rv, range=self._describe_range()
|
472 |
+
),
|
473 |
+
param,
|
474 |
+
ctx,
|
475 |
+
)
|
476 |
+
|
477 |
+
return rv
|
478 |
+
|
479 |
+
def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:
|
480 |
+
"""Find the valid value to clamp to bound in the given
|
481 |
+
direction.
|
482 |
+
|
483 |
+
:param bound: The boundary value.
|
484 |
+
:param dir: 1 or -1 indicating the direction to move.
|
485 |
+
:param open: If true, the range does not include the bound.
|
486 |
+
"""
|
487 |
+
raise NotImplementedError
|
488 |
+
|
489 |
+
def _describe_range(self) -> str:
|
490 |
+
"""Describe the range for use in help text."""
|
491 |
+
if self.min is None:
|
492 |
+
op = "<" if self.max_open else "<="
|
493 |
+
return f"x{op}{self.max}"
|
494 |
+
|
495 |
+
if self.max is None:
|
496 |
+
op = ">" if self.min_open else ">="
|
497 |
+
return f"x{op}{self.min}"
|
498 |
+
|
499 |
+
lop = "<" if self.min_open else "<="
|
500 |
+
rop = "<" if self.max_open else "<="
|
501 |
+
return f"{self.min}{lop}x{rop}{self.max}"
|
502 |
+
|
503 |
+
def __repr__(self) -> str:
|
504 |
+
clamp = " clamped" if self.clamp else ""
|
505 |
+
return f"<{type(self).__name__} {self._describe_range()}{clamp}>"
|
506 |
+
|
507 |
+
|
508 |
+
class IntParamType(_NumberParamTypeBase):
|
509 |
+
name = "integer"
|
510 |
+
_number_class = int
|
511 |
+
|
512 |
+
def __repr__(self) -> str:
|
513 |
+
return "INT"
|
514 |
+
|
515 |
+
|
516 |
+
class IntRange(_NumberRangeBase, IntParamType):
|
517 |
+
"""Restrict an :data:`click.INT` value to a range of accepted
|
518 |
+
values. See :ref:`ranges`.
|
519 |
+
|
520 |
+
If ``min`` or ``max`` are not passed, any value is accepted in that
|
521 |
+
direction. If ``min_open`` or ``max_open`` are enabled, the
|
522 |
+
corresponding boundary is not included in the range.
|
523 |
+
|
524 |
+
If ``clamp`` is enabled, a value outside the range is clamped to the
|
525 |
+
boundary instead of failing.
|
526 |
+
|
527 |
+
.. versionchanged:: 8.0
|
528 |
+
Added the ``min_open`` and ``max_open`` parameters.
|
529 |
+
"""
|
530 |
+
|
531 |
+
name = "integer range"
|
532 |
+
|
533 |
+
def _clamp( # type: ignore
|
534 |
+
self, bound: int, dir: "te.Literal[1, -1]", open: bool
|
535 |
+
) -> int:
|
536 |
+
if not open:
|
537 |
+
return bound
|
538 |
+
|
539 |
+
return bound + dir
|
540 |
+
|
541 |
+
|
542 |
+
class FloatParamType(_NumberParamTypeBase):
|
543 |
+
name = "float"
|
544 |
+
_number_class = float
|
545 |
+
|
546 |
+
def __repr__(self) -> str:
|
547 |
+
return "FLOAT"
|
548 |
+
|
549 |
+
|
550 |
+
class FloatRange(_NumberRangeBase, FloatParamType):
|
551 |
+
"""Restrict a :data:`click.FLOAT` value to a range of accepted
|
552 |
+
values. See :ref:`ranges`.
|
553 |
+
|
554 |
+
If ``min`` or ``max`` are not passed, any value is accepted in that
|
555 |
+
direction. If ``min_open`` or ``max_open`` are enabled, the
|
556 |
+
corresponding boundary is not included in the range.
|
557 |
+
|
558 |
+
If ``clamp`` is enabled, a value outside the range is clamped to the
|
559 |
+
boundary instead of failing. This is not supported if either
|
560 |
+
boundary is marked ``open``.
|
561 |
+
|
562 |
+
.. versionchanged:: 8.0
|
563 |
+
Added the ``min_open`` and ``max_open`` parameters.
|
564 |
+
"""
|
565 |
+
|
566 |
+
name = "float range"
|
567 |
+
|
568 |
+
def __init__(
|
569 |
+
self,
|
570 |
+
min: t.Optional[float] = None,
|
571 |
+
max: t.Optional[float] = None,
|
572 |
+
min_open: bool = False,
|
573 |
+
max_open: bool = False,
|
574 |
+
clamp: bool = False,
|
575 |
+
) -> None:
|
576 |
+
super().__init__(
|
577 |
+
min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp
|
578 |
+
)
|
579 |
+
|
580 |
+
if (min_open or max_open) and clamp:
|
581 |
+
raise TypeError("Clamping is not supported for open bounds.")
|
582 |
+
|
583 |
+
def _clamp(self, bound: float, dir: "te.Literal[1, -1]", open: bool) -> float:
|
584 |
+
if not open:
|
585 |
+
return bound
|
586 |
+
|
587 |
+
# Could use Python 3.9's math.nextafter here, but clamping an
|
588 |
+
# open float range doesn't seem to be particularly useful. It's
|
589 |
+
# left up to the user to write a callback to do it if needed.
|
590 |
+
raise RuntimeError("Clamping is not supported for open bounds.")
|
591 |
+
|
592 |
+
|
593 |
+
class BoolParamType(ParamType):
|
594 |
+
name = "boolean"
|
595 |
+
|
596 |
+
def convert(
|
597 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
598 |
+
) -> t.Any:
|
599 |
+
if value in {False, True}:
|
600 |
+
return bool(value)
|
601 |
+
|
602 |
+
norm = value.strip().lower()
|
603 |
+
|
604 |
+
if norm in {"1", "true", "t", "yes", "y", "on"}:
|
605 |
+
return True
|
606 |
+
|
607 |
+
if norm in {"0", "false", "f", "no", "n", "off"}:
|
608 |
+
return False
|
609 |
+
|
610 |
+
self.fail(
|
611 |
+
_("{value!r} is not a valid boolean.").format(value=value), param, ctx
|
612 |
+
)
|
613 |
+
|
614 |
+
def __repr__(self) -> str:
|
615 |
+
return "BOOL"
|
616 |
+
|
617 |
+
|
618 |
+
class UUIDParameterType(ParamType):
|
619 |
+
name = "uuid"
|
620 |
+
|
621 |
+
def convert(
|
622 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
623 |
+
) -> t.Any:
|
624 |
+
import uuid
|
625 |
+
|
626 |
+
if isinstance(value, uuid.UUID):
|
627 |
+
return value
|
628 |
+
|
629 |
+
value = value.strip()
|
630 |
+
|
631 |
+
try:
|
632 |
+
return uuid.UUID(value)
|
633 |
+
except ValueError:
|
634 |
+
self.fail(
|
635 |
+
_("{value!r} is not a valid UUID.").format(value=value), param, ctx
|
636 |
+
)
|
637 |
+
|
638 |
+
def __repr__(self) -> str:
|
639 |
+
return "UUID"
|
640 |
+
|
641 |
+
|
642 |
+
class File(ParamType):
|
643 |
+
"""Declares a parameter to be a file for reading or writing. The file
|
644 |
+
is automatically closed once the context tears down (after the command
|
645 |
+
finished working).
|
646 |
+
|
647 |
+
Files can be opened for reading or writing. The special value ``-``
|
648 |
+
indicates stdin or stdout depending on the mode.
|
649 |
+
|
650 |
+
By default, the file is opened for reading text data, but it can also be
|
651 |
+
opened in binary mode or for writing. The encoding parameter can be used
|
652 |
+
to force a specific encoding.
|
653 |
+
|
654 |
+
The `lazy` flag controls if the file should be opened immediately or upon
|
655 |
+
first IO. The default is to be non-lazy for standard input and output
|
656 |
+
streams as well as files opened for reading, `lazy` otherwise. When opening a
|
657 |
+
file lazily for reading, it is still opened temporarily for validation, but
|
658 |
+
will not be held open until first IO. lazy is mainly useful when opening
|
659 |
+
for writing to avoid creating the file until it is needed.
|
660 |
+
|
661 |
+
Starting with Click 2.0, files can also be opened atomically in which
|
662 |
+
case all writes go into a separate file in the same folder and upon
|
663 |
+
completion the file will be moved over to the original location. This
|
664 |
+
is useful if a file regularly read by other users is modified.
|
665 |
+
|
666 |
+
See :ref:`file-args` for more information.
|
667 |
+
"""
|
668 |
+
|
669 |
+
name = "filename"
|
670 |
+
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
|
671 |
+
|
672 |
+
def __init__(
|
673 |
+
self,
|
674 |
+
mode: str = "r",
|
675 |
+
encoding: t.Optional[str] = None,
|
676 |
+
errors: t.Optional[str] = "strict",
|
677 |
+
lazy: t.Optional[bool] = None,
|
678 |
+
atomic: bool = False,
|
679 |
+
) -> None:
|
680 |
+
self.mode = mode
|
681 |
+
self.encoding = encoding
|
682 |
+
self.errors = errors
|
683 |
+
self.lazy = lazy
|
684 |
+
self.atomic = atomic
|
685 |
+
|
686 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
687 |
+
info_dict = super().to_info_dict()
|
688 |
+
info_dict.update(mode=self.mode, encoding=self.encoding)
|
689 |
+
return info_dict
|
690 |
+
|
691 |
+
def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool:
|
692 |
+
if self.lazy is not None:
|
693 |
+
return self.lazy
|
694 |
+
if os.fspath(value) == "-":
|
695 |
+
return False
|
696 |
+
elif "w" in self.mode:
|
697 |
+
return True
|
698 |
+
return False
|
699 |
+
|
700 |
+
def convert(
|
701 |
+
self,
|
702 |
+
value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]],
|
703 |
+
param: t.Optional["Parameter"],
|
704 |
+
ctx: t.Optional["Context"],
|
705 |
+
) -> t.IO[t.Any]:
|
706 |
+
if _is_file_like(value):
|
707 |
+
return value
|
708 |
+
|
709 |
+
value = t.cast("t.Union[str, os.PathLike[str]]", value)
|
710 |
+
|
711 |
+
try:
|
712 |
+
lazy = self.resolve_lazy_flag(value)
|
713 |
+
|
714 |
+
if lazy:
|
715 |
+
lf = LazyFile(
|
716 |
+
value, self.mode, self.encoding, self.errors, atomic=self.atomic
|
717 |
+
)
|
718 |
+
|
719 |
+
if ctx is not None:
|
720 |
+
ctx.call_on_close(lf.close_intelligently)
|
721 |
+
|
722 |
+
return t.cast(t.IO[t.Any], lf)
|
723 |
+
|
724 |
+
f, should_close = open_stream(
|
725 |
+
value, self.mode, self.encoding, self.errors, atomic=self.atomic
|
726 |
+
)
|
727 |
+
|
728 |
+
# If a context is provided, we automatically close the file
|
729 |
+
# at the end of the context execution (or flush out). If a
|
730 |
+
# context does not exist, it's the caller's responsibility to
|
731 |
+
# properly close the file. This for instance happens when the
|
732 |
+
# type is used with prompts.
|
733 |
+
if ctx is not None:
|
734 |
+
if should_close:
|
735 |
+
ctx.call_on_close(safecall(f.close))
|
736 |
+
else:
|
737 |
+
ctx.call_on_close(safecall(f.flush))
|
738 |
+
|
739 |
+
return f
|
740 |
+
except OSError as e: # noqa: B014
|
741 |
+
self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)
|
742 |
+
|
743 |
+
def shell_complete(
|
744 |
+
self, ctx: "Context", param: "Parameter", incomplete: str
|
745 |
+
) -> t.List["CompletionItem"]:
|
746 |
+
"""Return a special completion marker that tells the completion
|
747 |
+
system to use the shell to provide file path completions.
|
748 |
+
|
749 |
+
:param ctx: Invocation context for this command.
|
750 |
+
:param param: The parameter that is requesting completion.
|
751 |
+
:param incomplete: Value being completed. May be empty.
|
752 |
+
|
753 |
+
.. versionadded:: 8.0
|
754 |
+
"""
|
755 |
+
from click.shell_completion import CompletionItem
|
756 |
+
|
757 |
+
return [CompletionItem(incomplete, type="file")]
|
758 |
+
|
759 |
+
|
760 |
+
def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":
|
761 |
+
return hasattr(value, "read") or hasattr(value, "write")
|
762 |
+
|
763 |
+
|
764 |
+
class Path(ParamType):
|
765 |
+
"""The ``Path`` type is similar to the :class:`File` type, but
|
766 |
+
returns the filename instead of an open file. Various checks can be
|
767 |
+
enabled to validate the type of file and permissions.
|
768 |
+
|
769 |
+
:param exists: The file or directory needs to exist for the value to
|
770 |
+
be valid. If this is not set to ``True``, and the file does not
|
771 |
+
exist, then all further checks are silently skipped.
|
772 |
+
:param file_okay: Allow a file as a value.
|
773 |
+
:param dir_okay: Allow a directory as a value.
|
774 |
+
:param readable: if true, a readable check is performed.
|
775 |
+
:param writable: if true, a writable check is performed.
|
776 |
+
:param executable: if true, an executable check is performed.
|
777 |
+
:param resolve_path: Make the value absolute and resolve any
|
778 |
+
symlinks. A ``~`` is not expanded, as this is supposed to be
|
779 |
+
done by the shell only.
|
780 |
+
:param allow_dash: Allow a single dash as a value, which indicates
|
781 |
+
a standard stream (but does not open it). Use
|
782 |
+
:func:`~click.open_file` to handle opening this value.
|
783 |
+
:param path_type: Convert the incoming path value to this type. If
|
784 |
+
``None``, keep Python's default, which is ``str``. Useful to
|
785 |
+
convert to :class:`pathlib.Path`.
|
786 |
+
|
787 |
+
.. versionchanged:: 8.1
|
788 |
+
Added the ``executable`` parameter.
|
789 |
+
|
790 |
+
.. versionchanged:: 8.0
|
791 |
+
Allow passing ``path_type=pathlib.Path``.
|
792 |
+
|
793 |
+
.. versionchanged:: 6.0
|
794 |
+
Added the ``allow_dash`` parameter.
|
795 |
+
"""
|
796 |
+
|
797 |
+
envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
|
798 |
+
|
799 |
+
def __init__(
|
800 |
+
self,
|
801 |
+
exists: bool = False,
|
802 |
+
file_okay: bool = True,
|
803 |
+
dir_okay: bool = True,
|
804 |
+
writable: bool = False,
|
805 |
+
readable: bool = True,
|
806 |
+
resolve_path: bool = False,
|
807 |
+
allow_dash: bool = False,
|
808 |
+
path_type: t.Optional[t.Type[t.Any]] = None,
|
809 |
+
executable: bool = False,
|
810 |
+
):
|
811 |
+
self.exists = exists
|
812 |
+
self.file_okay = file_okay
|
813 |
+
self.dir_okay = dir_okay
|
814 |
+
self.readable = readable
|
815 |
+
self.writable = writable
|
816 |
+
self.executable = executable
|
817 |
+
self.resolve_path = resolve_path
|
818 |
+
self.allow_dash = allow_dash
|
819 |
+
self.type = path_type
|
820 |
+
|
821 |
+
if self.file_okay and not self.dir_okay:
|
822 |
+
self.name: str = _("file")
|
823 |
+
elif self.dir_okay and not self.file_okay:
|
824 |
+
self.name = _("directory")
|
825 |
+
else:
|
826 |
+
self.name = _("path")
|
827 |
+
|
828 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
829 |
+
info_dict = super().to_info_dict()
|
830 |
+
info_dict.update(
|
831 |
+
exists=self.exists,
|
832 |
+
file_okay=self.file_okay,
|
833 |
+
dir_okay=self.dir_okay,
|
834 |
+
writable=self.writable,
|
835 |
+
readable=self.readable,
|
836 |
+
allow_dash=self.allow_dash,
|
837 |
+
)
|
838 |
+
return info_dict
|
839 |
+
|
840 |
+
def coerce_path_result(
|
841 |
+
self, value: "t.Union[str, os.PathLike[str]]"
|
842 |
+
) -> "t.Union[str, bytes, os.PathLike[str]]":
|
843 |
+
if self.type is not None and not isinstance(value, self.type):
|
844 |
+
if self.type is str:
|
845 |
+
return os.fsdecode(value)
|
846 |
+
elif self.type is bytes:
|
847 |
+
return os.fsencode(value)
|
848 |
+
else:
|
849 |
+
return t.cast("os.PathLike[str]", self.type(value))
|
850 |
+
|
851 |
+
return value
|
852 |
+
|
853 |
+
def convert(
|
854 |
+
self,
|
855 |
+
value: "t.Union[str, os.PathLike[str]]",
|
856 |
+
param: t.Optional["Parameter"],
|
857 |
+
ctx: t.Optional["Context"],
|
858 |
+
) -> "t.Union[str, bytes, os.PathLike[str]]":
|
859 |
+
rv = value
|
860 |
+
|
861 |
+
is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")
|
862 |
+
|
863 |
+
if not is_dash:
|
864 |
+
if self.resolve_path:
|
865 |
+
# os.path.realpath doesn't resolve symlinks on Windows
|
866 |
+
# until Python 3.8. Use pathlib for now.
|
867 |
+
import pathlib
|
868 |
+
|
869 |
+
rv = os.fsdecode(pathlib.Path(rv).resolve())
|
870 |
+
|
871 |
+
try:
|
872 |
+
st = os.stat(rv)
|
873 |
+
except OSError:
|
874 |
+
if not self.exists:
|
875 |
+
return self.coerce_path_result(rv)
|
876 |
+
self.fail(
|
877 |
+
_("{name} {filename!r} does not exist.").format(
|
878 |
+
name=self.name.title(), filename=format_filename(value)
|
879 |
+
),
|
880 |
+
param,
|
881 |
+
ctx,
|
882 |
+
)
|
883 |
+
|
884 |
+
if not self.file_okay and stat.S_ISREG(st.st_mode):
|
885 |
+
self.fail(
|
886 |
+
_("{name} {filename!r} is a file.").format(
|
887 |
+
name=self.name.title(), filename=format_filename(value)
|
888 |
+
),
|
889 |
+
param,
|
890 |
+
ctx,
|
891 |
+
)
|
892 |
+
if not self.dir_okay and stat.S_ISDIR(st.st_mode):
|
893 |
+
self.fail(
|
894 |
+
_("{name} '{filename}' is a directory.").format(
|
895 |
+
name=self.name.title(), filename=format_filename(value)
|
896 |
+
),
|
897 |
+
param,
|
898 |
+
ctx,
|
899 |
+
)
|
900 |
+
|
901 |
+
if self.readable and not os.access(rv, os.R_OK):
|
902 |
+
self.fail(
|
903 |
+
_("{name} {filename!r} is not readable.").format(
|
904 |
+
name=self.name.title(), filename=format_filename(value)
|
905 |
+
),
|
906 |
+
param,
|
907 |
+
ctx,
|
908 |
+
)
|
909 |
+
|
910 |
+
if self.writable and not os.access(rv, os.W_OK):
|
911 |
+
self.fail(
|
912 |
+
_("{name} {filename!r} is not writable.").format(
|
913 |
+
name=self.name.title(), filename=format_filename(value)
|
914 |
+
),
|
915 |
+
param,
|
916 |
+
ctx,
|
917 |
+
)
|
918 |
+
|
919 |
+
if self.executable and not os.access(value, os.X_OK):
|
920 |
+
self.fail(
|
921 |
+
_("{name} {filename!r} is not executable.").format(
|
922 |
+
name=self.name.title(), filename=format_filename(value)
|
923 |
+
),
|
924 |
+
param,
|
925 |
+
ctx,
|
926 |
+
)
|
927 |
+
|
928 |
+
return self.coerce_path_result(rv)
|
929 |
+
|
930 |
+
def shell_complete(
|
931 |
+
self, ctx: "Context", param: "Parameter", incomplete: str
|
932 |
+
) -> t.List["CompletionItem"]:
|
933 |
+
"""Return a special completion marker that tells the completion
|
934 |
+
system to use the shell to provide path completions for only
|
935 |
+
directories or any paths.
|
936 |
+
|
937 |
+
:param ctx: Invocation context for this command.
|
938 |
+
:param param: The parameter that is requesting completion.
|
939 |
+
:param incomplete: Value being completed. May be empty.
|
940 |
+
|
941 |
+
.. versionadded:: 8.0
|
942 |
+
"""
|
943 |
+
from click.shell_completion import CompletionItem
|
944 |
+
|
945 |
+
type = "dir" if self.dir_okay and not self.file_okay else "file"
|
946 |
+
return [CompletionItem(incomplete, type=type)]
|
947 |
+
|
948 |
+
|
949 |
+
class Tuple(CompositeParamType):
|
950 |
+
"""The default behavior of Click is to apply a type on a value directly.
|
951 |
+
This works well in most cases, except for when `nargs` is set to a fixed
|
952 |
+
count and different types should be used for different items. In this
|
953 |
+
case the :class:`Tuple` type can be used. This type can only be used
|
954 |
+
if `nargs` is set to a fixed number.
|
955 |
+
|
956 |
+
For more information see :ref:`tuple-type`.
|
957 |
+
|
958 |
+
This can be selected by using a Python tuple literal as a type.
|
959 |
+
|
960 |
+
:param types: a list of types that should be used for the tuple items.
|
961 |
+
"""
|
962 |
+
|
963 |
+
def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:
|
964 |
+
self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types]
|
965 |
+
|
966 |
+
def to_info_dict(self) -> t.Dict[str, t.Any]:
|
967 |
+
info_dict = super().to_info_dict()
|
968 |
+
info_dict["types"] = [t.to_info_dict() for t in self.types]
|
969 |
+
return info_dict
|
970 |
+
|
971 |
+
@property
|
972 |
+
def name(self) -> str: # type: ignore
|
973 |
+
return f"<{' '.join(ty.name for ty in self.types)}>"
|
974 |
+
|
975 |
+
@property
|
976 |
+
def arity(self) -> int: # type: ignore
|
977 |
+
return len(self.types)
|
978 |
+
|
979 |
+
def convert(
|
980 |
+
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
|
981 |
+
) -> t.Any:
|
982 |
+
len_type = len(self.types)
|
983 |
+
len_value = len(value)
|
984 |
+
|
985 |
+
if len_value != len_type:
|
986 |
+
self.fail(
|
987 |
+
ngettext(
|
988 |
+
"{len_type} values are required, but {len_value} was given.",
|
989 |
+
"{len_type} values are required, but {len_value} were given.",
|
990 |
+
len_value,
|
991 |
+
).format(len_type=len_type, len_value=len_value),
|
992 |
+
param=param,
|
993 |
+
ctx=ctx,
|
994 |
+
)
|
995 |
+
|
996 |
+
return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))
|
997 |
+
|
998 |
+
|
999 |
+
def convert_type(ty: t.Optional[t.Any], default: t.Optional[t.Any] = None) -> ParamType:
|
1000 |
+
"""Find the most appropriate :class:`ParamType` for the given Python
|
1001 |
+
type. If the type isn't provided, it can be inferred from a default
|
1002 |
+
value.
|
1003 |
+
"""
|
1004 |
+
guessed_type = False
|
1005 |
+
|
1006 |
+
if ty is None and default is not None:
|
1007 |
+
if isinstance(default, (tuple, list)):
|
1008 |
+
# If the default is empty, ty will remain None and will
|
1009 |
+
# return STRING.
|
1010 |
+
if default:
|
1011 |
+
item = default[0]
|
1012 |
+
|
1013 |
+
# A tuple of tuples needs to detect the inner types.
|
1014 |
+
# Can't call convert recursively because that would
|
1015 |
+
# incorrectly unwind the tuple to a single type.
|
1016 |
+
if isinstance(item, (tuple, list)):
|
1017 |
+
ty = tuple(map(type, item))
|
1018 |
+
else:
|
1019 |
+
ty = type(item)
|
1020 |
+
else:
|
1021 |
+
ty = type(default)
|
1022 |
+
|
1023 |
+
guessed_type = True
|
1024 |
+
|
1025 |
+
if isinstance(ty, tuple):
|
1026 |
+
return Tuple(ty)
|
1027 |
+
|
1028 |
+
if isinstance(ty, ParamType):
|
1029 |
+
return ty
|
1030 |
+
|
1031 |
+
if ty is str or ty is None:
|
1032 |
+
return STRING
|
1033 |
+
|
1034 |
+
if ty is int:
|
1035 |
+
return INT
|
1036 |
+
|
1037 |
+
if ty is float:
|
1038 |
+
return FLOAT
|
1039 |
+
|
1040 |
+
if ty is bool:
|
1041 |
+
return BOOL
|
1042 |
+
|
1043 |
+
if guessed_type:
|
1044 |
+
return STRING
|
1045 |
+
|
1046 |
+
if __debug__:
|
1047 |
+
try:
|
1048 |
+
if issubclass(ty, ParamType):
|
1049 |
+
raise AssertionError(
|
1050 |
+
f"Attempted to use an uninstantiated parameter type ({ty})."
|
1051 |
+
)
|
1052 |
+
except TypeError:
|
1053 |
+
# ty is an instance (correct), so issubclass fails.
|
1054 |
+
pass
|
1055 |
+
|
1056 |
+
return FuncParamType(ty)
|
1057 |
+
|
1058 |
+
|
1059 |
+
#: A dummy parameter type that just does nothing. From a user's
|
1060 |
+
#: perspective this appears to just be the same as `STRING` but
|
1061 |
+
#: internally no string conversion takes place if the input was bytes.
|
1062 |
+
#: This is usually useful when working with file paths as they can
|
1063 |
+
#: appear in bytes and unicode.
|
1064 |
+
#:
|
1065 |
+
#: For path related uses the :class:`Path` type is a better choice but
|
1066 |
+
#: there are situations where an unprocessed type is useful which is why
|
1067 |
+
#: it is is provided.
|
1068 |
+
#:
|
1069 |
+
#: .. versionadded:: 4.0
|
1070 |
+
UNPROCESSED = UnprocessedParamType()
|
1071 |
+
|
1072 |
+
#: A unicode string parameter type which is the implicit default. This
|
1073 |
+
#: can also be selected by using ``str`` as type.
|
1074 |
+
STRING = StringParamType()
|
1075 |
+
|
1076 |
+
#: An integer parameter. This can also be selected by using ``int`` as
|
1077 |
+
#: type.
|
1078 |
+
INT = IntParamType()
|
1079 |
+
|
1080 |
+
#: A floating point value parameter. This can also be selected by using
|
1081 |
+
#: ``float`` as type.
|
1082 |
+
FLOAT = FloatParamType()
|
1083 |
+
|
1084 |
+
#: A boolean parameter. This is the default for boolean flags. This can
|
1085 |
+
#: also be selected by using ``bool`` as a type.
|
1086 |
+
BOOL = BoolParamType()
|
1087 |
+
|
1088 |
+
#: A UUID parameter.
|
1089 |
+
UUID = UUIDParameterType()
|
venv/lib/python3.10/site-packages/click/utils.py
ADDED
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import re
|
3 |
+
import sys
|
4 |
+
import typing as t
|
5 |
+
from functools import update_wrapper
|
6 |
+
from types import ModuleType
|
7 |
+
from types import TracebackType
|
8 |
+
|
9 |
+
from ._compat import _default_text_stderr
|
10 |
+
from ._compat import _default_text_stdout
|
11 |
+
from ._compat import _find_binary_writer
|
12 |
+
from ._compat import auto_wrap_for_ansi
|
13 |
+
from ._compat import binary_streams
|
14 |
+
from ._compat import open_stream
|
15 |
+
from ._compat import should_strip_ansi
|
16 |
+
from ._compat import strip_ansi
|
17 |
+
from ._compat import text_streams
|
18 |
+
from ._compat import WIN
|
19 |
+
from .globals import resolve_color_default
|
20 |
+
|
21 |
+
if t.TYPE_CHECKING:
|
22 |
+
import typing_extensions as te
|
23 |
+
|
24 |
+
P = te.ParamSpec("P")
|
25 |
+
|
26 |
+
R = t.TypeVar("R")
|
27 |
+
|
28 |
+
|
29 |
+
def _posixify(name: str) -> str:
|
30 |
+
return "-".join(name.split()).lower()
|
31 |
+
|
32 |
+
|
33 |
+
def safecall(func: "t.Callable[P, R]") -> "t.Callable[P, t.Optional[R]]":
|
34 |
+
"""Wraps a function so that it swallows exceptions."""
|
35 |
+
|
36 |
+
def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Optional[R]:
|
37 |
+
try:
|
38 |
+
return func(*args, **kwargs)
|
39 |
+
except Exception:
|
40 |
+
pass
|
41 |
+
return None
|
42 |
+
|
43 |
+
return update_wrapper(wrapper, func)
|
44 |
+
|
45 |
+
|
46 |
+
def make_str(value: t.Any) -> str:
|
47 |
+
"""Converts a value into a valid string."""
|
48 |
+
if isinstance(value, bytes):
|
49 |
+
try:
|
50 |
+
return value.decode(sys.getfilesystemencoding())
|
51 |
+
except UnicodeError:
|
52 |
+
return value.decode("utf-8", "replace")
|
53 |
+
return str(value)
|
54 |
+
|
55 |
+
|
56 |
+
def make_default_short_help(help: str, max_length: int = 45) -> str:
|
57 |
+
"""Returns a condensed version of help string."""
|
58 |
+
# Consider only the first paragraph.
|
59 |
+
paragraph_end = help.find("\n\n")
|
60 |
+
|
61 |
+
if paragraph_end != -1:
|
62 |
+
help = help[:paragraph_end]
|
63 |
+
|
64 |
+
# Collapse newlines, tabs, and spaces.
|
65 |
+
words = help.split()
|
66 |
+
|
67 |
+
if not words:
|
68 |
+
return ""
|
69 |
+
|
70 |
+
# The first paragraph started with a "no rewrap" marker, ignore it.
|
71 |
+
if words[0] == "\b":
|
72 |
+
words = words[1:]
|
73 |
+
|
74 |
+
total_length = 0
|
75 |
+
last_index = len(words) - 1
|
76 |
+
|
77 |
+
for i, word in enumerate(words):
|
78 |
+
total_length += len(word) + (i > 0)
|
79 |
+
|
80 |
+
if total_length > max_length: # too long, truncate
|
81 |
+
break
|
82 |
+
|
83 |
+
if word[-1] == ".": # sentence end, truncate without "..."
|
84 |
+
return " ".join(words[: i + 1])
|
85 |
+
|
86 |
+
if total_length == max_length and i != last_index:
|
87 |
+
break # not at sentence end, truncate with "..."
|
88 |
+
else:
|
89 |
+
return " ".join(words) # no truncation needed
|
90 |
+
|
91 |
+
# Account for the length of the suffix.
|
92 |
+
total_length += len("...")
|
93 |
+
|
94 |
+
# remove words until the length is short enough
|
95 |
+
while i > 0:
|
96 |
+
total_length -= len(words[i]) + (i > 0)
|
97 |
+
|
98 |
+
if total_length <= max_length:
|
99 |
+
break
|
100 |
+
|
101 |
+
i -= 1
|
102 |
+
|
103 |
+
return " ".join(words[:i]) + "..."
|
104 |
+
|
105 |
+
|
106 |
+
class LazyFile:
|
107 |
+
"""A lazy file works like a regular file but it does not fully open
|
108 |
+
the file but it does perform some basic checks early to see if the
|
109 |
+
filename parameter does make sense. This is useful for safely opening
|
110 |
+
files for writing.
|
111 |
+
"""
|
112 |
+
|
113 |
+
def __init__(
|
114 |
+
self,
|
115 |
+
filename: t.Union[str, "os.PathLike[str]"],
|
116 |
+
mode: str = "r",
|
117 |
+
encoding: t.Optional[str] = None,
|
118 |
+
errors: t.Optional[str] = "strict",
|
119 |
+
atomic: bool = False,
|
120 |
+
):
|
121 |
+
self.name: str = os.fspath(filename)
|
122 |
+
self.mode = mode
|
123 |
+
self.encoding = encoding
|
124 |
+
self.errors = errors
|
125 |
+
self.atomic = atomic
|
126 |
+
self._f: t.Optional[t.IO[t.Any]]
|
127 |
+
self.should_close: bool
|
128 |
+
|
129 |
+
if self.name == "-":
|
130 |
+
self._f, self.should_close = open_stream(filename, mode, encoding, errors)
|
131 |
+
else:
|
132 |
+
if "r" in mode:
|
133 |
+
# Open and close the file in case we're opening it for
|
134 |
+
# reading so that we can catch at least some errors in
|
135 |
+
# some cases early.
|
136 |
+
open(filename, mode).close()
|
137 |
+
self._f = None
|
138 |
+
self.should_close = True
|
139 |
+
|
140 |
+
def __getattr__(self, name: str) -> t.Any:
|
141 |
+
return getattr(self.open(), name)
|
142 |
+
|
143 |
+
def __repr__(self) -> str:
|
144 |
+
if self._f is not None:
|
145 |
+
return repr(self._f)
|
146 |
+
return f"<unopened file '{format_filename(self.name)}' {self.mode}>"
|
147 |
+
|
148 |
+
def open(self) -> t.IO[t.Any]:
|
149 |
+
"""Opens the file if it's not yet open. This call might fail with
|
150 |
+
a :exc:`FileError`. Not handling this error will produce an error
|
151 |
+
that Click shows.
|
152 |
+
"""
|
153 |
+
if self._f is not None:
|
154 |
+
return self._f
|
155 |
+
try:
|
156 |
+
rv, self.should_close = open_stream(
|
157 |
+
self.name, self.mode, self.encoding, self.errors, atomic=self.atomic
|
158 |
+
)
|
159 |
+
except OSError as e: # noqa: E402
|
160 |
+
from .exceptions import FileError
|
161 |
+
|
162 |
+
raise FileError(self.name, hint=e.strerror) from e
|
163 |
+
self._f = rv
|
164 |
+
return rv
|
165 |
+
|
166 |
+
def close(self) -> None:
|
167 |
+
"""Closes the underlying file, no matter what."""
|
168 |
+
if self._f is not None:
|
169 |
+
self._f.close()
|
170 |
+
|
171 |
+
def close_intelligently(self) -> None:
|
172 |
+
"""This function only closes the file if it was opened by the lazy
|
173 |
+
file wrapper. For instance this will never close stdin.
|
174 |
+
"""
|
175 |
+
if self.should_close:
|
176 |
+
self.close()
|
177 |
+
|
178 |
+
def __enter__(self) -> "LazyFile":
|
179 |
+
return self
|
180 |
+
|
181 |
+
def __exit__(
|
182 |
+
self,
|
183 |
+
exc_type: t.Optional[t.Type[BaseException]],
|
184 |
+
exc_value: t.Optional[BaseException],
|
185 |
+
tb: t.Optional[TracebackType],
|
186 |
+
) -> None:
|
187 |
+
self.close_intelligently()
|
188 |
+
|
189 |
+
def __iter__(self) -> t.Iterator[t.AnyStr]:
|
190 |
+
self.open()
|
191 |
+
return iter(self._f) # type: ignore
|
192 |
+
|
193 |
+
|
194 |
+
class KeepOpenFile:
|
195 |
+
def __init__(self, file: t.IO[t.Any]) -> None:
|
196 |
+
self._file: t.IO[t.Any] = file
|
197 |
+
|
198 |
+
def __getattr__(self, name: str) -> t.Any:
|
199 |
+
return getattr(self._file, name)
|
200 |
+
|
201 |
+
def __enter__(self) -> "KeepOpenFile":
|
202 |
+
return self
|
203 |
+
|
204 |
+
def __exit__(
|
205 |
+
self,
|
206 |
+
exc_type: t.Optional[t.Type[BaseException]],
|
207 |
+
exc_value: t.Optional[BaseException],
|
208 |
+
tb: t.Optional[TracebackType],
|
209 |
+
) -> None:
|
210 |
+
pass
|
211 |
+
|
212 |
+
def __repr__(self) -> str:
|
213 |
+
return repr(self._file)
|
214 |
+
|
215 |
+
def __iter__(self) -> t.Iterator[t.AnyStr]:
|
216 |
+
return iter(self._file)
|
217 |
+
|
218 |
+
|
219 |
+
def echo(
|
220 |
+
message: t.Optional[t.Any] = None,
|
221 |
+
file: t.Optional[t.IO[t.Any]] = None,
|
222 |
+
nl: bool = True,
|
223 |
+
err: bool = False,
|
224 |
+
color: t.Optional[bool] = None,
|
225 |
+
) -> None:
|
226 |
+
"""Print a message and newline to stdout or a file. This should be
|
227 |
+
used instead of :func:`print` because it provides better support
|
228 |
+
for different data, files, and environments.
|
229 |
+
|
230 |
+
Compared to :func:`print`, this does the following:
|
231 |
+
|
232 |
+
- Ensures that the output encoding is not misconfigured on Linux.
|
233 |
+
- Supports Unicode in the Windows console.
|
234 |
+
- Supports writing to binary outputs, and supports writing bytes
|
235 |
+
to text outputs.
|
236 |
+
- Supports colors and styles on Windows.
|
237 |
+
- Removes ANSI color and style codes if the output does not look
|
238 |
+
like an interactive terminal.
|
239 |
+
- Always flushes the output.
|
240 |
+
|
241 |
+
:param message: The string or bytes to output. Other objects are
|
242 |
+
converted to strings.
|
243 |
+
:param file: The file to write to. Defaults to ``stdout``.
|
244 |
+
:param err: Write to ``stderr`` instead of ``stdout``.
|
245 |
+
:param nl: Print a newline after the message. Enabled by default.
|
246 |
+
:param color: Force showing or hiding colors and other styles. By
|
247 |
+
default Click will remove color if the output does not look like
|
248 |
+
an interactive terminal.
|
249 |
+
|
250 |
+
.. versionchanged:: 6.0
|
251 |
+
Support Unicode output on the Windows console. Click does not
|
252 |
+
modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``
|
253 |
+
will still not support Unicode.
|
254 |
+
|
255 |
+
.. versionchanged:: 4.0
|
256 |
+
Added the ``color`` parameter.
|
257 |
+
|
258 |
+
.. versionadded:: 3.0
|
259 |
+
Added the ``err`` parameter.
|
260 |
+
|
261 |
+
.. versionchanged:: 2.0
|
262 |
+
Support colors on Windows if colorama is installed.
|
263 |
+
"""
|
264 |
+
if file is None:
|
265 |
+
if err:
|
266 |
+
file = _default_text_stderr()
|
267 |
+
else:
|
268 |
+
file = _default_text_stdout()
|
269 |
+
|
270 |
+
# There are no standard streams attached to write to. For example,
|
271 |
+
# pythonw on Windows.
|
272 |
+
if file is None:
|
273 |
+
return
|
274 |
+
|
275 |
+
# Convert non bytes/text into the native string type.
|
276 |
+
if message is not None and not isinstance(message, (str, bytes, bytearray)):
|
277 |
+
out: t.Optional[t.Union[str, bytes]] = str(message)
|
278 |
+
else:
|
279 |
+
out = message
|
280 |
+
|
281 |
+
if nl:
|
282 |
+
out = out or ""
|
283 |
+
if isinstance(out, str):
|
284 |
+
out += "\n"
|
285 |
+
else:
|
286 |
+
out += b"\n"
|
287 |
+
|
288 |
+
if not out:
|
289 |
+
file.flush()
|
290 |
+
return
|
291 |
+
|
292 |
+
# If there is a message and the value looks like bytes, we manually
|
293 |
+
# need to find the binary stream and write the message in there.
|
294 |
+
# This is done separately so that most stream types will work as you
|
295 |
+
# would expect. Eg: you can write to StringIO for other cases.
|
296 |
+
if isinstance(out, (bytes, bytearray)):
|
297 |
+
binary_file = _find_binary_writer(file)
|
298 |
+
|
299 |
+
if binary_file is not None:
|
300 |
+
file.flush()
|
301 |
+
binary_file.write(out)
|
302 |
+
binary_file.flush()
|
303 |
+
return
|
304 |
+
|
305 |
+
# ANSI style code support. For no message or bytes, nothing happens.
|
306 |
+
# When outputting to a file instead of a terminal, strip codes.
|
307 |
+
else:
|
308 |
+
color = resolve_color_default(color)
|
309 |
+
|
310 |
+
if should_strip_ansi(file, color):
|
311 |
+
out = strip_ansi(out)
|
312 |
+
elif WIN:
|
313 |
+
if auto_wrap_for_ansi is not None:
|
314 |
+
file = auto_wrap_for_ansi(file) # type: ignore
|
315 |
+
elif not color:
|
316 |
+
out = strip_ansi(out)
|
317 |
+
|
318 |
+
file.write(out) # type: ignore
|
319 |
+
file.flush()
|
320 |
+
|
321 |
+
|
322 |
+
def get_binary_stream(name: "te.Literal['stdin', 'stdout', 'stderr']") -> t.BinaryIO:
|
323 |
+
"""Returns a system stream for byte processing.
|
324 |
+
|
325 |
+
:param name: the name of the stream to open. Valid names are ``'stdin'``,
|
326 |
+
``'stdout'`` and ``'stderr'``
|
327 |
+
"""
|
328 |
+
opener = binary_streams.get(name)
|
329 |
+
if opener is None:
|
330 |
+
raise TypeError(f"Unknown standard stream '{name}'")
|
331 |
+
return opener()
|
332 |
+
|
333 |
+
|
334 |
+
def get_text_stream(
|
335 |
+
name: "te.Literal['stdin', 'stdout', 'stderr']",
|
336 |
+
encoding: t.Optional[str] = None,
|
337 |
+
errors: t.Optional[str] = "strict",
|
338 |
+
) -> t.TextIO:
|
339 |
+
"""Returns a system stream for text processing. This usually returns
|
340 |
+
a wrapped stream around a binary stream returned from
|
341 |
+
:func:`get_binary_stream` but it also can take shortcuts for already
|
342 |
+
correctly configured streams.
|
343 |
+
|
344 |
+
:param name: the name of the stream to open. Valid names are ``'stdin'``,
|
345 |
+
``'stdout'`` and ``'stderr'``
|
346 |
+
:param encoding: overrides the detected default encoding.
|
347 |
+
:param errors: overrides the default error mode.
|
348 |
+
"""
|
349 |
+
opener = text_streams.get(name)
|
350 |
+
if opener is None:
|
351 |
+
raise TypeError(f"Unknown standard stream '{name}'")
|
352 |
+
return opener(encoding, errors)
|
353 |
+
|
354 |
+
|
355 |
+
def open_file(
|
356 |
+
filename: str,
|
357 |
+
mode: str = "r",
|
358 |
+
encoding: t.Optional[str] = None,
|
359 |
+
errors: t.Optional[str] = "strict",
|
360 |
+
lazy: bool = False,
|
361 |
+
atomic: bool = False,
|
362 |
+
) -> t.IO[t.Any]:
|
363 |
+
"""Open a file, with extra behavior to handle ``'-'`` to indicate
|
364 |
+
a standard stream, lazy open on write, and atomic write. Similar to
|
365 |
+
the behavior of the :class:`~click.File` param type.
|
366 |
+
|
367 |
+
If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is
|
368 |
+
wrapped so that using it in a context manager will not close it.
|
369 |
+
This makes it possible to use the function without accidentally
|
370 |
+
closing a standard stream:
|
371 |
+
|
372 |
+
.. code-block:: python
|
373 |
+
|
374 |
+
with open_file(filename) as f:
|
375 |
+
...
|
376 |
+
|
377 |
+
:param filename: The name of the file to open, or ``'-'`` for
|
378 |
+
``stdin``/``stdout``.
|
379 |
+
:param mode: The mode in which to open the file.
|
380 |
+
:param encoding: The encoding to decode or encode a file opened in
|
381 |
+
text mode.
|
382 |
+
:param errors: The error handling mode.
|
383 |
+
:param lazy: Wait to open the file until it is accessed. For read
|
384 |
+
mode, the file is temporarily opened to raise access errors
|
385 |
+
early, then closed until it is read again.
|
386 |
+
:param atomic: Write to a temporary file and replace the given file
|
387 |
+
on close.
|
388 |
+
|
389 |
+
.. versionadded:: 3.0
|
390 |
+
"""
|
391 |
+
if lazy:
|
392 |
+
return t.cast(
|
393 |
+
t.IO[t.Any], LazyFile(filename, mode, encoding, errors, atomic=atomic)
|
394 |
+
)
|
395 |
+
|
396 |
+
f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
|
397 |
+
|
398 |
+
if not should_close:
|
399 |
+
f = t.cast(t.IO[t.Any], KeepOpenFile(f))
|
400 |
+
|
401 |
+
return f
|
402 |
+
|
403 |
+
|
404 |
+
def format_filename(
|
405 |
+
filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",
|
406 |
+
shorten: bool = False,
|
407 |
+
) -> str:
|
408 |
+
"""Format a filename as a string for display. Ensures the filename can be
|
409 |
+
displayed by replacing any invalid bytes or surrogate escapes in the name
|
410 |
+
with the replacement character ``οΏ½``.
|
411 |
+
|
412 |
+
Invalid bytes or surrogate escapes will raise an error when written to a
|
413 |
+
stream with ``errors="strict". This will typically happen with ``stdout``
|
414 |
+
when the locale is something like ``en_GB.UTF-8``.
|
415 |
+
|
416 |
+
Many scenarios *are* safe to write surrogates though, due to PEP 538 and
|
417 |
+
PEP 540, including:
|
418 |
+
|
419 |
+
- Writing to ``stderr``, which uses ``errors="backslashreplace"``.
|
420 |
+
- The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens
|
421 |
+
stdout and stderr with ``errors="surrogateescape"``.
|
422 |
+
- None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.
|
423 |
+
- Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.
|
424 |
+
Python opens stdout and stderr with ``errors="surrogateescape"``.
|
425 |
+
|
426 |
+
:param filename: formats a filename for UI display. This will also convert
|
427 |
+
the filename into unicode without failing.
|
428 |
+
:param shorten: this optionally shortens the filename to strip of the
|
429 |
+
path that leads up to it.
|
430 |
+
"""
|
431 |
+
if shorten:
|
432 |
+
filename = os.path.basename(filename)
|
433 |
+
else:
|
434 |
+
filename = os.fspath(filename)
|
435 |
+
|
436 |
+
if isinstance(filename, bytes):
|
437 |
+
filename = filename.decode(sys.getfilesystemencoding(), "replace")
|
438 |
+
else:
|
439 |
+
filename = filename.encode("utf-8", "surrogateescape").decode(
|
440 |
+
"utf-8", "replace"
|
441 |
+
)
|
442 |
+
|
443 |
+
return filename
|
444 |
+
|
445 |
+
|
446 |
+
def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
|
447 |
+
r"""Returns the config folder for the application. The default behavior
|
448 |
+
is to return whatever is most appropriate for the operating system.
|
449 |
+
|
450 |
+
To give you an idea, for an app called ``"Foo Bar"``, something like
|
451 |
+
the following folders could be returned:
|
452 |
+
|
453 |
+
Mac OS X:
|
454 |
+
``~/Library/Application Support/Foo Bar``
|
455 |
+
Mac OS X (POSIX):
|
456 |
+
``~/.foo-bar``
|
457 |
+
Unix:
|
458 |
+
``~/.config/foo-bar``
|
459 |
+
Unix (POSIX):
|
460 |
+
``~/.foo-bar``
|
461 |
+
Windows (roaming):
|
462 |
+
``C:\Users\<user>\AppData\Roaming\Foo Bar``
|
463 |
+
Windows (not roaming):
|
464 |
+
``C:\Users\<user>\AppData\Local\Foo Bar``
|
465 |
+
|
466 |
+
.. versionadded:: 2.0
|
467 |
+
|
468 |
+
:param app_name: the application name. This should be properly capitalized
|
469 |
+
and can contain whitespace.
|
470 |
+
:param roaming: controls if the folder should be roaming or not on Windows.
|
471 |
+
Has no effect otherwise.
|
472 |
+
:param force_posix: if this is set to `True` then on any POSIX system the
|
473 |
+
folder will be stored in the home folder with a leading
|
474 |
+
dot instead of the XDG config home or darwin's
|
475 |
+
application support folder.
|
476 |
+
"""
|
477 |
+
if WIN:
|
478 |
+
key = "APPDATA" if roaming else "LOCALAPPDATA"
|
479 |
+
folder = os.environ.get(key)
|
480 |
+
if folder is None:
|
481 |
+
folder = os.path.expanduser("~")
|
482 |
+
return os.path.join(folder, app_name)
|
483 |
+
if force_posix:
|
484 |
+
return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))
|
485 |
+
if sys.platform == "darwin":
|
486 |
+
return os.path.join(
|
487 |
+
os.path.expanduser("~/Library/Application Support"), app_name
|
488 |
+
)
|
489 |
+
return os.path.join(
|
490 |
+
os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),
|
491 |
+
_posixify(app_name),
|
492 |
+
)
|
493 |
+
|
494 |
+
|
495 |
+
class PacifyFlushWrapper:
|
496 |
+
"""This wrapper is used to catch and suppress BrokenPipeErrors resulting
|
497 |
+
from ``.flush()`` being called on broken pipe during the shutdown/final-GC
|
498 |
+
of the Python interpreter. Notably ``.flush()`` is always called on
|
499 |
+
``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any
|
500 |
+
other cleanup code, and the case where the underlying file is not a broken
|
501 |
+
pipe, all calls and attributes are proxied.
|
502 |
+
"""
|
503 |
+
|
504 |
+
def __init__(self, wrapped: t.IO[t.Any]) -> None:
|
505 |
+
self.wrapped = wrapped
|
506 |
+
|
507 |
+
def flush(self) -> None:
|
508 |
+
try:
|
509 |
+
self.wrapped.flush()
|
510 |
+
except OSError as e:
|
511 |
+
import errno
|
512 |
+
|
513 |
+
if e.errno != errno.EPIPE:
|
514 |
+
raise
|
515 |
+
|
516 |
+
def __getattr__(self, attr: str) -> t.Any:
|
517 |
+
return getattr(self.wrapped, attr)
|
518 |
+
|
519 |
+
|
520 |
+
def _detect_program_name(
|
521 |
+
path: t.Optional[str] = None, _main: t.Optional[ModuleType] = None
|
522 |
+
) -> str:
|
523 |
+
"""Determine the command used to run the program, for use in help
|
524 |
+
text. If a file or entry point was executed, the file name is
|
525 |
+
returned. If ``python -m`` was used to execute a module or package,
|
526 |
+
``python -m name`` is returned.
|
527 |
+
|
528 |
+
This doesn't try to be too precise, the goal is to give a concise
|
529 |
+
name for help text. Files are only shown as their name without the
|
530 |
+
path. ``python`` is only shown for modules, and the full path to
|
531 |
+
``sys.executable`` is not shown.
|
532 |
+
|
533 |
+
:param path: The Python file being executed. Python puts this in
|
534 |
+
``sys.argv[0]``, which is used by default.
|
535 |
+
:param _main: The ``__main__`` module. This should only be passed
|
536 |
+
during internal testing.
|
537 |
+
|
538 |
+
.. versionadded:: 8.0
|
539 |
+
Based on command args detection in the Werkzeug reloader.
|
540 |
+
|
541 |
+
:meta private:
|
542 |
+
"""
|
543 |
+
if _main is None:
|
544 |
+
_main = sys.modules["__main__"]
|
545 |
+
|
546 |
+
if not path:
|
547 |
+
path = sys.argv[0]
|
548 |
+
|
549 |
+
# The value of __package__ indicates how Python was called. It may
|
550 |
+
# not exist if a setuptools script is installed as an egg. It may be
|
551 |
+
# set incorrectly for entry points created with pip on Windows.
|
552 |
+
# It is set to "" inside a Shiv or PEX zipapp.
|
553 |
+
if getattr(_main, "__package__", None) in {None, ""} or (
|
554 |
+
os.name == "nt"
|
555 |
+
and _main.__package__ == ""
|
556 |
+
and not os.path.exists(path)
|
557 |
+
and os.path.exists(f"{path}.exe")
|
558 |
+
):
|
559 |
+
# Executed a file, like "python app.py".
|
560 |
+
return os.path.basename(path)
|
561 |
+
|
562 |
+
# Executed a module, like "python -m example".
|
563 |
+
# Rewritten by Python from "-m script" to "/path/to/script.py".
|
564 |
+
# Need to look at main module to determine how it was executed.
|
565 |
+
py_module = t.cast(str, _main.__package__)
|
566 |
+
name = os.path.splitext(os.path.basename(path))[0]
|
567 |
+
|
568 |
+
# A submodule like "example.cli".
|
569 |
+
if name != "__main__":
|
570 |
+
py_module = f"{py_module}.{name}"
|
571 |
+
|
572 |
+
return f"python -m {py_module.lstrip('.')}"
|
573 |
+
|
574 |
+
|
575 |
+
def _expand_args(
|
576 |
+
args: t.Iterable[str],
|
577 |
+
*,
|
578 |
+
user: bool = True,
|
579 |
+
env: bool = True,
|
580 |
+
glob_recursive: bool = True,
|
581 |
+
) -> t.List[str]:
|
582 |
+
"""Simulate Unix shell expansion with Python functions.
|
583 |
+
|
584 |
+
See :func:`glob.glob`, :func:`os.path.expanduser`, and
|
585 |
+
:func:`os.path.expandvars`.
|
586 |
+
|
587 |
+
This is intended for use on Windows, where the shell does not do any
|
588 |
+
expansion. It may not exactly match what a Unix shell would do.
|
589 |
+
|
590 |
+
:param args: List of command line arguments to expand.
|
591 |
+
:param user: Expand user home directory.
|
592 |
+
:param env: Expand environment variables.
|
593 |
+
:param glob_recursive: ``**`` matches directories recursively.
|
594 |
+
|
595 |
+
.. versionchanged:: 8.1
|
596 |
+
Invalid glob patterns are treated as empty expansions rather
|
597 |
+
than raising an error.
|
598 |
+
|
599 |
+
.. versionadded:: 8.0
|
600 |
+
|
601 |
+
:meta private:
|
602 |
+
"""
|
603 |
+
from glob import glob
|
604 |
+
|
605 |
+
out = []
|
606 |
+
|
607 |
+
for arg in args:
|
608 |
+
if user:
|
609 |
+
arg = os.path.expanduser(arg)
|
610 |
+
|
611 |
+
if env:
|
612 |
+
arg = os.path.expandvars(arg)
|
613 |
+
|
614 |
+
try:
|
615 |
+
matches = glob(arg, recursive=glob_recursive)
|
616 |
+
except re.error:
|
617 |
+
matches = []
|
618 |
+
|
619 |
+
if not matches:
|
620 |
+
out.append(arg)
|
621 |
+
else:
|
622 |
+
out.extend(matches)
|
623 |
+
|
624 |
+
return out
|
venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/INSTALLER
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pip
|
venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/METADATA
ADDED
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Metadata-Version: 2.1
|
2 |
+
Name: colorama
|
3 |
+
Version: 0.4.6
|
4 |
+
Summary: Cross-platform colored terminal text.
|
5 |
+
Project-URL: Homepage, https://github.com/tartley/colorama
|
6 |
+
Author-email: Jonathan Hartley <[email protected]>
|
7 |
+
License-File: LICENSE.txt
|
8 |
+
Keywords: ansi,color,colour,crossplatform,terminal,text,windows,xplatform
|
9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
10 |
+
Classifier: Environment :: Console
|
11 |
+
Classifier: Intended Audience :: Developers
|
12 |
+
Classifier: License :: OSI Approved :: BSD License
|
13 |
+
Classifier: Operating System :: OS Independent
|
14 |
+
Classifier: Programming Language :: Python
|
15 |
+
Classifier: Programming Language :: Python :: 2
|
16 |
+
Classifier: Programming Language :: Python :: 2.7
|
17 |
+
Classifier: Programming Language :: Python :: 3
|
18 |
+
Classifier: Programming Language :: Python :: 3.7
|
19 |
+
Classifier: Programming Language :: Python :: 3.8
|
20 |
+
Classifier: Programming Language :: Python :: 3.9
|
21 |
+
Classifier: Programming Language :: Python :: 3.10
|
22 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
23 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
24 |
+
Classifier: Topic :: Terminals
|
25 |
+
Requires-Python: !=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7
|
26 |
+
Description-Content-Type: text/x-rst
|
27 |
+
|
28 |
+
.. image:: https://img.shields.io/pypi/v/colorama.svg
|
29 |
+
:target: https://pypi.org/project/colorama/
|
30 |
+
:alt: Latest Version
|
31 |
+
|
32 |
+
.. image:: https://img.shields.io/pypi/pyversions/colorama.svg
|
33 |
+
:target: https://pypi.org/project/colorama/
|
34 |
+
:alt: Supported Python versions
|
35 |
+
|
36 |
+
.. image:: https://github.com/tartley/colorama/actions/workflows/test.yml/badge.svg
|
37 |
+
:target: https://github.com/tartley/colorama/actions/workflows/test.yml
|
38 |
+
:alt: Build Status
|
39 |
+
|
40 |
+
Colorama
|
41 |
+
========
|
42 |
+
|
43 |
+
Makes ANSI escape character sequences (for producing colored terminal text and
|
44 |
+
cursor positioning) work under MS Windows.
|
45 |
+
|
46 |
+
.. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif
|
47 |
+
:target: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=2MZ9D2GMLYCUJ&item_name=Colorama¤cy_code=USD
|
48 |
+
:alt: Donate with Paypal
|
49 |
+
|
50 |
+
`PyPI for releases <https://pypi.org/project/colorama/>`_ |
|
51 |
+
`Github for source <https://github.com/tartley/colorama>`_ |
|
52 |
+
`Colorama for enterprise on Tidelift <https://github.com/tartley/colorama/blob/master/ENTERPRISE.md>`_
|
53 |
+
|
54 |
+
If you find Colorama useful, please |donate| to the authors. Thank you!
|
55 |
+
|
56 |
+
Installation
|
57 |
+
------------
|
58 |
+
|
59 |
+
Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8.
|
60 |
+
|
61 |
+
No requirements other than the standard library.
|
62 |
+
|
63 |
+
.. code-block:: bash
|
64 |
+
|
65 |
+
pip install colorama
|
66 |
+
# or
|
67 |
+
conda install -c anaconda colorama
|
68 |
+
|
69 |
+
Description
|
70 |
+
-----------
|
71 |
+
|
72 |
+
ANSI escape character sequences have long been used to produce colored terminal
|
73 |
+
text and cursor positioning on Unix and Macs. Colorama makes this work on
|
74 |
+
Windows, too, by wrapping ``stdout``, stripping ANSI sequences it finds (which
|
75 |
+
would appear as gobbledygook in the output), and converting them into the
|
76 |
+
appropriate win32 calls to modify the state of the terminal. On other platforms,
|
77 |
+
Colorama does nothing.
|
78 |
+
|
79 |
+
This has the upshot of providing a simple cross-platform API for printing
|
80 |
+
colored terminal text from Python, and has the happy side-effect that existing
|
81 |
+
applications or libraries which use ANSI sequences to produce colored output on
|
82 |
+
Linux or Macs can now also work on Windows, simply by calling
|
83 |
+
``colorama.just_fix_windows_console()`` (since v0.4.6) or ``colorama.init()``
|
84 |
+
(all versions, but may have other side-effects β see below).
|
85 |
+
|
86 |
+
An alternative approach is to install ``ansi.sys`` on Windows machines, which
|
87 |
+
provides the same behaviour for all applications running in terminals. Colorama
|
88 |
+
is intended for situations where that isn't easy (e.g., maybe your app doesn't
|
89 |
+
have an installer.)
|
90 |
+
|
91 |
+
Demo scripts in the source code repository print some colored text using
|
92 |
+
ANSI sequences. Compare their output under Gnome-terminal's built in ANSI
|
93 |
+
handling, versus on Windows Command-Prompt using Colorama:
|
94 |
+
|
95 |
+
.. image:: https://github.com/tartley/colorama/raw/master/screenshots/ubuntu-demo.png
|
96 |
+
:width: 661
|
97 |
+
:height: 357
|
98 |
+
:alt: ANSI sequences on Ubuntu under gnome-terminal.
|
99 |
+
|
100 |
+
.. image:: https://github.com/tartley/colorama/raw/master/screenshots/windows-demo.png
|
101 |
+
:width: 668
|
102 |
+
:height: 325
|
103 |
+
:alt: Same ANSI sequences on Windows, using Colorama.
|
104 |
+
|
105 |
+
These screenshots show that, on Windows, Colorama does not support ANSI 'dim
|
106 |
+
text'; it looks the same as 'normal text'.
|
107 |
+
|
108 |
+
Usage
|
109 |
+
-----
|
110 |
+
|
111 |
+
Initialisation
|
112 |
+
..............
|
113 |
+
|
114 |
+
If the only thing you want from Colorama is to get ANSI escapes to work on
|
115 |
+
Windows, then run:
|
116 |
+
|
117 |
+
.. code-block:: python
|
118 |
+
|
119 |
+
from colorama import just_fix_windows_console
|
120 |
+
just_fix_windows_console()
|
121 |
+
|
122 |
+
If you're on a recent version of Windows 10 or better, and your stdout/stderr
|
123 |
+
are pointing to a Windows console, then this will flip the magic configuration
|
124 |
+
switch to enable Windows' built-in ANSI support.
|
125 |
+
|
126 |
+
If you're on an older version of Windows, and your stdout/stderr are pointing to
|
127 |
+
a Windows console, then this will wrap ``sys.stdout`` and/or ``sys.stderr`` in a
|
128 |
+
magic file object that intercepts ANSI escape sequences and issues the
|
129 |
+
appropriate Win32 calls to emulate them.
|
130 |
+
|
131 |
+
In all other circumstances, it does nothing whatsoever. Basically the idea is
|
132 |
+
that this makes Windows act like Unix with respect to ANSI escape handling.
|
133 |
+
|
134 |
+
It's safe to call this function multiple times. It's safe to call this function
|
135 |
+
on non-Windows platforms, but it won't do anything. It's safe to call this
|
136 |
+
function when one or both of your stdout/stderr are redirected to a file β it
|
137 |
+
won't do anything to those streams.
|
138 |
+
|
139 |
+
Alternatively, you can use the older interface with more features (but also more
|
140 |
+
potential footguns):
|
141 |
+
|
142 |
+
.. code-block:: python
|
143 |
+
|
144 |
+
from colorama import init
|
145 |
+
init()
|
146 |
+
|
147 |
+
This does the same thing as ``just_fix_windows_console``, except for the
|
148 |
+
following differences:
|
149 |
+
|
150 |
+
- It's not safe to call ``init`` multiple times; you can end up with multiple
|
151 |
+
layers of wrapping and broken ANSI support.
|
152 |
+
|
153 |
+
- Colorama will apply a heuristic to guess whether stdout/stderr support ANSI,
|
154 |
+
and if it thinks they don't, then it will wrap ``sys.stdout`` and
|
155 |
+
``sys.stderr`` in a magic file object that strips out ANSI escape sequences
|
156 |
+
before printing them. This happens on all platforms, and can be convenient if
|
157 |
+
you want to write your code to emit ANSI escape sequences unconditionally, and
|
158 |
+
let Colorama decide whether they should actually be output. But note that
|
159 |
+
Colorama's heuristic is not particularly clever.
|
160 |
+
|
161 |
+
- ``init`` also accepts explicit keyword args to enable/disable various
|
162 |
+
functionality β see below.
|
163 |
+
|
164 |
+
To stop using Colorama before your program exits, simply call ``deinit()``.
|
165 |
+
This will restore ``stdout`` and ``stderr`` to their original values, so that
|
166 |
+
Colorama is disabled. To resume using Colorama again, call ``reinit()``; it is
|
167 |
+
cheaper than calling ``init()`` again (but does the same thing).
|
168 |
+
|
169 |
+
Most users should depend on ``colorama >= 0.4.6``, and use
|
170 |
+
``just_fix_windows_console``. The old ``init`` interface will be supported
|
171 |
+
indefinitely for backwards compatibility, but we don't plan to fix any issues
|
172 |
+
with it, also for backwards compatibility.
|
173 |
+
|
174 |
+
Colored Output
|
175 |
+
..............
|
176 |
+
|
177 |
+
Cross-platform printing of colored text can then be done using Colorama's
|
178 |
+
constant shorthand for ANSI escape sequences. These are deliberately
|
179 |
+
rudimentary, see below.
|
180 |
+
|
181 |
+
.. code-block:: python
|
182 |
+
|
183 |
+
from colorama import Fore, Back, Style
|
184 |
+
print(Fore.RED + 'some red text')
|
185 |
+
print(Back.GREEN + 'and with a green background')
|
186 |
+
print(Style.DIM + 'and in dim text')
|
187 |
+
print(Style.RESET_ALL)
|
188 |
+
print('back to normal now')
|
189 |
+
|
190 |
+
...or simply by manually printing ANSI sequences from your own code:
|
191 |
+
|
192 |
+
.. code-block:: python
|
193 |
+
|
194 |
+
print('\033[31m' + 'some red text')
|
195 |
+
print('\033[39m') # and reset to default color
|
196 |
+
|
197 |
+
...or, Colorama can be used in conjunction with existing ANSI libraries
|
198 |
+
such as the venerable `Termcolor <https://pypi.org/project/termcolor/>`_
|
199 |
+
the fabulous `Blessings <https://pypi.org/project/blessings/>`_,
|
200 |
+
or the incredible `_Rich <https://pypi.org/project/rich/>`_.
|
201 |
+
|
202 |
+
If you wish Colorama's Fore, Back and Style constants were more capable,
|
203 |
+
then consider using one of the above highly capable libraries to generate
|
204 |
+
colors, etc, and use Colorama just for its primary purpose: to convert
|
205 |
+
those ANSI sequences to also work on Windows:
|
206 |
+
|
207 |
+
SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama.
|
208 |
+
We are only interested in converting ANSI codes to win32 API calls, not
|
209 |
+
shortcuts like the above to generate ANSI characters.
|
210 |
+
|
211 |
+
.. code-block:: python
|
212 |
+
|
213 |
+
from colorama import just_fix_windows_console
|
214 |
+
from termcolor import colored
|
215 |
+
|
216 |
+
# use Colorama to make Termcolor work on Windows too
|
217 |
+
just_fix_windows_console()
|
218 |
+
|
219 |
+
# then use Termcolor for all colored text output
|
220 |
+
print(colored('Hello, World!', 'green', 'on_red'))
|
221 |
+
|
222 |
+
Available formatting constants are::
|
223 |
+
|
224 |
+
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
|
225 |
+
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
|
226 |
+
Style: DIM, NORMAL, BRIGHT, RESET_ALL
|
227 |
+
|
228 |
+
``Style.RESET_ALL`` resets foreground, background, and brightness. Colorama will
|
229 |
+
perform this reset automatically on program exit.
|
230 |
+
|
231 |
+
These are fairly well supported, but not part of the standard::
|
232 |
+
|
233 |
+
Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
|
234 |
+
Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
|
235 |
+
|
236 |
+
Cursor Positioning
|
237 |
+
..................
|
238 |
+
|
239 |
+
ANSI codes to reposition the cursor are supported. See ``demos/demo06.py`` for
|
240 |
+
an example of how to generate them.
|
241 |
+
|
242 |
+
Init Keyword Args
|
243 |
+
.................
|
244 |
+
|
245 |
+
``init()`` accepts some ``**kwargs`` to override default behaviour.
|
246 |
+
|
247 |
+
init(autoreset=False):
|
248 |
+
If you find yourself repeatedly sending reset sequences to turn off color
|
249 |
+
changes at the end of every print, then ``init(autoreset=True)`` will
|
250 |
+
automate that:
|
251 |
+
|
252 |
+
.. code-block:: python
|
253 |
+
|
254 |
+
from colorama import init
|
255 |
+
init(autoreset=True)
|
256 |
+
print(Fore.RED + 'some red text')
|
257 |
+
print('automatically back to default color again')
|
258 |
+
|
259 |
+
init(strip=None):
|
260 |
+
Pass ``True`` or ``False`` to override whether ANSI codes should be
|
261 |
+
stripped from the output. The default behaviour is to strip if on Windows
|
262 |
+
or if output is redirected (not a tty).
|
263 |
+
|
264 |
+
init(convert=None):
|
265 |
+
Pass ``True`` or ``False`` to override whether to convert ANSI codes in the
|
266 |
+
output into win32 calls. The default behaviour is to convert if on Windows
|
267 |
+
and output is to a tty (terminal).
|
268 |
+
|
269 |
+
init(wrap=True):
|
270 |
+
On Windows, Colorama works by replacing ``sys.stdout`` and ``sys.stderr``
|
271 |
+
with proxy objects, which override the ``.write()`` method to do their work.
|
272 |
+
If this wrapping causes you problems, then this can be disabled by passing
|
273 |
+
``init(wrap=False)``. The default behaviour is to wrap if ``autoreset`` or
|
274 |
+
``strip`` or ``convert`` are True.
|
275 |
+
|
276 |
+
When wrapping is disabled, colored printing on non-Windows platforms will
|
277 |
+
continue to work as normal. To do cross-platform colored output, you can
|
278 |
+
use Colorama's ``AnsiToWin32`` proxy directly:
|
279 |
+
|
280 |
+
.. code-block:: python
|
281 |
+
|
282 |
+
import sys
|
283 |
+
from colorama import init, AnsiToWin32
|
284 |
+
init(wrap=False)
|
285 |
+
stream = AnsiToWin32(sys.stderr).stream
|
286 |
+
|
287 |
+
# Python 2
|
288 |
+
print >>stream, Fore.BLUE + 'blue text on stderr'
|
289 |
+
|
290 |
+
# Python 3
|
291 |
+
print(Fore.BLUE + 'blue text on stderr', file=stream)
|
292 |
+
|
293 |
+
Recognised ANSI Sequences
|
294 |
+
.........................
|
295 |
+
|
296 |
+
ANSI sequences generally take the form::
|
297 |
+
|
298 |
+
ESC [ <param> ; <param> ... <command>
|
299 |
+
|
300 |
+
Where ``<param>`` is an integer, and ``<command>`` is a single letter. Zero or
|
301 |
+
more params are passed to a ``<command>``. If no params are passed, it is
|
302 |
+
generally synonymous with passing a single zero. No spaces exist in the
|
303 |
+
sequence; they have been inserted here simply to read more easily.
|
304 |
+
|
305 |
+
The only ANSI sequences that Colorama converts into win32 calls are::
|
306 |
+
|
307 |
+
ESC [ 0 m # reset all (colors and brightness)
|
308 |
+
ESC [ 1 m # bright
|
309 |
+
ESC [ 2 m # dim (looks same as normal brightness)
|
310 |
+
ESC [ 22 m # normal brightness
|
311 |
+
|
312 |
+
# FOREGROUND:
|
313 |
+
ESC [ 30 m # black
|
314 |
+
ESC [ 31 m # red
|
315 |
+
ESC [ 32 m # green
|
316 |
+
ESC [ 33 m # yellow
|
317 |
+
ESC [ 34 m # blue
|
318 |
+
ESC [ 35 m # magenta
|
319 |
+
ESC [ 36 m # cyan
|
320 |
+
ESC [ 37 m # white
|
321 |
+
ESC [ 39 m # reset
|
322 |
+
|
323 |
+
# BACKGROUND
|
324 |
+
ESC [ 40 m # black
|
325 |
+
ESC [ 41 m # red
|
326 |
+
ESC [ 42 m # green
|
327 |
+
ESC [ 43 m # yellow
|
328 |
+
ESC [ 44 m # blue
|
329 |
+
ESC [ 45 m # magenta
|
330 |
+
ESC [ 46 m # cyan
|
331 |
+
ESC [ 47 m # white
|
332 |
+
ESC [ 49 m # reset
|
333 |
+
|
334 |
+
# cursor positioning
|
335 |
+
ESC [ y;x H # position cursor at x across, y down
|
336 |
+
ESC [ y;x f # position cursor at x across, y down
|
337 |
+
ESC [ n A # move cursor n lines up
|
338 |
+
ESC [ n B # move cursor n lines down
|
339 |
+
ESC [ n C # move cursor n characters forward
|
340 |
+
ESC [ n D # move cursor n characters backward
|
341 |
+
|
342 |
+
# clear the screen
|
343 |
+
ESC [ mode J # clear the screen
|
344 |
+
|
345 |
+
# clear the line
|
346 |
+
ESC [ mode K # clear the line
|
347 |
+
|
348 |
+
Multiple numeric params to the ``'m'`` command can be combined into a single
|
349 |
+
sequence::
|
350 |
+
|
351 |
+
ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background
|
352 |
+
|
353 |
+
All other ANSI sequences of the form ``ESC [ <param> ; <param> ... <command>``
|
354 |
+
are silently stripped from the output on Windows.
|
355 |
+
|
356 |
+
Any other form of ANSI sequence, such as single-character codes or alternative
|
357 |
+
initial characters, are not recognised or stripped. It would be cool to add
|
358 |
+
them though. Let me know if it would be useful for you, via the Issues on
|
359 |
+
GitHub.
|
360 |
+
|
361 |
+
Status & Known Problems
|
362 |
+
-----------------------
|
363 |
+
|
364 |
+
I've personally only tested it on Windows XP (CMD, Console2), Ubuntu
|
365 |
+
(gnome-terminal, xterm), and OS X.
|
366 |
+
|
367 |
+
Some valid ANSI sequences aren't recognised.
|
368 |
+
|
369 |
+
If you're hacking on the code, see `README-hacking.md`_. ESPECIALLY, see the
|
370 |
+
explanation there of why we do not want PRs that allow Colorama to generate new
|
371 |
+
types of ANSI codes.
|
372 |
+
|
373 |
+
See outstanding issues and wish-list:
|
374 |
+
https://github.com/tartley/colorama/issues
|
375 |
+
|
376 |
+
If anything doesn't work for you, or doesn't do what you expected or hoped for,
|
377 |
+
I'd love to hear about it on that issues list, would be delighted by patches,
|
378 |
+
and would be happy to grant commit access to anyone who submits a working patch
|
379 |
+
or two.
|
380 |
+
|
381 |
+
.. _README-hacking.md: README-hacking.md
|
382 |
+
|
383 |
+
License
|
384 |
+
-------
|
385 |
+
|
386 |
+
Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see
|
387 |
+
LICENSE file.
|
388 |
+
|
389 |
+
Professional support
|
390 |
+
--------------------
|
391 |
+
|
392 |
+
.. |tideliftlogo| image:: https://cdn2.hubspot.net/hubfs/4008838/website/logos/logos_for_download/Tidelift_primary-shorthand-logo.png
|
393 |
+
:alt: Tidelift
|
394 |
+
:target: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme
|
395 |
+
|
396 |
+
.. list-table::
|
397 |
+
:widths: 10 100
|
398 |
+
|
399 |
+
* - |tideliftlogo|
|
400 |
+
- Professional support for colorama is available as part of the
|
401 |
+
`Tidelift Subscription`_.
|
402 |
+
Tidelift gives software development teams a single source for purchasing
|
403 |
+
and maintaining their software, with professional grade assurances from
|
404 |
+
the experts who know it best, while seamlessly integrating with existing
|
405 |
+
tools.
|
406 |
+
|
407 |
+
.. _Tidelift Subscription: https://tidelift.com/subscription/pkg/pypi-colorama?utm_source=pypi-colorama&utm_medium=referral&utm_campaign=readme
|
408 |
+
|
409 |
+
Thanks
|
410 |
+
------
|
411 |
+
|
412 |
+
See the CHANGELOG for more thanks!
|
413 |
+
|
414 |
+
* Marc Schlaich (schlamar) for a ``setup.py`` fix for Python2.5.
|
415 |
+
* Marc Abramowitz, reported & fixed a crash on exit with closed ``stdout``,
|
416 |
+
providing a solution to issue #7's setuptools/distutils debate,
|
417 |
+
and other fixes.
|
418 |
+
* User 'eryksun', for guidance on correctly instantiating ``ctypes.windll``.
|
419 |
+
* Matthew McCormick for politely pointing out a longstanding crash on non-Win.
|
420 |
+
* Ben Hoyt, for a magnificent fix under 64-bit Windows.
|
421 |
+
* Jesse at Empty Square for submitting a fix for examples in the README.
|
422 |
+
* User 'jamessp', an observant documentation fix for cursor positioning.
|
423 |
+
* User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7
|
424 |
+
fix.
|
425 |
+
* Julien Stuyck, for wisely suggesting Python3 compatible updates to README.
|
426 |
+
* Daniel Griffith for multiple fabulous patches.
|
427 |
+
* Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty
|
428 |
+
output.
|
429 |
+
* Roger Binns, for many suggestions, valuable feedback, & bug reports.
|
430 |
+
* Tim Golden for thought and much appreciated feedback on the initial idea.
|
431 |
+
* User 'Zearin' for updates to the README file.
|
432 |
+
* John Szakmeister for adding support for light colors
|
433 |
+
* Charles Merriam for adding documentation to demos
|
434 |
+
* Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes
|
435 |
+
* Florian Bruhin for a fix when stdout or stderr are None
|
436 |
+
* Thomas Weininger for fixing ValueError on Windows
|
437 |
+
* Remi Rampin for better Github integration and fixes to the README file
|
438 |
+
* Simeon Visser for closing a file handle using 'with' and updating classifiers
|
439 |
+
to include Python 3.3 and 3.4
|
440 |
+
* Andy Neff for fixing RESET of LIGHT_EX colors.
|
441 |
+
* Jonathan Hartley for the initial idea and implementation.
|
venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/RECORD
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
colorama-0.4.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
2 |
+
colorama-0.4.6.dist-info/METADATA,sha256=e67SnrUMOym9sz_4TjF3vxvAV4T3aF7NyqRHHH3YEMw,17158
|
3 |
+
colorama-0.4.6.dist-info/RECORD,,
|
4 |
+
colorama-0.4.6.dist-info/WHEEL,sha256=cdcF4Fbd0FPtw2EMIOwH-3rSOTUdTCeOSXRMD1iLUb8,105
|
5 |
+
colorama-0.4.6.dist-info/licenses/LICENSE.txt,sha256=ysNcAmhuXQSlpxQL-zs25zrtSWZW6JEQLkKIhteTAxg,1491
|
6 |
+
colorama/__init__.py,sha256=wePQA4U20tKgYARySLEC047ucNX-g8pRLpYBuiHlLb8,266
|
7 |
+
colorama/__pycache__/__init__.cpython-310.pyc,,
|
8 |
+
colorama/__pycache__/ansi.cpython-310.pyc,,
|
9 |
+
colorama/__pycache__/ansitowin32.cpython-310.pyc,,
|
10 |
+
colorama/__pycache__/initialise.cpython-310.pyc,,
|
11 |
+
colorama/__pycache__/win32.cpython-310.pyc,,
|
12 |
+
colorama/__pycache__/winterm.cpython-310.pyc,,
|
13 |
+
colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522
|
14 |
+
colorama/ansitowin32.py,sha256=vPNYa3OZbxjbuFyaVo0Tmhmy1FZ1lKMWCnT7odXpItk,11128
|
15 |
+
colorama/initialise.py,sha256=-hIny86ClXo39ixh5iSCfUIa2f_h_bgKRDW7gqs-KLU,3325
|
16 |
+
colorama/tests/__init__.py,sha256=MkgPAEzGQd-Rq0w0PZXSX2LadRWhUECcisJY8lSrm4Q,75
|
17 |
+
colorama/tests/__pycache__/__init__.cpython-310.pyc,,
|
18 |
+
colorama/tests/__pycache__/ansi_test.cpython-310.pyc,,
|
19 |
+
colorama/tests/__pycache__/ansitowin32_test.cpython-310.pyc,,
|
20 |
+
colorama/tests/__pycache__/initialise_test.cpython-310.pyc,,
|
21 |
+
colorama/tests/__pycache__/isatty_test.cpython-310.pyc,,
|
22 |
+
colorama/tests/__pycache__/utils.cpython-310.pyc,,
|
23 |
+
colorama/tests/__pycache__/winterm_test.cpython-310.pyc,,
|
24 |
+
colorama/tests/ansi_test.py,sha256=FeViDrUINIZcr505PAxvU4AjXz1asEiALs9GXMhwRaE,2839
|
25 |
+
colorama/tests/ansitowin32_test.py,sha256=RN7AIhMJ5EqDsYaCjVo-o4u8JzDD4ukJbmevWKS70rY,10678
|
26 |
+
colorama/tests/initialise_test.py,sha256=BbPy-XfyHwJ6zKozuQOvNvQZzsx9vdb_0bYXn7hsBTc,6741
|
27 |
+
colorama/tests/isatty_test.py,sha256=Pg26LRpv0yQDB5Ac-sxgVXG7hsA1NYvapFgApZfYzZg,1866
|
28 |
+
colorama/tests/utils.py,sha256=1IIRylG39z5-dzq09R_ngufxyPZxgldNbrxKxUGwGKE,1079
|
29 |
+
colorama/tests/winterm_test.py,sha256=qoWFPEjym5gm2RuMwpf3pOis3a5r_PJZFCzK254JL8A,3709
|
30 |
+
colorama/win32.py,sha256=YQOKwMTwtGBbsY4dL5HYTvwTeP9wIQra5MvPNddpxZs,6181
|
31 |
+
colorama/winterm.py,sha256=XCQFDHjPi6AHYNdZwy0tA02H-Jh48Jp-HvCjeLeLp3U,7134
|
venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/WHEEL
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Wheel-Version: 1.0
|
2 |
+
Generator: hatchling 1.11.1
|
3 |
+
Root-Is-Purelib: true
|
4 |
+
Tag: py2-none-any
|
5 |
+
Tag: py3-none-any
|
venv/lib/python3.10/site-packages/colorama-0.4.6.dist-info/licenses/LICENSE.txt
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2010 Jonathan Hartley
|
2 |
+
All rights reserved.
|
3 |
+
|
4 |
+
Redistribution and use in source and binary forms, with or without
|
5 |
+
modification, are permitted provided that the following conditions are met:
|
6 |
+
|
7 |
+
* Redistributions of source code must retain the above copyright notice, this
|
8 |
+
list of conditions and the following disclaimer.
|
9 |
+
|
10 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
11 |
+
this list of conditions and the following disclaimer in the documentation
|
12 |
+
and/or other materials provided with the distribution.
|
13 |
+
|
14 |
+
* Neither the name of the copyright holders, nor those of its contributors
|
15 |
+
may be used to endorse or promote products derived from this software without
|
16 |
+
specific prior written permission.
|
17 |
+
|
18 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
19 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
20 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
21 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
22 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
23 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
24 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
25 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
26 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
27 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
venv/lib/python3.10/site-packages/dill/__diff.py
ADDED
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
#
|
3 |
+
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
|
4 |
+
# Copyright (c) 2008-2016 California Institute of Technology.
|
5 |
+
# Copyright (c) 2016-2024 The Uncertainty Quantification Foundation.
|
6 |
+
# License: 3-clause BSD. The full license text is available at:
|
7 |
+
# - https://github.com/uqfoundation/dill/blob/master/LICENSE
|
8 |
+
|
9 |
+
"""
|
10 |
+
Module to show if an object has changed since it was memorised
|
11 |
+
"""
|
12 |
+
|
13 |
+
import builtins
|
14 |
+
import os
|
15 |
+
import sys
|
16 |
+
import types
|
17 |
+
try:
|
18 |
+
import numpy
|
19 |
+
HAS_NUMPY = True
|
20 |
+
except ImportError:
|
21 |
+
HAS_NUMPY = False
|
22 |
+
|
23 |
+
# pypy doesn't use reference counting
|
24 |
+
getrefcount = getattr(sys, 'getrefcount', lambda x:0)
|
25 |
+
|
26 |
+
# memo of objects indexed by id to a tuple (attributes, sequence items)
|
27 |
+
# attributes is a dict indexed by attribute name to attribute id
|
28 |
+
# sequence items is either a list of ids, of a dictionary of keys to ids
|
29 |
+
memo = {}
|
30 |
+
id_to_obj = {}
|
31 |
+
# types that cannot have changing attributes
|
32 |
+
builtins_types = set((str, list, dict, set, frozenset, int))
|
33 |
+
dont_memo = set(id(i) for i in (memo, sys.modules, sys.path_importer_cache,
|
34 |
+
os.environ, id_to_obj))
|
35 |
+
|
36 |
+
|
37 |
+
def get_attrs(obj):
|
38 |
+
"""
|
39 |
+
Gets all the attributes of an object though its __dict__ or return None
|
40 |
+
"""
|
41 |
+
if type(obj) in builtins_types \
|
42 |
+
or type(obj) is type and obj in builtins_types:
|
43 |
+
return
|
44 |
+
return getattr(obj, '__dict__', None)
|
45 |
+
|
46 |
+
|
47 |
+
def get_seq(obj, cache={str: False, frozenset: False, list: True, set: True,
|
48 |
+
dict: True, tuple: True, type: False,
|
49 |
+
types.ModuleType: False, types.FunctionType: False,
|
50 |
+
types.BuiltinFunctionType: False}):
|
51 |
+
"""
|
52 |
+
Gets all the items in a sequence or return None
|
53 |
+
"""
|
54 |
+
try:
|
55 |
+
o_type = obj.__class__
|
56 |
+
except AttributeError:
|
57 |
+
o_type = type(obj)
|
58 |
+
hsattr = hasattr
|
59 |
+
if o_type in cache:
|
60 |
+
if cache[o_type]:
|
61 |
+
if hsattr(obj, "copy"):
|
62 |
+
return obj.copy()
|
63 |
+
return obj
|
64 |
+
elif HAS_NUMPY and o_type in (numpy.ndarray, numpy.ma.core.MaskedConstant):
|
65 |
+
if obj.shape and obj.size:
|
66 |
+
return obj
|
67 |
+
else:
|
68 |
+
return []
|
69 |
+
elif hsattr(obj, "__contains__") and hsattr(obj, "__iter__") \
|
70 |
+
and hsattr(obj, "__len__") and hsattr(o_type, "__contains__") \
|
71 |
+
and hsattr(o_type, "__iter__") and hsattr(o_type, "__len__"):
|
72 |
+
cache[o_type] = True
|
73 |
+
if hsattr(obj, "copy"):
|
74 |
+
return obj.copy()
|
75 |
+
return obj
|
76 |
+
else:
|
77 |
+
cache[o_type] = False
|
78 |
+
return None
|
79 |
+
|
80 |
+
|
81 |
+
def memorise(obj, force=False):
|
82 |
+
"""
|
83 |
+
Adds an object to the memo, and recursively adds all the objects
|
84 |
+
attributes, and if it is a container, its items. Use force=True to update
|
85 |
+
an object already in the memo. Updating is not recursively done.
|
86 |
+
"""
|
87 |
+
obj_id = id(obj)
|
88 |
+
if obj_id in memo and not force or obj_id in dont_memo:
|
89 |
+
return
|
90 |
+
id_ = id
|
91 |
+
g = get_attrs(obj)
|
92 |
+
if g is None:
|
93 |
+
attrs_id = None
|
94 |
+
else:
|
95 |
+
attrs_id = dict((key,id_(value)) for key, value in g.items())
|
96 |
+
|
97 |
+
s = get_seq(obj)
|
98 |
+
if s is None:
|
99 |
+
seq_id = None
|
100 |
+
elif hasattr(s, "items"):
|
101 |
+
seq_id = dict((id_(key),id_(value)) for key, value in s.items())
|
102 |
+
elif not hasattr(s, "__len__"): #XXX: avoid TypeError from unexpected case
|
103 |
+
seq_id = None
|
104 |
+
else:
|
105 |
+
seq_id = [id_(i) for i in s]
|
106 |
+
|
107 |
+
memo[obj_id] = attrs_id, seq_id
|
108 |
+
id_to_obj[obj_id] = obj
|
109 |
+
mem = memorise
|
110 |
+
if g is not None:
|
111 |
+
[mem(value) for key, value in g.items()]
|
112 |
+
|
113 |
+
if s is not None:
|
114 |
+
if hasattr(s, "items"):
|
115 |
+
[(mem(key), mem(item))
|
116 |
+
for key, item in s.items()]
|
117 |
+
else:
|
118 |
+
if hasattr(s, '__len__'):
|
119 |
+
[mem(item) for item in s]
|
120 |
+
else: mem(s)
|
121 |
+
|
122 |
+
|
123 |
+
def release_gone():
|
124 |
+
itop, mp, src = id_to_obj.pop, memo.pop, getrefcount
|
125 |
+
[(itop(id_), mp(id_)) for id_, obj in list(id_to_obj.items())
|
126 |
+
if src(obj) < 4] #XXX: correct for pypy?
|
127 |
+
|
128 |
+
|
129 |
+
def whats_changed(obj, seen=None, simple=False, first=True):
|
130 |
+
"""
|
131 |
+
Check an object against the memo. Returns a list in the form
|
132 |
+
(attribute changes, container changed). Attribute changes is a dict of
|
133 |
+
attribute name to attribute value. container changed is a boolean.
|
134 |
+
If simple is true, just returns a boolean. None for either item means
|
135 |
+
that it has not been checked yet
|
136 |
+
"""
|
137 |
+
# Special cases
|
138 |
+
if first:
|
139 |
+
# ignore the _ variable, which only appears in interactive sessions
|
140 |
+
if "_" in builtins.__dict__:
|
141 |
+
del builtins._
|
142 |
+
if seen is None:
|
143 |
+
seen = {}
|
144 |
+
|
145 |
+
obj_id = id(obj)
|
146 |
+
|
147 |
+
if obj_id in seen:
|
148 |
+
if simple:
|
149 |
+
return any(seen[obj_id])
|
150 |
+
return seen[obj_id]
|
151 |
+
|
152 |
+
# Safety checks
|
153 |
+
if obj_id in dont_memo:
|
154 |
+
seen[obj_id] = [{}, False]
|
155 |
+
if simple:
|
156 |
+
return False
|
157 |
+
return seen[obj_id]
|
158 |
+
elif obj_id not in memo:
|
159 |
+
if simple:
|
160 |
+
return True
|
161 |
+
else:
|
162 |
+
raise RuntimeError("Object not memorised " + str(obj))
|
163 |
+
|
164 |
+
seen[obj_id] = ({}, False)
|
165 |
+
|
166 |
+
chngd = whats_changed
|
167 |
+
id_ = id
|
168 |
+
|
169 |
+
# compare attributes
|
170 |
+
attrs = get_attrs(obj)
|
171 |
+
if attrs is None:
|
172 |
+
changed = {}
|
173 |
+
else:
|
174 |
+
obj_attrs = memo[obj_id][0]
|
175 |
+
obj_get = obj_attrs.get
|
176 |
+
changed = dict((key,None) for key in obj_attrs if key not in attrs)
|
177 |
+
for key, o in attrs.items():
|
178 |
+
if id_(o) != obj_get(key, None) or chngd(o, seen, True, False):
|
179 |
+
changed[key] = o
|
180 |
+
|
181 |
+
# compare sequence
|
182 |
+
items = get_seq(obj)
|
183 |
+
seq_diff = False
|
184 |
+
if (items is not None) and (hasattr(items, '__len__')):
|
185 |
+
obj_seq = memo[obj_id][1]
|
186 |
+
if (len(items) != len(obj_seq)):
|
187 |
+
seq_diff = True
|
188 |
+
elif hasattr(obj, "items"): # dict type obj
|
189 |
+
obj_get = obj_seq.get
|
190 |
+
for key, item in items.items():
|
191 |
+
if id_(item) != obj_get(id_(key)) \
|
192 |
+
or chngd(key, seen, True, False) \
|
193 |
+
or chngd(item, seen, True, False):
|
194 |
+
seq_diff = True
|
195 |
+
break
|
196 |
+
else:
|
197 |
+
for i, j in zip(items, obj_seq): # list type obj
|
198 |
+
if id_(i) != j or chngd(i, seen, True, False):
|
199 |
+
seq_diff = True
|
200 |
+
break
|
201 |
+
seen[obj_id] = changed, seq_diff
|
202 |
+
if simple:
|
203 |
+
return changed or seq_diff
|
204 |
+
return changed, seq_diff
|
205 |
+
|
206 |
+
|
207 |
+
def has_changed(*args, **kwds):
|
208 |
+
kwds['simple'] = True # ignore simple if passed in
|
209 |
+
return whats_changed(*args, **kwds)
|
210 |
+
|
211 |
+
__import__ = __import__
|
212 |
+
|
213 |
+
|
214 |
+
def _imp(*args, **kwds):
|
215 |
+
"""
|
216 |
+
Replaces the default __import__, to allow a module to be memorised
|
217 |
+
before the user can change it
|
218 |
+
"""
|
219 |
+
before = set(sys.modules.keys())
|
220 |
+
mod = __import__(*args, **kwds)
|
221 |
+
after = set(sys.modules.keys()).difference(before)
|
222 |
+
for m in after:
|
223 |
+
memorise(sys.modules[m])
|
224 |
+
return mod
|
225 |
+
|
226 |
+
builtins.__import__ = _imp
|
227 |
+
if hasattr(builtins, "_"):
|
228 |
+
del builtins._
|
229 |
+
|
230 |
+
# memorise all already imported modules. This implies that this must be
|
231 |
+
# imported first for any changes to be recorded
|
232 |
+
for mod in list(sys.modules.values()):
|
233 |
+
memorise(mod)
|
234 |
+
release_gone()
|
venv/lib/python3.10/site-packages/dill/__info__.py
ADDED
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
#
|
3 |
+
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
|
4 |
+
# Copyright (c) 2024 The Uncertainty Quantification Foundation.
|
5 |
+
# License: 3-clause BSD. The full license text is available at:
|
6 |
+
# - https://github.com/uqfoundation/dill/blob/master/LICENSE
|
7 |
+
'''
|
8 |
+
-----------------------------
|
9 |
+
dill: serialize all of Python
|
10 |
+
-----------------------------
|
11 |
+
|
12 |
+
About Dill
|
13 |
+
==========
|
14 |
+
|
15 |
+
``dill`` extends Python's ``pickle`` module for serializing and de-serializing
|
16 |
+
Python objects to the majority of the built-in Python types. Serialization
|
17 |
+
is the process of converting an object to a byte stream, and the inverse
|
18 |
+
of which is converting a byte stream back to a Python object hierarchy.
|
19 |
+
|
20 |
+
``dill`` provides the user the same interface as the ``pickle`` module, and
|
21 |
+
also includes some additional features. In addition to pickling Python
|
22 |
+
objects, ``dill`` provides the ability to save the state of an interpreter
|
23 |
+
session in a single command. Hence, it would be feasible to save an
|
24 |
+
interpreter session, close the interpreter, ship the pickled file to
|
25 |
+
another computer, open a new interpreter, unpickle the session and
|
26 |
+
thus continue from the 'saved' state of the original interpreter
|
27 |
+
session.
|
28 |
+
|
29 |
+
``dill`` can be used to store Python objects to a file, but the primary
|
30 |
+
usage is to send Python objects across the network as a byte stream.
|
31 |
+
``dill`` is quite flexible, and allows arbitrary user defined classes
|
32 |
+
and functions to be serialized. Thus ``dill`` is not intended to be
|
33 |
+
secure against erroneously or maliciously constructed data. It is
|
34 |
+
left to the user to decide whether the data they unpickle is from
|
35 |
+
a trustworthy source.
|
36 |
+
|
37 |
+
``dill`` is part of ``pathos``, a Python framework for heterogeneous computing.
|
38 |
+
``dill`` is in active development, so any user feedback, bug reports, comments,
|
39 |
+
or suggestions are highly appreciated. A list of issues is located at
|
40 |
+
https://github.com/uqfoundation/dill/issues, with a legacy list maintained at
|
41 |
+
https://uqfoundation.github.io/project/pathos/query.
|
42 |
+
|
43 |
+
|
44 |
+
Major Features
|
45 |
+
==============
|
46 |
+
|
47 |
+
``dill`` can pickle the following standard types:
|
48 |
+
|
49 |
+
- none, type, bool, int, float, complex, bytes, str,
|
50 |
+
- tuple, list, dict, file, buffer, builtin,
|
51 |
+
- Python classes, namedtuples, dataclasses, metaclasses,
|
52 |
+
- instances of classes,
|
53 |
+
- set, frozenset, array, functions, exceptions
|
54 |
+
|
55 |
+
``dill`` can also pickle more 'exotic' standard types:
|
56 |
+
|
57 |
+
- functions with yields, nested functions, lambdas,
|
58 |
+
- cell, method, unboundmethod, module, code, methodwrapper,
|
59 |
+
- methoddescriptor, getsetdescriptor, memberdescriptor, wrapperdescriptor,
|
60 |
+
- dictproxy, slice, notimplemented, ellipsis, quit
|
61 |
+
|
62 |
+
``dill`` cannot yet pickle these standard types:
|
63 |
+
|
64 |
+
- frame, generator, traceback
|
65 |
+
|
66 |
+
``dill`` also provides the capability to:
|
67 |
+
|
68 |
+
- save and load Python interpreter sessions
|
69 |
+
- save and extract the source code from functions and classes
|
70 |
+
- interactively diagnose pickling errors
|
71 |
+
|
72 |
+
|
73 |
+
Current Release
|
74 |
+
===============
|
75 |
+
|
76 |
+
The latest released version of ``dill`` is available from:
|
77 |
+
|
78 |
+
https://pypi.org/project/dill
|
79 |
+
|
80 |
+
``dill`` is distributed under a 3-clause BSD license.
|
81 |
+
|
82 |
+
|
83 |
+
Development Version
|
84 |
+
===================
|
85 |
+
|
86 |
+
You can get the latest development version with all the shiny new features at:
|
87 |
+
|
88 |
+
https://github.com/uqfoundation
|
89 |
+
|
90 |
+
If you have a new contribution, please submit a pull request.
|
91 |
+
|
92 |
+
|
93 |
+
Installation
|
94 |
+
============
|
95 |
+
|
96 |
+
``dill`` can be installed with ``pip``::
|
97 |
+
|
98 |
+
$ pip install dill
|
99 |
+
|
100 |
+
To optionally include the ``objgraph`` diagnostic tool in the install::
|
101 |
+
|
102 |
+
$ pip install dill[graph]
|
103 |
+
|
104 |
+
To optionally include the ``gprof2dot`` diagnostic tool in the install::
|
105 |
+
|
106 |
+
$ pip install dill[profile]
|
107 |
+
|
108 |
+
For windows users, to optionally install session history tools::
|
109 |
+
|
110 |
+
$ pip install dill[readline]
|
111 |
+
|
112 |
+
|
113 |
+
Requirements
|
114 |
+
============
|
115 |
+
|
116 |
+
``dill`` requires:
|
117 |
+
|
118 |
+
- ``python`` (or ``pypy``), **>=3.8**
|
119 |
+
- ``setuptools``, **>=42**
|
120 |
+
|
121 |
+
Optional requirements:
|
122 |
+
|
123 |
+
- ``objgraph``, **>=1.7.2**
|
124 |
+
- ``gprof2dot``, **>=2022.7.29**
|
125 |
+
- ``pyreadline``, **>=1.7.1** (on windows)
|
126 |
+
|
127 |
+
|
128 |
+
Basic Usage
|
129 |
+
===========
|
130 |
+
|
131 |
+
``dill`` is a drop-in replacement for ``pickle``. Existing code can be
|
132 |
+
updated to allow complete pickling using::
|
133 |
+
|
134 |
+
>>> import dill as pickle
|
135 |
+
|
136 |
+
or::
|
137 |
+
|
138 |
+
>>> from dill import dumps, loads
|
139 |
+
|
140 |
+
``dumps`` converts the object to a unique byte string, and ``loads`` performs
|
141 |
+
the inverse operation::
|
142 |
+
|
143 |
+
>>> squared = lambda x: x**2
|
144 |
+
>>> loads(dumps(squared))(3)
|
145 |
+
9
|
146 |
+
|
147 |
+
There are a number of options to control serialization which are provided
|
148 |
+
as keyword arguments to several ``dill`` functions:
|
149 |
+
|
150 |
+
* with *protocol*, the pickle protocol level can be set. This uses the
|
151 |
+
same value as the ``pickle`` module, *DEFAULT_PROTOCOL*.
|
152 |
+
* with *byref=True*, ``dill`` to behave a lot more like pickle with
|
153 |
+
certain objects (like modules) pickled by reference as opposed to
|
154 |
+
attempting to pickle the object itself.
|
155 |
+
* with *recurse=True*, objects referred to in the global dictionary are
|
156 |
+
recursively traced and pickled, instead of the default behavior of
|
157 |
+
attempting to store the entire global dictionary.
|
158 |
+
* with *fmode*, the contents of the file can be pickled along with the file
|
159 |
+
handle, which is useful if the object is being sent over the wire to a
|
160 |
+
remote system which does not have the original file on disk. Options are
|
161 |
+
*HANDLE_FMODE* for just the handle, *CONTENTS_FMODE* for the file content
|
162 |
+
and *FILE_FMODE* for content and handle.
|
163 |
+
* with *ignore=False*, objects reconstructed with types defined in the
|
164 |
+
top-level script environment use the existing type in the environment
|
165 |
+
rather than a possibly different reconstructed type.
|
166 |
+
|
167 |
+
The default serialization can also be set globally in *dill.settings*.
|
168 |
+
Thus, we can modify how ``dill`` handles references to the global dictionary
|
169 |
+
locally or globally::
|
170 |
+
|
171 |
+
>>> import dill.settings
|
172 |
+
>>> dumps(absolute) == dumps(absolute, recurse=True)
|
173 |
+
False
|
174 |
+
>>> dill.settings['recurse'] = True
|
175 |
+
>>> dumps(absolute) == dumps(absolute, recurse=True)
|
176 |
+
True
|
177 |
+
|
178 |
+
``dill`` also includes source code inspection, as an alternate to pickling::
|
179 |
+
|
180 |
+
>>> import dill.source
|
181 |
+
>>> print(dill.source.getsource(squared))
|
182 |
+
squared = lambda x:x**2
|
183 |
+
|
184 |
+
To aid in debugging pickling issues, use *dill.detect* which provides
|
185 |
+
tools like pickle tracing::
|
186 |
+
|
187 |
+
>>> import dill.detect
|
188 |
+
>>> with dill.detect.trace():
|
189 |
+
>>> dumps(squared)
|
190 |
+
β¬ F1: <function <lambda> at 0x7fe074f8c280>
|
191 |
+
ββ¬ F2: <function _create_function at 0x7fe074c49c10>
|
192 |
+
ββ # F2 [34 B]
|
193 |
+
ββ¬ Co: <code object <lambda> at 0x7fe07501eb30, file "<stdin>", line 1>
|
194 |
+
βββ¬ F2: <function _create_code at 0x7fe074c49ca0>
|
195 |
+
βββ # F2 [19 B]
|
196 |
+
ββ # Co [87 B]
|
197 |
+
ββ¬ D1: <dict object at 0x7fe0750d4680>
|
198 |
+
ββ # D1 [22 B]
|
199 |
+
ββ¬ D2: <dict object at 0x7fe074c5a1c0>
|
200 |
+
ββ # D2 [2 B]
|
201 |
+
ββ¬ D2: <dict object at 0x7fe074f903c0>
|
202 |
+
βββ¬ D2: <dict object at 0x7fe074f8ebc0>
|
203 |
+
βββ # D2 [2 B]
|
204 |
+
ββ # D2 [23 B]
|
205 |
+
β # F1 [180 B]
|
206 |
+
|
207 |
+
With trace, we see how ``dill`` stored the lambda (``F1``) by first storing
|
208 |
+
``_create_function``, the underlying code object (``Co``) and ``_create_code``
|
209 |
+
(which is used to handle code objects), then we handle the reference to
|
210 |
+
the global dict (``D2``) plus other dictionaries (``D1`` and ``D2``) that
|
211 |
+
save the lambda object's state. A ``#`` marks when the object is actually stored.
|
212 |
+
|
213 |
+
|
214 |
+
More Information
|
215 |
+
================
|
216 |
+
|
217 |
+
Probably the best way to get started is to look at the documentation at
|
218 |
+
http://dill.rtfd.io. Also see ``dill.tests`` for a set of scripts that
|
219 |
+
demonstrate how ``dill`` can serialize different Python objects. You can
|
220 |
+
run the test suite with ``python -m dill.tests``. The contents of any
|
221 |
+
pickle file can be examined with ``undill``. As ``dill`` conforms to
|
222 |
+
the ``pickle`` interface, the examples and documentation found at
|
223 |
+
http://docs.python.org/library/pickle.html also apply to ``dill``
|
224 |
+
if one will ``import dill as pickle``. The source code is also generally
|
225 |
+
well documented, so further questions may be resolved by inspecting the
|
226 |
+
code itself. Please feel free to submit a ticket on github, or ask a
|
227 |
+
question on stackoverflow (**@Mike McKerns**).
|
228 |
+
If you would like to share how you use ``dill`` in your work, please send
|
229 |
+
an email (to **mmckerns at uqfoundation dot org**).
|
230 |
+
|
231 |
+
|
232 |
+
Citation
|
233 |
+
========
|
234 |
+
|
235 |
+
If you use ``dill`` to do research that leads to publication, we ask that you
|
236 |
+
acknowledge use of ``dill`` by citing the following in your publication::
|
237 |
+
|
238 |
+
M.M. McKerns, L. Strand, T. Sullivan, A. Fang, M.A.G. Aivazis,
|
239 |
+
"Building a framework for predictive science", Proceedings of
|
240 |
+
the 10th Python in Science Conference, 2011;
|
241 |
+
http://arxiv.org/pdf/1202.1056
|
242 |
+
|
243 |
+
Michael McKerns and Michael Aivazis,
|
244 |
+
"pathos: a framework for heterogeneous computing", 2010- ;
|
245 |
+
https://uqfoundation.github.io/project/pathos
|
246 |
+
|
247 |
+
Please see https://uqfoundation.github.io/project/pathos or
|
248 |
+
http://arxiv.org/pdf/1202.1056 for further information.
|
249 |
+
|
250 |
+
'''
|
251 |
+
|
252 |
+
__version__ = '0.3.8'
|
253 |
+
__author__ = 'Mike McKerns'
|
254 |
+
|
255 |
+
__license__ = '''
|
256 |
+
Copyright (c) 2004-2016 California Institute of Technology.
|
257 |
+
Copyright (c) 2016-2024 The Uncertainty Quantification Foundation.
|
258 |
+
All rights reserved.
|
259 |
+
|
260 |
+
This software is available subject to the conditions and terms laid
|
261 |
+
out below. By downloading and using this software you are agreeing
|
262 |
+
to the following conditions.
|
263 |
+
|
264 |
+
Redistribution and use in source and binary forms, with or without
|
265 |
+
modification, are permitted provided that the following conditions
|
266 |
+
are met:
|
267 |
+
|
268 |
+
- Redistributions of source code must retain the above copyright
|
269 |
+
notice, this list of conditions and the following disclaimer.
|
270 |
+
|
271 |
+
- Redistributions in binary form must reproduce the above copyright
|
272 |
+
notice, this list of conditions and the following disclaimer in the
|
273 |
+
documentation and/or other materials provided with the distribution.
|
274 |
+
|
275 |
+
- Neither the names of the copyright holders nor the names of any of
|
276 |
+
the contributors may be used to endorse or promote products derived
|
277 |
+
from this software without specific prior written permission.
|
278 |
+
|
279 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
280 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
281 |
+
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
282 |
+
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
283 |
+
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
284 |
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
285 |
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
|
286 |
+
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
287 |
+
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
288 |
+
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
|
289 |
+
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
290 |
+
|
291 |
+
'''
|