Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/other.cpython-310.pyc +0 -0
- llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal.cpython-310.pyc +0 -0
- llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/_mapping.py +23 -0
- llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/svg.py +185 -0
- llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/terminal256.py +338 -0
- minigpt2/lib/python3.10/site-packages/click/__init__.py +73 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/_compat.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/_termui_impl.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/_textwrap.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/_winconsole.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/core.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/decorators.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/exceptions.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/formatting.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/globals.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/parser.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/shell_completion.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/termui.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/testing.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/__pycache__/types.cpython-310.pyc +0 -0
- minigpt2/lib/python3.10/site-packages/click/_compat.py +623 -0
- minigpt2/lib/python3.10/site-packages/click/_termui_impl.py +739 -0
- minigpt2/lib/python3.10/site-packages/click/_textwrap.py +49 -0
- minigpt2/lib/python3.10/site-packages/click/core.py +0 -0
- minigpt2/lib/python3.10/site-packages/click/decorators.py +561 -0
- minigpt2/lib/python3.10/site-packages/click/exceptions.py +288 -0
- minigpt2/lib/python3.10/site-packages/click/formatting.py +301 -0
- minigpt2/lib/python3.10/site-packages/click/globals.py +68 -0
- minigpt2/lib/python3.10/site-packages/click/parser.py +529 -0
- minigpt2/lib/python3.10/site-packages/click/py.typed +0 -0
- minigpt2/lib/python3.10/site-packages/click/termui.py +784 -0
- minigpt2/lib/python3.10/site-packages/click/testing.py +479 -0
- minigpt2/lib/python3.10/site-packages/click/types.py +1089 -0
- minigpt2/lib/python3.10/site-packages/click/utils.py +624 -0
- minigpt2/lib/python3.10/site-packages/lazy_loader-0.4.dist-info/METADATA +207 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_efficientzerotensor_compositeexplicitautograd_dispatch.h +26 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_frac.h +44 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_jagged_to_padded_dense_forward_native.h +21 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_logcumsumexp_cuda_dispatch.h +25 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_copy_native.h +22 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_mask_left_aligned_ops.h +28 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_pack_padded_sequence_backward_ops.h +28 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_transformer_encoder_layer_fwd_native.h +22 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_validate_compressed_sparse_indices_ops.h +28 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_max_pool2d_backward.h +39 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/addcdiv_cuda_dispatch.h +26 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_cpu_dispatch.h +26 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/bmm_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/bucketize_cpu_dispatch.h +26 -0
- parrot/lib/python3.10/site-packages/torch/include/ATen/ops/cartesian_prod_compositeimplicitautograd_dispatch.h +23 -0
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/other.cpython-310.pyc
ADDED
|
Binary file (4.79 kB). View file
|
|
|
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal.cpython-310.pyc
ADDED
|
Binary file (3.98 kB). View file
|
|
|
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/_mapping.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Automatically generated by scripts/gen_mapfiles.py.
|
| 2 |
+
# DO NOT EDIT BY HAND; run `tox -e mapfiles` instead.
|
| 3 |
+
|
| 4 |
+
FORMATTERS = {
|
| 5 |
+
'BBCodeFormatter': ('pygments.formatters.bbcode', 'BBCode', ('bbcode', 'bb'), (), 'Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.'),
|
| 6 |
+
'BmpImageFormatter': ('pygments.formatters.img', 'img_bmp', ('bmp', 'bitmap'), ('*.bmp',), 'Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
|
| 7 |
+
'GifImageFormatter': ('pygments.formatters.img', 'img_gif', ('gif',), ('*.gif',), 'Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
|
| 8 |
+
'GroffFormatter': ('pygments.formatters.groff', 'groff', ('groff', 'troff', 'roff'), (), 'Format tokens with groff escapes to change their color and font style.'),
|
| 9 |
+
'HtmlFormatter': ('pygments.formatters.html', 'HTML', ('html',), ('*.html', '*.htm'), "Format tokens as HTML 4 ``<span>`` tags. By default, the content is enclosed in a ``<pre>`` tag, itself wrapped in a ``<div>`` tag (but see the `nowrap` option). The ``<div>``'s CSS class can be set by the `cssclass` option."),
|
| 10 |
+
'IRCFormatter': ('pygments.formatters.irc', 'IRC', ('irc', 'IRC'), (), 'Format tokens with IRC color sequences'),
|
| 11 |
+
'ImageFormatter': ('pygments.formatters.img', 'img', ('img', 'IMG', 'png'), ('*.png',), 'Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
|
| 12 |
+
'JpgImageFormatter': ('pygments.formatters.img', 'img_jpg', ('jpg', 'jpeg'), ('*.jpg',), 'Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
|
| 13 |
+
'LatexFormatter': ('pygments.formatters.latex', 'LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'),
|
| 14 |
+
'NullFormatter': ('pygments.formatters.other', 'Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'),
|
| 15 |
+
'PangoMarkupFormatter': ('pygments.formatters.pangomarkup', 'Pango Markup', ('pango', 'pangomarkup'), (), 'Format tokens as Pango Markup code. It can then be rendered to an SVG.'),
|
| 16 |
+
'RawTokenFormatter': ('pygments.formatters.other', 'Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'),
|
| 17 |
+
'RtfFormatter': ('pygments.formatters.rtf', 'RTF', ('rtf',), ('*.rtf',), 'Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents.'),
|
| 18 |
+
'SvgFormatter': ('pygments.formatters.svg', 'SVG', ('svg',), ('*.svg',), 'Format tokens as an SVG graphics file. This formatter is still experimental. Each line of code is a ``<text>`` element with explicit ``x`` and ``y`` coordinates containing ``<tspan>`` elements with the individual token styles.'),
|
| 19 |
+
'Terminal256Formatter': ('pygments.formatters.terminal256', 'Terminal256', ('terminal256', 'console256', '256'), (), 'Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),
|
| 20 |
+
'TerminalFormatter': ('pygments.formatters.terminal', 'Terminal', ('terminal', 'console'), (), 'Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.'),
|
| 21 |
+
'TerminalTrueColorFormatter': ('pygments.formatters.terminal256', 'TerminalTrueColor', ('terminal16m', 'console16m', '16m'), (), 'Format tokens with ANSI color sequences, for output in a true-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),
|
| 22 |
+
'TestcaseFormatter': ('pygments.formatters.other', 'Testcase', ('testcase',), (), 'Format tokens as appropriate for a new testcase.'),
|
| 23 |
+
}
|
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/svg.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.formatters.svg
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Formatter for SVG output.
|
| 6 |
+
|
| 7 |
+
:copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
|
| 8 |
+
:license: BSD, see LICENSE for details.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pip._vendor.pygments.formatter import Formatter
|
| 12 |
+
from pip._vendor.pygments.token import Comment
|
| 13 |
+
from pip._vendor.pygments.util import get_bool_opt, get_int_opt
|
| 14 |
+
|
| 15 |
+
__all__ = ['SvgFormatter']
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def escape_html(text):
|
| 19 |
+
"""Escape &, <, > as well as single and double quotes for HTML."""
|
| 20 |
+
return text.replace('&', '&'). \
|
| 21 |
+
replace('<', '<'). \
|
| 22 |
+
replace('>', '>'). \
|
| 23 |
+
replace('"', '"'). \
|
| 24 |
+
replace("'", ''')
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class2style = {}
|
| 28 |
+
|
| 29 |
+
class SvgFormatter(Formatter):
|
| 30 |
+
"""
|
| 31 |
+
Format tokens as an SVG graphics file. This formatter is still experimental.
|
| 32 |
+
Each line of code is a ``<text>`` element with explicit ``x`` and ``y``
|
| 33 |
+
coordinates containing ``<tspan>`` elements with the individual token styles.
|
| 34 |
+
|
| 35 |
+
By default, this formatter outputs a full SVG document including doctype
|
| 36 |
+
declaration and the ``<svg>`` root element.
|
| 37 |
+
|
| 38 |
+
.. versionadded:: 0.9
|
| 39 |
+
|
| 40 |
+
Additional options accepted:
|
| 41 |
+
|
| 42 |
+
`nowrap`
|
| 43 |
+
Don't wrap the SVG ``<text>`` elements in ``<svg><g>`` elements and
|
| 44 |
+
don't add a XML declaration and a doctype. If true, the `fontfamily`
|
| 45 |
+
and `fontsize` options are ignored. Defaults to ``False``.
|
| 46 |
+
|
| 47 |
+
`fontfamily`
|
| 48 |
+
The value to give the wrapping ``<g>`` element's ``font-family``
|
| 49 |
+
attribute, defaults to ``"monospace"``.
|
| 50 |
+
|
| 51 |
+
`fontsize`
|
| 52 |
+
The value to give the wrapping ``<g>`` element's ``font-size``
|
| 53 |
+
attribute, defaults to ``"14px"``.
|
| 54 |
+
|
| 55 |
+
`linenos`
|
| 56 |
+
If ``True``, add line numbers (default: ``False``).
|
| 57 |
+
|
| 58 |
+
`linenostart`
|
| 59 |
+
The line number for the first line (default: ``1``).
|
| 60 |
+
|
| 61 |
+
`linenostep`
|
| 62 |
+
If set to a number n > 1, only every nth line number is printed.
|
| 63 |
+
|
| 64 |
+
`linenowidth`
|
| 65 |
+
Maximum width devoted to line numbers (default: ``3*ystep``, sufficient
|
| 66 |
+
for up to 4-digit line numbers. Increase width for longer code blocks).
|
| 67 |
+
|
| 68 |
+
`xoffset`
|
| 69 |
+
Starting offset in X direction, defaults to ``0``.
|
| 70 |
+
|
| 71 |
+
`yoffset`
|
| 72 |
+
Starting offset in Y direction, defaults to the font size if it is given
|
| 73 |
+
in pixels, or ``20`` else. (This is necessary since text coordinates
|
| 74 |
+
refer to the text baseline, not the top edge.)
|
| 75 |
+
|
| 76 |
+
`ystep`
|
| 77 |
+
Offset to add to the Y coordinate for each subsequent line. This should
|
| 78 |
+
roughly be the text size plus 5. It defaults to that value if the text
|
| 79 |
+
size is given in pixels, or ``25`` else.
|
| 80 |
+
|
| 81 |
+
`spacehack`
|
| 82 |
+
Convert spaces in the source to `` ``, which are non-breaking
|
| 83 |
+
spaces. SVG provides the ``xml:space`` attribute to control how
|
| 84 |
+
whitespace inside tags is handled, in theory, the ``preserve`` value
|
| 85 |
+
could be used to keep all whitespace as-is. However, many current SVG
|
| 86 |
+
viewers don't obey that rule, so this option is provided as a workaround
|
| 87 |
+
and defaults to ``True``.
|
| 88 |
+
"""
|
| 89 |
+
name = 'SVG'
|
| 90 |
+
aliases = ['svg']
|
| 91 |
+
filenames = ['*.svg']
|
| 92 |
+
|
| 93 |
+
def __init__(self, **options):
|
| 94 |
+
Formatter.__init__(self, **options)
|
| 95 |
+
self.nowrap = get_bool_opt(options, 'nowrap', False)
|
| 96 |
+
self.fontfamily = options.get('fontfamily', 'monospace')
|
| 97 |
+
self.fontsize = options.get('fontsize', '14px')
|
| 98 |
+
self.xoffset = get_int_opt(options, 'xoffset', 0)
|
| 99 |
+
fs = self.fontsize.strip()
|
| 100 |
+
if fs.endswith('px'):
|
| 101 |
+
fs = fs[:-2].strip()
|
| 102 |
+
try:
|
| 103 |
+
int_fs = int(fs)
|
| 104 |
+
except ValueError:
|
| 105 |
+
int_fs = 20
|
| 106 |
+
self.yoffset = get_int_opt(options, 'yoffset', int_fs)
|
| 107 |
+
self.ystep = get_int_opt(options, 'ystep', int_fs + 5)
|
| 108 |
+
self.spacehack = get_bool_opt(options, 'spacehack', True)
|
| 109 |
+
self.linenos = get_bool_opt(options,'linenos',False)
|
| 110 |
+
self.linenostart = get_int_opt(options,'linenostart',1)
|
| 111 |
+
self.linenostep = get_int_opt(options,'linenostep',1)
|
| 112 |
+
self.linenowidth = get_int_opt(options,'linenowidth', 3*self.ystep)
|
| 113 |
+
self._stylecache = {}
|
| 114 |
+
|
| 115 |
+
def format_unencoded(self, tokensource, outfile):
|
| 116 |
+
"""
|
| 117 |
+
Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
|
| 118 |
+
tuples and write it into ``outfile``.
|
| 119 |
+
|
| 120 |
+
For our implementation we put all lines in their own 'line group'.
|
| 121 |
+
"""
|
| 122 |
+
x = self.xoffset
|
| 123 |
+
y = self.yoffset
|
| 124 |
+
if not self.nowrap:
|
| 125 |
+
if self.encoding:
|
| 126 |
+
outfile.write(f'<?xml version="1.0" encoding="{self.encoding}"?>\n')
|
| 127 |
+
else:
|
| 128 |
+
outfile.write('<?xml version="1.0"?>\n')
|
| 129 |
+
outfile.write('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" '
|
| 130 |
+
'"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/'
|
| 131 |
+
'svg10.dtd">\n')
|
| 132 |
+
outfile.write('<svg xmlns="http://www.w3.org/2000/svg">\n')
|
| 133 |
+
outfile.write(f'<g font-family="{self.fontfamily}" font-size="{self.fontsize}">\n')
|
| 134 |
+
|
| 135 |
+
counter = self.linenostart
|
| 136 |
+
counter_step = self.linenostep
|
| 137 |
+
counter_style = self._get_style(Comment)
|
| 138 |
+
line_x = x
|
| 139 |
+
|
| 140 |
+
if self.linenos:
|
| 141 |
+
if counter % counter_step == 0:
|
| 142 |
+
outfile.write(f'<text x="{x+self.linenowidth}" y="{y}" {counter_style} text-anchor="end">{counter}</text>')
|
| 143 |
+
line_x += self.linenowidth + self.ystep
|
| 144 |
+
counter += 1
|
| 145 |
+
|
| 146 |
+
outfile.write(f'<text x="{line_x}" y="{y}" xml:space="preserve">')
|
| 147 |
+
for ttype, value in tokensource:
|
| 148 |
+
style = self._get_style(ttype)
|
| 149 |
+
tspan = style and '<tspan' + style + '>' or ''
|
| 150 |
+
tspanend = tspan and '</tspan>' or ''
|
| 151 |
+
value = escape_html(value)
|
| 152 |
+
if self.spacehack:
|
| 153 |
+
value = value.expandtabs().replace(' ', ' ')
|
| 154 |
+
parts = value.split('\n')
|
| 155 |
+
for part in parts[:-1]:
|
| 156 |
+
outfile.write(tspan + part + tspanend)
|
| 157 |
+
y += self.ystep
|
| 158 |
+
outfile.write('</text>\n')
|
| 159 |
+
if self.linenos and counter % counter_step == 0:
|
| 160 |
+
outfile.write(f'<text x="{x+self.linenowidth}" y="{y}" text-anchor="end" {counter_style}>{counter}</text>')
|
| 161 |
+
|
| 162 |
+
counter += 1
|
| 163 |
+
outfile.write(f'<text x="{line_x}" y="{y}" ' 'xml:space="preserve">')
|
| 164 |
+
outfile.write(tspan + parts[-1] + tspanend)
|
| 165 |
+
outfile.write('</text>')
|
| 166 |
+
|
| 167 |
+
if not self.nowrap:
|
| 168 |
+
outfile.write('</g></svg>\n')
|
| 169 |
+
|
| 170 |
+
def _get_style(self, tokentype):
|
| 171 |
+
if tokentype in self._stylecache:
|
| 172 |
+
return self._stylecache[tokentype]
|
| 173 |
+
otokentype = tokentype
|
| 174 |
+
while not self.style.styles_token(tokentype):
|
| 175 |
+
tokentype = tokentype.parent
|
| 176 |
+
value = self.style.style_for_token(tokentype)
|
| 177 |
+
result = ''
|
| 178 |
+
if value['color']:
|
| 179 |
+
result = ' fill="#' + value['color'] + '"'
|
| 180 |
+
if value['bold']:
|
| 181 |
+
result += ' font-weight="bold"'
|
| 182 |
+
if value['italic']:
|
| 183 |
+
result += ' font-style="italic"'
|
| 184 |
+
self._stylecache[otokentype] = result
|
| 185 |
+
return result
|
llava/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/terminal256.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
pygments.formatters.terminal256
|
| 3 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 4 |
+
|
| 5 |
+
Formatter for 256-color terminal output with ANSI sequences.
|
| 6 |
+
|
| 7 |
+
RGB-to-XTERM color conversion routines adapted from xterm256-conv
|
| 8 |
+
tool (http://frexx.de/xterm-256-notes/data/xterm256-conv2.tar.bz2)
|
| 9 |
+
by Wolfgang Frisch.
|
| 10 |
+
|
| 11 |
+
Formatter version 1.
|
| 12 |
+
|
| 13 |
+
:copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
|
| 14 |
+
:license: BSD, see LICENSE for details.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
# TODO:
|
| 18 |
+
# - Options to map style's bold/underline/italic/border attributes
|
| 19 |
+
# to some ANSI attrbutes (something like 'italic=underline')
|
| 20 |
+
# - An option to output "style RGB to xterm RGB/index" conversion table
|
| 21 |
+
# - An option to indicate that we are running in "reverse background"
|
| 22 |
+
# xterm. This means that default colors are white-on-black, not
|
| 23 |
+
# black-on-while, so colors like "white background" need to be converted
|
| 24 |
+
# to "white background, black foreground", etc...
|
| 25 |
+
|
| 26 |
+
from pip._vendor.pygments.formatter import Formatter
|
| 27 |
+
from pip._vendor.pygments.console import codes
|
| 28 |
+
from pip._vendor.pygments.style import ansicolors
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
__all__ = ['Terminal256Formatter', 'TerminalTrueColorFormatter']
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class EscapeSequence:
|
| 35 |
+
def __init__(self, fg=None, bg=None, bold=False, underline=False, italic=False):
|
| 36 |
+
self.fg = fg
|
| 37 |
+
self.bg = bg
|
| 38 |
+
self.bold = bold
|
| 39 |
+
self.underline = underline
|
| 40 |
+
self.italic = italic
|
| 41 |
+
|
| 42 |
+
def escape(self, attrs):
|
| 43 |
+
if len(attrs):
|
| 44 |
+
return "\x1b[" + ";".join(attrs) + "m"
|
| 45 |
+
return ""
|
| 46 |
+
|
| 47 |
+
def color_string(self):
|
| 48 |
+
attrs = []
|
| 49 |
+
if self.fg is not None:
|
| 50 |
+
if self.fg in ansicolors:
|
| 51 |
+
esc = codes[self.fg.replace('ansi','')]
|
| 52 |
+
if ';01m' in esc:
|
| 53 |
+
self.bold = True
|
| 54 |
+
# extract fg color code.
|
| 55 |
+
attrs.append(esc[2:4])
|
| 56 |
+
else:
|
| 57 |
+
attrs.extend(("38", "5", "%i" % self.fg))
|
| 58 |
+
if self.bg is not None:
|
| 59 |
+
if self.bg in ansicolors:
|
| 60 |
+
esc = codes[self.bg.replace('ansi','')]
|
| 61 |
+
# extract fg color code, add 10 for bg.
|
| 62 |
+
attrs.append(str(int(esc[2:4])+10))
|
| 63 |
+
else:
|
| 64 |
+
attrs.extend(("48", "5", "%i" % self.bg))
|
| 65 |
+
if self.bold:
|
| 66 |
+
attrs.append("01")
|
| 67 |
+
if self.underline:
|
| 68 |
+
attrs.append("04")
|
| 69 |
+
if self.italic:
|
| 70 |
+
attrs.append("03")
|
| 71 |
+
return self.escape(attrs)
|
| 72 |
+
|
| 73 |
+
def true_color_string(self):
|
| 74 |
+
attrs = []
|
| 75 |
+
if self.fg:
|
| 76 |
+
attrs.extend(("38", "2", str(self.fg[0]), str(self.fg[1]), str(self.fg[2])))
|
| 77 |
+
if self.bg:
|
| 78 |
+
attrs.extend(("48", "2", str(self.bg[0]), str(self.bg[1]), str(self.bg[2])))
|
| 79 |
+
if self.bold:
|
| 80 |
+
attrs.append("01")
|
| 81 |
+
if self.underline:
|
| 82 |
+
attrs.append("04")
|
| 83 |
+
if self.italic:
|
| 84 |
+
attrs.append("03")
|
| 85 |
+
return self.escape(attrs)
|
| 86 |
+
|
| 87 |
+
def reset_string(self):
|
| 88 |
+
attrs = []
|
| 89 |
+
if self.fg is not None:
|
| 90 |
+
attrs.append("39")
|
| 91 |
+
if self.bg is not None:
|
| 92 |
+
attrs.append("49")
|
| 93 |
+
if self.bold or self.underline or self.italic:
|
| 94 |
+
attrs.append("00")
|
| 95 |
+
return self.escape(attrs)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class Terminal256Formatter(Formatter):
|
| 99 |
+
"""
|
| 100 |
+
Format tokens with ANSI color sequences, for output in a 256-color
|
| 101 |
+
terminal or console. Like in `TerminalFormatter` color sequences
|
| 102 |
+
are terminated at newlines, so that paging the output works correctly.
|
| 103 |
+
|
| 104 |
+
The formatter takes colors from a style defined by the `style` option
|
| 105 |
+
and converts them to nearest ANSI 256-color escape sequences. Bold and
|
| 106 |
+
underline attributes from the style are preserved (and displayed).
|
| 107 |
+
|
| 108 |
+
.. versionadded:: 0.9
|
| 109 |
+
|
| 110 |
+
.. versionchanged:: 2.2
|
| 111 |
+
If the used style defines foreground colors in the form ``#ansi*``, then
|
| 112 |
+
`Terminal256Formatter` will map these to non extended foreground color.
|
| 113 |
+
See :ref:`AnsiTerminalStyle` for more information.
|
| 114 |
+
|
| 115 |
+
.. versionchanged:: 2.4
|
| 116 |
+
The ANSI color names have been updated with names that are easier to
|
| 117 |
+
understand and align with colornames of other projects and terminals.
|
| 118 |
+
See :ref:`this table <new-ansi-color-names>` for more information.
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
Options accepted:
|
| 122 |
+
|
| 123 |
+
`style`
|
| 124 |
+
The style to use, can be a string or a Style subclass (default:
|
| 125 |
+
``'default'``).
|
| 126 |
+
|
| 127 |
+
`linenos`
|
| 128 |
+
Set to ``True`` to have line numbers on the terminal output as well
|
| 129 |
+
(default: ``False`` = no line numbers).
|
| 130 |
+
"""
|
| 131 |
+
name = 'Terminal256'
|
| 132 |
+
aliases = ['terminal256', 'console256', '256']
|
| 133 |
+
filenames = []
|
| 134 |
+
|
| 135 |
+
def __init__(self, **options):
|
| 136 |
+
Formatter.__init__(self, **options)
|
| 137 |
+
|
| 138 |
+
self.xterm_colors = []
|
| 139 |
+
self.best_match = {}
|
| 140 |
+
self.style_string = {}
|
| 141 |
+
|
| 142 |
+
self.usebold = 'nobold' not in options
|
| 143 |
+
self.useunderline = 'nounderline' not in options
|
| 144 |
+
self.useitalic = 'noitalic' not in options
|
| 145 |
+
|
| 146 |
+
self._build_color_table() # build an RGB-to-256 color conversion table
|
| 147 |
+
self._setup_styles() # convert selected style's colors to term. colors
|
| 148 |
+
|
| 149 |
+
self.linenos = options.get('linenos', False)
|
| 150 |
+
self._lineno = 0
|
| 151 |
+
|
| 152 |
+
def _build_color_table(self):
|
| 153 |
+
# colors 0..15: 16 basic colors
|
| 154 |
+
|
| 155 |
+
self.xterm_colors.append((0x00, 0x00, 0x00)) # 0
|
| 156 |
+
self.xterm_colors.append((0xcd, 0x00, 0x00)) # 1
|
| 157 |
+
self.xterm_colors.append((0x00, 0xcd, 0x00)) # 2
|
| 158 |
+
self.xterm_colors.append((0xcd, 0xcd, 0x00)) # 3
|
| 159 |
+
self.xterm_colors.append((0x00, 0x00, 0xee)) # 4
|
| 160 |
+
self.xterm_colors.append((0xcd, 0x00, 0xcd)) # 5
|
| 161 |
+
self.xterm_colors.append((0x00, 0xcd, 0xcd)) # 6
|
| 162 |
+
self.xterm_colors.append((0xe5, 0xe5, 0xe5)) # 7
|
| 163 |
+
self.xterm_colors.append((0x7f, 0x7f, 0x7f)) # 8
|
| 164 |
+
self.xterm_colors.append((0xff, 0x00, 0x00)) # 9
|
| 165 |
+
self.xterm_colors.append((0x00, 0xff, 0x00)) # 10
|
| 166 |
+
self.xterm_colors.append((0xff, 0xff, 0x00)) # 11
|
| 167 |
+
self.xterm_colors.append((0x5c, 0x5c, 0xff)) # 12
|
| 168 |
+
self.xterm_colors.append((0xff, 0x00, 0xff)) # 13
|
| 169 |
+
self.xterm_colors.append((0x00, 0xff, 0xff)) # 14
|
| 170 |
+
self.xterm_colors.append((0xff, 0xff, 0xff)) # 15
|
| 171 |
+
|
| 172 |
+
# colors 16..232: the 6x6x6 color cube
|
| 173 |
+
|
| 174 |
+
valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
|
| 175 |
+
|
| 176 |
+
for i in range(217):
|
| 177 |
+
r = valuerange[(i // 36) % 6]
|
| 178 |
+
g = valuerange[(i // 6) % 6]
|
| 179 |
+
b = valuerange[i % 6]
|
| 180 |
+
self.xterm_colors.append((r, g, b))
|
| 181 |
+
|
| 182 |
+
# colors 233..253: grayscale
|
| 183 |
+
|
| 184 |
+
for i in range(1, 22):
|
| 185 |
+
v = 8 + i * 10
|
| 186 |
+
self.xterm_colors.append((v, v, v))
|
| 187 |
+
|
| 188 |
+
def _closest_color(self, r, g, b):
|
| 189 |
+
distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
|
| 190 |
+
match = 0
|
| 191 |
+
|
| 192 |
+
for i in range(0, 254):
|
| 193 |
+
values = self.xterm_colors[i]
|
| 194 |
+
|
| 195 |
+
rd = r - values[0]
|
| 196 |
+
gd = g - values[1]
|
| 197 |
+
bd = b - values[2]
|
| 198 |
+
d = rd*rd + gd*gd + bd*bd
|
| 199 |
+
|
| 200 |
+
if d < distance:
|
| 201 |
+
match = i
|
| 202 |
+
distance = d
|
| 203 |
+
return match
|
| 204 |
+
|
| 205 |
+
def _color_index(self, color):
|
| 206 |
+
index = self.best_match.get(color, None)
|
| 207 |
+
if color in ansicolors:
|
| 208 |
+
# strip the `ansi/#ansi` part and look up code
|
| 209 |
+
index = color
|
| 210 |
+
self.best_match[color] = index
|
| 211 |
+
if index is None:
|
| 212 |
+
try:
|
| 213 |
+
rgb = int(str(color), 16)
|
| 214 |
+
except ValueError:
|
| 215 |
+
rgb = 0
|
| 216 |
+
|
| 217 |
+
r = (rgb >> 16) & 0xff
|
| 218 |
+
g = (rgb >> 8) & 0xff
|
| 219 |
+
b = rgb & 0xff
|
| 220 |
+
index = self._closest_color(r, g, b)
|
| 221 |
+
self.best_match[color] = index
|
| 222 |
+
return index
|
| 223 |
+
|
| 224 |
+
def _setup_styles(self):
|
| 225 |
+
for ttype, ndef in self.style:
|
| 226 |
+
escape = EscapeSequence()
|
| 227 |
+
# get foreground from ansicolor if set
|
| 228 |
+
if ndef['ansicolor']:
|
| 229 |
+
escape.fg = self._color_index(ndef['ansicolor'])
|
| 230 |
+
elif ndef['color']:
|
| 231 |
+
escape.fg = self._color_index(ndef['color'])
|
| 232 |
+
if ndef['bgansicolor']:
|
| 233 |
+
escape.bg = self._color_index(ndef['bgansicolor'])
|
| 234 |
+
elif ndef['bgcolor']:
|
| 235 |
+
escape.bg = self._color_index(ndef['bgcolor'])
|
| 236 |
+
if self.usebold and ndef['bold']:
|
| 237 |
+
escape.bold = True
|
| 238 |
+
if self.useunderline and ndef['underline']:
|
| 239 |
+
escape.underline = True
|
| 240 |
+
if self.useitalic and ndef['italic']:
|
| 241 |
+
escape.italic = True
|
| 242 |
+
self.style_string[str(ttype)] = (escape.color_string(),
|
| 243 |
+
escape.reset_string())
|
| 244 |
+
|
| 245 |
+
def _write_lineno(self, outfile):
|
| 246 |
+
self._lineno += 1
|
| 247 |
+
outfile.write("%s%04d: " % (self._lineno != 1 and '\n' or '', self._lineno))
|
| 248 |
+
|
| 249 |
+
def format(self, tokensource, outfile):
|
| 250 |
+
return Formatter.format(self, tokensource, outfile)
|
| 251 |
+
|
| 252 |
+
def format_unencoded(self, tokensource, outfile):
|
| 253 |
+
if self.linenos:
|
| 254 |
+
self._write_lineno(outfile)
|
| 255 |
+
|
| 256 |
+
for ttype, value in tokensource:
|
| 257 |
+
not_found = True
|
| 258 |
+
while ttype and not_found:
|
| 259 |
+
try:
|
| 260 |
+
# outfile.write( "<" + str(ttype) + ">" )
|
| 261 |
+
on, off = self.style_string[str(ttype)]
|
| 262 |
+
|
| 263 |
+
# Like TerminalFormatter, add "reset colors" escape sequence
|
| 264 |
+
# on newline.
|
| 265 |
+
spl = value.split('\n')
|
| 266 |
+
for line in spl[:-1]:
|
| 267 |
+
if line:
|
| 268 |
+
outfile.write(on + line + off)
|
| 269 |
+
if self.linenos:
|
| 270 |
+
self._write_lineno(outfile)
|
| 271 |
+
else:
|
| 272 |
+
outfile.write('\n')
|
| 273 |
+
|
| 274 |
+
if spl[-1]:
|
| 275 |
+
outfile.write(on + spl[-1] + off)
|
| 276 |
+
|
| 277 |
+
not_found = False
|
| 278 |
+
# outfile.write( '#' + str(ttype) + '#' )
|
| 279 |
+
|
| 280 |
+
except KeyError:
|
| 281 |
+
# ottype = ttype
|
| 282 |
+
ttype = ttype.parent
|
| 283 |
+
# outfile.write( '!' + str(ottype) + '->' + str(ttype) + '!' )
|
| 284 |
+
|
| 285 |
+
if not_found:
|
| 286 |
+
outfile.write(value)
|
| 287 |
+
|
| 288 |
+
if self.linenos:
|
| 289 |
+
outfile.write("\n")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class TerminalTrueColorFormatter(Terminal256Formatter):
|
| 294 |
+
r"""
|
| 295 |
+
Format tokens with ANSI color sequences, for output in a true-color
|
| 296 |
+
terminal or console. Like in `TerminalFormatter` color sequences
|
| 297 |
+
are terminated at newlines, so that paging the output works correctly.
|
| 298 |
+
|
| 299 |
+
.. versionadded:: 2.1
|
| 300 |
+
|
| 301 |
+
Options accepted:
|
| 302 |
+
|
| 303 |
+
`style`
|
| 304 |
+
The style to use, can be a string or a Style subclass (default:
|
| 305 |
+
``'default'``).
|
| 306 |
+
"""
|
| 307 |
+
name = 'TerminalTrueColor'
|
| 308 |
+
aliases = ['terminal16m', 'console16m', '16m']
|
| 309 |
+
filenames = []
|
| 310 |
+
|
| 311 |
+
def _build_color_table(self):
|
| 312 |
+
pass
|
| 313 |
+
|
| 314 |
+
def _color_tuple(self, color):
|
| 315 |
+
try:
|
| 316 |
+
rgb = int(str(color), 16)
|
| 317 |
+
except ValueError:
|
| 318 |
+
return None
|
| 319 |
+
r = (rgb >> 16) & 0xff
|
| 320 |
+
g = (rgb >> 8) & 0xff
|
| 321 |
+
b = rgb & 0xff
|
| 322 |
+
return (r, g, b)
|
| 323 |
+
|
| 324 |
+
def _setup_styles(self):
|
| 325 |
+
for ttype, ndef in self.style:
|
| 326 |
+
escape = EscapeSequence()
|
| 327 |
+
if ndef['color']:
|
| 328 |
+
escape.fg = self._color_tuple(ndef['color'])
|
| 329 |
+
if ndef['bgcolor']:
|
| 330 |
+
escape.bg = self._color_tuple(ndef['bgcolor'])
|
| 331 |
+
if self.usebold and ndef['bold']:
|
| 332 |
+
escape.bold = True
|
| 333 |
+
if self.useunderline and ndef['underline']:
|
| 334 |
+
escape.underline = True
|
| 335 |
+
if self.useitalic and ndef['italic']:
|
| 336 |
+
escape.italic = True
|
| 337 |
+
self.style_string[str(ttype)] = (escape.true_color_string(),
|
| 338 |
+
escape.reset_string())
|
minigpt2/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"
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/_compat.cpython-310.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/_termui_impl.cpython-310.pyc
ADDED
|
Binary file (16.3 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/_textwrap.cpython-310.pyc
ADDED
|
Binary file (1.54 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/_winconsole.cpython-310.pyc
ADDED
|
Binary file (7.65 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/core.cpython-310.pyc
ADDED
|
Binary file (91.1 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/decorators.cpython-310.pyc
ADDED
|
Binary file (17.2 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/exceptions.cpython-310.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/formatting.cpython-310.pyc
ADDED
|
Binary file (9.45 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/globals.cpython-310.pyc
ADDED
|
Binary file (2.42 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/parser.cpython-310.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/shell_completion.cpython-310.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/termui.cpython-310.pyc
ADDED
|
Binary file (26.1 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/testing.cpython-310.pyc
ADDED
|
Binary file (15.2 kB). View file
|
|
|
minigpt2/lib/python3.10/site-packages/click/__pycache__/types.cpython-310.pyc
ADDED
|
Binary file (33.7 kB). View file
|
|
|
minigpt2/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 |
+
] = {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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
|
minigpt2/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 |
+
|
| 44 |
+
if idx > 0:
|
| 45 |
+
indent = self.subsequent_indent
|
| 46 |
+
|
| 47 |
+
rv.append(f"{indent}{line}")
|
| 48 |
+
|
| 49 |
+
return "\n".join(rv)
|
minigpt2/lib/python3.10/site-packages/click/core.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
minigpt2/lib/python3.10/site-packages/click/decorators.py
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import types
|
| 3 |
+
import typing as t
|
| 4 |
+
from functools import update_wrapper
|
| 5 |
+
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)
|
minigpt2/lib/python3.10/site-packages/click/exceptions.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
__slots__ = ("exit_code",)
|
| 286 |
+
|
| 287 |
+
def __init__(self, code: int = 0) -> None:
|
| 288 |
+
self.exit_code: int = code
|
minigpt2/lib/python3.10/site-packages/click/formatting.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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
|
minigpt2/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: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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)
|
minigpt2/lib/python3.10/site-packages/click/py.typed
ADDED
|
File without changes
|
minigpt2/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)
|
minigpt2/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
|
minigpt2/lib/python3.10/site-packages/click/types.py
ADDED
|
@@ -0,0 +1,1089 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import stat
|
| 3 |
+
import sys
|
| 4 |
+
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 |
+
#: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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
|
minigpt2/lib/python3.10/site-packages/lazy_loader-0.4.dist-info/METADATA
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
Version: 0.4
|
| 4 |
+
Summary: Makes it easy to load subpackages and functions on demand.
|
| 5 |
+
Author: Scientific Python Developers
|
| 6 |
+
License: BSD 3-Clause License
|
| 7 |
+
|
| 8 |
+
Copyright (c) 2022--2023, Scientific Python project
|
| 9 |
+
All rights reserved.
|
| 10 |
+
|
| 11 |
+
Redistribution and use in source and binary forms, with or without
|
| 12 |
+
modification, are permitted provided that the following conditions are met:
|
| 13 |
+
|
| 14 |
+
1. Redistributions of source code must retain the above copyright notice, this
|
| 15 |
+
list of conditions and the following disclaimer.
|
| 16 |
+
|
| 17 |
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
| 18 |
+
this list of conditions and the following disclaimer in the documentation
|
| 19 |
+
and/or other materials provided with the distribution.
|
| 20 |
+
|
| 21 |
+
3. Neither the name of the copyright holder nor the names of its
|
| 22 |
+
contributors may be used to endorse or promote products derived from
|
| 23 |
+
this software without specific prior written permission.
|
| 24 |
+
|
| 25 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 26 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 27 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 28 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 29 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 30 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 31 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 32 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 33 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 34 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 35 |
+
|
| 36 |
+
Project-URL: Home, https://scientific-python.org/specs/spec-0001/
|
| 37 |
+
Project-URL: Source, https://github.com/scientific-python/lazy_loader
|
| 38 |
+
Classifier: Development Status :: 4 - Beta
|
| 39 |
+
Classifier: License :: OSI Approved :: BSD License
|
| 40 |
+
Classifier: Programming Language :: Python :: 3
|
| 41 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 42 |
+
Classifier: Programming Language :: Python :: 3.8
|
| 43 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 44 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 45 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 46 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 47 |
+
Requires-Python: >=3.7
|
| 48 |
+
Description-Content-Type: text/markdown
|
| 49 |
+
License-File: LICENSE.md
|
| 50 |
+
Requires-Dist: packaging
|
| 51 |
+
Requires-Dist: importlib-metadata ; python_version < "3.8"
|
| 52 |
+
Provides-Extra: dev
|
| 53 |
+
Requires-Dist: changelist ==0.5 ; extra == 'dev'
|
| 54 |
+
Provides-Extra: lint
|
| 55 |
+
Requires-Dist: pre-commit ==3.7.0 ; extra == 'lint'
|
| 56 |
+
Provides-Extra: test
|
| 57 |
+
Requires-Dist: pytest >=7.4 ; extra == 'test'
|
| 58 |
+
Requires-Dist: pytest-cov >=4.1 ; extra == 'test'
|
| 59 |
+
|
| 60 |
+
[](https://pypi.org/project/lazy_loader/)
|
| 61 |
+
[](https://github.com/scientific-python/lazy_loader/actions?query=workflow%3A%22test%22)
|
| 62 |
+
[](https://app.codecov.io/gh/scientific-python/lazy_loader/branch/main)
|
| 63 |
+
|
| 64 |
+
`lazy_loader` makes it easy to load subpackages and functions on demand.
|
| 65 |
+
|
| 66 |
+
## Motivation
|
| 67 |
+
|
| 68 |
+
1. Allow subpackages to be made visible to users without incurring import costs.
|
| 69 |
+
2. Allow external libraries to be imported only when used, improving import times.
|
| 70 |
+
|
| 71 |
+
For a more detailed discussion, see [the SPEC](https://scientific-python.org/specs/spec-0001/).
|
| 72 |
+
|
| 73 |
+
## Installation
|
| 74 |
+
|
| 75 |
+
```
|
| 76 |
+
pip install -U lazy_loader
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
We recommend using `lazy_loader` with Python >= 3.11.
|
| 80 |
+
If using Python 3.11, please upgrade to 3.11.9 or later.
|
| 81 |
+
If using Python 3.12, please upgrade to 3.12.3 or later.
|
| 82 |
+
These versions [avoid](https://github.com/python/cpython/pull/114781) a [known race condition](https://github.com/python/cpython/issues/114763).
|
| 83 |
+
|
| 84 |
+
## Usage
|
| 85 |
+
|
| 86 |
+
### Lazily load subpackages
|
| 87 |
+
|
| 88 |
+
Consider the `__init__.py` from [scikit-image](https://scikit-image.org):
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
subpackages = [
|
| 92 |
+
...,
|
| 93 |
+
'filters',
|
| 94 |
+
...
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
import lazy_loader as lazy
|
| 98 |
+
__getattr__, __dir__, _ = lazy.attach(__name__, subpackages)
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
You can now do:
|
| 102 |
+
|
| 103 |
+
```python
|
| 104 |
+
import skimage as ski
|
| 105 |
+
ski.filters.gaussian(...)
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
The `filters` subpackages will only be loaded once accessed.
|
| 109 |
+
|
| 110 |
+
### Lazily load subpackages and functions
|
| 111 |
+
|
| 112 |
+
Consider `skimage/filters/__init__.py`:
|
| 113 |
+
|
| 114 |
+
```python
|
| 115 |
+
from ..util import lazy
|
| 116 |
+
|
| 117 |
+
__getattr__, __dir__, __all__ = lazy.attach(
|
| 118 |
+
__name__,
|
| 119 |
+
submodules=['rank'],
|
| 120 |
+
submod_attrs={
|
| 121 |
+
'_gaussian': ['gaussian', 'difference_of_gaussians'],
|
| 122 |
+
'edges': ['sobel', 'scharr', 'prewitt', 'roberts',
|
| 123 |
+
'laplace', 'farid']
|
| 124 |
+
}
|
| 125 |
+
)
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
The above is equivalent to:
|
| 129 |
+
|
| 130 |
+
```python
|
| 131 |
+
from . import rank
|
| 132 |
+
from ._gaussian import gaussian, difference_of_gaussians
|
| 133 |
+
from .edges import (sobel, scharr, prewitt, roberts,
|
| 134 |
+
laplace, farid)
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
Except that all subpackages (such as `rank`) and functions (such as `sobel`) are loaded upon access.
|
| 138 |
+
|
| 139 |
+
### Type checkers
|
| 140 |
+
|
| 141 |
+
Static type checkers and IDEs cannot infer type information from
|
| 142 |
+
lazily loaded imports. As a workaround you can load [type
|
| 143 |
+
stubs](https://mypy.readthedocs.io/en/stable/stubs.html) (`.pyi`
|
| 144 |
+
files) with `lazy.attach_stub`:
|
| 145 |
+
|
| 146 |
+
```python
|
| 147 |
+
import lazy_loader as lazy
|
| 148 |
+
__getattr__, __dir__, _ = lazy.attach_stub(__name__, "subpackages.pyi")
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
Note that, since imports are now defined in `.pyi` files, those
|
| 152 |
+
are not only necessary for type checking but also at runtime.
|
| 153 |
+
|
| 154 |
+
The SPEC [describes this workaround in more
|
| 155 |
+
detail](https://scientific-python.org/specs/spec-0001/#type-checkers).
|
| 156 |
+
|
| 157 |
+
### Early failure
|
| 158 |
+
|
| 159 |
+
With lazy loading, missing imports no longer fail upon loading the
|
| 160 |
+
library. During development and testing, you can set the `EAGER_IMPORT`
|
| 161 |
+
environment variable to disable lazy loading.
|
| 162 |
+
|
| 163 |
+
### External libraries
|
| 164 |
+
|
| 165 |
+
The `lazy.attach` function discussed above is used to set up package
|
| 166 |
+
internal imports.
|
| 167 |
+
|
| 168 |
+
Use `lazy.load` to lazily import external libraries:
|
| 169 |
+
|
| 170 |
+
```python
|
| 171 |
+
sp = lazy.load('scipy') # `sp` will only be loaded when accessed
|
| 172 |
+
sp.linalg.norm(...)
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
_Note that lazily importing *sub*packages,
|
| 176 |
+
i.e. `load('scipy.linalg')` will cause the package containing the
|
| 177 |
+
subpackage to be imported immediately; thus, this usage is
|
| 178 |
+
discouraged._
|
| 179 |
+
|
| 180 |
+
You can ask `lazy.load` to raise import errors as soon as it is called:
|
| 181 |
+
|
| 182 |
+
```python
|
| 183 |
+
linalg = lazy.load('scipy.linalg', error_on_import=True)
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
#### Optional requirements
|
| 187 |
+
|
| 188 |
+
One use for lazy loading is for loading optional dependencies, with
|
| 189 |
+
`ImportErrors` only arising when optional functionality is accessed. If optional
|
| 190 |
+
functionality depends on a specific version, a version requirement can
|
| 191 |
+
be set:
|
| 192 |
+
|
| 193 |
+
```python
|
| 194 |
+
np = lazy.load("numpy", require="numpy >=1.24")
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
In this case, if `numpy` is installed, but the version is less than 1.24,
|
| 198 |
+
the `np` module returned will raise an error on attribute access. Using
|
| 199 |
+
this feature is not all-or-nothing: One module may rely on one version of
|
| 200 |
+
numpy, while another module may not set any requirement.
|
| 201 |
+
|
| 202 |
+
_Note that the requirement must use the package [distribution name][] instead
|
| 203 |
+
of the module [import name][]. For example, the `pyyaml` distribution provides
|
| 204 |
+
the `yaml` module for import._
|
| 205 |
+
|
| 206 |
+
[distribution name]: https://packaging.python.org/en/latest/glossary/#term-Distribution-Package
|
| 207 |
+
[import name]: https://packaging.python.org/en/latest/glossary/#term-Import-Package
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_efficientzerotensor_compositeexplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor & _efficientzerotensor_out(at::Tensor & out, at::IntArrayRef size);
|
| 21 |
+
TORCH_API at::Tensor & _efficientzerotensor_outf(at::IntArrayRef size, at::Tensor & out);
|
| 22 |
+
TORCH_API at::Tensor & _efficientzerotensor_symint_out(at::Tensor & out, c10::SymIntArrayRef size);
|
| 23 |
+
TORCH_API at::Tensor & _efficientzerotensor_symint_outf(c10::SymIntArrayRef size, at::Tensor & out);
|
| 24 |
+
|
| 25 |
+
} // namespace compositeexplicitautograd
|
| 26 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_frac.h
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/_foreach_frac_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::_foreach_frac(Tensor[] self) -> Tensor[]
|
| 26 |
+
inline ::std::vector<at::Tensor> _foreach_frac(at::TensorList self) {
|
| 27 |
+
return at::_ops::_foreach_frac::call(self);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
// aten::_foreach_frac_(Tensor(a!)[] self) -> ()
|
| 31 |
+
inline void _foreach_frac_(at::TensorList self) {
|
| 32 |
+
return at::_ops::_foreach_frac_::call(self);
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// aten::_foreach_frac.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
|
| 36 |
+
inline void _foreach_frac_out(at::TensorList out, at::TensorList self) {
|
| 37 |
+
return at::_ops::_foreach_frac_out::call(self, out);
|
| 38 |
+
}
|
| 39 |
+
// aten::_foreach_frac.out(Tensor[] self, *, Tensor(a!)[] out) -> ()
|
| 40 |
+
inline void _foreach_frac_outf(at::TensorList self, at::TensorList out) {
|
| 41 |
+
return at::_ops::_foreach_frac_out::call(self, out);
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
}
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_jagged_to_padded_dense_forward_native.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor _fbgemm_jagged_to_padded_dense_forward(const at::Tensor & values, at::TensorList offsets, at::IntArrayRef max_lengths, double padding_value=0.0);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_logcumsumexp_cuda_dispatch.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor _logcumsumexp(const at::Tensor & self, int64_t dim);
|
| 21 |
+
TORCH_API at::Tensor & _logcumsumexp_out(at::Tensor & out, const at::Tensor & self, int64_t dim);
|
| 22 |
+
TORCH_API at::Tensor & _logcumsumexp_outf(const at::Tensor & self, int64_t dim, at::Tensor & out);
|
| 23 |
+
|
| 24 |
+
} // namespace cuda
|
| 25 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_copy_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor & _neg_view_copy_out(const at::Tensor & self, at::Tensor & out);
|
| 20 |
+
TORCH_API at::Tensor _neg_view_copy(const at::Tensor & self);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_mask_left_aligned_ops.h
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API _nested_tensor_from_mask_left_aligned {
|
| 18 |
+
using schema = bool (const at::Tensor &, const at::Tensor &);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_nested_tensor_from_mask_left_aligned")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_tensor_from_mask_left_aligned(Tensor t, Tensor mask) -> bool")
|
| 24 |
+
static bool call(const at::Tensor & t, const at::Tensor & mask);
|
| 25 |
+
static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & t, const at::Tensor & mask);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
}} // namespace at::_ops
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_pack_padded_sequence_backward_ops.h
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API _pack_padded_sequence_backward {
|
| 18 |
+
using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, const at::Tensor &, bool);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_pack_padded_sequence_backward")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_pack_padded_sequence_backward(Tensor grad, SymInt[] input_size, Tensor batch_sizes, bool batch_first) -> Tensor")
|
| 24 |
+
static at::Tensor call(const at::Tensor & grad, c10::SymIntArrayRef input_size, const at::Tensor & batch_sizes, bool batch_first);
|
| 25 |
+
static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, c10::SymIntArrayRef input_size, const at::Tensor & batch_sizes, bool batch_first);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
}} // namespace at::_ops
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_transformer_encoder_layer_fwd_native.h
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor & _transformer_encoder_layer_fwd_out(const at::Tensor & src, int64_t embed_dim, int64_t num_heads, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, bool use_gelu, bool norm_first, double eps, const at::Tensor & norm_weight_1, const at::Tensor & norm_bias_1, const at::Tensor & norm_weight_2, const at::Tensor & norm_bias_2, const at::Tensor & ffn_weight_1, const at::Tensor & ffn_bias_1, const at::Tensor & ffn_weight_2, const at::Tensor & ffn_bias_2, const ::std::optional<at::Tensor> & mask, ::std::optional<int64_t> mask_type, at::Tensor & out);
|
| 20 |
+
TORCH_API at::Tensor transformer_encoder_layer_forward(const at::Tensor & src, int64_t embed_dim, int64_t num_heads, const at::Tensor & qkv_weight, const at::Tensor & qkv_bias, const at::Tensor & proj_weight, const at::Tensor & proj_bias, bool use_gelu, bool norm_first, double eps, const at::Tensor & norm_weight_1, const at::Tensor & norm_bias_1, const at::Tensor & norm_weight_2, const at::Tensor & norm_bias_2, const at::Tensor & ffn_weight_1, const at::Tensor & ffn_bias_1, const at::Tensor & ffn_weight_2, const at::Tensor & ffn_bias_2, const ::std::optional<at::Tensor> & mask={}, ::std::optional<int64_t> mask_type=::std::nullopt);
|
| 21 |
+
} // namespace native
|
| 22 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_validate_compressed_sparse_indices_ops.h
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Operator.h
|
| 4 |
+
|
| 5 |
+
#include <tuple>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 9 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 10 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 11 |
+
#include <ATen/core/ATen_fwd.h>
|
| 12 |
+
|
| 13 |
+
namespace at {
|
| 14 |
+
namespace _ops {
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
struct TORCH_API _validate_compressed_sparse_indices {
|
| 18 |
+
using schema = void (bool, const at::Tensor &, const at::Tensor &, int64_t, int64_t, int64_t);
|
| 19 |
+
using ptr_schema = schema*;
|
| 20 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 21 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_validate_compressed_sparse_indices")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_validate_compressed_sparse_indices(bool is_crow, Tensor compressed_idx, Tensor plain_idx, int cdim, int dim, int nnz) -> ()")
|
| 24 |
+
static void call(bool is_crow, const at::Tensor & compressed_idx, const at::Tensor & plain_idx, int64_t cdim, int64_t dim, int64_t nnz);
|
| 25 |
+
static void redispatch(c10::DispatchKeySet dispatchKeySet, bool is_crow, const at::Tensor & compressed_idx, const at::Tensor & plain_idx, int64_t cdim, int64_t dim, int64_t nnz);
|
| 26 |
+
};
|
| 27 |
+
|
| 28 |
+
}} // namespace at::_ops
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_max_pool2d_backward.h
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/adaptive_max_pool2d_backward_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::adaptive_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
|
| 26 |
+
inline at::Tensor & adaptive_max_pool2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices) {
|
| 27 |
+
return at::_ops::adaptive_max_pool2d_backward_grad_input::call(grad_output, self, indices, grad_input);
|
| 28 |
+
}
|
| 29 |
+
// aten::adaptive_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!)
|
| 30 |
+
inline at::Tensor & adaptive_max_pool2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices, at::Tensor & grad_input) {
|
| 31 |
+
return at::_ops::adaptive_max_pool2d_backward_grad_input::call(grad_output, self, indices, grad_input);
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
// aten::adaptive_max_pool2d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor
|
| 35 |
+
inline at::Tensor adaptive_max_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices) {
|
| 36 |
+
return at::_ops::adaptive_max_pool2d_backward::call(grad_output, self, indices);
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
}
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/addcdiv_cuda_dispatch.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cuda {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor addcdiv(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
|
| 21 |
+
TORCH_API at::Tensor & addcdiv_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
|
| 22 |
+
TORCH_API at::Tensor & addcdiv_outf(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out);
|
| 23 |
+
TORCH_API at::Tensor & addcdiv_(at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
|
| 24 |
+
|
| 25 |
+
} // namespace cuda
|
| 26 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_cpu_dispatch.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cpu {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor addcmul(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
|
| 21 |
+
TORCH_API at::Tensor & addcmul_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
|
| 22 |
+
TORCH_API at::Tensor & addcmul_outf(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out);
|
| 23 |
+
TORCH_API at::Tensor & addcmul_(at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
|
| 24 |
+
|
| 25 |
+
} // namespace cpu
|
| 26 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/bmm_compositeexplicitautogradnonfunctional_dispatch.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeexplicitautogradnonfunctional {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor bmm(const at::Tensor & self, const at::Tensor & mat2);
|
| 21 |
+
|
| 22 |
+
} // namespace compositeexplicitautogradnonfunctional
|
| 23 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/bucketize_cpu_dispatch.h
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cpu {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor bucketize(const at::Tensor & self, const at::Tensor & boundaries, bool out_int32=false, bool right=false);
|
| 21 |
+
TORCH_API at::Tensor & bucketize_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & boundaries, bool out_int32=false, bool right=false);
|
| 22 |
+
TORCH_API at::Tensor & bucketize_outf(const at::Tensor & self, const at::Tensor & boundaries, bool out_int32, bool right, at::Tensor & out);
|
| 23 |
+
TORCH_API at::Tensor bucketize(const at::Scalar & self, const at::Tensor & boundaries, bool out_int32=false, bool right=false);
|
| 24 |
+
|
| 25 |
+
} // namespace cpu
|
| 26 |
+
} // namespace at
|
parrot/lib/python3.10/site-packages/torch/include/ATen/ops/cartesian_prod_compositeimplicitautograd_dispatch.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeimplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor cartesian_prod(at::TensorList tensors);
|
| 21 |
+
|
| 22 |
+
} // namespace compositeimplicitautograd
|
| 23 |
+
} // namespace at
|