anbinh39 commited on
Commit
02e9074
·
verified ·
1 Parent(s): b33e5eb

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/INSTALLER +1 -0
  2. .venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/METADATA +78 -0
  3. .venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/RECORD +12 -0
  4. .venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/REQUESTED +0 -0
  5. .venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/WHEEL +5 -0
  6. .venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/top_level.txt +1 -0
  7. .venv/lib/python3.11/site-packages/certifi/__init__.py +4 -0
  8. .venv/lib/python3.11/site-packages/certifi/__main__.py +12 -0
  9. .venv/lib/python3.11/site-packages/certifi/cacert.pem +0 -0
  10. .venv/lib/python3.11/site-packages/certifi/core.py +83 -0
  11. .venv/lib/python3.11/site-packages/certifi/py.typed +0 -0
  12. .venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/INSTALLER +1 -0
  13. .venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/METADATA +808 -0
  14. .venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/RECORD +25 -0
  15. .venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/REQUESTED +0 -0
  16. .venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/WHEEL +7 -0
  17. .venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/entry_points.txt +2 -0
  18. .venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/top_level.txt +2 -0
  19. .venv/lib/python3.11/site-packages/charset_normalizer/__init__.py +48 -0
  20. .venv/lib/python3.11/site-packages/charset_normalizer/md.cpython-311-x86_64-linux-gnu.so +0 -0
  21. .venv/lib/python3.11/site-packages/click-8.4.1.dist-info/INSTALLER +1 -0
  22. .venv/lib/python3.11/site-packages/click-8.4.1.dist-info/METADATA +84 -0
  23. .venv/lib/python3.11/site-packages/click-8.4.1.dist-info/RECORD +24 -0
  24. .venv/lib/python3.11/site-packages/click-8.4.1.dist-info/REQUESTED +0 -0
  25. .venv/lib/python3.11/site-packages/click-8.4.1.dist-info/WHEEL +4 -0
  26. .venv/lib/python3.11/site-packages/click/__init__.py +126 -0
  27. .venv/lib/python3.11/site-packages/click/_compat.py +627 -0
  28. .venv/lib/python3.11/site-packages/click/_termui_impl.py +929 -0
  29. .venv/lib/python3.11/site-packages/click/_textwrap.py +188 -0
  30. .venv/lib/python3.11/site-packages/click/_utils.py +36 -0
  31. .venv/lib/python3.11/site-packages/click/_winconsole.py +297 -0
  32. .venv/lib/python3.11/site-packages/click/core.py +0 -0
  33. .venv/lib/python3.11/site-packages/click/decorators.py +551 -0
  34. .venv/lib/python3.11/site-packages/click/exceptions.py +347 -0
  35. .venv/lib/python3.11/site-packages/click/formatting.py +315 -0
  36. .venv/lib/python3.11/site-packages/click/globals.py +67 -0
  37. .venv/lib/python3.11/site-packages/click/parser.py +533 -0
  38. .venv/lib/python3.11/site-packages/click/py.typed +0 -0
  39. .venv/lib/python3.11/site-packages/click/shell_completion.py +680 -0
  40. .venv/lib/python3.11/site-packages/click/termui.py +941 -0
  41. .venv/lib/python3.11/site-packages/click/testing.py +736 -0
  42. .venv/lib/python3.11/site-packages/click/types.py +1309 -0
  43. .venv/lib/python3.11/site-packages/click/utils.py +641 -0
  44. .venv/lib/python3.11/site-packages/git/__init__.py +300 -0
  45. .venv/lib/python3.11/site-packages/git/cmd.py +1761 -0
  46. .venv/lib/python3.11/site-packages/git/compat.py +165 -0
  47. .venv/lib/python3.11/site-packages/git/config.py +998 -0
  48. .venv/lib/python3.11/site-packages/git/db.py +71 -0
  49. .venv/lib/python3.11/site-packages/git/diff.py +776 -0
  50. .venv/lib/python3.11/site-packages/git/exc.py +228 -0
.venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
.venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/METADATA ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: certifi
3
+ Version: 2026.5.20
4
+ Summary: Python package for providing Mozilla's CA Bundle.
5
+ Home-page: https://github.com/certifi/python-certifi
6
+ Author: Kenneth Reitz
7
+ Author-email: me@kennethreitz.com
8
+ License: MPL-2.0
9
+ Project-URL: Source, https://github.com/certifi/python-certifi
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
13
+ Classifier: Natural Language :: English
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.7
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Requires-Python: >=3.7
26
+ License-File: LICENSE
27
+ Dynamic: author
28
+ Dynamic: author-email
29
+ Dynamic: classifier
30
+ Dynamic: description
31
+ Dynamic: home-page
32
+ Dynamic: license
33
+ Dynamic: license-file
34
+ Dynamic: project-url
35
+ Dynamic: requires-python
36
+ Dynamic: summary
37
+
38
+ Certifi: Python SSL Certificates
39
+ ================================
40
+
41
+ Certifi provides Mozilla's carefully curated collection of Root Certificates for
42
+ validating the trustworthiness of SSL certificates while verifying the identity
43
+ of TLS hosts. It has been extracted from the `Requests`_ project.
44
+
45
+ Installation
46
+ ------------
47
+
48
+ ``certifi`` is available on PyPI. Simply install it with ``pip``::
49
+
50
+ $ pip install certifi
51
+
52
+ Usage
53
+ -----
54
+
55
+ To reference the installed certificate authority (CA) bundle, you can use the
56
+ built-in function::
57
+
58
+ >>> import certifi
59
+
60
+ >>> certifi.where()
61
+ '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
62
+
63
+ Or from the command line::
64
+
65
+ $ python -m certifi
66
+ /usr/local/lib/python3.7/site-packages/certifi/cacert.pem
67
+
68
+ Enjoy!
69
+
70
+ .. _`Requests`: https://requests.readthedocs.io/en/master/
71
+
72
+ Addition/Removal of Certificates
73
+ --------------------------------
74
+
75
+ Certifi does not support any addition/removal or other modification of the
76
+ CA trust store content. This project is intended to provide a reliable and
77
+ highly portable root of trust to python deployments. Look to upstream projects
78
+ for methods to use alternate trust.
.venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/RECORD ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ certifi-2026.5.20.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
2
+ certifi-2026.5.20.dist-info/METADATA,sha256=HDiCa8lfd0TGlQFongDjoaLJOhWJiJN84y707Vwd8PY,2474
3
+ certifi-2026.5.20.dist-info/RECORD,,
4
+ certifi-2026.5.20.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ certifi-2026.5.20.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
+ certifi-2026.5.20.dist-info/licenses/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989
7
+ certifi-2026.5.20.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
8
+ certifi/__init__.py,sha256=-8ljc7w7fyi5Kyi06c1_L0lG_kD_J0FvbUTa8mEpdzQ,94
9
+ certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
10
+ certifi/cacert.pem,sha256=fO9UDGrzvwo8fQBwvT_XquNPiqgFtAjRwnoByK6zBd8,236095
11
+ certifi/core.py,sha256=XFXycndG5pf37ayeF8N32HUuDafsyhkVMbO4BAPWHa0,3394
12
+ certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
.venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv/lib/python3.11/site-packages/certifi-2026.5.20.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ certifi
.venv/lib/python3.11/site-packages/certifi/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .core import contents, where
2
+
3
+ __all__ = ["contents", "where"]
4
+ __version__ = "2026.05.20"
.venv/lib/python3.11/site-packages/certifi/__main__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from certifi import contents, where
4
+
5
+ parser = argparse.ArgumentParser()
6
+ parser.add_argument("-c", "--contents", action="store_true")
7
+ args = parser.parse_args()
8
+
9
+ if args.contents:
10
+ print(contents())
11
+ else:
12
+ print(where())
.venv/lib/python3.11/site-packages/certifi/cacert.pem ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.11/site-packages/certifi/core.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ certifi.py
3
+ ~~~~~~~~~~
4
+
5
+ This module returns the installation location of cacert.pem or its contents.
6
+ """
7
+ import sys
8
+ import atexit
9
+
10
+ def exit_cacert_ctx() -> None:
11
+ _CACERT_CTX.__exit__(None, None, None) # type: ignore[union-attr]
12
+
13
+
14
+ if sys.version_info >= (3, 11):
15
+
16
+ from importlib.resources import as_file, files
17
+
18
+ _CACERT_CTX = None
19
+ _CACERT_PATH = None
20
+
21
+ def where() -> str:
22
+ # This is slightly terrible, but we want to delay extracting the file
23
+ # in cases where we're inside of a zipimport situation until someone
24
+ # actually calls where(), but we don't want to re-extract the file
25
+ # on every call of where(), so we'll do it once then store it in a
26
+ # global variable.
27
+ global _CACERT_CTX
28
+ global _CACERT_PATH
29
+ if _CACERT_PATH is None:
30
+ # This is slightly janky, the importlib.resources API wants you to
31
+ # manage the cleanup of this file, so it doesn't actually return a
32
+ # path, it returns a context manager that will give you the path
33
+ # when you enter it and will do any cleanup when you leave it. In
34
+ # the common case of not needing a temporary file, it will just
35
+ # return the file system location and the __exit__() is a no-op.
36
+ #
37
+ # We also have to hold onto the actual context manager, because
38
+ # it will do the cleanup whenever it gets garbage collected, so
39
+ # we will also store that at the global level as well.
40
+ _CACERT_CTX = as_file(files("certifi").joinpath("cacert.pem"))
41
+ _CACERT_PATH = str(_CACERT_CTX.__enter__())
42
+ atexit.register(exit_cacert_ctx)
43
+
44
+ return _CACERT_PATH
45
+
46
+ def contents() -> str:
47
+ return files("certifi").joinpath("cacert.pem").read_text(encoding="ascii")
48
+
49
+ else:
50
+
51
+ from importlib.resources import path as get_path, read_text
52
+
53
+ _CACERT_CTX = None
54
+ _CACERT_PATH = None
55
+
56
+ def where() -> str:
57
+ # This is slightly terrible, but we want to delay extracting the
58
+ # file in cases where we're inside of a zipimport situation until
59
+ # someone actually calls where(), but we don't want to re-extract
60
+ # the file on every call of where(), so we'll do it once then store
61
+ # it in a global variable.
62
+ global _CACERT_CTX
63
+ global _CACERT_PATH
64
+ if _CACERT_PATH is None:
65
+ # This is slightly janky, the importlib.resources API wants you
66
+ # to manage the cleanup of this file, so it doesn't actually
67
+ # return a path, it returns a context manager that will give
68
+ # you the path when you enter it and will do any cleanup when
69
+ # you leave it. In the common case of not needing a temporary
70
+ # file, it will just return the file system location and the
71
+ # __exit__() is a no-op.
72
+ #
73
+ # We also have to hold onto the actual context manager, because
74
+ # it will do the cleanup whenever it gets garbage collected, so
75
+ # we will also store that at the global level as well.
76
+ _CACERT_CTX = get_path("certifi", "cacert.pem")
77
+ _CACERT_PATH = str(_CACERT_CTX.__enter__())
78
+ atexit.register(exit_cacert_ctx)
79
+
80
+ return _CACERT_PATH
81
+
82
+ def contents() -> str:
83
+ return read_text("certifi", "cacert.pem", encoding="ascii")
.venv/lib/python3.11/site-packages/certifi/py.typed ADDED
File without changes
.venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
.venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/METADATA ADDED
@@ -0,0 +1,808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: charset-normalizer
3
+ Version: 3.4.7
4
+ Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet.
5
+ Author-email: "Ahmed R. TAHRI" <tahri.ahmed@proton.me>
6
+ Maintainer-email: "Ahmed R. TAHRI" <tahri.ahmed@proton.me>
7
+ License: MIT
8
+ Project-URL: Changelog, https://github.com/jawah/charset_normalizer/blob/master/CHANGELOG.md
9
+ Project-URL: Documentation, https://charset-normalizer.readthedocs.io/
10
+ Project-URL: Code, https://github.com/jawah/charset_normalizer
11
+ Project-URL: Issue tracker, https://github.com/jawah/charset_normalizer/issues
12
+ Keywords: encoding,charset,charset-detector,detector,normalization,unicode,chardet,detect
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.7
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Classifier: Programming Language :: Python :: 3 :: Only
27
+ Classifier: Programming Language :: Python :: Implementation :: CPython
28
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
29
+ Classifier: Programming Language :: Python :: Free Threading :: 4 - Resilient
30
+ Classifier: Topic :: Text Processing :: Linguistic
31
+ Classifier: Topic :: Utilities
32
+ Classifier: Typing :: Typed
33
+ Requires-Python: >=3.7
34
+ Description-Content-Type: text/markdown
35
+ License-File: LICENSE
36
+ Provides-Extra: unicode-backport
37
+ Dynamic: license-file
38
+
39
+ <h1 align="center">Charset Detection, for Everyone 👋</h1>
40
+
41
+ <p align="center">
42
+ <sup>The Real First Universal Charset Detector</sup><br>
43
+ <a href="https://pypi.org/project/charset-normalizer">
44
+ <img src="https://img.shields.io/pypi/pyversions/charset_normalizer.svg?orange=blue" />
45
+ </a>
46
+ <a href="https://pepy.tech/project/charset-normalizer/">
47
+ <img alt="Download Count Total" src="https://static.pepy.tech/badge/charset-normalizer/month" />
48
+ </a>
49
+ <a href="https://bestpractices.coreinfrastructure.org/projects/7297">
50
+ <img src="https://bestpractices.coreinfrastructure.org/projects/7297/badge">
51
+ </a>
52
+ </p>
53
+ <p align="center">
54
+ <sup><i>Featured Packages</i></sup><br>
55
+ <a href="https://github.com/jawah/niquests">
56
+ <img alt="Static Badge" src="https://img.shields.io/badge/Niquests-Most_Advanced_HTTP_Client-cyan">
57
+ </a>
58
+ <a href="https://github.com/jawah/wassima">
59
+ <img alt="Static Badge" src="https://img.shields.io/badge/Wassima-Certifi_Replacement-cyan">
60
+ </a>
61
+ </p>
62
+ <p align="center">
63
+ <sup><i>In other language (unofficial port - by the community)</i></sup><br>
64
+ <a href="https://github.com/nickspring/charset-normalizer-rs">
65
+ <img alt="Static Badge" src="https://img.shields.io/badge/Rust-red">
66
+ </a>
67
+ </p>
68
+
69
+ > A library that helps you read text from an unknown charset encoding.<br /> Motivated by `chardet`,
70
+ > I'm trying to resolve the issue by taking a new approach.
71
+ > All IANA character set names for which the Python core library provides codecs are supported.
72
+ > You can also register your own set of codecs, and yes, it would work as-is.
73
+
74
+ <p align="center">
75
+ >>>>> <a href="https://charsetnormalizerweb.ousret.now.sh" target="_blank">👉 Try Me Online Now, Then Adopt Me 👈 </a> <<<<<
76
+ </p>
77
+
78
+ This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**.
79
+
80
+ | Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) |
81
+ |--------------------------------------------------|:---------------------------------------------:|:-----------------------------------------------------------------------------------------------:|:-----------------------------------------------:|
82
+ | `Fast` | ✅ | ✅ | ✅ |
83
+ | `Universal`[^1] | ❌ | ✅ | ❌ |
84
+ | `Reliable` **without** distinguishable standards | ✅ | ✅ | ✅ |
85
+ | `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ |
86
+ | `License` | _Disputed_[^2]<br>_restrictive_ | MIT | MPL-1.1<br>_restrictive_ |
87
+ | `Native Python` | ✅ | ✅ | ❌ |
88
+ | `Detect spoken language` | ✅ | ✅ | N/A |
89
+ | `UnicodeDecodeError Safety` | ✅ | ✅ | ❌ |
90
+ | `Whl Size (min)` | 500 kB | 150 kB | ~200 kB |
91
+ | `Supported Encoding` | 99 | [99](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 |
92
+ | `Can register custom encoding` | ❌ | ✅ | ❌ |
93
+
94
+ <p align="center">
95
+ <img src="https://i.imgflip.com/373iay.gif" alt="Reading Normalized Text" width="226"/><img src="https://media.tenor.com/images/c0180f70732a18b4965448d33adba3d0/tenor.gif" alt="Cat Reading Text" width="200"/>
96
+ </p>
97
+
98
+ [^1]: They are clearly using specific code for a specific encoding even if covering most of used one.
99
+ [^2]: Chardet 7.0+ was relicensed from LGPL-2.1 to MIT following an AI-assisted rewrite. This relicensing is disputed on two independent grounds: **(a)** the original author [contests](https://github.com/chardet/chardet/issues/327) that the maintainer had the right to relicense, arguing the rewrite is a derivative work of the LGPL-licensed codebase since it was not a clean room implementation; **(b)** the copyright claim itself is [questionable](https://github.com/chardet/chardet/issues/334) given the code was primarily generated by an LLM, and AI-generated output may not be copyrightable under most jurisdictions. Either issue alone could undermine the MIT license. Beyond licensing, the rewrite raises questions about responsible use of AI in open source: key architectural ideas pioneered by charset-normalizer - notably decode-first validity filtering (our foundational approach since v1) and encoding pairwise similarity with the same algorithm and threshold — surfaced in chardet 7 without acknowledgment. The project also imported test files from charset-normalizer to train and benchmark against it, then claimed superior accuracy on those very files. Charset-normalizer has always been MIT-licensed, encoding-agnostic by design, and built on a verifiable human-authored history.
100
+
101
+ ## ⚡ Performance
102
+
103
+ This package offer better performances (99th, and 95th) against Chardet. Here are some numbers.
104
+
105
+ | Package | Accuracy | Mean per file (ms) | File per sec (est) |
106
+ |---------------------------------------------------|:--------:|:------------------:|:------------------:|
107
+ | [chardet 7.1](https://github.com/chardet/chardet) | 89 % | 3 ms | 333 file/sec |
108
+ | charset-normalizer | **97 %** | 3 ms | 333 file/sec |
109
+
110
+ | Package | 99th percentile | 95th percentile | 50th percentile |
111
+ |---------------------------------------------------|:---------------:|:---------------:|:---------------:|
112
+ | [chardet 7.1](https://github.com/chardet/chardet) | 32 ms | 17 ms | < 1 ms |
113
+ | charset-normalizer | 16 ms | 10 ms | 1 ms |
114
+
115
+ _updated as of March 2026 using CPython 3.12, Charset-Normalizer 3.4.6, and Chardet 7.1.0_
116
+
117
+ ~Chardet's performance on larger file (1MB+) are very poor. Expect huge difference on large payload.~ No longer the case since Chardet 7.0+
118
+
119
+ > Stats are generated using 400+ files using default parameters. More details on used files, see GHA workflows.
120
+ > And yes, these results might change at any time. The dataset can be updated to include more files.
121
+ > The actual delays heavily depends on your CPU capabilities. The factors should remain the same.
122
+ > Chardet claims on his documentation to have a greater accuracy than us based on the dataset they trained Chardet on(...)
123
+ > Well, it's normal, the opposite would have been worrying. Whereas charset-normalizer don't train on anything, our solution
124
+ > is based on a completely different algorithm, still heuristic through, it does not need weights across every encoding tables.
125
+
126
+ ## ✨ Installation
127
+
128
+ Using pip:
129
+
130
+ ```sh
131
+ pip install charset-normalizer -U
132
+ ```
133
+
134
+ ## 🚀 Basic Usage
135
+
136
+ ### CLI
137
+ This package comes with a CLI.
138
+
139
+ ```
140
+ usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD]
141
+ file [file ...]
142
+
143
+ The Real First Universal Charset Detector. Discover originating encoding used
144
+ on text file. Normalize text to unicode.
145
+
146
+ positional arguments:
147
+ files File(s) to be analysed
148
+
149
+ optional arguments:
150
+ -h, --help show this help message and exit
151
+ -v, --verbose Display complementary information about file if any.
152
+ Stdout will contain logs about the detection process.
153
+ -a, --with-alternative
154
+ Output complementary possibilities if any. Top-level
155
+ JSON WILL be a list.
156
+ -n, --normalize Permit to normalize input file. If not set, program
157
+ does not write anything.
158
+ -m, --minimal Only output the charset detected to STDOUT. Disabling
159
+ JSON output.
160
+ -r, --replace Replace file when trying to normalize it instead of
161
+ creating a new one.
162
+ -f, --force Replace file without asking if you are sure, use this
163
+ flag with caution.
164
+ -t THRESHOLD, --threshold THRESHOLD
165
+ Define a custom maximum amount of chaos allowed in
166
+ decoded content. 0. <= chaos <= 1.
167
+ --version Show version information and exit.
168
+ ```
169
+
170
+ ```bash
171
+ normalizer ./data/sample.1.fr.srt
172
+ ```
173
+
174
+ or
175
+
176
+ ```bash
177
+ python -m charset_normalizer ./data/sample.1.fr.srt
178
+ ```
179
+
180
+ 🎉 Since version 1.4.0 the CLI produce easily usable stdout result in JSON format.
181
+
182
+ ```json
183
+ {
184
+ "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt",
185
+ "encoding": "cp1252",
186
+ "encoding_aliases": [
187
+ "1252",
188
+ "windows_1252"
189
+ ],
190
+ "alternative_encodings": [
191
+ "cp1254",
192
+ "cp1256",
193
+ "cp1258",
194
+ "iso8859_14",
195
+ "iso8859_15",
196
+ "iso8859_16",
197
+ "iso8859_3",
198
+ "iso8859_9",
199
+ "latin_1",
200
+ "mbcs"
201
+ ],
202
+ "language": "French",
203
+ "alphabets": [
204
+ "Basic Latin",
205
+ "Latin-1 Supplement"
206
+ ],
207
+ "has_sig_or_bom": false,
208
+ "chaos": 0.149,
209
+ "coherence": 97.152,
210
+ "unicode_path": null,
211
+ "is_preferred": true
212
+ }
213
+ ```
214
+
215
+ ### Python
216
+ *Just print out normalized text*
217
+ ```python
218
+ from charset_normalizer import from_path
219
+
220
+ results = from_path('./my_subtitle.srt')
221
+
222
+ print(str(results.best()))
223
+ ```
224
+
225
+ *Upgrade your code without effort*
226
+ ```python
227
+ from charset_normalizer import detect
228
+ ```
229
+
230
+ The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible.
231
+
232
+ See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/)
233
+
234
+ ## 😇 Why
235
+
236
+ When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a
237
+ reliable alternative using a completely different method. Also! I never back down on a good challenge!
238
+
239
+ I **don't care** about the **originating charset** encoding, because **two different tables** can
240
+ produce **two identical rendered string.**
241
+ What I want is to get readable text, the best I can.
242
+
243
+ In a way, **I'm brute forcing text decoding.** How cool is that ? 😎
244
+
245
+ Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair Unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode.
246
+
247
+ ## 🍰 How
248
+
249
+ - Discard all charset encoding table that could not fit the binary content.
250
+ - Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding.
251
+ - Extract matches with the lowest mess detected.
252
+ - Additionally, we measure coherence / probe for a language.
253
+
254
+ **Wait a minute**, what is noise/mess and coherence according to **YOU ?**
255
+
256
+ *Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then
257
+ **I established** some ground rules about **what is obvious** when **it seems like** a mess (aka. defining noise in rendered text).
258
+ I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to
259
+ improve or rewrite it.
260
+
261
+ *Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought
262
+ that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design.
263
+
264
+ ## ⚡ Known limitations
265
+
266
+ - Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters))
267
+ - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content.
268
+
269
+ ## ⚠️ About Python EOLs
270
+
271
+ **If you are running:**
272
+
273
+ - Python >=2.7,<3.5: Unsupported
274
+ - Python 3.5: charset-normalizer < 2.1
275
+ - Python 3.6: charset-normalizer < 3.1
276
+
277
+ Upgrade your Python interpreter as soon as possible.
278
+
279
+ ## 👤 Contributing
280
+
281
+ Contributions, issues and feature requests are very much welcome.<br />
282
+ Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute.
283
+
284
+ ## 📝 License
285
+
286
+ Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret).<br />
287
+ This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed.
288
+
289
+ Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/)
290
+
291
+ ## 💼 For Enterprise
292
+
293
+ Professional support for charset-normalizer is available as part of the [Tidelift
294
+ Subscription][1]. Tidelift gives software development teams a single source for
295
+ purchasing and maintaining their software, with professional grade assurances
296
+ from the experts who know it best, while seamlessly integrating with existing
297
+ tools.
298
+
299
+ [1]: https://tidelift.com/subscription/pkg/pypi-charset-normalizer?utm_source=pypi-charset-normalizer&utm_medium=readme
300
+
301
+ [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/7297/badge)](https://www.bestpractices.dev/projects/7297)
302
+
303
+ # Changelog
304
+ All notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
305
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
306
+
307
+ ## [3.4.7](https://github.com/Ousret/charset_normalizer/compare/3.4.6...3.4.7) (2026-04-02)
308
+
309
+ ### Changed
310
+ - Pre-built optimized version using mypy[c] v1.20.
311
+ - Relax `setuptools` constraint to `setuptools>=68,<82.1`.
312
+
313
+ ### Fixed
314
+ - Correctly remove SIG remnant in utf-7 decoded string. (#718) (#716)
315
+
316
+ ## [3.4.6](https://github.com/Ousret/charset_normalizer/compare/3.4.5...3.4.6) (2026-03-15)
317
+
318
+ ### Changed
319
+ - Flattened the logic in `charset_normalizer.md` for higher performance. Removed `eligible(..)` and `feed(...)`
320
+ in favor of `feed_info(...)`.
321
+ - Raised upper bound for mypy[c] to 1.20, for our optimized version.
322
+ - Updated `UNICODE_RANGES_COMBINED` using Unicode blocks v17.
323
+
324
+ ### Fixed
325
+ - Edge case where noise difference between two candidates can be almost insignificant. (#672)
326
+ - CLI `--normalize` writing to wrong path when passing multiple files in. (#702)
327
+
328
+ ### Misc
329
+ - Freethreaded pre-built wheels now shipped in PyPI starting with 3.14t. (#616)
330
+
331
+ ## [3.4.5](https://github.com/Ousret/charset_normalizer/compare/3.4.4...3.4.5) (2026-03-06)
332
+
333
+ ### Changed
334
+ - Update `setuptools` constraint to `setuptools>=68,<=82`.
335
+ - Raised upper bound of mypyc for the optional pre-built extension to v1.19.1
336
+
337
+ ### Fixed
338
+ - Add explicit link to lib math in our optimized build. (#692)
339
+ - Logger level not restored correctly for empty byte sequences. (#701)
340
+ - TypeError when passing bytearray to from_bytes. (#703)
341
+
342
+ ### Misc
343
+ - Applied safe micro-optimizations in both our noise detector and language detector.
344
+ - Rewrote the `query_yes_no` function (inside CLI) to avoid using ambiguous licensed code.
345
+ - Added `cd.py` submodule into mypyc optional compilation to reduce further the performance impact.
346
+
347
+ ## [3.4.4](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.4) (2025-10-13)
348
+
349
+ ### Changed
350
+ - Bound `setuptools` to a specific constraint `setuptools>=68,<=81`.
351
+ - Raised upper bound of mypyc for the optional pre-built extension to v1.18.2
352
+
353
+ ### Removed
354
+ - `setuptools-scm` as a build dependency.
355
+
356
+ ### Misc
357
+ - Enforced hashes in `dev-requirements.txt` and created `ci-requirements.txt` for security purposes.
358
+ - Additional pre-built wheels for riscv64, s390x, and armv7l architectures.
359
+ - Restore ` multiple.intoto.jsonl` in GitHub releases in addition to individual attestation file per wheel.
360
+
361
+ ## [3.4.3](https://github.com/Ousret/charset_normalizer/compare/3.4.2...3.4.3) (2025-08-09)
362
+
363
+ ### Changed
364
+ - mypy(c) is no longer a required dependency at build time if `CHARSET_NORMALIZER_USE_MYPYC` isn't set to `1`. (#595) (#583)
365
+ - automatically lower confidence on small bytes samples that are not Unicode in `detect` output legacy function. (#391)
366
+
367
+ ### Added
368
+ - Custom build backend to overcome inability to mark mypy as an optional dependency in the build phase.
369
+ - Support for Python 3.14
370
+
371
+ ### Fixed
372
+ - sdist archive contained useless directories.
373
+ - automatically fallback on valid UTF-16 or UTF-32 even if the md says it's noisy. (#633)
374
+
375
+ ### Misc
376
+ - SBOM are automatically published to the relevant GitHub release to comply with regulatory changes.
377
+ Each published wheel comes with its SBOM. We choose CycloneDX as the format.
378
+ - Prebuilt optimized wheel are no longer distributed by default for CPython 3.7 due to a change in cibuildwheel.
379
+
380
+ ## [3.4.2](https://github.com/Ousret/charset_normalizer/compare/3.4.1...3.4.2) (2025-05-02)
381
+
382
+ ### Fixed
383
+ - Addressed the DeprecationWarning in our CLI regarding `argparse.FileType` by backporting the target class into the package. (#591)
384
+ - Improved the overall reliability of the detector with CJK Ideographs. (#605) (#587)
385
+
386
+ ### Changed
387
+ - Optional mypyc compilation upgraded to version 1.15 for Python >= 3.8
388
+
389
+ ## [3.4.1](https://github.com/Ousret/charset_normalizer/compare/3.4.0...3.4.1) (2024-12-24)
390
+
391
+ ### Changed
392
+ - Project metadata are now stored using `pyproject.toml` instead of `setup.cfg` using setuptools as the build backend.
393
+ - Enforce annotation delayed loading for a simpler and consistent types in the project.
394
+ - Optional mypyc compilation upgraded to version 1.14 for Python >= 3.8
395
+
396
+ ### Added
397
+ - pre-commit configuration.
398
+ - noxfile.
399
+
400
+ ### Removed
401
+ - `build-requirements.txt` as per using `pyproject.toml` native build configuration.
402
+ - `bin/integration.py` and `bin/serve.py` in favor of downstream integration test (see noxfile).
403
+ - `setup.cfg` in favor of `pyproject.toml` metadata configuration.
404
+ - Unused `utils.range_scan` function.
405
+
406
+ ### Fixed
407
+ - Converting content to Unicode bytes may insert `utf_8` instead of preferred `utf-8`. (#572)
408
+ - Deprecation warning "'count' is passed as positional argument" when converting to Unicode bytes on Python 3.13+
409
+
410
+ ## [3.4.0](https://github.com/Ousret/charset_normalizer/compare/3.3.2...3.4.0) (2024-10-08)
411
+
412
+ ### Added
413
+ - Argument `--no-preemptive` in the CLI to prevent the detector to search for hints.
414
+ - Support for Python 3.13 (#512)
415
+
416
+ ### Fixed
417
+ - Relax the TypeError exception thrown when trying to compare a CharsetMatch with anything else than a CharsetMatch.
418
+ - Improved the general reliability of the detector based on user feedbacks. (#520) (#509) (#498) (#407) (#537)
419
+ - Declared charset in content (preemptive detection) not changed when converting to utf-8 bytes. (#381)
420
+
421
+ ## [3.3.2](https://github.com/Ousret/charset_normalizer/compare/3.3.1...3.3.2) (2023-10-31)
422
+
423
+ ### Fixed
424
+ - Unintentional memory usage regression when using large payload that match several encoding (#376)
425
+ - Regression on some detection case showcased in the documentation (#371)
426
+
427
+ ### Added
428
+ - Noise (md) probe that identify malformed arabic representation due to the presence of letters in isolated form (credit to my wife)
429
+
430
+ ## [3.3.1](https://github.com/Ousret/charset_normalizer/compare/3.3.0...3.3.1) (2023-10-22)
431
+
432
+ ### Changed
433
+ - Optional mypyc compilation upgraded to version 1.6.1 for Python >= 3.8
434
+ - Improved the general detection reliability based on reports from the community
435
+
436
+ ## [3.3.0](https://github.com/Ousret/charset_normalizer/compare/3.2.0...3.3.0) (2023-09-30)
437
+
438
+ ### Added
439
+ - Allow to execute the CLI (e.g. normalizer) through `python -m charset_normalizer.cli` or `python -m charset_normalizer`
440
+ - Support for 9 forgotten encoding that are supported by Python but unlisted in `encoding.aliases` as they have no alias (#323)
441
+
442
+ ### Removed
443
+ - (internal) Redundant utils.is_ascii function and unused function is_private_use_only
444
+ - (internal) charset_normalizer.assets is moved inside charset_normalizer.constant
445
+
446
+ ### Changed
447
+ - (internal) Unicode code blocks in constants are updated using the latest v15.0.0 definition to improve detection
448
+ - Optional mypyc compilation upgraded to version 1.5.1 for Python >= 3.8
449
+
450
+ ### Fixed
451
+ - Unable to properly sort CharsetMatch when both chaos/noise and coherence were close due to an unreachable condition in \_\_lt\_\_ (#350)
452
+
453
+ ## [3.2.0](https://github.com/Ousret/charset_normalizer/compare/3.1.0...3.2.0) (2023-06-07)
454
+
455
+ ### Changed
456
+ - Typehint for function `from_path` no longer enforce `PathLike` as its first argument
457
+ - Minor improvement over the global detection reliability
458
+
459
+ ### Added
460
+ - Introduce function `is_binary` that relies on main capabilities, and optimized to detect binaries
461
+ - Propagate `enable_fallback` argument throughout `from_bytes`, `from_path`, and `from_fp` that allow a deeper control over the detection (default True)
462
+ - Explicit support for Python 3.12
463
+
464
+ ### Fixed
465
+ - Edge case detection failure where a file would contain 'very-long' camel cased word (Issue #289)
466
+
467
+ ## [3.1.0](https://github.com/Ousret/charset_normalizer/compare/3.0.1...3.1.0) (2023-03-06)
468
+
469
+ ### Added
470
+ - Argument `should_rename_legacy` for legacy function `detect` and disregard any new arguments without errors (PR #262)
471
+
472
+ ### Removed
473
+ - Support for Python 3.6 (PR #260)
474
+
475
+ ### Changed
476
+ - Optional speedup provided by mypy/c 1.0.1
477
+
478
+ ## [3.0.1](https://github.com/Ousret/charset_normalizer/compare/3.0.0...3.0.1) (2022-11-18)
479
+
480
+ ### Fixed
481
+ - Multi-bytes cutter/chunk generator did not always cut correctly (PR #233)
482
+
483
+ ### Changed
484
+ - Speedup provided by mypy/c 0.990 on Python >= 3.7
485
+
486
+ ## [3.0.0](https://github.com/Ousret/charset_normalizer/compare/2.1.1...3.0.0) (2022-10-20)
487
+
488
+ ### Added
489
+ - Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results
490
+ - Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES
491
+ - Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio
492
+ - `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl)
493
+
494
+ ### Changed
495
+ - Build with static metadata using 'build' frontend
496
+ - Make the language detection stricter
497
+ - Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1
498
+
499
+ ### Fixed
500
+ - CLI with opt --normalize fail when using full path for files
501
+ - TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it
502
+ - Sphinx warnings when generating the documentation
503
+
504
+ ### Removed
505
+ - Coherence detector no longer return 'Simple English' instead return 'English'
506
+ - Coherence detector no longer return 'Classical Chinese' instead return 'Chinese'
507
+ - Breaking: Method `first()` and `best()` from CharsetMatch
508
+ - UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII)
509
+ - Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches
510
+ - Breaking: Top-level function `normalize`
511
+ - Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch
512
+ - Support for the backport `unicodedata2`
513
+
514
+ ## [3.0.0rc1](https://github.com/Ousret/charset_normalizer/compare/3.0.0b2...3.0.0rc1) (2022-10-18)
515
+
516
+ ### Added
517
+ - Extend the capability of explain=True when cp_isolation contains at most two entries (min one), will log in details of the Mess-detector results
518
+ - Support for alternative language frequency set in charset_normalizer.assets.FREQUENCIES
519
+ - Add parameter `language_threshold` in `from_bytes`, `from_path` and `from_fp` to adjust the minimum expected coherence ratio
520
+
521
+ ### Changed
522
+ - Build with static metadata using 'build' frontend
523
+ - Make the language detection stricter
524
+
525
+ ### Fixed
526
+ - CLI with opt --normalize fail when using full path for files
527
+ - TooManyAccentuatedPlugin induce false positive on the mess detection when too few alpha character have been fed to it
528
+
529
+ ### Removed
530
+ - Coherence detector no longer return 'Simple English' instead return 'English'
531
+ - Coherence detector no longer return 'Classical Chinese' instead return 'Chinese'
532
+
533
+ ## [3.0.0b2](https://github.com/Ousret/charset_normalizer/compare/3.0.0b1...3.0.0b2) (2022-08-21)
534
+
535
+ ### Added
536
+ - `normalizer --version` now specify if current version provide extra speedup (meaning mypyc compilation whl)
537
+
538
+ ### Removed
539
+ - Breaking: Method `first()` and `best()` from CharsetMatch
540
+ - UTF-7 will no longer appear as "detected" without a recognized SIG/mark (is unreliable/conflict with ASCII)
541
+
542
+ ### Fixed
543
+ - Sphinx warnings when generating the documentation
544
+
545
+ ## [3.0.0b1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...3.0.0b1) (2022-08-15)
546
+
547
+ ### Changed
548
+ - Optional: Module `md.py` can be compiled using Mypyc to provide an extra speedup up to 4x faster than v2.1
549
+
550
+ ### Removed
551
+ - Breaking: Class aliases CharsetDetector, CharsetDoctor, CharsetNormalizerMatch and CharsetNormalizerMatches
552
+ - Breaking: Top-level function `normalize`
553
+ - Breaking: Properties `chaos_secondary_pass`, `coherence_non_latin` and `w_counter` from CharsetMatch
554
+ - Support for the backport `unicodedata2`
555
+
556
+ ## [2.1.1](https://github.com/Ousret/charset_normalizer/compare/2.1.0...2.1.1) (2022-08-19)
557
+
558
+ ### Deprecated
559
+ - Function `normalize` scheduled for removal in 3.0
560
+
561
+ ### Changed
562
+ - Removed useless call to decode in fn is_unprintable (#206)
563
+
564
+ ### Fixed
565
+ - Third-party library (i18n xgettext) crashing not recognizing utf_8 (PEP 263) with underscore from [@aleksandernovikov](https://github.com/aleksandernovikov) (#204)
566
+
567
+ ## [2.1.0](https://github.com/Ousret/charset_normalizer/compare/2.0.12...2.1.0) (2022-06-19)
568
+
569
+ ### Added
570
+ - Output the Unicode table version when running the CLI with `--version` (PR #194)
571
+
572
+ ### Changed
573
+ - Re-use decoded buffer for single byte character sets from [@nijel](https://github.com/nijel) (PR #175)
574
+ - Fixing some performance bottlenecks from [@deedy5](https://github.com/deedy5) (PR #183)
575
+
576
+ ### Fixed
577
+ - Workaround potential bug in cpython with Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space (PR #175)
578
+ - CLI default threshold aligned with the API threshold from [@oleksandr-kuzmenko](https://github.com/oleksandr-kuzmenko) (PR #181)
579
+
580
+ ### Removed
581
+ - Support for Python 3.5 (PR #192)
582
+
583
+ ### Deprecated
584
+ - Use of backport unicodedata from `unicodedata2` as Python is quickly catching up, scheduled for removal in 3.0 (PR #194)
585
+
586
+ ## [2.0.12](https://github.com/Ousret/charset_normalizer/compare/2.0.11...2.0.12) (2022-02-12)
587
+
588
+ ### Fixed
589
+ - ASCII miss-detection on rare cases (PR #170)
590
+
591
+ ## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30)
592
+
593
+ ### Added
594
+ - Explicit support for Python 3.11 (PR #164)
595
+
596
+ ### Changed
597
+ - The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165)
598
+
599
+ ## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04)
600
+
601
+ ### Fixed
602
+ - Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154)
603
+
604
+ ### Changed
605
+ - Skipping the language-detection (CD) on ASCII (PR #155)
606
+
607
+ ## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03)
608
+
609
+ ### Changed
610
+ - Moderating the logging impact (since 2.0.8) for specific environments (PR #147)
611
+
612
+ ### Fixed
613
+ - Wrong logging level applied when setting kwarg `explain` to True (PR #146)
614
+
615
+ ## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24)
616
+ ### Changed
617
+ - Improvement over Vietnamese detection (PR #126)
618
+ - MD improvement on trailing data and long foreign (non-pure latin) data (PR #124)
619
+ - Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122)
620
+ - call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129)
621
+ - Code style as refactored by Sourcery-AI (PR #131)
622
+ - Minor adjustment on the MD around european words (PR #133)
623
+ - Remove and replace SRTs from assets / tests (PR #139)
624
+ - Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135)
625
+ - Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135)
626
+
627
+ ### Fixed
628
+ - Fix large (misleading) sequence giving UnicodeDecodeError (PR #137)
629
+ - Avoid using too insignificant chunk (PR #137)
630
+
631
+ ### Added
632
+ - Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135)
633
+ - Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141)
634
+
635
+ ## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11)
636
+ ### Added
637
+ - Add support for Kazakh (Cyrillic) language detection (PR #109)
638
+
639
+ ### Changed
640
+ - Further, improve inferring the language from a given single-byte code page (PR #112)
641
+ - Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116)
642
+ - Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113)
643
+ - Various detection improvement (MD+CD) (PR #117)
644
+
645
+ ### Removed
646
+ - Remove redundant logging entry about detected language(s) (PR #115)
647
+
648
+ ### Fixed
649
+ - Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102)
650
+
651
+ ## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18)
652
+ ### Fixed
653
+ - Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100)
654
+ - Fix CLI crash when using --minimal output in certain cases (PR #103)
655
+
656
+ ### Changed
657
+ - Minor improvement to the detection efficiency (less than 1%) (PR #106 #101)
658
+
659
+ ## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14)
660
+ ### Changed
661
+ - The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81)
662
+ - The BC-support with v1.x was improved, the old staticmethods are restored (PR #82)
663
+ - The Unicode detection is slightly improved (PR #93)
664
+ - Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91)
665
+
666
+ ### Removed
667
+ - The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92)
668
+
669
+ ### Fixed
670
+ - In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95)
671
+ - Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96)
672
+ - The MANIFEST.in was not exhaustive (PR #78)
673
+
674
+ ## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30)
675
+ ### Fixed
676
+ - The CLI no longer raise an unexpected exception when no encoding has been found (PR #70)
677
+ - Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68)
678
+ - The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72)
679
+ - Submatch factoring could be wrong in rare edge cases (PR #72)
680
+ - Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72)
681
+ - Fix line endings from CRLF to LF for certain project files (PR #67)
682
+
683
+ ### Changed
684
+ - Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76)
685
+ - Allow fallback on specified encoding if any (PR #71)
686
+
687
+ ## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16)
688
+ ### Changed
689
+ - Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63)
690
+ - According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64)
691
+
692
+ ## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15)
693
+ ### Fixed
694
+ - Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59)
695
+
696
+ ### Changed
697
+ - Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57)
698
+
699
+ ## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13)
700
+ ### Fixed
701
+ - Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55)
702
+ - Using explain=False permanently disable the verbose output in the current runtime (PR #47)
703
+ - One log entry (language target preemptive) was not show in logs when using explain=True (PR #47)
704
+ - Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52)
705
+
706
+ ### Changed
707
+ - Public function normalize default args values were not aligned with from_bytes (PR #53)
708
+
709
+ ### Added
710
+ - You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47)
711
+
712
+ ## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02)
713
+ ### Changed
714
+ - 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet.
715
+ - Accent has been made on UTF-8 detection, should perform rather instantaneous.
716
+ - The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible.
717
+ - The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time)
718
+ - The program has been rewritten to ease the readability and maintainability. (+Using static typing)+
719
+ - utf_7 detection has been reinstated.
720
+
721
+ ### Removed
722
+ - This package no longer require anything when used with Python 3.5 (Dropped cached_property)
723
+ - Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian.
724
+ - The exception hook on UnicodeDecodeError has been removed.
725
+
726
+ ### Deprecated
727
+ - Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0
728
+
729
+ ### Fixed
730
+ - The CLI output used the relative path of the file(s). Should be absolute.
731
+
732
+ ## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28)
733
+ ### Fixed
734
+ - Logger configuration/usage no longer conflict with others (PR #44)
735
+
736
+ ## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21)
737
+ ### Removed
738
+ - Using standard logging instead of using the package loguru.
739
+ - Dropping nose test framework in favor of the maintained pytest.
740
+ - Choose to not use dragonmapper package to help with gibberish Chinese/CJK text.
741
+ - Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version.
742
+ - Stop support for UTF-7 that does not contain a SIG.
743
+ - Dropping PrettyTable, replaced with pure JSON output in CLI.
744
+
745
+ ### Fixed
746
+ - BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process.
747
+ - Not searching properly for the BOM when trying utf32/16 parent codec.
748
+
749
+ ### Changed
750
+ - Improving the package final size by compressing frequencies.json.
751
+ - Huge improvement over the larges payload.
752
+
753
+ ### Added
754
+ - CLI now produces JSON consumable output.
755
+ - Return ASCII if given sequences fit. Given reasonable confidence.
756
+
757
+ ## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13)
758
+
759
+ ### Fixed
760
+ - In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40)
761
+
762
+ ## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12)
763
+
764
+ ### Fixed
765
+ - Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39)
766
+
767
+ ## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12)
768
+
769
+ ### Fixed
770
+ - The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38)
771
+
772
+ ## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09)
773
+
774
+ ### Changed
775
+ - Amend the previous release to allow prettytable 2.0 (PR #35)
776
+
777
+ ## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08)
778
+
779
+ ### Fixed
780
+ - Fix error while using the package with a python pre-release interpreter (PR #33)
781
+
782
+ ### Changed
783
+ - Dependencies refactoring, constraints revised.
784
+
785
+ ### Added
786
+ - Add python 3.9 and 3.10 to the supported interpreters
787
+
788
+ MIT License
789
+
790
+ Copyright (c) 2025 TAHRI Ahmed R.
791
+
792
+ Permission is hereby granted, free of charge, to any person obtaining a copy
793
+ of this software and associated documentation files (the "Software"), to deal
794
+ in the Software without restriction, including without limitation the rights
795
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
796
+ copies of the Software, and to permit persons to whom the Software is
797
+ furnished to do so, subject to the following conditions:
798
+
799
+ The above copyright notice and this permission notice shall be included in all
800
+ copies or substantial portions of the Software.
801
+
802
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
803
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
804
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
805
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
806
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
807
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
808
+ SOFTWARE.
.venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/RECORD ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/normalizer,sha256=tHQgVQWtARWtD-GtJTSofQosfOqZYzDoPu4IRIPnjTA,355
2
+ 81d243bd2c585b0f4821__mypyc.cpython-311-x86_64-linux-gnu.so,sha256=gpIx9m7J0jRbZd0AlebeKN_1Xwc7C5UeNi7DqVD8vgM,429672
3
+ charset_normalizer-3.4.7.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
4
+ charset_normalizer-3.4.7.dist-info/METADATA,sha256=K8lK8L8LaZ1YmKvWLt3zEkpIxiCOC58xNhzFQrfQJxQ,40931
5
+ charset_normalizer-3.4.7.dist-info/RECORD,,
6
+ charset_normalizer-3.4.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ charset_normalizer-3.4.7.dist-info/WHEEL,sha256=M5wZqvm0RPz434ksvS2jyqHKJ9fsZFXCH8JlrvbFuNs,190
8
+ charset_normalizer-3.4.7.dist-info/entry_points.txt,sha256=ADSTKrkXZ3hhdOVFi6DcUEHQRS0xfxDIE_pEz4wLIXA,65
9
+ charset_normalizer-3.4.7.dist-info/licenses/LICENSE,sha256=bQ1Bv-FwrGx9wkjJpj4lTQ-0WmDVCoJX0K-SxuJJuIc,1071
10
+ charset_normalizer-3.4.7.dist-info/top_level.txt,sha256=c_vZbitqecT2GfK3zdxSTLCn8C-6pGnHQY5o_5Y32M0,47
11
+ charset_normalizer/__init__.py,sha256=OKRxRv2Zhnqk00tqkN0c1BtJjm165fWXLydE52IKuHc,1590
12
+ charset_normalizer/__main__.py,sha256=yzYxMR-IhKRHYwcSlavEv8oGdwxsR89mr2X09qXGdps,109
13
+ charset_normalizer/api.py,sha256=387F3n23MlMu-xfSbFULW2DLGsBmVrZVGhnkiGXeKBo,38844
14
+ charset_normalizer/cd.cpython-311-x86_64-linux-gnu.so,sha256=q9uObNt5v2-3JR3GmbMsHY7cJIiCz9Eez4Hmvs0IR3M,15912
15
+ charset_normalizer/cd.py,sha256=v0iPJweGsRegXywrM1LzUgqW9bJ1KFvIblQHP1jm5FQ,15174
16
+ charset_normalizer/cli/__init__.py,sha256=D8I86lFk2-py45JvqxniTirSj_sFyE6sjaY_0-G1shc,136
17
+ charset_normalizer/cli/__main__.py,sha256=E9FFSV1E2iOE_B2B1tJHQT9ExJqc60Ks_c-08sNawh8,11940
18
+ charset_normalizer/constant.py,sha256=yvLAWDrdSC743Cu4amhwHLIO-FGuRTOTZouCzZKGikc,44431
19
+ charset_normalizer/legacy.py,sha256=yBIFMNABNPE5JkdKOWyVo36fZtV9nm8bf37LrDWulz8,2661
20
+ charset_normalizer/md.cpython-311-x86_64-linux-gnu.so,sha256=MvlOADQzK-FTt2QLGo1y7joPU_7evdj0LunrWj6uzXs,15912
21
+ charset_normalizer/md.py,sha256=AYCdfDX79FrgoId3zXqmbCuDcbGr1NRuGqgJN94Rx9Q,30441
22
+ charset_normalizer/models.py,sha256=FbaQnI6ECmVmyHRSvVM5fHNeMAQ3KSGdwLjGcQqWDws,12821
23
+ charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
24
+ charset_normalizer/utils.py,sha256=9cpi-_0-vC9pGDfuoarhC6VlF_Jxwx5Jsa_8I4w2D8k,12282
25
+ charset_normalizer/version.py,sha256=2LxFuGp3BBuIwt95cp64y7v8bCNHcMAi08IfXt_47Co,115
.venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/WHEEL ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp311-cp311-manylinux_2_17_x86_64
5
+ Tag: cp311-cp311-manylinux2014_x86_64
6
+ Tag: cp311-cp311-manylinux_2_28_x86_64
7
+
.venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ normalizer = charset_normalizer.cli:cli_detect
.venv/lib/python3.11/site-packages/charset_normalizer-3.4.7.dist-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ 81d243bd2c585b0f4821__mypyc
2
+ charset_normalizer
.venv/lib/python3.11/site-packages/charset_normalizer/__init__.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Charset-Normalizer
3
+ ~~~~~~~~~~~~~~
4
+ The Real First Universal Charset Detector.
5
+ A library that helps you read text from an unknown charset encoding.
6
+ Motivated by chardet, This package is trying to resolve the issue by taking a new approach.
7
+ All IANA character set names for which the Python core library provides codecs are supported.
8
+
9
+ Basic usage:
10
+ >>> from charset_normalizer import from_bytes
11
+ >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието!'.encode('utf_8'))
12
+ >>> best_guess = results.best()
13
+ >>> str(best_guess)
14
+ 'Bсеки човек има право на образование. Oбразованието!'
15
+
16
+ Others methods and usages are available - see the full documentation
17
+ at <https://github.com/Ousret/charset_normalizer>.
18
+ :copyright: (c) 2021 by Ahmed TAHRI
19
+ :license: MIT, see LICENSE for more details.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import logging
25
+
26
+ from .api import from_bytes, from_fp, from_path, is_binary
27
+ from .legacy import detect
28
+ from .models import CharsetMatch, CharsetMatches
29
+ from .utils import set_logging_handler
30
+ from .version import VERSION, __version__
31
+
32
+ __all__ = (
33
+ "from_fp",
34
+ "from_path",
35
+ "from_bytes",
36
+ "is_binary",
37
+ "detect",
38
+ "CharsetMatch",
39
+ "CharsetMatches",
40
+ "__version__",
41
+ "VERSION",
42
+ "set_logging_handler",
43
+ )
44
+
45
+ # Attach a NullHandler to the top level logger by default
46
+ # https://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library
47
+
48
+ logging.getLogger("charset_normalizer").addHandler(logging.NullHandler())
.venv/lib/python3.11/site-packages/charset_normalizer/md.cpython-311-x86_64-linux-gnu.so ADDED
Binary file (15.9 kB). View file
 
.venv/lib/python3.11/site-packages/click-8.4.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ uv
.venv/lib/python3.11/site-packages/click-8.4.1.dist-info/METADATA ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: click
3
+ Version: 8.4.1
4
+ Summary: Composable command line interface toolkit
5
+ Maintainer-email: Pallets <contact@palletsprojects.com>
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-Expression: BSD-3-Clause
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Typing :: Typed
14
+ License-File: LICENSE.txt
15
+ Requires-Dist: colorama; platform_system == 'Windows'
16
+ Project-URL: Changes, https://click.palletsprojects.com/page/changes/
17
+ Project-URL: Chat, https://discord.gg/pallets
18
+ Project-URL: Documentation, https://click.palletsprojects.com/
19
+ Project-URL: Donate, https://palletsprojects.com/donate
20
+ Project-URL: Source, https://github.com/pallets/click/
21
+
22
+ <div align="center"><img src="https://raw.githubusercontent.com/pallets/click/refs/heads/stable/docs/_static/click-name.svg" alt="" height="150"></div>
23
+
24
+ # Click
25
+
26
+ Click is a Python package for creating beautiful command line interfaces
27
+ in a composable way with as little code as necessary. It's the "Command
28
+ Line Interface Creation Kit". It's highly configurable but comes with
29
+ sensible defaults out of the box.
30
+
31
+ It aims to make the process of writing command line tools quick and fun
32
+ while also preventing any frustration caused by the inability to
33
+ implement an intended CLI API.
34
+
35
+ Click in three points:
36
+
37
+ - Arbitrary nesting of commands
38
+ - Automatic help page generation
39
+ - Supports lazy loading of subcommands at runtime
40
+
41
+
42
+ ## A Simple Example
43
+
44
+ ```python
45
+ import click
46
+
47
+ @click.command()
48
+ @click.option("--count", default=1, help="Number of greetings.")
49
+ @click.option("--name", prompt="Your name", help="The person to greet.")
50
+ def hello(count, name):
51
+ """Simple program that greets NAME for a total of COUNT times."""
52
+ for _ in range(count):
53
+ click.echo(f"Hello, {name}!")
54
+
55
+ if __name__ == '__main__':
56
+ hello()
57
+ ```
58
+
59
+ ```
60
+ $ python hello.py --count=3
61
+ Your name: Click
62
+ Hello, Click!
63
+ Hello, Click!
64
+ Hello, Click!
65
+ ```
66
+
67
+
68
+ ## Donate
69
+
70
+ The Pallets organization develops and supports Click and other popular
71
+ packages. In order to grow the community of contributors and users, and
72
+ allow the maintainers to devote more time to the projects, [please
73
+ donate today][].
74
+
75
+ [please donate today]: https://palletsprojects.com/donate
76
+
77
+ ## Contributing
78
+
79
+ See our [detailed contributing documentation][contrib] for many ways to
80
+ contribute, including reporting issues, requesting features, asking or answering
81
+ questions, and making PRs.
82
+
83
+ [contrib]: https://palletsprojects.com/contributing/
84
+
.venv/lib/python3.11/site-packages/click-8.4.1.dist-info/RECORD ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ click-8.4.1.dist-info/INSTALLER,sha256=5hhM4Q4mYTT9z6QB6PGpUAW81PGNFrYrdXMj4oM_6ak,2
2
+ click-8.4.1.dist-info/METADATA,sha256=uWALc7Y-Ixjj35al3B2qNsyXk-0tf578YgIsL1Vbn98,2621
3
+ click-8.4.1.dist-info/RECORD,,
4
+ click-8.4.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ click-8.4.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
6
+ click-8.4.1.dist-info/licenses/LICENSE.txt,sha256=morRBqOU6FO_4h9C9OctWSgZoigF2ZG18ydQKSkrZY0,1475
7
+ click/__init__.py,sha256=FId2fXCSJB3yeWD-e2uON-mBhFa2Yc9MvXGmHu8OXG0,4634
8
+ click/_compat.py,sha256=XK1woqBSPRb1KNAwWwVsSMfEm8ZlfDwBCjceWzSGmEY,18910
9
+ click/_termui_impl.py,sha256=VNyWY27pm0JUq12WK__pJNYxeUoDyfNwYEgE6vz_cnM,30411
10
+ click/_textwrap.py,sha256=7Z0N7Vmn-66TNSTUwp6OXJbcUXRmYET9h9c2ucD8oQQ,6270
11
+ click/_utils.py,sha256=eCZCtwJtsYD5QYkkNWJ8MY_8ABIjy8MczgMMyVY32rQ,996
12
+ click/_winconsole.py,sha256=KSxfNbMlYRa6GOJuCLgsg2Pb3dVkgJNPqLJPae-Pa10,8543
13
+ click/core.py,sha256=CQaJ0ALw4zyyVp6E7gP6a_G88eiuXE9mBzFnIJQ-igY,137917
14
+ click/decorators.py,sha256=xgR8vZAClhWVkzitP22k6jETFRhKralh81zvA69Csd0,18467
15
+ click/exceptions.py,sha256=FJitDd6MSZLj6CtKQWpkQzHnfsUw3UypxDU0t76bn0c,11294
16
+ click/formatting.py,sha256=r6kGLpPyF0Cva6uSTwSZ_8ONRE7jp93I1C0JVRYQEqE,10370
17
+ click/globals.py,sha256=gM-Nh6A4M0HB_SgkaF5M4ncGGMDHc_flHXu9_oh4GEU,1923
18
+ click/parser.py,sha256=oJ-fU_3mvxugIuNtHaCATZ56lgEmHRggjJiSqEgYrjA,19052
19
+ click/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ click/shell_completion.py,sha256=QxeFb3RapNSP8ZwvK2BDVI2jrEKS1RbJaeuFMrHJAnU,21748
21
+ click/termui.py,sha256=hflZ_tK7P4WUv_ef_RVVRL7n0nRPhTD0wN0pkHE7hDo,33000
22
+ click/testing.py,sha256=0k_v5By_5ZO2McjBT7lTqQ57W8QJuW0_5Sx7d2ZLKec,25717
23
+ click/types.py,sha256=UiVEx0yoQtrWO2wH22NgME4LfDxMNQi8j1qtJupYIpw,42783
24
+ click/utils.py,sha256=YsTNrChEfwDXl39CTC_yWnQ-ZVkZxYjFESRCfEgClY4,20386
.venv/lib/python3.11/site-packages/click-8.4.1.dist-info/REQUESTED ADDED
File without changes
.venv/lib/python3.11/site-packages/click-8.4.1.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: flit 3.12.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv/lib/python3.11/site-packages/click/__init__.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ from __future__ import annotations
9
+
10
+ from .core import Argument as Argument
11
+ from .core import Command as Command
12
+ from .core import CommandCollection as CommandCollection
13
+ from .core import Context as Context
14
+ from .core import Group as Group
15
+ from .core import Option as Option
16
+ from .core import Parameter as Parameter
17
+ from .core import ParameterSource as ParameterSource
18
+ from .decorators import argument as argument
19
+ from .decorators import command as command
20
+ from .decorators import confirmation_option as confirmation_option
21
+ from .decorators import group as group
22
+ from .decorators import help_option as help_option
23
+ from .decorators import make_pass_decorator as make_pass_decorator
24
+ from .decorators import option as option
25
+ from .decorators import pass_context as pass_context
26
+ from .decorators import pass_obj as pass_obj
27
+ from .decorators import password_option as password_option
28
+ from .decorators import version_option as version_option
29
+ from .exceptions import Abort as Abort
30
+ from .exceptions import BadArgumentUsage as BadArgumentUsage
31
+ from .exceptions import BadOptionUsage as BadOptionUsage
32
+ from .exceptions import BadParameter as BadParameter
33
+ from .exceptions import ClickException as ClickException
34
+ from .exceptions import FileError as FileError
35
+ from .exceptions import MissingParameter as MissingParameter
36
+ from .exceptions import NoSuchCommand as NoSuchCommand
37
+ from .exceptions import NoSuchOption as NoSuchOption
38
+ from .exceptions import UsageError as UsageError
39
+ from .formatting import HelpFormatter as HelpFormatter
40
+ from .formatting import wrap_text as wrap_text
41
+ from .globals import get_current_context as get_current_context
42
+ from .termui import clear as clear
43
+ from .termui import confirm as confirm
44
+ from .termui import echo_via_pager as echo_via_pager
45
+ from .termui import edit as edit
46
+ from .termui import get_pager_file as get_pager_file
47
+ from .termui import getchar as getchar
48
+ from .termui import launch as launch
49
+ from .termui import pause as pause
50
+ from .termui import progressbar as progressbar
51
+ from .termui import prompt as prompt
52
+ from .termui import secho as secho
53
+ from .termui import style as style
54
+ from .termui import unstyle as unstyle
55
+ from .types import BOOL as BOOL
56
+ from .types import Choice as Choice
57
+ from .types import DateTime as DateTime
58
+ from .types import File as File
59
+ from .types import FLOAT as FLOAT
60
+ from .types import FloatRange as FloatRange
61
+ from .types import INT as INT
62
+ from .types import IntRange as IntRange
63
+ from .types import ParamType as ParamType
64
+ from .types import Path as Path
65
+ from .types import STRING as STRING
66
+ from .types import Tuple as Tuple
67
+ from .types import UNPROCESSED as UNPROCESSED
68
+ from .types import UUID as UUID
69
+ from .utils import echo as echo
70
+ from .utils import format_filename as format_filename
71
+ from .utils import get_app_dir as get_app_dir
72
+ from .utils import get_binary_stream as get_binary_stream
73
+ from .utils import get_text_stream as get_text_stream
74
+ from .utils import open_file as open_file
75
+
76
+
77
+ def __getattr__(name: str) -> object:
78
+ import warnings
79
+
80
+ if name == "BaseCommand":
81
+ from .core import _BaseCommand
82
+
83
+ warnings.warn(
84
+ "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"
85
+ " 'Command' instead.",
86
+ DeprecationWarning,
87
+ stacklevel=2,
88
+ )
89
+ return _BaseCommand
90
+
91
+ if name == "MultiCommand":
92
+ from .core import _MultiCommand
93
+
94
+ warnings.warn(
95
+ "'MultiCommand' is deprecated and will be removed in Click 9.0. Use"
96
+ " 'Group' instead.",
97
+ DeprecationWarning,
98
+ stacklevel=2,
99
+ )
100
+ return _MultiCommand
101
+
102
+ if name == "OptionParser":
103
+ from .parser import _OptionParser
104
+
105
+ warnings.warn(
106
+ "'OptionParser' is deprecated and will be removed in Click 9.0. The"
107
+ " old parser is available in 'optparse'.",
108
+ DeprecationWarning,
109
+ stacklevel=2,
110
+ )
111
+ return _OptionParser
112
+
113
+ if name == "__version__":
114
+ import importlib.metadata
115
+ import warnings
116
+
117
+ warnings.warn(
118
+ "The '__version__' attribute is deprecated and will be removed in"
119
+ " Click 9.1. Use feature detection or"
120
+ " 'importlib.metadata.version(\"click\")' instead.",
121
+ DeprecationWarning,
122
+ stacklevel=2,
123
+ )
124
+ return importlib.metadata.version("click")
125
+
126
+ raise AttributeError(name)
.venv/lib/python3.11/site-packages/click/_compat.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import codecs
4
+ import collections.abc as cabc
5
+ import io
6
+ import os
7
+ import re
8
+ import sys
9
+ import typing as t
10
+ from types import TracebackType
11
+ from weakref import WeakKeyDictionary
12
+
13
+ CYGWIN = sys.platform.startswith("cygwin")
14
+ WIN = sys.platform.startswith("win")
15
+ MAC = sys.platform == "darwin"
16
+ auto_wrap_for_ansi: t.Callable[[t.TextIO], t.TextIO] | None = None
17
+ _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
18
+
19
+
20
+ def _make_text_stream(
21
+ stream: t.BinaryIO,
22
+ encoding: str | None,
23
+ errors: str | None,
24
+ force_readable: bool = False,
25
+ force_writable: bool = False,
26
+ ) -> t.TextIO:
27
+ if encoding is None:
28
+ encoding = get_best_encoding(stream)
29
+ if errors is None:
30
+ errors = "replace"
31
+ return _NonClosingTextIOWrapper(
32
+ stream,
33
+ encoding,
34
+ errors,
35
+ line_buffering=True,
36
+ force_readable=force_readable,
37
+ force_writable=force_writable,
38
+ )
39
+
40
+
41
+ def is_ascii_encoding(encoding: str) -> bool:
42
+ """Checks if a given encoding is ascii."""
43
+ try:
44
+ return codecs.lookup(encoding).name == "ascii"
45
+ except LookupError:
46
+ return False
47
+
48
+
49
+ def get_best_encoding(stream: t.IO[t.Any]) -> str:
50
+ """Returns the default stream encoding if not found."""
51
+ rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()
52
+ if is_ascii_encoding(rv):
53
+ return "utf-8"
54
+ return rv
55
+
56
+
57
+ class _NonClosingTextIOWrapper(io.TextIOWrapper):
58
+ def __init__(
59
+ self,
60
+ stream: t.BinaryIO,
61
+ encoding: str | None,
62
+ errors: str | None,
63
+ force_readable: bool = False,
64
+ force_writable: bool = False,
65
+ **extra: t.Any,
66
+ ) -> None:
67
+ self._stream = stream = t.cast(
68
+ t.BinaryIO, _FixupStream(stream, force_readable, force_writable)
69
+ )
70
+ super().__init__(stream, encoding, errors, **extra)
71
+
72
+ def __del__(self) -> None:
73
+ try:
74
+ self.detach()
75
+ except Exception:
76
+ pass
77
+
78
+ def isatty(self) -> bool:
79
+ # https://bitbucket.org/pypy/pypy/issue/1803
80
+ return self._stream.isatty()
81
+
82
+
83
+ class _FixupStream:
84
+ """The new io interface needs more from streams than streams
85
+ traditionally implement. As such, this fix-up code is necessary in
86
+ some circumstances.
87
+
88
+ The forcing of readable and writable flags are there because some tools
89
+ put badly patched objects on sys (one such offender are certain version
90
+ of jupyter notebook).
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ stream: t.BinaryIO,
96
+ force_readable: bool = False,
97
+ force_writable: bool = False,
98
+ ):
99
+ self._stream = stream
100
+ self._force_readable = force_readable
101
+ self._force_writable = force_writable
102
+
103
+ def __getattr__(self, name: str) -> t.Any:
104
+ return getattr(self._stream, name)
105
+
106
+ def read1(self, size: int) -> bytes:
107
+ f = getattr(self._stream, "read1", None)
108
+
109
+ if f is not None:
110
+ return t.cast(bytes, f(size))
111
+
112
+ return self._stream.read(size)
113
+
114
+ def readable(self) -> bool:
115
+ if self._force_readable:
116
+ return True
117
+ x = getattr(self._stream, "readable", None)
118
+ if x is not None:
119
+ return t.cast(bool, x())
120
+ try:
121
+ self._stream.read(0)
122
+ except Exception:
123
+ return False
124
+ return True
125
+
126
+ def writable(self) -> bool:
127
+ if self._force_writable:
128
+ return True
129
+ x = getattr(self._stream, "writable", None)
130
+ if x is not None:
131
+ return t.cast(bool, x())
132
+ try:
133
+ self._stream.write(b"")
134
+ except Exception:
135
+ try:
136
+ self._stream.write(b"")
137
+ except Exception:
138
+ return False
139
+ return True
140
+
141
+ def seekable(self) -> bool:
142
+ x = getattr(self._stream, "seekable", None)
143
+ if x is not None:
144
+ return t.cast(bool, x())
145
+ try:
146
+ self._stream.seek(self._stream.tell())
147
+ except Exception:
148
+ return False
149
+ return True
150
+
151
+
152
+ def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool:
153
+ try:
154
+ return isinstance(stream.read(0), bytes)
155
+ except Exception:
156
+ return default
157
+ # This happens in some cases where the stream was already
158
+ # closed. In this case, we assume the default.
159
+
160
+
161
+ def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool:
162
+ try:
163
+ stream.write(b"")
164
+ except Exception:
165
+ try:
166
+ stream.write("")
167
+ return False
168
+ except Exception:
169
+ pass
170
+ return default
171
+ return True
172
+
173
+
174
+ def _find_binary_reader(stream: t.IO[t.Any]) -> t.BinaryIO | None:
175
+ # We need to figure out if the given stream is already binary.
176
+ # This can happen because the official docs recommend detaching
177
+ # the streams to get binary streams. Some code might do this, so
178
+ # we need to deal with this case explicitly.
179
+ if _is_binary_reader(stream, False):
180
+ return t.cast(t.BinaryIO, stream)
181
+
182
+ buf = getattr(stream, "buffer", None)
183
+
184
+ # Same situation here; this time we assume that the buffer is
185
+ # actually binary in case it's closed.
186
+ if buf is not None and _is_binary_reader(buf, True):
187
+ return t.cast(t.BinaryIO, buf)
188
+
189
+ return None
190
+
191
+
192
+ def _find_binary_writer(stream: t.IO[t.Any]) -> t.BinaryIO | None:
193
+ # We need to figure out if the given stream is already binary.
194
+ # This can happen because the official docs recommend detaching
195
+ # the streams to get binary streams. Some code might do this, so
196
+ # we need to deal with this case explicitly.
197
+ if _is_binary_writer(stream, False):
198
+ return t.cast(t.BinaryIO, stream)
199
+
200
+ buf = getattr(stream, "buffer", None)
201
+
202
+ # Same situation here; this time we assume that the buffer is
203
+ # actually binary in case it's closed.
204
+ if buf is not None and _is_binary_writer(buf, True):
205
+ return t.cast(t.BinaryIO, buf)
206
+
207
+ return None
208
+
209
+
210
+ def _stream_is_misconfigured(stream: t.TextIO) -> bool:
211
+ """A stream is misconfigured if its encoding is ASCII."""
212
+ # If the stream does not have an encoding set, we assume it's set
213
+ # to ASCII. This appears to happen in certain unittest
214
+ # environments. It's not quite clear what the correct behavior is
215
+ # but this at least will force Click to recover somehow.
216
+ return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")
217
+
218
+
219
+ def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: str | None) -> bool:
220
+ """A stream attribute is compatible if it is equal to the
221
+ desired value or the desired value is unset and the attribute
222
+ has a value.
223
+ """
224
+ stream_value = getattr(stream, attr, None)
225
+ return stream_value == value or (value is None and stream_value is not None)
226
+
227
+
228
+ def _is_compatible_text_stream(
229
+ stream: t.TextIO, encoding: str | None, errors: str | None
230
+ ) -> bool:
231
+ """Check if a stream's encoding and errors attributes are
232
+ compatible with the desired values.
233
+ """
234
+ return _is_compat_stream_attr(
235
+ stream, "encoding", encoding
236
+ ) and _is_compat_stream_attr(stream, "errors", errors)
237
+
238
+
239
+ def _force_correct_text_stream(
240
+ text_stream: t.IO[t.Any],
241
+ encoding: str | None,
242
+ errors: str | None,
243
+ is_binary: t.Callable[[t.IO[t.Any], bool], bool],
244
+ find_binary: t.Callable[[t.IO[t.Any]], t.BinaryIO | None],
245
+ force_readable: bool = False,
246
+ force_writable: bool = False,
247
+ ) -> t.TextIO:
248
+ if is_binary(text_stream, False):
249
+ binary_reader = t.cast(t.BinaryIO, text_stream)
250
+ else:
251
+ text_stream = t.cast(t.TextIO, text_stream)
252
+ # If the stream looks compatible, and won't default to a
253
+ # misconfigured ascii encoding, return it as-is.
254
+ if _is_compatible_text_stream(text_stream, encoding, errors) and not (
255
+ encoding is None and _stream_is_misconfigured(text_stream)
256
+ ):
257
+ return text_stream
258
+
259
+ # Otherwise, get the underlying binary reader.
260
+ possible_binary_reader = find_binary(text_stream)
261
+
262
+ # If that's not possible, silently use the original reader
263
+ # and get mojibake instead of exceptions.
264
+ if possible_binary_reader is None:
265
+ return text_stream
266
+
267
+ binary_reader = possible_binary_reader
268
+
269
+ # Default errors to replace instead of strict in order to get
270
+ # something that works.
271
+ if errors is None:
272
+ errors = "replace"
273
+
274
+ # Wrap the binary stream in a text stream with the correct
275
+ # encoding parameters.
276
+ return _make_text_stream(
277
+ binary_reader,
278
+ encoding,
279
+ errors,
280
+ force_readable=force_readable,
281
+ force_writable=force_writable,
282
+ )
283
+
284
+
285
+ def _force_correct_text_reader(
286
+ text_reader: t.IO[t.Any],
287
+ encoding: str | None,
288
+ errors: str | None,
289
+ force_readable: bool = False,
290
+ ) -> t.TextIO:
291
+ return _force_correct_text_stream(
292
+ text_reader,
293
+ encoding,
294
+ errors,
295
+ _is_binary_reader,
296
+ _find_binary_reader,
297
+ force_readable=force_readable,
298
+ )
299
+
300
+
301
+ def _force_correct_text_writer(
302
+ text_writer: t.IO[t.Any],
303
+ encoding: str | None,
304
+ errors: str | None,
305
+ force_writable: bool = False,
306
+ ) -> t.TextIO:
307
+ return _force_correct_text_stream(
308
+ text_writer,
309
+ encoding,
310
+ errors,
311
+ _is_binary_writer,
312
+ _find_binary_writer,
313
+ force_writable=force_writable,
314
+ )
315
+
316
+
317
+ def get_binary_stdin() -> t.BinaryIO:
318
+ reader = _find_binary_reader(sys.stdin)
319
+ if reader is None:
320
+ raise RuntimeError("Was not able to determine binary stream for sys.stdin.")
321
+ return reader
322
+
323
+
324
+ def get_binary_stdout() -> t.BinaryIO:
325
+ writer = _find_binary_writer(sys.stdout)
326
+ if writer is None:
327
+ raise RuntimeError("Was not able to determine binary stream for sys.stdout.")
328
+ return writer
329
+
330
+
331
+ def get_binary_stderr() -> t.BinaryIO:
332
+ writer = _find_binary_writer(sys.stderr)
333
+ if writer is None:
334
+ raise RuntimeError("Was not able to determine binary stream for sys.stderr.")
335
+ return writer
336
+
337
+
338
+ def get_text_stdin(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
339
+ rv = _get_windows_console_stream(sys.stdin, encoding, errors)
340
+ if rv is not None:
341
+ return rv
342
+ return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)
343
+
344
+
345
+ def get_text_stdout(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
346
+ rv = _get_windows_console_stream(sys.stdout, encoding, errors)
347
+ if rv is not None:
348
+ return rv
349
+ return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)
350
+
351
+
352
+ def get_text_stderr(encoding: str | None = None, errors: str | None = None) -> t.TextIO:
353
+ rv = _get_windows_console_stream(sys.stderr, encoding, errors)
354
+ if rv is not None:
355
+ return rv
356
+ return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)
357
+
358
+
359
+ def _wrap_io_open(
360
+ file: str | os.PathLike[str] | int,
361
+ mode: str,
362
+ encoding: str | None,
363
+ errors: str | None,
364
+ ) -> t.IO[t.Any]:
365
+ """Handles not passing ``encoding`` and ``errors`` in binary mode."""
366
+ if "b" in mode:
367
+ return open(file, mode)
368
+
369
+ return open(file, mode, encoding=encoding, errors=errors)
370
+
371
+
372
+ def open_stream(
373
+ filename: str | os.PathLike[str],
374
+ mode: str = "r",
375
+ encoding: str | None = None,
376
+ errors: str | None = "strict",
377
+ atomic: bool = False,
378
+ ) -> tuple[t.IO[t.Any], bool]:
379
+ binary = "b" in mode
380
+ filename = os.fspath(filename)
381
+
382
+ # Standard streams first. These are simple because they ignore the
383
+ # atomic flag. Use fsdecode to handle Path("-").
384
+ if os.fsdecode(filename) == "-":
385
+ if any(m in mode for m in ["w", "a", "x"]):
386
+ if binary:
387
+ return get_binary_stdout(), False
388
+ return get_text_stdout(encoding=encoding, errors=errors), False
389
+ if binary:
390
+ return get_binary_stdin(), False
391
+ return get_text_stdin(encoding=encoding, errors=errors), False
392
+
393
+ # Non-atomic writes directly go out through the regular open functions.
394
+ if not atomic:
395
+ return _wrap_io_open(filename, mode, encoding, errors), True
396
+
397
+ # Some usability stuff for atomic writes
398
+ if "a" in mode:
399
+ raise ValueError(
400
+ "Appending to an existing file is not supported, because that"
401
+ " would involve an expensive `copy`-operation to a temporary"
402
+ " file. Open the file in normal `w`-mode and copy explicitly"
403
+ " if that's what you're after."
404
+ )
405
+ if "x" in mode:
406
+ raise ValueError("Use the `overwrite`-parameter instead.")
407
+ if "w" not in mode:
408
+ raise ValueError("Atomic writes only make sense with `w`-mode.")
409
+
410
+ # Atomic writes are more complicated. They work by opening a file
411
+ # as a proxy in the same folder and then using the fdopen
412
+ # functionality to wrap it in a Python file. Then we wrap it in an
413
+ # atomic file that moves the file over on close.
414
+ import errno
415
+ import random
416
+
417
+ try:
418
+ perm: int | None = os.stat(filename).st_mode
419
+ except OSError:
420
+ perm = None
421
+
422
+ flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
423
+
424
+ if binary:
425
+ flags |= getattr(os, "O_BINARY", 0)
426
+
427
+ while True:
428
+ tmp_filename = os.path.join(
429
+ os.path.dirname(filename),
430
+ f".__atomic-write{random.randrange(1 << 32):08x}",
431
+ )
432
+ try:
433
+ fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)
434
+ break
435
+ except OSError as e:
436
+ if e.errno == errno.EEXIST or (
437
+ os.name == "nt"
438
+ and e.errno == errno.EACCES
439
+ and os.path.isdir(e.filename)
440
+ and os.access(e.filename, os.W_OK)
441
+ ):
442
+ continue
443
+ raise
444
+
445
+ if perm is not None:
446
+ os.chmod(tmp_filename, perm) # in case perm includes bits in umask
447
+
448
+ f = _wrap_io_open(fd, mode, encoding, errors)
449
+ af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))
450
+ return t.cast(t.IO[t.Any], af), True
451
+
452
+
453
+ class _AtomicFile:
454
+ def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None:
455
+ self._f = f
456
+ self._tmp_filename = tmp_filename
457
+ self._real_filename = real_filename
458
+ self.closed = False
459
+
460
+ @property
461
+ def name(self) -> str:
462
+ return self._real_filename
463
+
464
+ def close(self, delete: bool = False) -> None:
465
+ if self.closed:
466
+ return
467
+ self._f.close()
468
+ os.replace(self._tmp_filename, self._real_filename)
469
+ self.closed = True
470
+
471
+ def __getattr__(self, name: str) -> t.Any:
472
+ return getattr(self._f, name)
473
+
474
+ def __enter__(self) -> _AtomicFile:
475
+ return self
476
+
477
+ def __exit__(
478
+ self,
479
+ exc_type: type[BaseException] | None,
480
+ exc_value: BaseException | None,
481
+ tb: TracebackType | None,
482
+ ) -> None:
483
+ self.close(delete=exc_type is not None)
484
+
485
+ def __repr__(self) -> str:
486
+ return repr(self._f)
487
+
488
+
489
+ def strip_ansi(value: str) -> str:
490
+ return _ansi_re.sub("", value)
491
+
492
+
493
+ def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:
494
+ while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):
495
+ stream = stream._stream
496
+
497
+ return stream.__class__.__module__.startswith("ipykernel.")
498
+
499
+
500
+ def should_strip_ansi(
501
+ stream: t.IO[t.Any] | None = None, color: bool | None = None
502
+ ) -> bool:
503
+ if color is None:
504
+ if stream is None:
505
+ stream = sys.stdin
506
+ elif hasattr(stream, "color"):
507
+ # ._termui_impl.MaybeStripAnsi handles stripping ansi itself,
508
+ # so we don't need to strip it here
509
+ return False
510
+ return not isatty(stream) and not _is_jupyter_kernel_output(stream)
511
+ return not color
512
+
513
+
514
+ # On Windows, wrap the output streams with colorama to support ANSI
515
+ # color codes.
516
+ # NOTE: double check is needed so mypy does not analyze this on Linux
517
+ if sys.platform.startswith("win") and WIN:
518
+ from ._winconsole import _get_windows_console_stream
519
+
520
+ def _get_argv_encoding() -> str:
521
+ import locale
522
+
523
+ return locale.getpreferredencoding()
524
+
525
+ _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
526
+
527
+ def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO:
528
+ """Support ANSI color and style codes on Windows by wrapping a
529
+ stream with colorama.
530
+ """
531
+ try:
532
+ cached = _ansi_stream_wrappers.get(stream)
533
+ except Exception:
534
+ cached = None
535
+
536
+ if cached is not None:
537
+ return cached
538
+
539
+ import colorama
540
+
541
+ strip = should_strip_ansi(stream, color)
542
+ ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
543
+ rv = t.cast(t.TextIO, ansi_wrapper.stream)
544
+ _write = rv.write
545
+
546
+ def _safe_write(s: str) -> int:
547
+ try:
548
+ return _write(s)
549
+ except BaseException:
550
+ ansi_wrapper.reset_all()
551
+ raise
552
+
553
+ rv.write = _safe_write # type: ignore[method-assign]
554
+
555
+ try:
556
+ _ansi_stream_wrappers[stream] = rv
557
+ except Exception:
558
+ pass
559
+
560
+ return rv
561
+
562
+ else:
563
+
564
+ def _get_argv_encoding() -> str:
565
+ return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()
566
+
567
+ def _get_windows_console_stream(
568
+ f: t.TextIO, encoding: str | None, errors: str | None
569
+ ) -> t.TextIO | None:
570
+ return None
571
+
572
+
573
+ def term_len(x: str) -> int:
574
+ return len(strip_ansi(x))
575
+
576
+
577
+ def isatty(stream: t.IO[t.Any]) -> bool:
578
+ try:
579
+ return stream.isatty()
580
+ except Exception:
581
+ return False
582
+
583
+
584
+ def _make_cached_stream_func(
585
+ src_func: t.Callable[[], t.TextIO | None],
586
+ wrapper_func: t.Callable[[], t.TextIO],
587
+ ) -> t.Callable[[], t.TextIO | None]:
588
+ cache: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
589
+
590
+ def func() -> t.TextIO | None:
591
+ stream = src_func()
592
+
593
+ if stream is None:
594
+ return None
595
+
596
+ try:
597
+ rv = cache.get(stream)
598
+ except Exception:
599
+ rv = None
600
+ if rv is not None:
601
+ return rv
602
+ rv = wrapper_func()
603
+ try:
604
+ cache[stream] = rv
605
+ except Exception:
606
+ pass
607
+ return rv
608
+
609
+ return func
610
+
611
+
612
+ _default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)
613
+ _default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)
614
+ _default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)
615
+
616
+
617
+ binary_streams: cabc.Mapping[str, t.Callable[[], t.BinaryIO]] = {
618
+ "stdin": get_binary_stdin,
619
+ "stdout": get_binary_stdout,
620
+ "stderr": get_binary_stderr,
621
+ }
622
+
623
+ text_streams: cabc.Mapping[str, t.Callable[[str | None, str | None], t.TextIO]] = {
624
+ "stdin": get_text_stdin,
625
+ "stdout": get_text_stdout,
626
+ "stderr": get_text_stderr,
627
+ }
.venv/lib/python3.11/site-packages/click/_termui_impl.py ADDED
@@ -0,0 +1,929 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
7
+ from __future__ import annotations
8
+
9
+ import collections.abc as cabc
10
+ import contextlib
11
+ import io
12
+ import math
13
+ import os
14
+ import shlex
15
+ import sys
16
+ import time
17
+ import typing as t
18
+ from gettext import gettext as _
19
+ from io import StringIO
20
+ from pathlib import Path
21
+ from types import TracebackType
22
+
23
+ from ._compat import _default_text_stdout
24
+ from ._compat import CYGWIN
25
+ from ._compat import get_best_encoding
26
+ from ._compat import isatty
27
+ from ._compat import strip_ansi
28
+ from ._compat import term_len
29
+ from ._compat import WIN
30
+ from .exceptions import ClickException
31
+ from .utils import echo
32
+
33
+ V = t.TypeVar("V")
34
+
35
+
36
+ class _BufferedTextPagerStream(t.Protocol):
37
+ buffer: t.BinaryIO
38
+
39
+
40
+ def _has_binary_buffer(
41
+ stream: t.BinaryIO | t.TextIO,
42
+ ) -> t.TypeGuard[_BufferedTextPagerStream]:
43
+ # TextIO is wider than TextIOWrapper; text-only streams such as StringIO
44
+ # are valid TextIO values but do not expose a binary buffer to wrap.
45
+ return getattr(stream, "buffer", None) is not None
46
+
47
+
48
+ if os.name == "nt":
49
+ BEFORE_BAR = "\r"
50
+ AFTER_BAR = "\n"
51
+ else:
52
+ BEFORE_BAR = "\r\033[?25l"
53
+ AFTER_BAR = "\033[?25h\n"
54
+
55
+
56
+ class ProgressBar(t.Generic[V]):
57
+ def __init__(
58
+ self,
59
+ iterable: cabc.Iterable[V] | None,
60
+ length: int | None = None,
61
+ fill_char: str = "#",
62
+ empty_char: str = " ",
63
+ bar_template: str = "%(bar)s",
64
+ info_sep: str = " ",
65
+ hidden: bool = False,
66
+ show_eta: bool = True,
67
+ show_percent: bool | None = None,
68
+ show_pos: bool = False,
69
+ item_show_func: t.Callable[[V | None], str | None] | None = None,
70
+ label: str | None = None,
71
+ file: t.TextIO | None = None,
72
+ color: bool | None = None,
73
+ update_min_steps: int = 1,
74
+ width: int = 30,
75
+ ) -> None:
76
+ self.fill_char = fill_char
77
+ self.empty_char = empty_char
78
+ self.bar_template = bar_template
79
+ self.info_sep = info_sep
80
+ self.hidden = hidden
81
+ self.show_eta = show_eta
82
+ self.show_percent = show_percent
83
+ self.show_pos = show_pos
84
+ self.item_show_func = item_show_func
85
+ self.label: str = label or ""
86
+
87
+ if file is None:
88
+ file = _default_text_stdout()
89
+
90
+ # There are no standard streams attached to write to. For example,
91
+ # pythonw on Windows.
92
+ if file is None:
93
+ file = StringIO()
94
+
95
+ self.file = file
96
+ self.color = color
97
+ self.update_min_steps = update_min_steps
98
+ self._completed_intervals = 0
99
+ self.width: int = width
100
+ self.autowidth: bool = width == 0
101
+
102
+ if length is None:
103
+ from operator import length_hint
104
+
105
+ length = length_hint(iterable, -1)
106
+
107
+ if length == -1:
108
+ length = None
109
+ if iterable is None:
110
+ if length is None:
111
+ raise TypeError("iterable or length is required")
112
+ iterable = t.cast("cabc.Iterable[V]", range(length))
113
+ self.iter: cabc.Iterable[V] = iter(iterable)
114
+ self.length = length
115
+ self.pos: int = 0
116
+ self.avg: list[float] = []
117
+ self.last_eta: float
118
+ self.start: float
119
+ self.start = self.last_eta = time.time()
120
+ self.eta_known: bool = False
121
+ self.finished: bool = False
122
+ self.max_width: int | None = None
123
+ self.entered: bool = False
124
+ self.current_item: V | None = None
125
+ self._is_atty = isatty(self.file)
126
+ self._last_line: str | None = None
127
+
128
+ def __enter__(self) -> ProgressBar[V]:
129
+ self.entered = True
130
+ self.render_progress()
131
+ return self
132
+
133
+ def __exit__(
134
+ self,
135
+ exc_type: type[BaseException] | None,
136
+ exc_value: BaseException | None,
137
+ tb: TracebackType | None,
138
+ ) -> None:
139
+ self.render_finish()
140
+
141
+ def __iter__(self) -> cabc.Iterator[V]:
142
+ if not self.entered:
143
+ raise RuntimeError("You need to use progress bars in a with block.")
144
+ self.render_progress()
145
+ return self.generator()
146
+
147
+ def __next__(self) -> V:
148
+ # Iteration is defined in terms of a generator function,
149
+ # returned by iter(self); use that to define next(). This works
150
+ # because `self.iter` is an iterable consumed by that generator,
151
+ # so it is re-entry safe. Calling `next(self.generator())`
152
+ # twice works and does "what you want".
153
+ return next(iter(self))
154
+
155
+ def render_finish(self) -> None:
156
+ if self.hidden or not self._is_atty:
157
+ return
158
+ self.file.write(AFTER_BAR)
159
+ self.file.flush()
160
+
161
+ @property
162
+ def pct(self) -> float:
163
+ if self.finished:
164
+ return 1.0
165
+ return min(self.pos / (float(self.length or 1) or 1), 1.0)
166
+
167
+ @property
168
+ def time_per_iteration(self) -> float:
169
+ if not self.avg:
170
+ return 0.0
171
+ return sum(self.avg) / float(len(self.avg))
172
+
173
+ @property
174
+ def eta(self) -> float:
175
+ if self.length is not None and not self.finished:
176
+ return self.time_per_iteration * (self.length - self.pos)
177
+ return 0.0
178
+
179
+ def format_eta(self) -> str:
180
+ if self.eta_known:
181
+ t = int(self.eta)
182
+ seconds = t % 60
183
+ t //= 60
184
+ minutes = t % 60
185
+ t //= 60
186
+ hours = t % 24
187
+ t //= 24
188
+ if t > 0:
189
+ return "{d}{day_label} {h:02}:{m:02}:{s:02}".format(
190
+ d=t,
191
+ day_label=_("d"),
192
+ h=hours,
193
+ m=minutes,
194
+ s=seconds,
195
+ )
196
+ else:
197
+ return f"{hours:02}:{minutes:02}:{seconds:02}"
198
+ return ""
199
+
200
+ def format_pos(self) -> str:
201
+ pos = str(self.pos)
202
+ if self.length is not None:
203
+ pos += f"/{self.length}"
204
+ return pos
205
+
206
+ def format_pct(self) -> str:
207
+ return f"{int(self.pct * 100): 4}%"[1:]
208
+
209
+ def format_bar(self) -> str:
210
+ if self.length is not None:
211
+ bar_length = int(self.pct * self.width)
212
+ bar = self.fill_char * bar_length
213
+ bar += self.empty_char * (self.width - bar_length)
214
+ elif self.finished:
215
+ bar = self.fill_char * self.width
216
+ else:
217
+ chars = list(self.empty_char * (self.width or 1))
218
+ if self.time_per_iteration != 0:
219
+ chars[
220
+ int(
221
+ (math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)
222
+ * self.width
223
+ )
224
+ ] = self.fill_char
225
+ bar = "".join(chars)
226
+ return bar
227
+
228
+ def format_progress_line(self) -> str:
229
+ show_percent = self.show_percent
230
+
231
+ info_bits = []
232
+ if self.length is not None and show_percent is None:
233
+ show_percent = not self.show_pos
234
+
235
+ if self.show_pos:
236
+ info_bits.append(self.format_pos())
237
+ if show_percent:
238
+ info_bits.append(self.format_pct())
239
+ if self.show_eta and self.eta_known and not self.finished:
240
+ info_bits.append(self.format_eta())
241
+ if self.item_show_func is not None:
242
+ item_info = self.item_show_func(self.current_item)
243
+ if item_info is not None:
244
+ info_bits.append(item_info)
245
+
246
+ return (
247
+ self.bar_template
248
+ % {
249
+ "label": self.label,
250
+ "bar": self.format_bar(),
251
+ "info": self.info_sep.join(info_bits),
252
+ }
253
+ ).rstrip()
254
+
255
+ def render_progress(self) -> None:
256
+ if self.hidden:
257
+ return
258
+
259
+ if not self._is_atty:
260
+ # Only output the label once if the output is not a TTY.
261
+ if self._last_line != self.label:
262
+ self._last_line = self.label
263
+ echo(self.label, file=self.file, color=self.color)
264
+ return
265
+
266
+ buf = []
267
+ # Update width in case the terminal has been resized
268
+ if self.autowidth:
269
+ import shutil
270
+
271
+ old_width = self.width
272
+ self.width = 0
273
+ clutter_length = term_len(self.format_progress_line())
274
+ new_width = max(0, shutil.get_terminal_size().columns - clutter_length)
275
+ if new_width < old_width and self.max_width is not None:
276
+ buf.append(BEFORE_BAR)
277
+ buf.append(" " * self.max_width)
278
+ self.max_width = new_width
279
+ self.width = new_width
280
+
281
+ clear_width = self.width
282
+ if self.max_width is not None:
283
+ clear_width = self.max_width
284
+
285
+ buf.append(BEFORE_BAR)
286
+ line = self.format_progress_line()
287
+ line_len = term_len(line)
288
+ if self.max_width is None or self.max_width < line_len:
289
+ self.max_width = line_len
290
+
291
+ buf.append(line)
292
+ buf.append(" " * (clear_width - line_len))
293
+ line = "".join(buf)
294
+ # Render the line only if it changed.
295
+
296
+ if line != self._last_line:
297
+ self._last_line = line
298
+ echo(line, file=self.file, color=self.color, nl=False)
299
+ self.file.flush()
300
+
301
+ def make_step(self, n_steps: int) -> None:
302
+ self.pos += n_steps
303
+ if self.length is not None and self.pos >= self.length:
304
+ self.finished = True
305
+
306
+ if (time.time() - self.last_eta) < 1.0:
307
+ return
308
+
309
+ self.last_eta = time.time()
310
+
311
+ # self.avg is a rolling list of length <= 7 of steps where steps are
312
+ # defined as time elapsed divided by the total progress through
313
+ # self.length.
314
+ if self.pos:
315
+ step = (time.time() - self.start) / self.pos
316
+ else:
317
+ step = time.time() - self.start
318
+
319
+ self.avg = self.avg[-6:] + [step]
320
+
321
+ self.eta_known = self.length is not None
322
+
323
+ def update(self, n_steps: int, current_item: V | None = None) -> None:
324
+ """Update the progress bar by advancing a specified number of
325
+ steps, and optionally set the ``current_item`` for this new
326
+ position.
327
+
328
+ :param n_steps: Number of steps to advance.
329
+ :param current_item: Optional item to set as ``current_item``
330
+ for the updated position.
331
+
332
+ .. versionchanged:: 8.0
333
+ Added the ``current_item`` optional parameter.
334
+
335
+ .. versionchanged:: 8.0
336
+ Only render when the number of steps meets the
337
+ ``update_min_steps`` threshold.
338
+ """
339
+ if current_item is not None:
340
+ self.current_item = current_item
341
+
342
+ self._completed_intervals += n_steps
343
+
344
+ if self._completed_intervals >= self.update_min_steps:
345
+ self.make_step(self._completed_intervals)
346
+ self.render_progress()
347
+ self._completed_intervals = 0
348
+
349
+ def finish(self) -> None:
350
+ self.eta_known = False
351
+ self.current_item = None
352
+ self.finished = True
353
+
354
+ def generator(self) -> cabc.Iterator[V]:
355
+ """Return a generator which yields the items added to the bar
356
+ during construction, and updates the progress bar *after* the
357
+ yielded block returns.
358
+ """
359
+ # WARNING: the iterator interface for `ProgressBar` relies on
360
+ # this and only works because this is a simple generator which
361
+ # doesn't create or manage additional state. If this function
362
+ # changes, the impact should be evaluated both against
363
+ # `iter(bar)` and `next(bar)`. `next()` in particular may call
364
+ # `self.generator()` repeatedly, and this must remain safe in
365
+ # order for that interface to work.
366
+ if not self.entered:
367
+ raise RuntimeError("You need to use progress bars in a with block.")
368
+
369
+ if not self._is_atty:
370
+ yield from self.iter
371
+ else:
372
+ for rv in self.iter:
373
+ self.current_item = rv
374
+
375
+ # This allows show_item_func to be updated before the
376
+ # item is processed. Only trigger at the beginning of
377
+ # the update interval.
378
+ if self._completed_intervals == 0:
379
+ self.render_progress()
380
+
381
+ yield rv
382
+ self.update(1)
383
+
384
+ self.finish()
385
+ self.render_progress()
386
+
387
+
388
+ class MaybeStripAnsi(io.TextIOWrapper):
389
+ def __init__(self, stream: t.IO[bytes], *, color: bool, **kwargs: t.Any):
390
+ super().__init__(stream, **kwargs)
391
+ self.color = color
392
+
393
+ def write(self, text: str) -> int:
394
+ if not self.color:
395
+ text = strip_ansi(text)
396
+ return super().write(text)
397
+
398
+
399
+ def _pager_contextmanager(
400
+ color: bool | None = None,
401
+ ) -> t.ContextManager[tuple[t.BinaryIO | t.TextIO, str, bool]]:
402
+ """Decide what method to use for paging through text."""
403
+ stdout = _default_text_stdout()
404
+
405
+ # There are no standard streams attached to write to. For example,
406
+ # pythonw on Windows.
407
+ if stdout is None:
408
+ stdout = StringIO()
409
+
410
+ if not isatty(sys.stdin) or not isatty(stdout):
411
+ return _nullpager(stdout, color)
412
+
413
+ # Split using POSIX mode (the default) so that quote characters are
414
+ # stripped from tokens and quoted Windows paths are preserved.
415
+ # Non-POSIX mode retains quotes in tokens, and wrapping tokens
416
+ # with shlex.quote re-introduces quoting issues on Windows.
417
+ pager_cmd_parts = shlex.split(os.environ.get("PAGER", ""))
418
+ if pager_cmd_parts:
419
+ if WIN:
420
+ return _tempfilepager(pager_cmd_parts, color)
421
+ return _pipepager(pager_cmd_parts, color)
422
+
423
+ if os.environ.get("TERM") in ("dumb", "emacs"):
424
+ return _nullpager(stdout, color)
425
+ if WIN or sys.platform.startswith("os2"):
426
+ return _tempfilepager(["more"], color)
427
+ return _pipepager(["less"], color)
428
+
429
+
430
+ @contextlib.contextmanager
431
+ def get_pager_file(color: bool | None = None) -> t.Generator[t.TextIO, None, None]:
432
+ """Context manager.
433
+ Yields a writable file-like object which can be used as an output pager.
434
+ .. versionadded:: 8.4
435
+ :param color: controls if the pager supports ANSI colors or not. The
436
+ default is autodetection.
437
+ """
438
+ with _pager_contextmanager(color=color) as (stream, encoding, color):
439
+ # Split streams by capabilities rather than the abstract TextIO /
440
+ # BinaryIO annotations: buffered text streams can be unwrapped to bytes,
441
+ # while text-only streams are yielded as-is.
442
+ if _has_binary_buffer(stream):
443
+ # Text stream backed by a binary buffer.
444
+ stream = MaybeStripAnsi(stream.buffer, color=color, encoding=encoding)
445
+ elif isinstance(stream, t.BinaryIO):
446
+ # Binary stream
447
+ stream = MaybeStripAnsi(stream, color=color, encoding=encoding)
448
+ try:
449
+ yield stream
450
+ finally:
451
+ stream.flush()
452
+
453
+
454
+ @contextlib.contextmanager
455
+ def _pipepager(
456
+ cmd_parts: list[str], color: bool | None = None
457
+ ) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:
458
+ """Page through text by feeding it to another program.
459
+
460
+ Invokes the pager via :class:`subprocess.Popen` with an ``argv`` list
461
+ produced by :func:`shlex.split`. The command is resolved to an absolute
462
+ path with :func:`shutil.which` as recommended by the
463
+ :mod:`subprocess` docs for Windows compatibility.
464
+
465
+ Invoking a pager through this might support colors: if piping to
466
+ ``less`` and the user hasn't decided on colors, ``LESS=-R`` is set
467
+ automatically.
468
+ """
469
+ # Split the command into the invoked CLI and its parameters.
470
+ if not cmd_parts:
471
+ stdout = _default_text_stdout() or StringIO()
472
+ yield stdout, "utf-8", False
473
+ return
474
+
475
+ import shutil
476
+
477
+ cmd = cmd_parts[0]
478
+ cmd_params = cmd_parts[1:]
479
+
480
+ cmd_filepath = shutil.which(cmd)
481
+ if not cmd_filepath:
482
+ stdout = _default_text_stdout() or StringIO()
483
+ yield stdout, "utf-8", False
484
+ return
485
+
486
+ # Produces a normalized absolute path string.
487
+ # multi-call binaries such as busybox derive their identity from the symlink
488
+ # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)
489
+ cmd_path = Path(cmd_filepath).absolute()
490
+ cmd_name = cmd_path.name
491
+
492
+ import subprocess
493
+
494
+ # Make a local copy of the environment to not affect the global one.
495
+ env = dict(os.environ)
496
+
497
+ # If we're piping to less and the user hasn't decided on colors, we enable
498
+ # them by default we find the -R flag in the command line arguments.
499
+ if color is None and cmd_name == "less":
500
+ less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_params)}"
501
+ if not less_flags:
502
+ env["LESS"] = "-R"
503
+ color = True
504
+ elif "r" in less_flags or "R" in less_flags:
505
+ color = True
506
+
507
+ if color is None:
508
+ color = False
509
+
510
+ c = subprocess.Popen(
511
+ [str(cmd_path)] + cmd_params,
512
+ shell=False,
513
+ stdin=subprocess.PIPE,
514
+ env=env,
515
+ errors="replace",
516
+ text=True,
517
+ )
518
+ stdin = t.cast(t.BinaryIO, c.stdin)
519
+ encoding = get_best_encoding(stdin)
520
+ try:
521
+ yield stdin, encoding, color
522
+ except BrokenPipeError:
523
+ # In case the pager exited unexpectedly, ignore the broken pipe error.
524
+ pass
525
+ except Exception as e:
526
+ # In case there is an exception we want to close the pager immediately
527
+ # and let the caller handle it.
528
+ # Otherwise the pager will keep running, and the user may not notice
529
+ # the error message, or worse yet it may leave the terminal in a broken state.
530
+ c.terminate()
531
+ raise e
532
+ finally:
533
+ # We must close stdin and wait for the pager to exit before we continue
534
+ try:
535
+ stdin.close()
536
+ # Close implies flush, so it might throw a BrokenPipeError if the pager
537
+ # process exited already.
538
+ except BrokenPipeError:
539
+ pass
540
+
541
+ # Less doesn't respect ^C, but catches it for its own UI purposes (aborting
542
+ # search or other commands inside less).
543
+ #
544
+ # That means when the user hits ^C, the parent process (click) terminates,
545
+ # but less is still alive, paging the output and messing up the terminal.
546
+ #
547
+ # If the user wants to make the pager exit on ^C, they should set
548
+ # `LESS='-K'`. It's not our decision to make.
549
+ while True:
550
+ try:
551
+ c.wait()
552
+ except KeyboardInterrupt:
553
+ pass
554
+ else:
555
+ break
556
+
557
+
558
+ @contextlib.contextmanager
559
+ def _tempfilepager(
560
+ cmd_parts: list[str], color: bool | None = None
561
+ ) -> t.Iterator[tuple[t.BinaryIO | t.TextIO, str, bool]]:
562
+ """Page through text by invoking a program on a temporary file.
563
+
564
+ Used as the primary pager strategy on Windows (where piping to
565
+ ``more`` adds spurious ``\\r\\n``), and as a fallback on other
566
+ platforms. The command is resolved to an absolute path with
567
+ :func:`shutil.which`.
568
+ """
569
+ # Split the command into the invoked CLI and its parameters.
570
+ if not cmd_parts:
571
+ stdout = _default_text_stdout() or StringIO()
572
+ yield stdout, "utf-8", False
573
+ return
574
+
575
+ import shutil
576
+ import subprocess
577
+
578
+ cmd = cmd_parts[0]
579
+
580
+ cmd_filepath = shutil.which(cmd)
581
+ if not cmd_filepath:
582
+ stdout = _default_text_stdout() or StringIO()
583
+ yield stdout, "utf-8", False
584
+ return
585
+
586
+ # Produces a normalized absolute path string.
587
+ # multi-call binaries such as busybox derive their identity from the symlink
588
+ # less -> busybox. resolve() causes them to misbehave. (eg. less becomes busybox)
589
+ cmd_path = Path(cmd_filepath).absolute()
590
+
591
+ import tempfile
592
+
593
+ encoding = get_best_encoding(sys.stdout)
594
+ if color is None:
595
+ color = False
596
+ # On Windows, NamedTemporaryFile cannot be opened by another process
597
+ # while Python still has it open, so we use delete=False and clean up manually
598
+ # rather than using a contextmanager here.
599
+ f = tempfile.NamedTemporaryFile(mode="wb", delete=False)
600
+ try:
601
+ yield t.cast(t.BinaryIO, f), encoding, color
602
+ f.flush()
603
+ f.close()
604
+ subprocess.call([str(cmd_path), f.name])
605
+ finally:
606
+ os.unlink(f.name)
607
+
608
+
609
+ class _SkipClose:
610
+ def __init__(self, stream: t.IO[t.Any]) -> None:
611
+ self.stream = stream
612
+
613
+ def __getattr__(self, name: str) -> t.Any:
614
+ return getattr(self.stream, name)
615
+
616
+ @property
617
+ def buffer(self) -> t.BinaryIO:
618
+ return _SkipClose(self.stream.buffer) # type: ignore[attr-defined, return-value]
619
+
620
+ def close(self) -> None:
621
+ pass
622
+
623
+
624
+ @contextlib.contextmanager
625
+ def _nullpager(
626
+ stream: t.TextIO, color: bool | None = None
627
+ ) -> t.Iterator[tuple[t.TextIO, str, bool]]:
628
+ """Simply print unformatted text. This is the ultimate fallback. Don't close the
629
+ output stream in this case, since it's coming from elsewhere rather than our
630
+ internal helpers.
631
+ """
632
+ encoding = get_best_encoding(stream)
633
+
634
+ if color is None:
635
+ color = False
636
+
637
+ yield _SkipClose(stream), encoding, color # type: ignore[misc]
638
+
639
+
640
+ class Editor:
641
+ def __init__(
642
+ self,
643
+ editor: str | None = None,
644
+ env: cabc.Mapping[str, str] | None = None,
645
+ require_save: bool = True,
646
+ extension: str = ".txt",
647
+ ) -> None:
648
+ self.editor = editor
649
+ self.env = env
650
+ self.require_save = require_save
651
+ self.extension = extension
652
+
653
+ def get_editor(self) -> str:
654
+ if self.editor is not None:
655
+ return self.editor
656
+ for key in "VISUAL", "EDITOR":
657
+ rv = os.environ.get(key)
658
+ if rv:
659
+ return rv
660
+ if WIN:
661
+ return "notepad"
662
+
663
+ from shutil import which
664
+
665
+ for editor in "sensible-editor", "vim", "nano":
666
+ if which(editor) is not None:
667
+ return editor
668
+ return "vi"
669
+
670
+ def edit_files(self, filenames: cabc.Iterable[str]) -> None:
671
+ """Open files in the user's editor."""
672
+ import shlex
673
+ import subprocess
674
+
675
+ editor = self.get_editor()
676
+ environ: dict[str, str] | None = None
677
+
678
+ if self.env:
679
+ environ = os.environ.copy()
680
+ environ.update(self.env)
681
+
682
+ try:
683
+ # Split in POSIX mode (the default) for the same reasons as
684
+ # in pager(): strips quotes from tokens and preserves quoted
685
+ # Windows paths.
686
+ c = subprocess.Popen(
687
+ args=shlex.split(editor) + list(filenames),
688
+ env=environ,
689
+ )
690
+ exit_code = c.wait()
691
+ if exit_code != 0:
692
+ raise ClickException(
693
+ _("{editor}: Editing failed").format(editor=editor)
694
+ )
695
+ except OSError as e:
696
+ raise ClickException(
697
+ _("{editor}: Editing failed: {e}").format(editor=editor, e=e)
698
+ ) from e
699
+
700
+ @t.overload
701
+ def edit(self, text: bytes | bytearray) -> bytes | None: ...
702
+
703
+ # We cannot know whether or not the type expected is str or bytes when None
704
+ # is passed, so str is returned as that was what was done before.
705
+ @t.overload
706
+ def edit(self, text: str | None) -> str | None: ...
707
+
708
+ def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None:
709
+ import tempfile
710
+
711
+ if text is None:
712
+ data: bytes | bytearray = b""
713
+ elif isinstance(text, (bytes, bytearray)):
714
+ data = text
715
+ else:
716
+ if text and not text.endswith("\n"):
717
+ text += "\n"
718
+
719
+ if WIN:
720
+ data = text.replace("\n", "\r\n").encode("utf-8-sig")
721
+ else:
722
+ data = text.encode("utf-8")
723
+
724
+ fd, name = tempfile.mkstemp(prefix="editor-", suffix=self.extension)
725
+ f: t.BinaryIO
726
+
727
+ try:
728
+ with os.fdopen(fd, "wb") as f:
729
+ f.write(data)
730
+
731
+ # If the filesystem resolution is 1 second, like Mac OS
732
+ # 10.12 Extended, or 2 seconds, like FAT32, and the editor
733
+ # closes very fast, require_save can fail. Set the modified
734
+ # time to be 2 seconds in the past to work around this.
735
+ os.utime(name, (os.path.getatime(name), os.path.getmtime(name) - 2))
736
+ # Depending on the resolution, the exact value might not be
737
+ # recorded, so get the new recorded value.
738
+ timestamp = os.path.getmtime(name)
739
+
740
+ self.edit_files((name,))
741
+
742
+ if self.require_save and os.path.getmtime(name) == timestamp:
743
+ return None
744
+
745
+ with open(name, "rb") as f:
746
+ rv = f.read()
747
+
748
+ if isinstance(text, (bytes, bytearray)):
749
+ return rv
750
+
751
+ return rv.decode("utf-8-sig").replace("\r\n", "\n")
752
+ finally:
753
+ os.unlink(name)
754
+
755
+
756
+ def open_url(url: str, wait: bool = False, locate: bool = False) -> int:
757
+ import subprocess
758
+
759
+ def _unquote_file(url: str) -> str:
760
+ from urllib.parse import unquote
761
+
762
+ if url.startswith("file://"):
763
+ url = unquote(url[7:])
764
+
765
+ return url
766
+
767
+ if sys.platform == "darwin":
768
+ args = ["open"]
769
+ if wait:
770
+ args.append("-W")
771
+ if locate:
772
+ args.append("-R")
773
+ args.append(_unquote_file(url))
774
+ null = open("/dev/null", "w")
775
+ try:
776
+ return subprocess.Popen(args, stderr=null).wait()
777
+ finally:
778
+ null.close()
779
+ elif WIN:
780
+ if locate:
781
+ url = _unquote_file(url)
782
+ args = ["explorer", "/select,", url]
783
+ try:
784
+ return subprocess.call(args)
785
+ except OSError:
786
+ return 127
787
+ else:
788
+ try:
789
+ os.startfile(url) # type: ignore[attr-defined]
790
+ except OSError:
791
+ return 127
792
+ return 0
793
+ elif CYGWIN:
794
+ if locate:
795
+ url = _unquote_file(url)
796
+ args = ["cygstart", os.path.dirname(url)]
797
+ else:
798
+ args = ["cygstart"]
799
+ if wait:
800
+ args.append("-w")
801
+ args.append(url)
802
+ try:
803
+ return subprocess.call(args)
804
+ except OSError:
805
+ # Command not found
806
+ return 127
807
+
808
+ try:
809
+ if locate:
810
+ url = os.path.dirname(_unquote_file(url)) or "."
811
+ else:
812
+ url = _unquote_file(url)
813
+ c = subprocess.Popen(["xdg-open", url])
814
+ if wait:
815
+ return c.wait()
816
+ return 0
817
+ except OSError:
818
+ if url.startswith(("http://", "https://")) and not locate and not wait:
819
+ import webbrowser
820
+
821
+ webbrowser.open(url)
822
+ return 0
823
+ return 1
824
+
825
+
826
+ def _translate_ch_to_exc(ch: str) -> None:
827
+ if ch == "\x03":
828
+ raise KeyboardInterrupt()
829
+
830
+ if ch == "\x04" and not WIN: # Unix-like, Ctrl+D
831
+ raise EOFError()
832
+
833
+ if ch == "\x1a" and WIN: # Windows, Ctrl+Z
834
+ raise EOFError()
835
+
836
+
837
+ if sys.platform == "win32":
838
+ import msvcrt
839
+
840
+ @contextlib.contextmanager
841
+ def raw_terminal() -> cabc.Iterator[int]:
842
+ yield -1
843
+
844
+ def getchar(echo: bool) -> str:
845
+ # The function `getch` will return a bytes object corresponding to
846
+ # the pressed character. Since Windows 10 build 1803, it will also
847
+ # return \x00 when called a second time after pressing a regular key.
848
+ #
849
+ # `getwch` does not share this probably-bugged behavior. Moreover, it
850
+ # returns a Unicode object by default, which is what we want.
851
+ #
852
+ # Either of these functions will return \x00 or \xe0 to indicate
853
+ # a special key, and you need to call the same function again to get
854
+ # the "rest" of the code. The fun part is that \u00e0 is
855
+ # "latin small letter a with grave", so if you type that on a French
856
+ # keyboard, you _also_ get a \xe0.
857
+ # E.g., consider the Up arrow. This returns \xe0 and then \x48. The
858
+ # resulting Unicode string reads as "a with grave" + "capital H".
859
+ # This is indistinguishable from when the user actually types
860
+ # "a with grave" and then "capital H".
861
+ #
862
+ # When \xe0 is returned, we assume it's part of a special-key sequence
863
+ # and call `getwch` again, but that means that when the user types
864
+ # the \u00e0 character, `getchar` doesn't return until a second
865
+ # character is typed.
866
+ # The alternative is returning immediately, but that would mess up
867
+ # cross-platform handling of arrow keys and others that start with
868
+ # \xe0. Another option is using `getch`, but then we can't reliably
869
+ # read non-ASCII characters, because return values of `getch` are
870
+ # limited to the current 8-bit codepage.
871
+ #
872
+ # Anyway, Click doesn't claim to do this Right(tm), and using `getwch`
873
+ # is doing the right thing in more situations than with `getch`.
874
+
875
+ if echo:
876
+ func = t.cast(t.Callable[[], str], msvcrt.getwche)
877
+ else:
878
+ func = t.cast(t.Callable[[], str], msvcrt.getwch)
879
+
880
+ rv = func()
881
+
882
+ if rv in ("\x00", "\xe0"):
883
+ # \x00 and \xe0 are control characters that indicate special key,
884
+ # see above.
885
+ rv += func()
886
+
887
+ _translate_ch_to_exc(rv)
888
+ return rv
889
+
890
+ else:
891
+ import termios
892
+ import tty
893
+
894
+ @contextlib.contextmanager
895
+ def raw_terminal() -> cabc.Iterator[int]:
896
+ f: t.TextIO | None
897
+ fd: int
898
+
899
+ if not isatty(sys.stdin):
900
+ f = open("/dev/tty")
901
+ fd = f.fileno()
902
+ else:
903
+ fd = sys.stdin.fileno()
904
+ f = None
905
+
906
+ try:
907
+ old_settings = termios.tcgetattr(fd)
908
+
909
+ try:
910
+ tty.setraw(fd)
911
+ yield fd
912
+ finally:
913
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
914
+ sys.stdout.flush()
915
+
916
+ if f is not None:
917
+ f.close()
918
+ except termios.error:
919
+ pass
920
+
921
+ def getchar(echo: bool) -> str:
922
+ with raw_terminal() as fd:
923
+ ch = os.read(fd, 32).decode(get_best_encoding(sys.stdin), "replace")
924
+
925
+ if echo and isatty(sys.stdout):
926
+ sys.stdout.write(ch)
927
+
928
+ _translate_ch_to_exc(ch)
929
+ return ch
.venv/lib/python3.11/site-packages/click/_textwrap.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import textwrap
5
+ from contextlib import contextmanager
6
+
7
+ from ._compat import _ansi_re
8
+ from ._compat import term_len
9
+
10
+
11
+ def _truncate_visible(text: str, n: int) -> str:
12
+ """Return the longest prefix of ``text`` containing at most ``n`` visible
13
+ characters.
14
+
15
+ ANSI escape sequences inside the prefix are kept intact and do not count
16
+ toward the visible width. A cut is never placed inside an escape sequence.
17
+ """
18
+ if n <= 0:
19
+ return ""
20
+
21
+ visible = 0
22
+ i = 0
23
+ cut = 0
24
+ end = len(text)
25
+ while i < end:
26
+ m = _ansi_re.match(text, i)
27
+ if m is not None:
28
+ i = m.end()
29
+ continue
30
+ visible += 1
31
+ i += 1
32
+ cut = i
33
+ if visible >= n:
34
+ break
35
+ return text[:cut]
36
+
37
+
38
+ class TextWrapper(textwrap.TextWrapper):
39
+ """``textwrap.TextWrapper`` variant that measures widths by visible
40
+ character count.
41
+
42
+ ANSI escape sequences embedded in chunks, indents, or the placeholder are
43
+ excluded from the width budget. Without this, styled help text (a styled
44
+ ``Usage:`` prefix, a colorized option name, ...) would be wrapped earlier
45
+ than its visible length warrants and tokens would split mid-word.
46
+ """
47
+
48
+ def _handle_long_word(
49
+ self,
50
+ reversed_chunks: list[str],
51
+ cur_line: list[str],
52
+ cur_len: int,
53
+ width: int,
54
+ ) -> None:
55
+ space_left = max(width - cur_len, 1)
56
+
57
+ if self.break_long_words:
58
+ last = reversed_chunks[-1]
59
+ cut = _truncate_visible(last, space_left)
60
+ res = last[len(cut) :]
61
+ cur_line.append(cut)
62
+ reversed_chunks[-1] = res
63
+ elif not cur_line:
64
+ cur_line.append(reversed_chunks.pop())
65
+
66
+ def _wrap_chunks(self, chunks: list[str]) -> list[str]:
67
+ """Wrap chunks counting widths in visible characters.
68
+
69
+ Mirrors the algorithm of :meth:`textwrap.TextWrapper._wrap_chunks`
70
+ with every width measurement routed through
71
+ :func:`click._compat.term_len` instead of :func:`len`, so ANSI escape
72
+ bytes in chunks, indents, or the placeholder do not inflate the count.
73
+
74
+ .. seealso::
75
+ :class:`textwrap.TextWrapper` in the Python standard library documentation:
76
+ https://docs.python.org/3/library/textwrap.html#textwrap.TextWrapper
77
+
78
+ Reference implementation in CPython:
79
+ https://github.com/python/cpython/blob/main/Lib/textwrap.py
80
+ """
81
+ lines: list[str] = []
82
+ if self.width <= 0:
83
+ raise ValueError(f"invalid width {self.width!r} (must be > 0)")
84
+ if self.max_lines is not None:
85
+ if self.max_lines > 1:
86
+ indent = self.subsequent_indent
87
+ else:
88
+ indent = self.initial_indent
89
+ if term_len(indent) + term_len(self.placeholder.lstrip()) > self.width:
90
+ raise ValueError("placeholder too large for max width")
91
+
92
+ chunks.reverse()
93
+
94
+ while chunks:
95
+ cur_line: list[str] = []
96
+ cur_len = 0
97
+
98
+ if lines:
99
+ indent = self.subsequent_indent
100
+ else:
101
+ indent = self.initial_indent
102
+
103
+ width = self.width - term_len(indent)
104
+
105
+ if self.drop_whitespace and chunks[-1].strip() == "" and lines:
106
+ del chunks[-1]
107
+
108
+ while chunks:
109
+ n = term_len(chunks[-1])
110
+
111
+ if cur_len + n <= width:
112
+ cur_line.append(chunks.pop())
113
+ cur_len += n
114
+
115
+ else:
116
+ break
117
+
118
+ if chunks and term_len(chunks[-1]) > width:
119
+ self._handle_long_word(chunks, cur_line, cur_len, width)
120
+ cur_len = sum(map(term_len, cur_line))
121
+
122
+ if self.drop_whitespace and cur_line and cur_line[-1].strip() == "":
123
+ cur_len -= term_len(cur_line[-1])
124
+ del cur_line[-1]
125
+
126
+ if cur_line:
127
+ if (
128
+ self.max_lines is None
129
+ or len(lines) + 1 < self.max_lines
130
+ or (
131
+ not chunks
132
+ or self.drop_whitespace
133
+ and len(chunks) == 1
134
+ and not chunks[0].strip()
135
+ )
136
+ and cur_len <= width
137
+ ):
138
+ lines.append(indent + "".join(cur_line))
139
+ else:
140
+ while cur_line:
141
+ if (
142
+ cur_line[-1].strip()
143
+ and cur_len + term_len(self.placeholder) <= width
144
+ ):
145
+ cur_line.append(self.placeholder)
146
+ lines.append(indent + "".join(cur_line))
147
+ break
148
+ cur_len -= term_len(cur_line[-1])
149
+ del cur_line[-1]
150
+ else:
151
+ if lines:
152
+ prev_line = lines[-1].rstrip()
153
+ if (
154
+ term_len(prev_line) + term_len(self.placeholder)
155
+ <= self.width
156
+ ):
157
+ lines[-1] = prev_line + self.placeholder
158
+ break
159
+ lines.append(indent + self.placeholder.lstrip())
160
+ break
161
+
162
+ return lines
163
+
164
+ @contextmanager
165
+ def extra_indent(self, indent: str) -> cabc.Iterator[None]:
166
+ old_initial_indent = self.initial_indent
167
+ old_subsequent_indent = self.subsequent_indent
168
+ self.initial_indent += indent
169
+ self.subsequent_indent += indent
170
+
171
+ try:
172
+ yield
173
+ finally:
174
+ self.initial_indent = old_initial_indent
175
+ self.subsequent_indent = old_subsequent_indent
176
+
177
+ def indent_only(self, text: str) -> str:
178
+ rv = []
179
+
180
+ for idx, line in enumerate(text.splitlines()):
181
+ indent = self.initial_indent
182
+
183
+ if idx > 0:
184
+ indent = self.subsequent_indent
185
+
186
+ rv.append(f"{indent}{line}")
187
+
188
+ return "\n".join(rv)
.venv/lib/python3.11/site-packages/click/_utils.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import enum
4
+ import typing as t
5
+
6
+
7
+ class Sentinel(enum.Enum):
8
+ """Enum used to define sentinel values.
9
+
10
+ .. seealso::
11
+
12
+ `PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_.
13
+ """
14
+
15
+ UNSET = object()
16
+ FLAG_NEEDS_VALUE = object()
17
+
18
+ def __repr__(self) -> str:
19
+ return f"{self.__class__.__name__}.{self.name}"
20
+
21
+
22
+ UNSET: t.Literal[Sentinel.UNSET] = Sentinel.UNSET
23
+ """Sentinel used to indicate that a value is not set."""
24
+
25
+ FLAG_NEEDS_VALUE: t.Literal[Sentinel.FLAG_NEEDS_VALUE] = Sentinel.FLAG_NEEDS_VALUE
26
+ """Sentinel used to indicate an option was passed as a flag without a
27
+ value but is not a flag option.
28
+
29
+ ``Option.consume_value`` uses this to prompt or use the ``flag_value``.
30
+ """
31
+
32
+ T_UNSET: t.TypeAlias = t.Literal[Sentinel.UNSET]
33
+ """Type hint for the :data:`UNSET` sentinel value."""
34
+
35
+ T_FLAG_NEEDS_VALUE: t.TypeAlias = t.Literal[Sentinel.FLAG_NEEDS_VALUE]
36
+ """Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""
.venv/lib/python3.11/site-packages/click/_winconsole.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module is based on the excellent work by Adam Bartoš who
2
+ # provided a lot of what went into the implementation here in
3
+ # the discussion to issue1602 in the Python bug tracker.
4
+ #
5
+ # There are some general differences in regards to how this works
6
+ # compared to the original patches as we do not need to patch
7
+ # the entire interpreter but just work in our little world of
8
+ # echo and prompt.
9
+ from __future__ import annotations
10
+
11
+ import collections.abc as cabc
12
+ import io
13
+ import sys
14
+ import time
15
+ import typing as t
16
+ from ctypes import Array
17
+ from ctypes import byref
18
+ from ctypes import c_char
19
+ from ctypes import c_char_p
20
+ from ctypes import c_int
21
+ from ctypes import c_ssize_t
22
+ from ctypes import c_ulong
23
+ from ctypes import c_void_p
24
+ from ctypes import POINTER
25
+ from ctypes import py_object
26
+ from ctypes import Structure
27
+ from ctypes.wintypes import DWORD
28
+ from ctypes.wintypes import HANDLE
29
+ from ctypes.wintypes import LPCWSTR
30
+ from ctypes.wintypes import LPWSTR
31
+ from gettext import gettext as _
32
+
33
+ from ._compat import _NonClosingTextIOWrapper
34
+
35
+ assert sys.platform == "win32"
36
+ import msvcrt # noqa: E402
37
+ from ctypes import windll # noqa: E402
38
+ from ctypes import WINFUNCTYPE # noqa: E402
39
+
40
+ c_ssize_p = POINTER(c_ssize_t)
41
+
42
+ kernel32 = windll.kernel32
43
+ GetStdHandle = kernel32.GetStdHandle
44
+ ReadConsoleW = kernel32.ReadConsoleW
45
+ WriteConsoleW = kernel32.WriteConsoleW
46
+ GetConsoleMode = kernel32.GetConsoleMode
47
+ GetLastError = kernel32.GetLastError
48
+ GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
49
+ CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
50
+ ("CommandLineToArgvW", windll.shell32)
51
+ )
52
+ LocalFree = WINFUNCTYPE(c_void_p, c_void_p)(("LocalFree", windll.kernel32))
53
+
54
+ STDIN_HANDLE = GetStdHandle(-10)
55
+ STDOUT_HANDLE = GetStdHandle(-11)
56
+ STDERR_HANDLE = GetStdHandle(-12)
57
+
58
+ PyBUF_SIMPLE = 0
59
+ PyBUF_WRITABLE = 1
60
+
61
+ ERROR_SUCCESS = 0
62
+ ERROR_NOT_ENOUGH_MEMORY = 8
63
+ ERROR_OPERATION_ABORTED = 995
64
+
65
+ STDIN_FILENO = 0
66
+ STDOUT_FILENO = 1
67
+ STDERR_FILENO = 2
68
+
69
+ EOF = b"\x1a"
70
+ MAX_BYTES_WRITTEN = 32767
71
+
72
+ if t.TYPE_CHECKING:
73
+ try:
74
+ # Using `typing_extensions.Buffer` instead of `collections.abc`
75
+ # on Windows for some reason does not have `Sized` implemented.
76
+ from collections.abc import Buffer # type: ignore
77
+ except ImportError:
78
+ from typing_extensions import Buffer
79
+
80
+ try:
81
+ from ctypes import pythonapi
82
+ except ImportError:
83
+ # On PyPy we cannot get buffers so our ability to operate here is
84
+ # severely limited.
85
+ get_buffer = None
86
+ else:
87
+
88
+ class Py_buffer(Structure):
89
+ _fields_ = [ # noqa: RUF012
90
+ ("buf", c_void_p),
91
+ ("obj", py_object),
92
+ ("len", c_ssize_t),
93
+ ("itemsize", c_ssize_t),
94
+ ("readonly", c_int),
95
+ ("ndim", c_int),
96
+ ("format", c_char_p),
97
+ ("shape", c_ssize_p),
98
+ ("strides", c_ssize_p),
99
+ ("suboffsets", c_ssize_p),
100
+ ("internal", c_void_p),
101
+ ]
102
+
103
+ PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
104
+ PyBuffer_Release = pythonapi.PyBuffer_Release
105
+
106
+ def get_buffer(obj: Buffer, writable: bool = False) -> Array[c_char]:
107
+ buf = Py_buffer()
108
+ flags: int = PyBUF_WRITABLE if writable else PyBUF_SIMPLE
109
+ PyObject_GetBuffer(py_object(obj), byref(buf), flags)
110
+
111
+ try:
112
+ buffer_type = c_char * buf.len
113
+ out: Array[c_char] = buffer_type.from_address(buf.buf)
114
+ return out
115
+ finally:
116
+ PyBuffer_Release(byref(buf))
117
+
118
+
119
+ class _WindowsConsoleRawIOBase(io.RawIOBase):
120
+ def __init__(self, handle: int | None) -> None:
121
+ self.handle = handle
122
+
123
+ def isatty(self) -> t.Literal[True]:
124
+ super().isatty()
125
+ return True
126
+
127
+
128
+ class _WindowsConsoleReader(_WindowsConsoleRawIOBase):
129
+ def readable(self) -> t.Literal[True]:
130
+ return True
131
+
132
+ def readinto(self, b: Buffer) -> int:
133
+ bytes_to_be_read = len(b)
134
+ if not bytes_to_be_read:
135
+ return 0
136
+ elif bytes_to_be_read % 2:
137
+ raise ValueError(
138
+ "cannot read odd number of bytes from UTF-16-LE encoded console"
139
+ )
140
+
141
+ buffer = get_buffer(b, writable=True)
142
+ code_units_to_be_read = bytes_to_be_read // 2
143
+ code_units_read = c_ulong()
144
+
145
+ rv = ReadConsoleW(
146
+ HANDLE(self.handle),
147
+ buffer,
148
+ code_units_to_be_read,
149
+ byref(code_units_read),
150
+ None,
151
+ )
152
+ if GetLastError() == ERROR_OPERATION_ABORTED:
153
+ # wait for KeyboardInterrupt
154
+ time.sleep(0.1)
155
+ if not rv:
156
+ raise OSError(_("Windows error: {error}").format(error=GetLastError()))
157
+
158
+ if buffer[0] == EOF:
159
+ return 0
160
+ return 2 * code_units_read.value
161
+
162
+
163
+ class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):
164
+ def writable(self) -> t.Literal[True]:
165
+ return True
166
+
167
+ @staticmethod
168
+ def _get_error_message(errno: int) -> str:
169
+ if errno == ERROR_SUCCESS:
170
+ return "ERROR_SUCCESS"
171
+ elif errno == ERROR_NOT_ENOUGH_MEMORY:
172
+ return "ERROR_NOT_ENOUGH_MEMORY"
173
+ return _("Windows error: {error}").format(error=errno)
174
+
175
+ def write(self, b: Buffer) -> int:
176
+ bytes_to_be_written = len(b)
177
+ buf = get_buffer(b)
178
+ code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2
179
+ code_units_written = c_ulong()
180
+
181
+ WriteConsoleW(
182
+ HANDLE(self.handle),
183
+ buf,
184
+ code_units_to_be_written,
185
+ byref(code_units_written),
186
+ None,
187
+ )
188
+ bytes_written = 2 * code_units_written.value
189
+
190
+ if bytes_written == 0 and bytes_to_be_written > 0:
191
+ raise OSError(self._get_error_message(GetLastError()))
192
+ return bytes_written
193
+
194
+
195
+ class ConsoleStream:
196
+ def __init__(self, text_stream: t.TextIO, byte_stream: t.BinaryIO) -> None:
197
+ self._text_stream = text_stream
198
+ self.buffer = byte_stream
199
+
200
+ @property
201
+ def name(self) -> str:
202
+ return self.buffer.name
203
+
204
+ def write(self, x: t.AnyStr) -> int:
205
+ if isinstance(x, str):
206
+ return self._text_stream.write(x)
207
+ try:
208
+ self.flush()
209
+ except Exception:
210
+ pass
211
+ return self.buffer.write(x)
212
+
213
+ def writelines(self, lines: cabc.Iterable[t.AnyStr]) -> None:
214
+ for line in lines:
215
+ self.write(line)
216
+
217
+ def __getattr__(self, name: str) -> t.Any:
218
+ return getattr(self._text_stream, name)
219
+
220
+ def isatty(self) -> bool:
221
+ return self.buffer.isatty()
222
+
223
+ def __repr__(self) -> str:
224
+ return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"
225
+
226
+
227
+ def _get_text_stdin(buffer_stream: t.BinaryIO) -> t.TextIO:
228
+ text_stream = _NonClosingTextIOWrapper(
229
+ io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
230
+ "utf-16-le",
231
+ "strict",
232
+ line_buffering=True,
233
+ )
234
+ return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
235
+
236
+
237
+ def _get_text_stdout(buffer_stream: t.BinaryIO) -> t.TextIO:
238
+ text_stream = _NonClosingTextIOWrapper(
239
+ io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
240
+ "utf-16-le",
241
+ "strict",
242
+ line_buffering=True,
243
+ )
244
+ return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
245
+
246
+
247
+ def _get_text_stderr(buffer_stream: t.BinaryIO) -> t.TextIO:
248
+ text_stream = _NonClosingTextIOWrapper(
249
+ io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
250
+ "utf-16-le",
251
+ "strict",
252
+ line_buffering=True,
253
+ )
254
+ return t.cast(t.TextIO, ConsoleStream(text_stream, buffer_stream))
255
+
256
+
257
+ _stream_factories: cabc.Mapping[int, t.Callable[[t.BinaryIO], t.TextIO]] = {
258
+ 0: _get_text_stdin,
259
+ 1: _get_text_stdout,
260
+ 2: _get_text_stderr,
261
+ }
262
+
263
+
264
+ def _is_console(f: t.TextIO) -> bool:
265
+ if not hasattr(f, "fileno"):
266
+ return False
267
+
268
+ try:
269
+ fileno = f.fileno()
270
+ except (OSError, io.UnsupportedOperation):
271
+ return False
272
+
273
+ handle = msvcrt.get_osfhandle(fileno)
274
+ return bool(GetConsoleMode(handle, byref(DWORD())))
275
+
276
+
277
+ def _get_windows_console_stream(
278
+ f: t.TextIO, encoding: str | None, errors: str | None
279
+ ) -> t.TextIO | None:
280
+ if (
281
+ get_buffer is None
282
+ or encoding not in {"utf-16-le", None}
283
+ or errors not in {"strict", None}
284
+ or not _is_console(f)
285
+ ):
286
+ return None
287
+
288
+ func = _stream_factories.get(f.fileno())
289
+ if func is None:
290
+ return None
291
+
292
+ b = getattr(f, "buffer", None)
293
+
294
+ if b is None:
295
+ return None
296
+
297
+ return func(b)
.venv/lib/python3.11/site-packages/click/core.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.11/site-packages/click/decorators.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import typing as t
5
+ from functools import update_wrapper
6
+ from gettext import gettext as _
7
+
8
+ from .core import Argument
9
+ from .core import Command
10
+ from .core import Context
11
+ from .core import Group
12
+ from .core import Option
13
+ from .core import Parameter
14
+ from .globals import get_current_context
15
+ from .utils import echo
16
+
17
+ if t.TYPE_CHECKING:
18
+ import typing_extensions as te
19
+
20
+ P = te.ParamSpec("P")
21
+
22
+ R = t.TypeVar("R")
23
+ T = t.TypeVar("T")
24
+ _AnyCallable = t.Callable[..., t.Any]
25
+ FC = t.TypeVar("FC", bound="_AnyCallable | Command")
26
+
27
+
28
+ def pass_context(f: t.Callable[te.Concatenate[Context, P], R]) -> t.Callable[P, R]:
29
+ """Marks a callback as wanting to receive the current context
30
+ object as first argument.
31
+ """
32
+
33
+ def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
34
+ return f(get_current_context(), *args, **kwargs)
35
+
36
+ return update_wrapper(new_func, f)
37
+
38
+
39
+ def pass_obj(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:
40
+ """Similar to :func:`pass_context`, but only pass the object on the
41
+ context onwards (:attr:`Context.obj`). This is useful if that object
42
+ represents the state of a nested system.
43
+ """
44
+
45
+ def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
46
+ return f(get_current_context().obj, *args, **kwargs)
47
+
48
+ return update_wrapper(new_func, f)
49
+
50
+
51
+ def make_pass_decorator(
52
+ object_type: type[T], ensure: bool = False
53
+ ) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]:
54
+ """Given an object type this creates a decorator that will work
55
+ similar to :func:`pass_obj` but instead of passing the object of the
56
+ current context, it will find the innermost context of type
57
+ :func:`object_type`.
58
+
59
+ This generates a decorator that works roughly like this::
60
+
61
+ from functools import update_wrapper
62
+
63
+ def decorator(f):
64
+ @pass_context
65
+ def new_func(ctx, *args, **kwargs):
66
+ obj = ctx.find_object(object_type)
67
+ return ctx.invoke(f, obj, *args, **kwargs)
68
+ return update_wrapper(new_func, f)
69
+ return decorator
70
+
71
+ :param object_type: the type of the object to pass.
72
+ :param ensure: if set to `True`, a new object will be created and
73
+ remembered on the context if it's not there yet.
74
+ """
75
+
76
+ def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:
77
+ def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
78
+ ctx = get_current_context()
79
+
80
+ obj: T | None
81
+ if ensure:
82
+ obj = ctx.ensure_object(object_type)
83
+ else:
84
+ obj = ctx.find_object(object_type)
85
+
86
+ if obj is None:
87
+ raise RuntimeError(
88
+ "Managed to invoke callback without a context"
89
+ f" object of type {object_type.__name__!r}"
90
+ " existing."
91
+ )
92
+
93
+ return ctx.invoke(f, obj, *args, **kwargs)
94
+
95
+ return update_wrapper(new_func, f)
96
+
97
+ return decorator
98
+
99
+
100
+ def pass_meta_key(
101
+ key: str, *, doc_description: str | None = None
102
+ ) -> t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]:
103
+ """Create a decorator that passes a key from
104
+ :attr:`click.Context.meta` as the first argument to the decorated
105
+ function.
106
+
107
+ :param key: Key in ``Context.meta`` to pass.
108
+ :param doc_description: Description of the object being passed,
109
+ inserted into the decorator's docstring. Defaults to "the 'key'
110
+ key from Context.meta".
111
+
112
+ .. versionadded:: 8.0
113
+ """
114
+
115
+ def decorator(f: t.Callable[te.Concatenate[T, P], R]) -> t.Callable[P, R]:
116
+ def new_func(*args: P.args, **kwargs: P.kwargs) -> R:
117
+ ctx = get_current_context()
118
+ obj = ctx.meta[key]
119
+ return ctx.invoke(f, obj, *args, **kwargs)
120
+
121
+ return update_wrapper(new_func, f)
122
+
123
+ if doc_description is None:
124
+ doc_description = f"the {key!r} key from :attr:`click.Context.meta`"
125
+
126
+ decorator.__doc__ = (
127
+ f"Decorator that passes {doc_description} as the first argument"
128
+ " to the decorated function."
129
+ )
130
+ return decorator
131
+
132
+
133
+ CmdType = t.TypeVar("CmdType", bound=Command)
134
+
135
+
136
+ # variant: no call, directly as decorator for a function.
137
+ @t.overload
138
+ def command(name: _AnyCallable) -> Command: ...
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: str | None,
146
+ cls: type[CmdType],
147
+ **attrs: t.Any,
148
+ ) -> t.Callable[[_AnyCallable], CmdType]: ...
149
+
150
+
151
+ # variant: name omitted, cls _must_ be a keyword argument, @command(cls=CommandCls, ...)
152
+ @t.overload
153
+ def command(
154
+ name: None = None,
155
+ *,
156
+ cls: type[CmdType],
157
+ **attrs: t.Any,
158
+ ) -> t.Callable[[_AnyCallable], CmdType]: ...
159
+
160
+
161
+ # variant: with optional string name, no cls argument provided.
162
+ @t.overload
163
+ def command(
164
+ name: str | None = ..., cls: None = None, **attrs: t.Any
165
+ ) -> t.Callable[[_AnyCallable], Command]: ...
166
+
167
+
168
+ def command(
169
+ name: str | _AnyCallable | None = None,
170
+ cls: type[CmdType] | None = None,
171
+ **attrs: t.Any,
172
+ ) -> Command | t.Callable[[_AnyCallable], Command | CmdType]:
173
+ r"""Creates a new :class:`Command` and uses the decorated function as
174
+ callback. This will also automatically attach all decorated
175
+ :func:`option`\s and :func:`argument`\s as parameters to the command.
176
+
177
+ The name of the command defaults to the name of the function, converted to
178
+ lowercase, with underscores ``_`` replaced by dashes ``-``, and the suffixes
179
+ ``_command``, ``_cmd``, ``_group``, and ``_grp`` are removed. For example,
180
+ ``init_data_command`` becomes ``init-data``.
181
+
182
+ All keyword arguments are forwarded to the underlying command class.
183
+ For the ``params`` argument, any decorated params are appended to
184
+ the end of the list.
185
+
186
+ Once decorated the function turns into a :class:`Command` instance
187
+ that can be invoked as a command line utility or be attached to a
188
+ command :class:`Group`.
189
+
190
+ :param name: The name of the command. Defaults to modifying the function's
191
+ name as described above.
192
+ :param cls: The command class to create. Defaults to :class:`Command`.
193
+
194
+ .. versionchanged:: 8.2
195
+ The suffixes ``_command``, ``_cmd``, ``_group``, and ``_grp`` are
196
+ removed when generating the name.
197
+
198
+ .. versionchanged:: 8.1
199
+ This decorator can be applied without parentheses.
200
+
201
+ .. versionchanged:: 8.1
202
+ The ``params`` argument can be used. Decorated params are
203
+ appended to the end of the list.
204
+ """
205
+
206
+ func: t.Callable[[_AnyCallable], t.Any] | None = None
207
+
208
+ if callable(name):
209
+ func = name
210
+ name = None
211
+ assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."
212
+ assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."
213
+
214
+ if cls is None:
215
+ cls = t.cast("type[CmdType]", Command)
216
+
217
+ def decorator(f: _AnyCallable) -> CmdType:
218
+ if isinstance(f, Command):
219
+ raise TypeError("Attempted to convert a callback into a command twice.")
220
+
221
+ attr_params = attrs.pop("params", None)
222
+ params = attr_params if attr_params is not None else []
223
+
224
+ try:
225
+ decorator_params = f.__click_params__ # type: ignore
226
+ except AttributeError:
227
+ pass
228
+ else:
229
+ del f.__click_params__ # type: ignore
230
+ params.extend(reversed(decorator_params))
231
+
232
+ if attrs.get("help") is None:
233
+ attrs["help"] = f.__doc__
234
+
235
+ if t.TYPE_CHECKING:
236
+ assert cls is not None
237
+ assert not callable(name)
238
+
239
+ if name is not None:
240
+ cmd_name = name
241
+ else:
242
+ cmd_name = f.__name__.lower().replace("_", "-")
243
+ cmd_left, sep, suffix = cmd_name.rpartition("-")
244
+
245
+ if sep and suffix in {"command", "cmd", "group", "grp"}:
246
+ cmd_name = cmd_left
247
+
248
+ cmd = cls(name=cmd_name, callback=f, params=params, **attrs)
249
+ cmd.__doc__ = f.__doc__
250
+ return cmd
251
+
252
+ if func is not None:
253
+ return decorator(func)
254
+
255
+ return decorator
256
+
257
+
258
+ GrpType = t.TypeVar("GrpType", bound=Group)
259
+
260
+
261
+ # variant: no call, directly as decorator for a function.
262
+ @t.overload
263
+ def group(name: _AnyCallable) -> Group: ...
264
+
265
+
266
+ # variant: with positional name and with positional or keyword cls argument:
267
+ # @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)
268
+ @t.overload
269
+ def group(
270
+ name: str | None,
271
+ cls: type[GrpType],
272
+ **attrs: t.Any,
273
+ ) -> t.Callable[[_AnyCallable], GrpType]: ...
274
+
275
+
276
+ # variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)
277
+ @t.overload
278
+ def group(
279
+ name: None = None,
280
+ *,
281
+ cls: type[GrpType],
282
+ **attrs: t.Any,
283
+ ) -> t.Callable[[_AnyCallable], GrpType]: ...
284
+
285
+
286
+ # variant: with optional string name, no cls argument provided.
287
+ @t.overload
288
+ def group(
289
+ name: str | None = ..., cls: None = None, **attrs: t.Any
290
+ ) -> t.Callable[[_AnyCallable], Group]: ...
291
+
292
+
293
+ def group(
294
+ name: str | _AnyCallable | None = None,
295
+ cls: type[GrpType] | None = None,
296
+ **attrs: t.Any,
297
+ ) -> Group | t.Callable[[_AnyCallable], Group | GrpType]:
298
+ """Creates a new :class:`Group` with a function as callback. This
299
+ works otherwise the same as :func:`command` just that the `cls`
300
+ parameter is set to :class:`Group`.
301
+
302
+ .. versionchanged:: 8.1
303
+ This decorator can be applied without parentheses.
304
+ """
305
+ if cls is None:
306
+ cls = t.cast("type[GrpType]", Group)
307
+
308
+ if callable(name):
309
+ return command(cls=cls, **attrs)(name)
310
+
311
+ return command(name, cls, **attrs)
312
+
313
+
314
+ def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None:
315
+ if isinstance(f, Command):
316
+ f.params.append(param)
317
+ else:
318
+ if not hasattr(f, "__click_params__"):
319
+ f.__click_params__ = [] # type: ignore
320
+
321
+ f.__click_params__.append(param) # type: ignore
322
+
323
+
324
+ def argument(
325
+ *param_decls: str, cls: type[Argument] | None = None, **attrs: t.Any
326
+ ) -> t.Callable[[FC], FC]:
327
+ """Attaches an argument to the command. All positional arguments are
328
+ passed as parameter declarations to :class:`Argument`; all keyword
329
+ arguments are forwarded unchanged (except ``cls``).
330
+ This is equivalent to creating an :class:`Argument` instance manually
331
+ and attaching it to the :attr:`Command.params` list.
332
+
333
+ For the default argument class, refer to :class:`Argument` and
334
+ :class:`Parameter` for descriptions of parameters.
335
+
336
+ :param cls: the argument class to instantiate. This defaults to
337
+ :class:`Argument`.
338
+ :param param_decls: Passed as positional arguments to the constructor of
339
+ ``cls``.
340
+ :param attrs: Passed as keyword arguments to the constructor of ``cls``.
341
+ """
342
+ if cls is None:
343
+ cls = Argument
344
+
345
+ def decorator(f: FC) -> FC:
346
+ _param_memo(f, cls(param_decls, **attrs))
347
+ return f
348
+
349
+ return decorator
350
+
351
+
352
+ def option(
353
+ *param_decls: str, cls: type[Option] | None = None, **attrs: t.Any
354
+ ) -> t.Callable[[FC], FC]:
355
+ """Attaches an option to the command. All positional arguments are
356
+ passed as parameter declarations to :class:`Option`; all keyword
357
+ arguments are forwarded unchanged (except ``cls``).
358
+ This is equivalent to creating an :class:`Option` instance manually
359
+ and attaching it to the :attr:`Command.params` list.
360
+
361
+ For the default option class, refer to :class:`Option` and
362
+ :class:`Parameter` for descriptions of parameters.
363
+
364
+ :param cls: the option class to instantiate. This defaults to
365
+ :class:`Option`.
366
+ :param param_decls: Passed as positional arguments to the constructor of
367
+ ``cls``.
368
+ :param attrs: Passed as keyword arguments to the constructor of ``cls``.
369
+ """
370
+ if cls is None:
371
+ cls = Option
372
+
373
+ def decorator(f: FC) -> FC:
374
+ _param_memo(f, cls(param_decls, **attrs))
375
+ return f
376
+
377
+ return decorator
378
+
379
+
380
+ def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
381
+ """Add a ``--yes`` option which shows a prompt before continuing if
382
+ not passed. If the prompt is declined, the program will exit.
383
+
384
+ :param param_decls: One or more option names. Defaults to the single
385
+ value ``"--yes"``.
386
+ :param kwargs: Extra arguments are passed to :func:`option`.
387
+ """
388
+
389
+ def callback(ctx: Context, param: Parameter, value: bool) -> None:
390
+ if not value:
391
+ ctx.abort()
392
+
393
+ if not param_decls:
394
+ param_decls = ("--yes",)
395
+
396
+ kwargs.setdefault("is_flag", True)
397
+ kwargs.setdefault("callback", callback)
398
+ kwargs.setdefault("expose_value", False)
399
+ kwargs.setdefault("prompt", _("Do you want to continue?"))
400
+ kwargs.setdefault("help", _("Confirm the action without prompting."))
401
+ return option(*param_decls, **kwargs)
402
+
403
+
404
+ def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
405
+ """Add a ``--password`` option which prompts for a password, hiding
406
+ input and asking to enter the value again for confirmation.
407
+
408
+ :param param_decls: One or more option names. Defaults to the single
409
+ value ``"--password"``.
410
+ :param kwargs: Extra arguments are passed to :func:`option`.
411
+ """
412
+ if not param_decls:
413
+ param_decls = ("--password",)
414
+
415
+ kwargs.setdefault("prompt", True)
416
+ kwargs.setdefault("confirmation_prompt", True)
417
+ kwargs.setdefault("hide_input", True)
418
+ return option(*param_decls, **kwargs)
419
+
420
+
421
+ def version_option(
422
+ version: str | None = None,
423
+ *param_decls: str,
424
+ package_name: str | None = None,
425
+ prog_name: str | None = None,
426
+ message: str | None = None,
427
+ **kwargs: t.Any,
428
+ ) -> t.Callable[[FC], FC]:
429
+ """Add a ``--version`` option which immediately prints the version
430
+ number and exits the program.
431
+
432
+ If ``version`` is not provided, Click will try to detect it using
433
+ :func:`importlib.metadata.version` to get the version for the
434
+ ``package_name``.
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
+ import importlib.metadata
496
+
497
+ try:
498
+ version = importlib.metadata.version(package_name)
499
+ except importlib.metadata.PackageNotFoundError:
500
+ raise RuntimeError(
501
+ f"{package_name!r} is not installed. Try passing"
502
+ " 'package_name' instead."
503
+ ) from None
504
+
505
+ if version is None:
506
+ raise RuntimeError(
507
+ f"Could not determine the version for {package_name!r} automatically."
508
+ )
509
+
510
+ echo(
511
+ message % {"prog": prog_name, "package": package_name, "version": version},
512
+ color=ctx.color,
513
+ )
514
+ ctx.exit()
515
+
516
+ if not param_decls:
517
+ param_decls = ("--version",)
518
+
519
+ kwargs.setdefault("is_flag", True)
520
+ kwargs.setdefault("expose_value", False)
521
+ kwargs.setdefault("is_eager", True)
522
+ kwargs.setdefault("help", _("Show the version and exit."))
523
+ kwargs["callback"] = callback
524
+ return option(*param_decls, **kwargs)
525
+
526
+
527
+ def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:
528
+ """Pre-configured ``--help`` option which immediately prints the help page
529
+ and exits the program.
530
+
531
+ :param param_decls: One or more option names. Defaults to the single
532
+ value ``"--help"``.
533
+ :param kwargs: Extra arguments are passed to :func:`option`.
534
+ """
535
+
536
+ def show_help(ctx: Context, param: Parameter, value: bool) -> None:
537
+ """Callback that print the help page on ``<stdout>`` and exits."""
538
+ if value and not ctx.resilient_parsing:
539
+ echo(ctx.get_help(), color=ctx.color)
540
+ ctx.exit()
541
+
542
+ if not param_decls:
543
+ param_decls = ("--help",)
544
+
545
+ kwargs.setdefault("is_flag", True)
546
+ kwargs.setdefault("expose_value", False)
547
+ kwargs.setdefault("is_eager", True)
548
+ kwargs.setdefault("help", _("Show this message and exit."))
549
+ kwargs.setdefault("callback", show_help)
550
+
551
+ return option(*param_decls, **kwargs)
.venv/lib/python3.11/site-packages/click/exceptions.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import typing as t
5
+ from gettext import gettext as _
6
+ from gettext import ngettext
7
+
8
+ from ._compat import get_text_stderr
9
+ from .globals import resolve_color_default
10
+ from .utils import echo
11
+ from .utils import format_filename
12
+
13
+ if t.TYPE_CHECKING:
14
+ from .core import Command
15
+ from .core import Context
16
+ from .core import Parameter
17
+
18
+
19
+ def _join_param_hints(param_hint: cabc.Sequence[str] | str | None) -> str | None:
20
+ if param_hint is not None and not isinstance(param_hint, str):
21
+ return " / ".join(repr(x) for x in param_hint)
22
+
23
+ return param_hint
24
+
25
+
26
+ def _format_possibilities(possibilities: list[str]) -> str:
27
+ possibility_str = ", ".join(repr(p) for p in sorted(possibilities))
28
+ return ngettext(
29
+ "Did you mean {possibility}?",
30
+ "(Did you mean one of: {possibilities}?)",
31
+ len(possibilities),
32
+ ).format(possibility=possibility_str, possibilities=possibility_str)
33
+
34
+
35
+ class ClickException(Exception):
36
+ """An exception that Click can handle and show to the user."""
37
+
38
+ #: The exit code for this exception.
39
+ exit_code = 1
40
+
41
+ def __init__(self, message: str) -> None:
42
+ super().__init__(message)
43
+ # The context will be removed by the time we print the message, so cache
44
+ # the color settings here to be used later on (in `show`)
45
+ self.show_color: bool | None = resolve_color_default()
46
+ self.message = message
47
+
48
+ def format_message(self) -> str:
49
+ return self.message
50
+
51
+ def __str__(self) -> str:
52
+ return self.message
53
+
54
+ def show(self, file: t.IO[t.Any] | None = None) -> None:
55
+ if file is None:
56
+ file = get_text_stderr()
57
+
58
+ echo(
59
+ _("Error: {message}").format(message=self.format_message()),
60
+ file=file,
61
+ color=self.show_color,
62
+ )
63
+
64
+
65
+ class UsageError(ClickException):
66
+ """An internal exception that signals a usage error. This typically
67
+ aborts any further handling.
68
+
69
+ :param message: the error message to display.
70
+ :param ctx: optionally the context that caused this error. Click will
71
+ fill in the context automatically in some situations.
72
+ """
73
+
74
+ exit_code = 2
75
+
76
+ def __init__(self, message: str, ctx: Context | None = None) -> None:
77
+ super().__init__(message)
78
+ self.ctx = ctx
79
+ self.cmd: Command | None = self.ctx.command if self.ctx else None
80
+
81
+ def show(self, file: t.IO[t.Any] | None = None) -> None:
82
+ if file is None:
83
+ file = get_text_stderr()
84
+ color = None
85
+ hint = ""
86
+ if (
87
+ self.ctx is not None
88
+ and self.ctx.command.get_help_option(self.ctx) is not None
89
+ ):
90
+ help_names = self.ctx.command.get_help_option_names(self.ctx)
91
+ # Pick the longest name (like ``--help`` over ``-h``) for
92
+ # readability in error messages.
93
+ hint = _("Try '{command} {option}' for help.").format(
94
+ command=self.ctx.command_path,
95
+ option=max(help_names, key=len),
96
+ )
97
+ hint = f"{hint}\n"
98
+ if self.ctx is not None:
99
+ color = self.ctx.color
100
+ echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)
101
+ echo(
102
+ _("Error: {message}").format(message=self.format_message()),
103
+ file=file,
104
+ color=color,
105
+ )
106
+
107
+
108
+ class BadParameter(UsageError):
109
+ """An exception that formats out a standardized error message for a
110
+ bad parameter. This is useful when thrown from a callback or type as
111
+ Click will attach contextual information to it (for instance, which
112
+ parameter it is).
113
+
114
+ .. versionadded:: 2.0
115
+
116
+ :param param: the parameter object that caused this error. This can
117
+ be left out, and Click will attach this info itself
118
+ if possible.
119
+ :param param_hint: a string that shows up as parameter name. This
120
+ can be used as alternative to `param` in cases
121
+ where custom validation should happen. If it is
122
+ a string it's used as such, if it's a list then
123
+ each item is quoted and separated.
124
+ """
125
+
126
+ def __init__(
127
+ self,
128
+ message: str,
129
+ ctx: Context | None = None,
130
+ param: Parameter | None = None,
131
+ param_hint: cabc.Sequence[str] | str | None = None,
132
+ ) -> None:
133
+ super().__init__(message, ctx)
134
+ self.param = param
135
+ self.param_hint = param_hint
136
+
137
+ def format_message(self) -> str:
138
+ if self.param_hint is not None:
139
+ param_hint = self.param_hint
140
+ elif self.param is not None:
141
+ param_hint = self.param.get_error_hint(self.ctx)
142
+ else:
143
+ return _("Invalid value: {message}").format(message=self.message)
144
+
145
+ return _("Invalid value for {param_hint}: {message}").format(
146
+ param_hint=_join_param_hints(param_hint), message=self.message
147
+ )
148
+
149
+
150
+ class MissingParameter(BadParameter):
151
+ """Raised if click required an option or argument but it was not
152
+ provided when invoking the script.
153
+
154
+ .. versionadded:: 4.0
155
+
156
+ :param param_type: a string that indicates the type of the parameter.
157
+ The default is to inherit the parameter type from
158
+ the given `param`. Valid values are ``'parameter'``,
159
+ ``'option'`` or ``'argument'``.
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ message: str | None = None,
165
+ ctx: Context | None = None,
166
+ param: Parameter | None = None,
167
+ param_hint: cabc.Sequence[str] | str | None = None,
168
+ param_type: str | None = None,
169
+ ) -> None:
170
+ super().__init__(message or "", ctx, param, param_hint)
171
+ self.param_type = param_type
172
+
173
+ def format_message(self) -> str:
174
+ if self.param_hint is not None:
175
+ param_hint: cabc.Sequence[str] | str | None = self.param_hint
176
+ elif self.param is not None:
177
+ param_hint = self.param.get_error_hint(self.ctx)
178
+ else:
179
+ param_hint = None
180
+
181
+ param_hint = _join_param_hints(param_hint)
182
+ param_hint = f" {param_hint}" if param_hint else ""
183
+
184
+ param_type = self.param_type
185
+ if param_type is None and self.param is not None:
186
+ param_type = self.param.param_type_name
187
+
188
+ msg = self.message
189
+ if self.param is not None:
190
+ msg_extra = self.param.type.get_missing_message(
191
+ param=self.param, ctx=self.ctx
192
+ )
193
+ if msg_extra:
194
+ if msg:
195
+ msg += f". {msg_extra}"
196
+ else:
197
+ msg = msg_extra
198
+
199
+ msg = f" {msg}" if msg else ""
200
+
201
+ # Translate param_type for known types.
202
+ if param_type == "argument":
203
+ missing = _("Missing argument")
204
+ elif param_type == "option":
205
+ missing = _("Missing option")
206
+ elif param_type == "parameter":
207
+ missing = _("Missing parameter")
208
+ else:
209
+ missing = _("Missing {param_type}").format(param_type=param_type)
210
+
211
+ return f"{missing}{param_hint}.{msg}"
212
+
213
+ def __str__(self) -> str:
214
+ if not self.message:
215
+ param_name = self.param.name if self.param else None
216
+ return _("Missing parameter: {param_name}").format(param_name=param_name)
217
+ else:
218
+ return self.message
219
+
220
+
221
+ class NoSuchOption(UsageError):
222
+ """Raised if Click attempted to handle an option that does not exist.
223
+
224
+ .. versionadded:: 4.0
225
+ """
226
+
227
+ def __init__(
228
+ self,
229
+ option_name: str,
230
+ message: str | None = None,
231
+ possibilities: cabc.Iterable[str] | None = None,
232
+ ctx: Context | None = None,
233
+ ) -> None:
234
+ if message is None:
235
+ message = _("No such option {name!r}.").format(name=option_name)
236
+
237
+ super().__init__(message, ctx)
238
+ self.option_name = option_name
239
+ self.possibilities: list[str] | None = None
240
+ if possibilities:
241
+ from difflib import get_close_matches
242
+
243
+ self.possibilities = get_close_matches(option_name, possibilities)
244
+
245
+ def format_message(self) -> str:
246
+ if not self.possibilities:
247
+ return self.message
248
+ return f"{self.message} {_format_possibilities(self.possibilities)}"
249
+
250
+
251
+ class NoSuchCommand(UsageError):
252
+ """Raised if Click attempted to handle a command that does not exist.
253
+
254
+ .. versionadded:: 8.4.0
255
+ """
256
+
257
+ def __init__(
258
+ self,
259
+ command_name: str,
260
+ message: str | None = None,
261
+ possibilities: cabc.Iterable[str] | None = None,
262
+ ctx: Context | None = None,
263
+ ) -> None:
264
+ if message is None:
265
+ message = _("No such command {name!r}.").format(name=command_name)
266
+
267
+ super().__init__(message, ctx)
268
+ self.command_name = command_name
269
+ self.possibilities: list[str] | None = None
270
+ if possibilities:
271
+ from difflib import get_close_matches
272
+
273
+ self.possibilities = get_close_matches(command_name, possibilities)
274
+
275
+ def format_message(self) -> str:
276
+ if not self.possibilities:
277
+ return self.message
278
+ return f"{self.message} {_format_possibilities(self.possibilities)}"
279
+
280
+
281
+ class BadOptionUsage(UsageError):
282
+ """Raised if an option is generally supplied but the use of the option
283
+ was incorrect. This is for instance raised if the number of arguments
284
+ for an option is not correct.
285
+
286
+ .. versionadded:: 4.0
287
+
288
+ :param option_name: the name of the option being used incorrectly.
289
+ """
290
+
291
+ def __init__(
292
+ self, option_name: str, message: str, ctx: Context | None = None
293
+ ) -> None:
294
+ super().__init__(message, ctx)
295
+ self.option_name = option_name
296
+
297
+
298
+ class BadArgumentUsage(UsageError):
299
+ """Raised if an argument is generally supplied but the use of the argument
300
+ was incorrect. This is for instance raised if the number of values
301
+ for an argument is not correct.
302
+
303
+ .. versionadded:: 6.0
304
+ """
305
+
306
+
307
+ class NoArgsIsHelpError(UsageError):
308
+ def __init__(self, ctx: Context) -> None:
309
+ self.ctx: Context
310
+ super().__init__(ctx.get_help(), ctx=ctx)
311
+
312
+ def show(self, file: t.IO[t.Any] | None = None) -> None:
313
+ echo(self.format_message(), file=file, err=True, color=self.ctx.color)
314
+
315
+
316
+ class FileError(ClickException):
317
+ """Raised if a file cannot be opened."""
318
+
319
+ def __init__(self, filename: str, hint: str | None = None) -> None:
320
+ if hint is None:
321
+ hint = _("unknown error")
322
+
323
+ super().__init__(hint)
324
+ self.ui_filename: str = format_filename(filename)
325
+ self.filename = filename
326
+
327
+ def format_message(self) -> str:
328
+ return _("Could not open file {filename!r}: {message}").format(
329
+ filename=self.ui_filename, message=self.message
330
+ )
331
+
332
+
333
+ class Abort(RuntimeError):
334
+ """An internal signalling exception that signals Click to abort."""
335
+
336
+
337
+ class Exit(RuntimeError):
338
+ """An exception that indicates that the application should exit with some
339
+ status code.
340
+
341
+ :param code: the status code to exit with.
342
+ """
343
+
344
+ __slots__ = ("exit_code",)
345
+
346
+ def __init__(self, code: int = 0) -> None:
347
+ self.exit_code: int = code
.venv/lib/python3.11/site-packages/click/formatting.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ from contextlib import contextmanager
5
+ from gettext import gettext as _
6
+
7
+ from ._compat import term_len
8
+ from .parser import _split_opt
9
+
10
+ # Can force a width. This is used by the test system
11
+ FORCED_WIDTH: int | None = None
12
+
13
+
14
+ def measure_table(rows: cabc.Iterable[tuple[str, str]]) -> tuple[int, ...]:
15
+ widths: dict[int, int] = {}
16
+
17
+ for row in rows:
18
+ for idx, col in enumerate(row):
19
+ widths[idx] = max(widths.get(idx, 0), term_len(col))
20
+
21
+ return tuple(y for x, y in sorted(widths.items()))
22
+
23
+
24
+ def iter_rows(
25
+ rows: cabc.Iterable[tuple[str, str]], col_count: int
26
+ ) -> cabc.Iterator[tuple[str, ...]]:
27
+ for row in rows:
28
+ yield row + ("",) * (col_count - len(row))
29
+
30
+
31
+ def wrap_text(
32
+ text: str,
33
+ width: int = 78,
34
+ initial_indent: str = "",
35
+ subsequent_indent: str = "",
36
+ preserve_paragraphs: bool = False,
37
+ ) -> str:
38
+ """A helper function that intelligently wraps text. By default, it
39
+ assumes that it operates on a single paragraph of text but if the
40
+ `preserve_paragraphs` parameter is provided it will intelligently
41
+ handle paragraphs (defined by two empty lines).
42
+
43
+ If paragraphs are handled, a paragraph can be prefixed with an empty
44
+ line containing the ``\\b`` character (``\\x08``) to indicate that
45
+ no rewrapping should happen in that block.
46
+
47
+ :param text: the text that should be rewrapped.
48
+ :param width: the maximum width for the text.
49
+ :param initial_indent: the initial indent that should be placed on the
50
+ first line as a string.
51
+ :param subsequent_indent: the indent string that should be placed on
52
+ each consecutive line.
53
+ :param preserve_paragraphs: if this flag is set then the wrapping will
54
+ intelligently handle paragraphs.
55
+
56
+ .. versionchanged:: 8.4.0
57
+ Width is measured in visible characters. ANSI escape sequences in
58
+ ``text``, ``initial_indent``, or ``subsequent_indent`` no longer
59
+ count toward the width budget, so styled input wraps based on what
60
+ the user sees instead of raw byte length.
61
+ """
62
+ from ._textwrap import TextWrapper
63
+
64
+ text = text.expandtabs()
65
+ wrapper = TextWrapper(
66
+ width,
67
+ initial_indent=initial_indent,
68
+ subsequent_indent=subsequent_indent,
69
+ replace_whitespace=False,
70
+ )
71
+ if not preserve_paragraphs:
72
+ return wrapper.fill(text)
73
+
74
+ p: list[tuple[int, bool, str]] = []
75
+ buf: list[str] = []
76
+ indent = None
77
+
78
+ def _flush_par() -> None:
79
+ if not buf:
80
+ return
81
+ if buf[0].strip() == "\b":
82
+ p.append((indent or 0, True, "\n".join(buf[1:])))
83
+ else:
84
+ p.append((indent or 0, False, " ".join(buf)))
85
+ del buf[:]
86
+
87
+ for line in text.splitlines():
88
+ if not line:
89
+ _flush_par()
90
+ indent = None
91
+ else:
92
+ if indent is None:
93
+ orig_len = term_len(line)
94
+ line = line.lstrip()
95
+ indent = orig_len - term_len(line)
96
+ buf.append(line)
97
+ _flush_par()
98
+
99
+ rv = []
100
+ for indent, raw, text in p:
101
+ with wrapper.extra_indent(" " * indent):
102
+ if raw:
103
+ rv.append(wrapper.indent_only(text))
104
+ else:
105
+ rv.append(wrapper.fill(text))
106
+
107
+ return "\n\n".join(rv)
108
+
109
+
110
+ class HelpFormatter:
111
+ """This class helps with formatting text-based help pages. It's
112
+ usually just needed for very special internal cases, but it's also
113
+ exposed so that developers can write their own fancy outputs.
114
+
115
+ At present, it always writes into memory.
116
+
117
+ :param indent_increment: the additional increment for each level.
118
+ :param width: the width for the text. This defaults to the terminal
119
+ width clamped to a maximum of 78.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ indent_increment: int = 2,
125
+ width: int | None = None,
126
+ max_width: int | None = None,
127
+ ) -> None:
128
+ self.indent_increment = indent_increment
129
+ if max_width is None:
130
+ max_width = 80
131
+ if width is None:
132
+ import shutil
133
+
134
+ width = FORCED_WIDTH
135
+ if width is None:
136
+ width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)
137
+ self.width = width
138
+ self.current_indent: int = 0
139
+ self.buffer: list[str] = []
140
+
141
+ def write(self, string: str) -> None:
142
+ """Writes a unicode string into the internal buffer."""
143
+ self.buffer.append(string)
144
+
145
+ def indent(self) -> None:
146
+ """Increases the indentation."""
147
+ self.current_indent += self.indent_increment
148
+
149
+ def dedent(self) -> None:
150
+ """Decreases the indentation."""
151
+ self.current_indent -= self.indent_increment
152
+
153
+ def write_usage(self, prog: str, args: str = "", prefix: str | None = None) -> None:
154
+ """Writes a usage line into the buffer.
155
+
156
+ :param prog: the program name.
157
+ :param args: whitespace separated list of arguments.
158
+ :param prefix: The prefix for the first line. Defaults to
159
+ ``"Usage: "``.
160
+ """
161
+ if prefix is None:
162
+ prefix = "{usage} ".format(usage=_("Usage:"))
163
+
164
+ usage_prefix = f"{prefix:>{self.current_indent}}{prog} "
165
+ text_width = self.width - self.current_indent
166
+
167
+ if not args:
168
+ # Without args, the prefix's trailing space and the wrap_text
169
+ # call that would normally place args on the line are both
170
+ # unnecessary. Emit just the prefix line.
171
+ self.write(usage_prefix.rstrip(" "))
172
+ self.write("\n")
173
+ return
174
+
175
+ if text_width >= (term_len(usage_prefix) + 20):
176
+ # The arguments will fit to the right of the prefix.
177
+ indent = " " * term_len(usage_prefix)
178
+ self.write(
179
+ wrap_text(
180
+ args,
181
+ text_width,
182
+ initial_indent=usage_prefix,
183
+ subsequent_indent=indent,
184
+ )
185
+ )
186
+ else:
187
+ # The prefix is too long, put the arguments on the next line.
188
+ self.write(usage_prefix)
189
+ self.write("\n")
190
+ indent = " " * (max(self.current_indent, term_len(prefix)) + 4)
191
+ self.write(
192
+ wrap_text(
193
+ args, text_width, initial_indent=indent, subsequent_indent=indent
194
+ )
195
+ )
196
+
197
+ self.write("\n")
198
+
199
+ def write_heading(self, heading: str) -> None:
200
+ """Writes a heading into the buffer."""
201
+ self.write(f"{'':>{self.current_indent}}{heading}:\n")
202
+
203
+ def write_paragraph(self) -> None:
204
+ """Writes a paragraph into the buffer."""
205
+ if self.buffer:
206
+ self.write("\n")
207
+
208
+ def write_text(self, text: str) -> None:
209
+ """Writes re-indented text into the buffer. This rewraps and
210
+ preserves paragraphs.
211
+ """
212
+ indent = " " * self.current_indent
213
+ self.write(
214
+ wrap_text(
215
+ text,
216
+ self.width,
217
+ initial_indent=indent,
218
+ subsequent_indent=indent,
219
+ preserve_paragraphs=True,
220
+ )
221
+ )
222
+ self.write("\n")
223
+
224
+ def write_dl(
225
+ self,
226
+ rows: cabc.Sequence[tuple[str, str]],
227
+ col_max: int = 30,
228
+ col_spacing: int = 2,
229
+ ) -> None:
230
+ """Writes a definition list into the buffer. This is how options
231
+ and commands are usually formatted.
232
+
233
+ :param rows: a list of two item tuples for the terms and values.
234
+ :param col_max: the maximum width of the first column.
235
+ :param col_spacing: the number of spaces between the first and
236
+ second column.
237
+ """
238
+ rows = list(rows)
239
+ widths = measure_table(rows)
240
+ if len(widths) != 2:
241
+ raise TypeError("Expected two columns for definition list")
242
+
243
+ first_col = min(widths[0], col_max) + col_spacing
244
+
245
+ for first, second in iter_rows(rows, len(widths)):
246
+ self.write(f"{'':>{self.current_indent}}{first}")
247
+ if not second:
248
+ self.write("\n")
249
+ continue
250
+ if term_len(first) <= first_col - col_spacing:
251
+ self.write(" " * (first_col - term_len(first)))
252
+ else:
253
+ self.write("\n")
254
+ self.write(" " * (first_col + self.current_indent))
255
+
256
+ text_width = max(self.width - first_col - 2, 10)
257
+ wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)
258
+ lines = wrapped_text.splitlines()
259
+
260
+ if lines:
261
+ self.write(f"{lines[0]}\n")
262
+
263
+ for line in lines[1:]:
264
+ self.write(f"{'':>{first_col + self.current_indent}}{line}\n")
265
+ else:
266
+ self.write("\n")
267
+
268
+ @contextmanager
269
+ def section(self, name: str) -> cabc.Iterator[None]:
270
+ """Helpful context manager that writes a paragraph, a heading,
271
+ and the indents.
272
+
273
+ :param name: the section name that is written as heading.
274
+ """
275
+ self.write_paragraph()
276
+ self.write_heading(name)
277
+ self.indent()
278
+ try:
279
+ yield
280
+ finally:
281
+ self.dedent()
282
+
283
+ @contextmanager
284
+ def indentation(self) -> cabc.Iterator[None]:
285
+ """A context manager that increases the indentation."""
286
+ self.indent()
287
+ try:
288
+ yield
289
+ finally:
290
+ self.dedent()
291
+
292
+ def getvalue(self) -> str:
293
+ """Returns the buffer contents."""
294
+ return "".join(self.buffer)
295
+
296
+
297
+ def join_options(options: cabc.Sequence[str]) -> tuple[str, bool]:
298
+ """Given a list of option strings this joins them in the most appropriate
299
+ way and returns them in the form ``(formatted_string,
300
+ any_prefix_is_slash)`` where the second item in the tuple is a flag that
301
+ indicates if any of the option prefixes was a slash.
302
+ """
303
+ rv = []
304
+ any_prefix_is_slash = False
305
+
306
+ for opt in options:
307
+ prefix = _split_opt(opt)[0]
308
+
309
+ if prefix == "/":
310
+ any_prefix_is_slash = True
311
+
312
+ rv.append((len(prefix), opt))
313
+
314
+ rv.sort(key=lambda x: x[0])
315
+ return ", ".join(x[1] for x in rv), any_prefix_is_slash
.venv/lib/python3.11/site-packages/click/globals.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+ from threading import local
5
+
6
+ if t.TYPE_CHECKING:
7
+ from .core import Context
8
+
9
+ _local = local()
10
+
11
+
12
+ @t.overload
13
+ def get_current_context(silent: t.Literal[False] = False) -> Context: ...
14
+
15
+
16
+ @t.overload
17
+ def get_current_context(silent: bool = ...) -> Context | None: ...
18
+
19
+
20
+ def get_current_context(silent: bool = False) -> Context | None:
21
+ """Returns the current click context. This can be used as a way to
22
+ access the current context object from anywhere. This is a more implicit
23
+ alternative to the :func:`pass_context` decorator. This function is
24
+ primarily useful for helpers such as :func:`echo` which might be
25
+ interested in changing its behavior based on the current context.
26
+
27
+ To push the current context, :meth:`Context.scope` can be used.
28
+
29
+ .. versionadded:: 5.0
30
+
31
+ :param silent: if set to `True` the return value is `None` if no context
32
+ is available. The default behavior is to raise a
33
+ :exc:`RuntimeError`.
34
+ """
35
+ try:
36
+ return t.cast("Context", _local.stack[-1])
37
+ except (AttributeError, IndexError) as e:
38
+ if not silent:
39
+ raise RuntimeError("There is no active click context.") from e
40
+
41
+ return None
42
+
43
+
44
+ def push_context(ctx: Context) -> None:
45
+ """Pushes a new context to the current stack."""
46
+ _local.__dict__.setdefault("stack", []).append(ctx)
47
+
48
+
49
+ def pop_context() -> None:
50
+ """Removes the top level from the stack."""
51
+ _local.stack.pop()
52
+
53
+
54
+ def resolve_color_default(color: bool | None = None) -> bool | None:
55
+ """Internal helper to get the default value of the color flag. If a
56
+ value is passed it's returned unchanged, otherwise it's looked up from
57
+ the current context.
58
+ """
59
+ if color is not None:
60
+ return color
61
+
62
+ ctx = get_current_context(silent=True)
63
+
64
+ if ctx is not None:
65
+ return ctx.color
66
+
67
+ return None
.venv/lib/python3.11/site-packages/click/parser.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
21
+ # This code uses parts of optparse written by Gregory P. Ward and
22
+ # maintained by the Python Software Foundation.
23
+ # Copyright 2001-2006 Gregory P. Ward
24
+ # Copyright 2002-2006 Python Software Foundation
25
+ from __future__ import annotations
26
+
27
+ import collections.abc as cabc
28
+ import typing as t
29
+ from collections import deque
30
+ from gettext import gettext as _
31
+ from gettext import ngettext
32
+
33
+ from ._utils import FLAG_NEEDS_VALUE
34
+ from ._utils import UNSET
35
+ from .exceptions import BadArgumentUsage
36
+ from .exceptions import BadOptionUsage
37
+ from .exceptions import NoSuchOption
38
+ from .exceptions import UsageError
39
+
40
+ if t.TYPE_CHECKING:
41
+ from ._utils import T_FLAG_NEEDS_VALUE
42
+ from ._utils import T_UNSET
43
+ from .core import Argument as CoreArgument
44
+ from .core import Context
45
+ from .core import Option as CoreOption
46
+ from .core import Parameter as CoreParameter
47
+
48
+ V = t.TypeVar("V")
49
+
50
+
51
+ def _unpack_args(
52
+ args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]
53
+ ) -> tuple[cabc.Sequence[str | cabc.Sequence[str | T_UNSET] | T_UNSET], list[str]]:
54
+ """Given an iterable of arguments and an iterable of nargs specifications,
55
+ it returns a tuple with all the unpacked arguments at the first index
56
+ and all remaining arguments as the second.
57
+
58
+ The nargs specification is the number of arguments that should be consumed
59
+ or `-1` to indicate that this position should eat up all the remainders.
60
+
61
+ Missing items are filled with ``UNSET``.
62
+ """
63
+ args = deque(args)
64
+ nargs_spec = deque(nargs_spec)
65
+ rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []
66
+ spos: int | None = None
67
+
68
+ def _fetch(c: deque[str]) -> str | T_UNSET:
69
+ try:
70
+ if spos is None:
71
+ return c.popleft()
72
+ else:
73
+ return c.pop()
74
+ except IndexError:
75
+ return UNSET
76
+
77
+ while nargs_spec:
78
+ if spos is None:
79
+ nargs = nargs_spec.popleft()
80
+ else:
81
+ nargs = nargs_spec.pop()
82
+
83
+ if nargs == 1:
84
+ rv.append(_fetch(args))
85
+ elif nargs > 1:
86
+ x: list[str | T_UNSET] = [_fetch(args) for _ in range(nargs)]
87
+
88
+ # If we're reversed, we're pulling in the arguments in reverse,
89
+ # so we need to turn them around.
90
+ if spos is not None:
91
+ x.reverse()
92
+
93
+ rv.append(tuple(x))
94
+ elif nargs < 0:
95
+ if spos is not None:
96
+ raise TypeError("Cannot have two nargs < 0")
97
+
98
+ spos = len(rv)
99
+ rv.append(UNSET)
100
+
101
+ # spos is the position of the wildcard (star). If it's not `None`,
102
+ # we fill it with the remainder.
103
+ if spos is not None:
104
+ rv[spos] = tuple(args)
105
+ args = []
106
+ rv[spos + 1 :] = reversed(rv[spos + 1 :])
107
+
108
+ return tuple(rv), list(args)
109
+
110
+
111
+ def _split_opt(opt: str) -> tuple[str, str]:
112
+ first = opt[:1]
113
+ if first.isalnum():
114
+ return "", opt
115
+ if opt[1:2] == first:
116
+ return opt[:2], opt[2:]
117
+ return first, opt[1:]
118
+
119
+
120
+ def _normalize_opt(opt: str, ctx: Context | None) -> str:
121
+ if ctx is None or ctx.token_normalize_func is None:
122
+ return opt
123
+ prefix, opt = _split_opt(opt)
124
+ return f"{prefix}{ctx.token_normalize_func(opt)}"
125
+
126
+
127
+ class _Option:
128
+ def __init__(
129
+ self,
130
+ obj: CoreOption,
131
+ opts: cabc.Sequence[str],
132
+ dest: str | None,
133
+ action: str | None = None,
134
+ nargs: int = 1,
135
+ const: t.Any | None = None,
136
+ ):
137
+ self._short_opts = []
138
+ self._long_opts = []
139
+ self.prefixes: set[str] = set()
140
+
141
+ for opt in opts:
142
+ prefix, value = _split_opt(opt)
143
+ if not prefix:
144
+ raise ValueError(
145
+ _("Invalid start character for option ({option})").format(
146
+ option=opt
147
+ )
148
+ )
149
+ self.prefixes.add(prefix[0])
150
+ if len(prefix) == 1 and len(value) == 1:
151
+ self._short_opts.append(opt)
152
+ else:
153
+ self._long_opts.append(opt)
154
+ self.prefixes.add(prefix)
155
+
156
+ if action is None:
157
+ action = "store"
158
+
159
+ self.dest = dest
160
+ self.action = action
161
+ self.nargs = nargs
162
+ self.const = const
163
+ self.obj = obj
164
+
165
+ @property
166
+ def takes_value(self) -> bool:
167
+ return self.action in ("store", "append")
168
+
169
+ def process(self, value: t.Any, state: _ParsingState) -> None:
170
+ if self.action == "store":
171
+ state.opts[self.dest] = value # type: ignore
172
+ elif self.action == "store_const":
173
+ state.opts[self.dest] = self.const # type: ignore
174
+ elif self.action == "append":
175
+ state.opts.setdefault(self.dest, []).append(value) # type: ignore
176
+ elif self.action == "append_const":
177
+ state.opts.setdefault(self.dest, []).append(self.const) # type: ignore
178
+ elif self.action == "count":
179
+ state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 # type: ignore
180
+ else:
181
+ raise ValueError(f"unknown action '{self.action}'")
182
+ state.order.append(self.obj)
183
+
184
+
185
+ class _Argument:
186
+ def __init__(self, obj: CoreArgument, dest: str | None, nargs: int = 1):
187
+ self.dest = dest
188
+ self.nargs = nargs
189
+ self.obj = obj
190
+
191
+ def process(
192
+ self,
193
+ value: str | cabc.Sequence[str | T_UNSET] | T_UNSET,
194
+ state: _ParsingState,
195
+ ) -> None:
196
+ if self.nargs > 1:
197
+ assert isinstance(value, cabc.Sequence)
198
+ holes = sum(x is UNSET for x in value)
199
+ if holes == len(value):
200
+ value = UNSET
201
+ elif holes != 0:
202
+ raise BadArgumentUsage(
203
+ _("Argument {name!r} takes {nargs} values.").format(
204
+ name=self.dest, nargs=self.nargs
205
+ )
206
+ )
207
+
208
+ # We failed to collect any argument value so we consider the argument as unset.
209
+ if value == ():
210
+ value = UNSET
211
+
212
+ state.opts[self.dest] = value # type: ignore
213
+ state.order.append(self.obj)
214
+
215
+
216
+ class _ParsingState:
217
+ def __init__(self, rargs: list[str]) -> None:
218
+ self.opts: dict[str, t.Any] = {}
219
+ self.largs: list[str] = []
220
+ self.rargs = rargs
221
+ self.order: list[CoreParameter] = []
222
+
223
+
224
+ class _OptionParser:
225
+ """The option parser is an internal class that is ultimately used to
226
+ parse options and arguments. It's modelled after optparse and brings
227
+ a similar but vastly simplified API. It should generally not be used
228
+ directly as the high level Click classes wrap it for you.
229
+
230
+ It's not nearly as extensible as optparse or argparse as it does not
231
+ implement features that are implemented on a higher level (such as
232
+ types or defaults).
233
+
234
+ :param ctx: optionally the :class:`~click.Context` where this parser
235
+ should go with.
236
+
237
+ .. deprecated:: 8.2
238
+ Will be removed in Click 9.0.
239
+ """
240
+
241
+ def __init__(self, ctx: Context | None = None) -> None:
242
+ #: The :class:`~click.Context` for this parser. This might be
243
+ #: `None` for some advanced use cases.
244
+ self.ctx = ctx
245
+ #: This controls how the parser deals with interspersed arguments.
246
+ #: If this is set to `False`, the parser will stop on the first
247
+ #: non-option. Click uses this to implement nested subcommands
248
+ #: safely.
249
+ self.allow_interspersed_args: bool = True
250
+ #: This tells the parser how to deal with unknown options. By
251
+ #: default it will error out (which is sensible), but there is a
252
+ #: second mode where it will ignore it and continue processing
253
+ #: after shifting all the unknown options into the resulting args.
254
+ self.ignore_unknown_options: bool = False
255
+
256
+ if ctx is not None:
257
+ self.allow_interspersed_args = ctx.allow_interspersed_args
258
+ self.ignore_unknown_options = ctx.ignore_unknown_options
259
+
260
+ self._short_opt: dict[str, _Option] = {}
261
+ self._long_opt: dict[str, _Option] = {}
262
+ self._opt_prefixes = {"-", "--"}
263
+ self._args: list[_Argument] = []
264
+
265
+ def add_option(
266
+ self,
267
+ obj: CoreOption,
268
+ opts: cabc.Sequence[str],
269
+ dest: str | None,
270
+ action: str | None = None,
271
+ nargs: int = 1,
272
+ const: t.Any | None = None,
273
+ ) -> None:
274
+ """Adds a new option named `dest` to the parser. The destination
275
+ is not inferred (unlike with optparse) and needs to be explicitly
276
+ provided. Action can be any of ``store``, ``store_const``,
277
+ ``append``, ``append_const`` or ``count``.
278
+
279
+ The `obj` can be used to identify the option in the order list
280
+ that is returned from the parser.
281
+ """
282
+ opts = [_normalize_opt(opt, self.ctx) for opt in opts]
283
+ option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const)
284
+ self._opt_prefixes.update(option.prefixes)
285
+ for opt in option._short_opts:
286
+ self._short_opt[opt] = option
287
+ for opt in option._long_opts:
288
+ self._long_opt[opt] = option
289
+
290
+ def add_argument(self, obj: CoreArgument, dest: str | None, nargs: int = 1) -> None:
291
+ """Adds a positional argument named `dest` to the parser.
292
+
293
+ The `obj` can be used to identify the option in the order list
294
+ that is returned from the parser.
295
+ """
296
+ self._args.append(_Argument(obj, dest=dest, nargs=nargs))
297
+
298
+ def parse_args(
299
+ self, args: list[str]
300
+ ) -> tuple[dict[str, t.Any], list[str], list[CoreParameter]]:
301
+ """Parses positional arguments and returns ``(values, args, order)``
302
+ for the parsed options and arguments as well as the leftover
303
+ arguments if there are any. The order is a list of objects as they
304
+ appear on the command line. If arguments appear multiple times they
305
+ will be memorized multiple times as well.
306
+ """
307
+ state = _ParsingState(args)
308
+ try:
309
+ self._process_args_for_options(state)
310
+ self._process_args_for_args(state)
311
+ except UsageError:
312
+ if self.ctx is None or not self.ctx.resilient_parsing:
313
+ raise
314
+ return state.opts, state.largs, state.order
315
+
316
+ def _process_args_for_args(self, state: _ParsingState) -> None:
317
+ pargs, args = _unpack_args(
318
+ state.largs + state.rargs, [x.nargs for x in self._args]
319
+ )
320
+
321
+ for idx, arg in enumerate(self._args):
322
+ arg.process(pargs[idx], state)
323
+
324
+ state.largs = args
325
+ state.rargs = []
326
+
327
+ def _process_args_for_options(self, state: _ParsingState) -> None:
328
+ while state.rargs:
329
+ arg = state.rargs.pop(0)
330
+ arglen = len(arg)
331
+ # Double dashes always handled explicitly regardless of what
332
+ # prefixes are valid.
333
+ if arg == "--":
334
+ return
335
+ elif arg[:1] in self._opt_prefixes and arglen > 1:
336
+ self._process_opts(arg, state)
337
+ elif self.allow_interspersed_args:
338
+ state.largs.append(arg)
339
+ else:
340
+ state.rargs.insert(0, arg)
341
+ return
342
+
343
+ # Say this is the original argument list:
344
+ # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
345
+ # ^
346
+ # (we are about to process arg(i)).
347
+ #
348
+ # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
349
+ # [arg0, ..., arg(i-1)] (any options and their arguments will have
350
+ # been removed from largs).
351
+ #
352
+ # The while loop will usually consume 1 or more arguments per pass.
353
+ # If it consumes 1 (eg. arg is an option that takes no arguments),
354
+ # then after _process_arg() is done the situation is:
355
+ #
356
+ # largs = subset of [arg0, ..., arg(i)]
357
+ # rargs = [arg(i+1), ..., arg(N-1)]
358
+ #
359
+ # If allow_interspersed_args is false, largs will always be
360
+ # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
361
+ # not a very interesting subset!
362
+
363
+ def _match_long_opt(
364
+ self, opt: str, explicit_value: str | None, state: _ParsingState
365
+ ) -> None:
366
+ if opt not in self._long_opt:
367
+ raise NoSuchOption(opt, possibilities=self._long_opt, ctx=self.ctx)
368
+
369
+ option = self._long_opt[opt]
370
+ if option.takes_value:
371
+ # At this point it's safe to modify rargs by injecting the
372
+ # explicit value, because no exception is raised in this
373
+ # branch. This means that the inserted value will be fully
374
+ # consumed.
375
+ if explicit_value is not None:
376
+ state.rargs.insert(0, explicit_value)
377
+
378
+ value = self._get_value_from_state(opt, option, state)
379
+
380
+ elif explicit_value is not None:
381
+ raise BadOptionUsage(
382
+ opt, _("Option {name!r} does not take a value.").format(name=opt)
383
+ )
384
+
385
+ else:
386
+ value = UNSET
387
+
388
+ option.process(value, state)
389
+
390
+ def _match_short_opt(self, arg: str, state: _ParsingState) -> None:
391
+ stop = False
392
+ i = 1
393
+ prefix = arg[0]
394
+ unknown_options = []
395
+
396
+ for ch in arg[1:]:
397
+ opt = _normalize_opt(f"{prefix}{ch}", self.ctx)
398
+ option = self._short_opt.get(opt)
399
+ i += 1
400
+
401
+ if not option:
402
+ if self.ignore_unknown_options:
403
+ unknown_options.append(ch)
404
+ continue
405
+ raise NoSuchOption(opt, ctx=self.ctx)
406
+ if option.takes_value:
407
+ # Any characters left in arg? Pretend they're the
408
+ # next arg, and stop consuming characters of arg.
409
+ if i < len(arg):
410
+ state.rargs.insert(0, arg[i:])
411
+ stop = True
412
+
413
+ value = self._get_value_from_state(opt, option, state)
414
+
415
+ else:
416
+ value = UNSET
417
+
418
+ option.process(value, state)
419
+
420
+ if stop:
421
+ break
422
+
423
+ # If we got any unknown options we recombine the string of the
424
+ # remaining options and re-attach the prefix, then report that
425
+ # to the state as new large. This way there is basic combinatorics
426
+ # that can be achieved while still ignoring unknown arguments.
427
+ if self.ignore_unknown_options and unknown_options:
428
+ state.largs.append(f"{prefix}{''.join(unknown_options)}")
429
+
430
+ def _get_value_from_state(
431
+ self, option_name: str, option: _Option, state: _ParsingState
432
+ ) -> str | cabc.Sequence[str] | T_UNSET | T_FLAG_NEEDS_VALUE:
433
+ nargs = option.nargs
434
+
435
+ value: str | cabc.Sequence[str] | T_UNSET | T_FLAG_NEEDS_VALUE
436
+
437
+ if len(state.rargs) < nargs:
438
+ if option.obj._flag_needs_value:
439
+ # Option allows omitting the value.
440
+ value = FLAG_NEEDS_VALUE
441
+ else:
442
+ raise BadOptionUsage(
443
+ option_name,
444
+ ngettext(
445
+ "Option {name!r} requires an argument.",
446
+ "Option {name!r} requires {nargs} arguments.",
447
+ nargs,
448
+ ).format(name=option_name, nargs=nargs),
449
+ )
450
+ elif nargs == 1:
451
+ next_rarg = state.rargs[0]
452
+
453
+ if (
454
+ option.obj._flag_needs_value
455
+ and isinstance(next_rarg, str)
456
+ and next_rarg[:1] in self._opt_prefixes
457
+ and len(next_rarg) > 1
458
+ ):
459
+ # The next arg looks like the start of an option, don't
460
+ # use it as the value if omitting the value is allowed.
461
+ value = FLAG_NEEDS_VALUE
462
+ else:
463
+ value = state.rargs.pop(0)
464
+ else:
465
+ value = tuple(state.rargs[:nargs])
466
+ del state.rargs[:nargs]
467
+
468
+ return value
469
+
470
+ def _process_opts(self, arg: str, state: _ParsingState) -> None:
471
+ explicit_value = None
472
+ # Long option handling happens in two parts. The first part is
473
+ # supporting explicitly attached values. In any case, we will try
474
+ # to long match the option first.
475
+ if "=" in arg:
476
+ long_opt, explicit_value = arg.split("=", 1)
477
+ else:
478
+ long_opt = arg
479
+ norm_long_opt = _normalize_opt(long_opt, self.ctx)
480
+
481
+ # At this point we will match the (assumed) long option through
482
+ # the long option matching code. Note that this allows options
483
+ # like "-foo" to be matched as long options.
484
+ try:
485
+ self._match_long_opt(norm_long_opt, explicit_value, state)
486
+ except NoSuchOption:
487
+ # At this point the long option matching failed, and we need
488
+ # to try with short options. However there is a special rule
489
+ # which says, that if we have a two character options prefix
490
+ # (applies to "--foo" for instance), we do not dispatch to the
491
+ # short option code and will instead raise the no option
492
+ # error.
493
+ if arg[:2] not in self._opt_prefixes:
494
+ self._match_short_opt(arg, state)
495
+ return
496
+
497
+ if not self.ignore_unknown_options:
498
+ raise
499
+
500
+ state.largs.append(arg)
501
+
502
+
503
+ def __getattr__(name: str) -> object:
504
+ import warnings
505
+
506
+ if name in {
507
+ "OptionParser",
508
+ "Argument",
509
+ "Option",
510
+ "split_opt",
511
+ "normalize_opt",
512
+ "ParsingState",
513
+ }:
514
+ warnings.warn(
515
+ f"'parser.{name}' is deprecated and will be removed in Click 9.0."
516
+ " The old parser is available in 'optparse'.",
517
+ DeprecationWarning,
518
+ stacklevel=2,
519
+ )
520
+ return globals()[f"_{name}"]
521
+
522
+ if name == "split_arg_string":
523
+ from .shell_completion import split_arg_string
524
+
525
+ warnings.warn(
526
+ "Importing 'parser.split_arg_string' is deprecated, it will only be"
527
+ " available in 'shell_completion' in Click 9.0.",
528
+ DeprecationWarning,
529
+ stacklevel=2,
530
+ )
531
+ return split_arg_string
532
+
533
+ raise AttributeError(name)
.venv/lib/python3.11/site-packages/click/py.typed ADDED
File without changes
.venv/lib/python3.11/site-packages/click/shell_completion.py ADDED
@@ -0,0 +1,680 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import os
5
+ import re
6
+ import typing as t
7
+ from gettext import gettext as _
8
+
9
+ from .core import Argument
10
+ from .core import Command
11
+ from .core import Context
12
+ from .core import Group
13
+ from .core import Option
14
+ from .core import Parameter
15
+ from .core import ParameterSource
16
+ from .utils import echo
17
+
18
+
19
+ def shell_complete(
20
+ cli: Command,
21
+ ctx_args: cabc.MutableMapping[str, t.Any],
22
+ prog_name: str,
23
+ complete_var: str,
24
+ instruction: str,
25
+ ) -> int:
26
+ """Perform shell completion for the given CLI program.
27
+
28
+ :param cli: Command being called.
29
+ :param ctx_args: Extra arguments to pass to
30
+ ``cli.make_context``.
31
+ :param prog_name: Name of the executable in the shell.
32
+ :param complete_var: Name of the environment variable that holds
33
+ the completion instruction.
34
+ :param instruction: Value of ``complete_var`` with the completion
35
+ instruction and shell, in the form ``instruction_shell``.
36
+ :return: Status code to exit with.
37
+ """
38
+ shell, _, instruction = instruction.partition("_")
39
+ comp_cls = get_completion_class(shell)
40
+
41
+ if comp_cls is None:
42
+ return 1
43
+
44
+ comp = comp_cls(cli, ctx_args, prog_name, complete_var)
45
+
46
+ # Write bytes, otherwise Windows text stdout translates LF to CRLF and breaks.
47
+ if instruction == "source":
48
+ echo(comp.source().encode(), nl=False)
49
+ return 0
50
+
51
+ if instruction == "complete":
52
+ echo(comp.complete().encode())
53
+ return 0
54
+
55
+ return 1
56
+
57
+
58
+ class CompletionItem:
59
+ """Represents a completion value and metadata about the value. The
60
+ default metadata is ``type`` to indicate special shell handling,
61
+ and ``help`` if a shell supports showing a help string next to the
62
+ value.
63
+
64
+ Arbitrary parameters can be passed when creating the object, and
65
+ accessed using ``item.attr``. If an attribute wasn't passed,
66
+ accessing it returns ``None``.
67
+
68
+ :param value: The completion suggestion.
69
+ :param type: Tells the shell script to provide special completion
70
+ support for the type. Click uses ``"dir"`` and ``"file"``.
71
+ :param help: String shown next to the value if supported.
72
+ :param kwargs: Arbitrary metadata. The built-in implementations
73
+ don't use this, but custom type completions paired with custom
74
+ shell support could use it.
75
+ """
76
+
77
+ __slots__ = ("value", "type", "help", "_info")
78
+
79
+ def __init__(
80
+ self,
81
+ value: t.Any,
82
+ type: str = "plain",
83
+ help: str | None = None,
84
+ **kwargs: t.Any,
85
+ ) -> None:
86
+ self.value: t.Any = value
87
+ self.type: str = type
88
+ self.help: str | None = help
89
+ self._info = kwargs
90
+
91
+ def __getattr__(self, name: str) -> t.Any:
92
+ return self._info.get(name)
93
+
94
+
95
+ # Only Bash >= 4.4 has the nosort option.
96
+ _SOURCE_BASH = """\
97
+ %(complete_func)s() {
98
+ local IFS=$'\\n'
99
+ local response
100
+
101
+ response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
102
+ %(complete_var)s=bash_complete $1)
103
+
104
+ for completion in $response; do
105
+ IFS=',' read type value <<< "$completion"
106
+
107
+ if [[ $type == 'dir' ]]; then
108
+ COMPREPLY=()
109
+ compopt -o dirnames
110
+ elif [[ $type == 'file' ]]; then
111
+ COMPREPLY=()
112
+ compopt -o default
113
+ elif [[ $type == 'plain' ]]; then
114
+ COMPREPLY+=($value)
115
+ fi
116
+ done
117
+
118
+ return 0
119
+ }
120
+
121
+ %(complete_func)s_setup() {
122
+ complete -o nosort -F %(complete_func)s %(prog_name)s
123
+ }
124
+
125
+ %(complete_func)s_setup;
126
+ """
127
+
128
+ # See ZshComplete.format_completion below, and issue #2703, before
129
+ # changing this script.
130
+ #
131
+ # (TL;DR: _describe is picky about the format, but this Zsh script snippet
132
+ # is already widely deployed. So freeze this script, and use clever-ish
133
+ # handling of colons in ZshComplet.format_completion.)
134
+ _SOURCE_ZSH = """\
135
+ #compdef %(prog_name)s
136
+
137
+ %(complete_func)s() {
138
+ local -a completions
139
+ local -a completions_with_descriptions
140
+ local -a response
141
+ (( ! $+commands[%(prog_name)s] )) && return 1
142
+
143
+ response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) \
144
+ %(complete_var)s=zsh_complete %(prog_name)s)}")
145
+
146
+ for type key descr in ${response}; do
147
+ if [[ "$type" == "plain" ]]; then
148
+ if [[ "$descr" == "_" ]]; then
149
+ completions+=("$key")
150
+ else
151
+ completions_with_descriptions+=("$key":"$descr")
152
+ fi
153
+ elif [[ "$type" == "dir" ]]; then
154
+ _path_files -/
155
+ elif [[ "$type" == "file" ]]; then
156
+ _path_files -f
157
+ fi
158
+ done
159
+
160
+ if [ -n "$completions_with_descriptions" ]; then
161
+ _describe -V unsorted completions_with_descriptions -U
162
+ fi
163
+
164
+ if [ -n "$completions" ]; then
165
+ compadd -U -V unsorted -a completions
166
+ fi
167
+ }
168
+
169
+ if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
170
+ # autoload from fpath, call function directly
171
+ %(complete_func)s "$@"
172
+ else
173
+ # eval/source/. command, register function for later
174
+ compdef %(complete_func)s %(prog_name)s
175
+ fi
176
+ """
177
+
178
+ _SOURCE_FISH = """\
179
+ function %(complete_func)s;
180
+ set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \
181
+ COMP_CWORD=(commandline -t) %(prog_name)s);
182
+
183
+ for completion in $response;
184
+ set -l metadata (string split \n $completion);
185
+
186
+ if test $metadata[1] = "dir";
187
+ __fish_complete_directories $metadata[2];
188
+ else if test $metadata[1] = "file";
189
+ __fish_complete_path $metadata[2];
190
+ else if test $metadata[1] = "plain";
191
+ if test $metadata[3] != "_";
192
+ echo $metadata[2]\t$metadata[3];
193
+ else;
194
+ echo $metadata[2];
195
+ end;
196
+ end;
197
+ end;
198
+ end;
199
+
200
+ complete --no-files --command %(prog_name)s --arguments \
201
+ "(%(complete_func)s)";
202
+ """
203
+
204
+
205
+ class ShellComplete:
206
+ """Base class for providing shell completion support. A subclass for
207
+ a given shell will override attributes and methods to implement the
208
+ completion instructions (``source`` and ``complete``).
209
+
210
+ :param cli: Command being called.
211
+ :param prog_name: Name of the executable in the shell.
212
+ :param complete_var: Name of the environment variable that holds
213
+ the completion instruction.
214
+
215
+ .. versionadded:: 8.0
216
+ """
217
+
218
+ name: t.ClassVar[str]
219
+ """Name to register the shell as with :func:`add_completion_class`.
220
+ This is used in completion instructions (``{name}_source`` and
221
+ ``{name}_complete``).
222
+ """
223
+
224
+ source_template: t.ClassVar[str]
225
+ """Completion script template formatted by :meth:`source`. This must
226
+ be provided by subclasses.
227
+ """
228
+
229
+ def __init__(
230
+ self,
231
+ cli: Command,
232
+ ctx_args: cabc.MutableMapping[str, t.Any],
233
+ prog_name: str,
234
+ complete_var: str,
235
+ ) -> None:
236
+ self.cli = cli
237
+ self.ctx_args = ctx_args
238
+ self.prog_name = prog_name
239
+ self.complete_var = complete_var
240
+
241
+ @property
242
+ def func_name(self) -> str:
243
+ """The name of the shell function defined by the completion
244
+ script.
245
+ """
246
+ safe_name = re.sub(r"\W*", "", self.prog_name.replace("-", "_"), flags=re.ASCII)
247
+ return f"_{safe_name}_completion"
248
+
249
+ def source_vars(self) -> dict[str, t.Any]:
250
+ """Vars for formatting :attr:`source_template`.
251
+
252
+ By default this provides ``complete_func``, ``complete_var``,
253
+ and ``prog_name``.
254
+ """
255
+ return {
256
+ "complete_func": self.func_name,
257
+ "complete_var": self.complete_var,
258
+ "prog_name": self.prog_name,
259
+ }
260
+
261
+ def source(self) -> str:
262
+ """Produce the shell script that defines the completion
263
+ function. By default this ``%``-style formats
264
+ :attr:`source_template` with the dict returned by
265
+ :meth:`source_vars`.
266
+ """
267
+ return self.source_template % self.source_vars()
268
+
269
+ def get_completion_args(self) -> tuple[list[str], str]:
270
+ """Use the env vars defined by the shell script to return a
271
+ tuple of ``args, incomplete``. This must be implemented by
272
+ subclasses.
273
+ """
274
+ raise NotImplementedError
275
+
276
+ def get_completions(self, args: list[str], incomplete: str) -> list[CompletionItem]:
277
+ """Determine the context and last complete command or parameter
278
+ from the complete args. Call that object's ``shell_complete``
279
+ method to get the completions for the incomplete value.
280
+
281
+ :param args: List of complete args before the incomplete value.
282
+ :param incomplete: Value being completed. May be empty.
283
+ """
284
+ ctx = _resolve_context(self.cli, self.ctx_args, self.prog_name, args)
285
+ obj, incomplete = _resolve_incomplete(ctx, args, incomplete)
286
+ return obj.shell_complete(ctx, incomplete)
287
+
288
+ def format_completion(self, item: CompletionItem) -> str:
289
+ """Format a completion item into the form recognized by the
290
+ shell script. This must be implemented by subclasses.
291
+
292
+ :param item: Completion item to format.
293
+ """
294
+ raise NotImplementedError
295
+
296
+ def complete(self) -> str:
297
+ """Produce the completion data to send back to the shell.
298
+
299
+ By default this calls :meth:`get_completion_args`, gets the
300
+ completions, then calls :meth:`format_completion` for each
301
+ completion.
302
+ """
303
+ args, incomplete = self.get_completion_args()
304
+ completions = self.get_completions(args, incomplete)
305
+ out = [self.format_completion(item) for item in completions]
306
+ return "\n".join(out)
307
+
308
+
309
+ class BashComplete(ShellComplete):
310
+ """Shell completion for Bash."""
311
+
312
+ name = "bash"
313
+ source_template = _SOURCE_BASH
314
+
315
+ @staticmethod
316
+ def _check_version() -> None:
317
+ import shutil
318
+ import subprocess
319
+
320
+ bash_exe = shutil.which("bash")
321
+
322
+ if bash_exe is None:
323
+ match = None
324
+ else:
325
+ output = subprocess.run(
326
+ [bash_exe, "--norc", "-c", 'echo "${BASH_VERSION}"'],
327
+ stdout=subprocess.PIPE,
328
+ )
329
+ match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
330
+
331
+ if match is not None:
332
+ major, minor = match.groups()
333
+
334
+ if major < "4" or major == "4" and minor < "4":
335
+ echo(
336
+ _(
337
+ "Shell completion is not supported for Bash"
338
+ " versions older than 4.4."
339
+ ),
340
+ err=True,
341
+ )
342
+ else:
343
+ echo(
344
+ _("Couldn't detect Bash version, shell completion is not supported."),
345
+ err=True,
346
+ )
347
+
348
+ def source(self) -> str:
349
+ self._check_version()
350
+ return super().source()
351
+
352
+ def get_completion_args(self) -> tuple[list[str], str]:
353
+ cwords = split_arg_string(os.environ["COMP_WORDS"])
354
+ cword = int(os.environ["COMP_CWORD"])
355
+ args = cwords[1:cword]
356
+
357
+ try:
358
+ incomplete = cwords[cword]
359
+ except IndexError:
360
+ incomplete = ""
361
+
362
+ return args, incomplete
363
+
364
+ def format_completion(self, item: CompletionItem) -> str:
365
+ return f"{item.type},{item.value}"
366
+
367
+
368
+ class ZshComplete(ShellComplete):
369
+ """Shell completion for Zsh."""
370
+
371
+ name = "zsh"
372
+ source_template = _SOURCE_ZSH
373
+
374
+ def get_completion_args(self) -> tuple[list[str], str]:
375
+ cwords = split_arg_string(os.environ["COMP_WORDS"])
376
+ cword = int(os.environ["COMP_CWORD"])
377
+ args = cwords[1:cword]
378
+
379
+ try:
380
+ incomplete = cwords[cword]
381
+ except IndexError:
382
+ incomplete = ""
383
+
384
+ return args, incomplete
385
+
386
+ def format_completion(self, item: CompletionItem) -> str:
387
+ help_ = item.help or "_"
388
+ # The zsh completion script uses `_describe` on items with help
389
+ # texts (which splits the item help from the item value at the
390
+ # first unescaped colon) and `compadd` on items without help
391
+ # text (which uses the item value as-is and does not support
392
+ # colon escaping). So escape colons in the item value if and
393
+ # only if the item help is not the sentinel "_" value, as used
394
+ # by the completion script.
395
+ #
396
+ # (The zsh completion script is potentially widely deployed, and
397
+ # thus harder to fix than this method.)
398
+ #
399
+ # See issue #1812 and issue #2703 for further context.
400
+ value = item.value.replace(":", r"\:") if help_ != "_" else item.value
401
+ return f"{item.type}\n{value}\n{help_}"
402
+
403
+
404
+ class FishComplete(ShellComplete):
405
+ """Shell completion for Fish."""
406
+
407
+ name = "fish"
408
+ source_template = _SOURCE_FISH
409
+
410
+ def get_completion_args(self) -> tuple[list[str], str]:
411
+ cwords = split_arg_string(os.environ["COMP_WORDS"])
412
+ incomplete = os.environ["COMP_CWORD"]
413
+ if incomplete:
414
+ incomplete = split_arg_string(incomplete)[0]
415
+ args = cwords[1:]
416
+
417
+ # Fish stores the partial word in both COMP_WORDS and
418
+ # COMP_CWORD, remove it from complete args.
419
+ if incomplete and args and args[-1] == incomplete:
420
+ args.pop()
421
+
422
+ return args, incomplete
423
+
424
+ def format_completion(self, item: CompletionItem) -> str:
425
+ """
426
+ .. versionchanged:: 8.4.0
427
+ Escape newlines in value and help to fix completion errors with
428
+ multi-line help strings.
429
+ """
430
+ # The fish completion script splits each response line on literal
431
+ # newlines, so any newline in the value or help would corrupt the
432
+ # frame. Replace them with the two-character escape "\n" so the text
433
+ # round-trips through fish without breaking the format. The "_"
434
+ # sentinel for missing help mirrors :class:`ZshComplete`.
435
+ help_ = item.help or "_"
436
+ value = item.value.replace("\n", r"\n")
437
+ help_escaped = help_.replace("\n", r"\n")
438
+ return f"{item.type}\n{value}\n{help_escaped}"
439
+
440
+
441
+ ShellCompleteType = t.TypeVar("ShellCompleteType", bound="type[ShellComplete]")
442
+
443
+
444
+ _available_shells: dict[str, type[ShellComplete]] = {
445
+ "bash": BashComplete,
446
+ "fish": FishComplete,
447
+ "zsh": ZshComplete,
448
+ }
449
+
450
+
451
+ def add_completion_class(
452
+ cls: ShellCompleteType, name: str | None = None
453
+ ) -> ShellCompleteType:
454
+ """Register a :class:`ShellComplete` subclass under the given name.
455
+ The name will be provided by the completion instruction environment
456
+ variable during completion.
457
+
458
+ :param cls: The completion class that will handle completion for the
459
+ shell.
460
+ :param name: Name to register the class under. Defaults to the
461
+ class's ``name`` attribute.
462
+ """
463
+ if name is None:
464
+ name = cls.name
465
+
466
+ _available_shells[name] = cls
467
+
468
+ return cls
469
+
470
+
471
+ def get_completion_class(shell: str) -> type[ShellComplete] | None:
472
+ """Look up a registered :class:`ShellComplete` subclass by the name
473
+ provided by the completion instruction environment variable. If the
474
+ name isn't registered, returns ``None``.
475
+
476
+ :param shell: Name the class is registered under.
477
+ """
478
+ return _available_shells.get(shell)
479
+
480
+
481
+ def split_arg_string(string: str) -> list[str]:
482
+ """Split an argument string as with :func:`shlex.split`, but don't
483
+ fail if the string is incomplete. Ignores a missing closing quote or
484
+ incomplete escape sequence and uses the partial token as-is.
485
+
486
+ .. code-block:: python
487
+
488
+ split_arg_string("example 'my file")
489
+ ["example", "my file"]
490
+
491
+ split_arg_string("example my\\")
492
+ ["example", "my"]
493
+
494
+ :param string: String to split.
495
+
496
+ .. versionchanged:: 8.2
497
+ Moved to ``shell_completion`` from ``parser``.
498
+ """
499
+ import shlex
500
+
501
+ lex = shlex.shlex(string, posix=True)
502
+ lex.whitespace_split = True
503
+ lex.commenters = ""
504
+ out = []
505
+
506
+ try:
507
+ for token in lex:
508
+ out.append(token)
509
+ except ValueError:
510
+ # Raised when end-of-string is reached in an invalid state. Use
511
+ # the partial token as-is. The quote or escape character is in
512
+ # lex.state, not lex.token.
513
+ out.append(lex.token)
514
+
515
+ return out
516
+
517
+
518
+ def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:
519
+ """Determine if the given parameter is an argument that can still
520
+ accept values.
521
+
522
+ :param ctx: Invocation context for the command represented by the
523
+ parsed complete args.
524
+ :param param: Argument object being checked.
525
+ """
526
+ if not isinstance(param, Argument):
527
+ return False
528
+
529
+ value = ctx.params.get(param.name)
530
+ return (
531
+ param.nargs == -1
532
+ or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE
533
+ or (
534
+ param.nargs > 1
535
+ and isinstance(value, (tuple, list))
536
+ and len(value) < param.nargs
537
+ )
538
+ )
539
+
540
+
541
+ def _start_of_option(ctx: Context, value: str) -> bool:
542
+ """Check if the value looks like the start of an option."""
543
+ if not value:
544
+ return False
545
+
546
+ c = value[0]
547
+ return c in ctx._opt_prefixes
548
+
549
+
550
+ def _is_incomplete_option(ctx: Context, args: list[str], param: Parameter) -> bool:
551
+ """Determine if the given parameter is an option that needs a value.
552
+
553
+ :param args: List of complete args before the incomplete value.
554
+ :param param: Option object being checked.
555
+ """
556
+ if not isinstance(param, Option):
557
+ return False
558
+
559
+ if param.is_flag or param.count:
560
+ return False
561
+
562
+ last_option = None
563
+
564
+ for index, arg in enumerate(reversed(args)):
565
+ if index + 1 > param.nargs:
566
+ break
567
+
568
+ if _start_of_option(ctx, arg):
569
+ last_option = arg
570
+ break
571
+
572
+ return last_option is not None and last_option in param.opts
573
+
574
+
575
+ def _resolve_context(
576
+ cli: Command,
577
+ ctx_args: cabc.MutableMapping[str, t.Any],
578
+ prog_name: str,
579
+ args: list[str],
580
+ ) -> Context:
581
+ """Produce the context hierarchy starting with the command and
582
+ traversing the complete arguments. This only follows the commands,
583
+ it doesn't trigger input prompts or callbacks.
584
+
585
+ :param cli: Command being called.
586
+ :param prog_name: Name of the executable in the shell.
587
+ :param args: List of complete args before the incomplete value.
588
+ """
589
+ ctx_args["resilient_parsing"] = True
590
+ with cli.make_context(prog_name, args.copy(), **ctx_args) as ctx:
591
+ args = ctx._protected_args + ctx.args
592
+
593
+ while args:
594
+ command = ctx.command
595
+
596
+ if isinstance(command, Group):
597
+ if not command.chain:
598
+ name, cmd, args = command.resolve_command(ctx, args)
599
+
600
+ if cmd is None:
601
+ return ctx
602
+
603
+ with cmd.make_context(
604
+ name, args, parent=ctx, resilient_parsing=True
605
+ ) as sub_ctx:
606
+ ctx = sub_ctx
607
+ args = ctx._protected_args + ctx.args
608
+ else:
609
+ sub_ctx = ctx
610
+
611
+ while args:
612
+ name, cmd, args = command.resolve_command(ctx, args)
613
+
614
+ if cmd is None:
615
+ return ctx
616
+
617
+ with cmd.make_context(
618
+ name,
619
+ args,
620
+ parent=ctx,
621
+ allow_extra_args=True,
622
+ allow_interspersed_args=False,
623
+ resilient_parsing=True,
624
+ ) as sub_sub_ctx:
625
+ sub_ctx = sub_sub_ctx
626
+ args = sub_ctx.args
627
+
628
+ ctx = sub_ctx
629
+ args = [*sub_ctx._protected_args, *sub_ctx.args]
630
+ else:
631
+ break
632
+
633
+ return ctx
634
+
635
+
636
+ def _resolve_incomplete(
637
+ ctx: Context, args: list[str], incomplete: str
638
+ ) -> tuple[Command | Parameter, str]:
639
+ """Find the Click object that will handle the completion of the
640
+ incomplete value. Return the object and the incomplete value.
641
+
642
+ :param ctx: Invocation context for the command represented by
643
+ the parsed complete args.
644
+ :param args: List of complete args before the incomplete value.
645
+ :param incomplete: Value being completed. May be empty.
646
+ """
647
+ # Different shells treat an "=" between a long option name and
648
+ # value differently. Might keep the value joined, return the "="
649
+ # as a separate item, or return the split name and value. Always
650
+ # split and discard the "=" to make completion easier.
651
+ if incomplete == "=":
652
+ incomplete = ""
653
+ elif "=" in incomplete and _start_of_option(ctx, incomplete):
654
+ name, _, incomplete = incomplete.partition("=")
655
+ args.append(name)
656
+
657
+ # The "--" marker tells Click to stop treating values as options
658
+ # even if they start with the option character. If it hasn't been
659
+ # given and the incomplete arg looks like an option, the current
660
+ # command will provide option name completions.
661
+ if "--" not in args and _start_of_option(ctx, incomplete):
662
+ return ctx.command, incomplete
663
+
664
+ params = ctx.command.get_params(ctx)
665
+
666
+ # If the last complete arg is an option name with an incomplete
667
+ # value, the option will provide value completions.
668
+ for param in params:
669
+ if _is_incomplete_option(ctx, args, param):
670
+ return param, incomplete
671
+
672
+ # It's not an option name or value. The first argument without a
673
+ # parsed value will provide value completions.
674
+ for param in params:
675
+ if _is_incomplete_argument(ctx, param):
676
+ return param, incomplete
677
+
678
+ # There were no unparsed arguments, the command may be a group that
679
+ # will provide command name completions.
680
+ return ctx.command, incomplete
.venv/lib/python3.11/site-packages/click/termui.py ADDED
@@ -0,0 +1,941 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import inspect
5
+ import io
6
+ import itertools
7
+ import re
8
+ import sys
9
+ import typing as t
10
+ from contextlib import AbstractContextManager
11
+ from contextlib import redirect_stdout
12
+ from gettext import gettext as _
13
+
14
+ from ._compat import isatty
15
+ from ._compat import strip_ansi
16
+ from ._compat import WIN
17
+ from .exceptions import Abort
18
+ from .exceptions import UsageError
19
+ from .globals import resolve_color_default
20
+ from .types import Choice
21
+ from .types import convert_type
22
+ from .types import ParamType
23
+ from .utils import echo
24
+ from .utils import LazyFile
25
+
26
+ if t.TYPE_CHECKING:
27
+ from ._termui_impl import ProgressBar
28
+
29
+ V = t.TypeVar("V")
30
+
31
+ # The prompt functions to use. The doc tools currently override these
32
+ # functions to customize how they work.
33
+ visible_prompt_func: t.Callable[[str], str] = input
34
+
35
+ _ansi_colors = {
36
+ "black": 30,
37
+ "red": 31,
38
+ "green": 32,
39
+ "yellow": 33,
40
+ "blue": 34,
41
+ "magenta": 35,
42
+ "cyan": 36,
43
+ "white": 37,
44
+ "reset": 39,
45
+ "bright_black": 90,
46
+ "bright_red": 91,
47
+ "bright_green": 92,
48
+ "bright_yellow": 93,
49
+ "bright_blue": 94,
50
+ "bright_magenta": 95,
51
+ "bright_cyan": 96,
52
+ "bright_white": 97,
53
+ }
54
+ _ansi_reset_all = "\033[0m"
55
+
56
+
57
+ _HIDDEN_INPUT_MASK = "'***'"
58
+
59
+
60
+ def _mask_hidden_input(message: str, value: str) -> str:
61
+ """Replace occurrences of ``value`` in ``message`` with a fixed mask.
62
+
63
+ Both ``repr(value)`` (the form built-in :class:`ParamType` errors use
64
+ via ``{value!r}``) and the raw value are masked. The raw-value pass
65
+ uses word-boundary lookarounds so a substring like ``"1"`` does not
66
+ match inside ``"10"``, and ``"ent"`` does not match inside
67
+ ``"Authentication"``. The empty string is skipped to avoid matching
68
+ at every boundary.
69
+ """
70
+ message = message.replace(repr(value), _HIDDEN_INPUT_MASK)
71
+ if value:
72
+ message = re.sub(
73
+ rf"(?<!\w){re.escape(value)}(?!\w)", _HIDDEN_INPUT_MASK, message
74
+ )
75
+ return message
76
+
77
+
78
+ def hidden_prompt_func(prompt: str) -> str:
79
+ import getpass
80
+
81
+ return getpass.getpass(prompt)
82
+
83
+
84
+ def _readline_prompt(func: t.Callable[[str], str], text: str, err: bool) -> str:
85
+ """Call a prompt function, passing the full prompt on non-Windows so
86
+ readline can handle line editing and cursor positioning correctly.
87
+
88
+ On Windows the prompt is written separately via :func:`echo` for
89
+ colorama support, with only the last character passed to *func*.
90
+ """
91
+ if WIN:
92
+ # Write the prompt separately so that we get nice coloring
93
+ # through colorama on Windows.
94
+ echo(text[:-1], nl=False, err=err)
95
+ # Echo the last character to stdout to work around an issue
96
+ # where readline causes backspace to clear the whole line.
97
+ return func(text[-1:])
98
+ if err:
99
+ with redirect_stdout(sys.stderr):
100
+ return func(text)
101
+ return func(text)
102
+
103
+
104
+ def _build_prompt(
105
+ text: str,
106
+ suffix: str,
107
+ show_default: bool | str = False,
108
+ default: t.Any | None = None,
109
+ show_choices: bool = True,
110
+ type: ParamType[t.Any] | None = None,
111
+ ) -> str:
112
+ prompt = text
113
+ if type is not None and show_choices and isinstance(type, Choice):
114
+ prompt += f" ({', '.join(map(str, type.choices))})"
115
+ if isinstance(show_default, str):
116
+ default = f"({show_default})"
117
+ if default is not None and show_default:
118
+ prompt = f"{prompt} [{_format_default(default)}]"
119
+ return f"{prompt}{suffix}"
120
+
121
+
122
+ def _format_default(default: t.Any) -> t.Any:
123
+ if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
124
+ return default.name
125
+
126
+ return default
127
+
128
+
129
+ def prompt(
130
+ text: str,
131
+ default: t.Any | None = None,
132
+ hide_input: bool = False,
133
+ confirmation_prompt: bool | str = False,
134
+ type: ParamType[t.Any] | t.Any | None = None,
135
+ value_proc: t.Callable[[str], t.Any] | None = None,
136
+ prompt_suffix: str = ": ",
137
+ show_default: bool | str = True,
138
+ err: bool = False,
139
+ show_choices: bool = True,
140
+ ) -> t.Any:
141
+ """Prompts a user for input. This is a convenience function that can
142
+ be used to prompt a user for input later.
143
+
144
+ If the user aborts the input by sending an interrupt signal, this
145
+ function will catch it and raise a :exc:`Abort` exception.
146
+
147
+ :param text: the text to show for the prompt.
148
+ :param default: the default value to use if no input happens. If this
149
+ is not given it will prompt until it's aborted.
150
+ :param hide_input: if this is set to true then the input value will
151
+ be hidden.
152
+ :param confirmation_prompt: Prompt a second time to confirm the
153
+ value. Can be set to a string instead of ``True`` to customize
154
+ the message.
155
+ :param type: the type to use to check the value against.
156
+ :param value_proc: if this parameter is provided it's a function that
157
+ is invoked instead of the type conversion to
158
+ convert a value.
159
+ :param prompt_suffix: a suffix that should be added to the prompt.
160
+ :param show_default: shows or hides the default value in the prompt.
161
+ If this value is a string, it shows that string
162
+ in parentheses instead of the actual value.
163
+ :param err: if set to true the file defaults to ``stderr`` instead of
164
+ ``stdout``, the same as with echo.
165
+ :param show_choices: Show or hide choices if the passed type is a Choice.
166
+ For example if type is a Choice of either day or week,
167
+ show_choices is true and text is "Group by" then the
168
+ prompt will be "Group by (day, week): ".
169
+
170
+ .. versionchanged:: 8.3.3
171
+ ``show_default`` can be a string to show a custom value instead
172
+ of the actual default, matching the help text behavior.
173
+
174
+ .. versionchanged:: 8.3.1
175
+ A space is no longer appended to the prompt.
176
+
177
+ .. versionadded:: 8.0
178
+ ``confirmation_prompt`` can be a custom string.
179
+
180
+ .. versionadded:: 7.0
181
+ Added the ``show_choices`` parameter.
182
+
183
+ .. versionadded:: 6.0
184
+ Added unicode support for cmd.exe on Windows.
185
+
186
+ .. versionadded:: 4.0
187
+ Added the `err` parameter.
188
+
189
+ """
190
+
191
+ def prompt_func(text: str) -> str:
192
+ f = hidden_prompt_func if hide_input else visible_prompt_func
193
+ try:
194
+ return _readline_prompt(f, text, err)
195
+ except (KeyboardInterrupt, EOFError):
196
+ # getpass doesn't print a newline if the user aborts input with ^C.
197
+ # Allegedly this behavior is inherited from getpass(3).
198
+ # A doc bug has been filed at https://bugs.python.org/issue24711
199
+ if hide_input:
200
+ echo(None, err=err)
201
+ raise Abort() from None
202
+
203
+ if value_proc is None:
204
+ value_proc = convert_type(type, default)
205
+
206
+ prompt = _build_prompt(
207
+ text, prompt_suffix, show_default, default, show_choices, type
208
+ )
209
+
210
+ if confirmation_prompt:
211
+ if confirmation_prompt is True:
212
+ confirmation_prompt = _("Repeat for confirmation")
213
+
214
+ confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)
215
+
216
+ while True:
217
+ while True:
218
+ value = prompt_func(prompt)
219
+ if value:
220
+ break
221
+ elif default is not None:
222
+ value = default
223
+ break
224
+ try:
225
+ result = value_proc(value)
226
+ except UsageError as e:
227
+ message = _mask_hidden_input(e.message, value) if hide_input else e.message
228
+ echo(_("Error: {message}").format(message=message), err=err)
229
+ continue
230
+ if not confirmation_prompt:
231
+ return result
232
+ while True:
233
+ value2 = prompt_func(confirmation_prompt)
234
+ is_empty = not value and not value2
235
+ if value2 or is_empty:
236
+ break
237
+ if value == value2:
238
+ return result
239
+ echo(_("Error: The two entered values do not match."), err=err)
240
+
241
+
242
+ def confirm(
243
+ text: str,
244
+ default: bool | None = False,
245
+ abort: bool = False,
246
+ prompt_suffix: str = ": ",
247
+ show_default: bool = True,
248
+ err: bool = False,
249
+ ) -> bool:
250
+ """Prompts for confirmation (yes/no question).
251
+
252
+ If the user aborts the input by sending a interrupt signal this
253
+ function will catch it and raise a :exc:`Abort` exception.
254
+
255
+ :param text: the question to ask.
256
+ :param default: The default value to use when no input is given. If
257
+ ``None``, repeat until input is given.
258
+ :param abort: if this is set to `True` a negative answer aborts the
259
+ exception by raising :exc:`Abort`.
260
+ :param prompt_suffix: a suffix that should be added to the prompt.
261
+ :param show_default: shows or hides the default value in the prompt.
262
+ :param err: if set to true the file defaults to ``stderr`` instead of
263
+ ``stdout``, the same as with echo.
264
+
265
+ .. versionchanged:: 8.3.1
266
+ A space is no longer appended to the prompt.
267
+
268
+ .. versionchanged:: 8.0
269
+ Repeat until input is given if ``default`` is ``None``.
270
+
271
+ .. versionadded:: 4.0
272
+ Added the ``err`` parameter.
273
+ """
274
+ prompt = _build_prompt(
275
+ text,
276
+ prompt_suffix,
277
+ show_default,
278
+ "y/n" if default is None else ("Y/n" if default else "y/N"),
279
+ )
280
+
281
+ while True:
282
+ try:
283
+ value = _readline_prompt(visible_prompt_func, prompt, err).lower().strip()
284
+ except (KeyboardInterrupt, EOFError):
285
+ raise Abort() from None
286
+ if value in ("y", "yes"):
287
+ rv = True
288
+ elif value in ("n", "no"):
289
+ rv = False
290
+ elif default is not None and value == "":
291
+ rv = default
292
+ else:
293
+ echo(_("Error: invalid input"), err=err)
294
+ continue
295
+ break
296
+ if abort and not rv:
297
+ raise Abort()
298
+ return rv
299
+
300
+
301
+ def get_pager_file(
302
+ color: bool | None = None,
303
+ ) -> t.ContextManager[t.TextIO]:
304
+ """Context manager.
305
+
306
+ Yields a writable file-like object which can be used as an output pager.
307
+
308
+ .. versionadded:: 8.4.0
309
+
310
+ :param color: controls if the pager supports ANSI colors or not. The
311
+ default is autodetection.
312
+ """
313
+ from ._termui_impl import get_pager_file
314
+
315
+ color = resolve_color_default(color)
316
+
317
+ return get_pager_file(color=color)
318
+
319
+
320
+ def echo_via_pager(
321
+ text_or_generator: cabc.Iterable[str] | t.Callable[[], cabc.Iterable[str]] | str,
322
+ color: bool | None = None,
323
+ ) -> None:
324
+ """This function takes a text and shows it via an environment specific
325
+ pager on stdout.
326
+
327
+ .. versionchanged:: 3.0
328
+ Added the `color` flag.
329
+
330
+ :param text_or_generator: the text to page, or alternatively, a
331
+ generator emitting the text to page.
332
+ :param color: controls if the pager supports ANSI colors or not. The
333
+ default is autodetection.
334
+ """
335
+
336
+ if inspect.isgeneratorfunction(text_or_generator):
337
+ i = t.cast("t.Callable[[], cabc.Iterable[str]]", text_or_generator)()
338
+ elif isinstance(text_or_generator, str):
339
+ i = [text_or_generator]
340
+ else:
341
+ i = iter(t.cast("cabc.Iterable[str]", text_or_generator))
342
+
343
+ # convert every element of i to a text type if necessary
344
+ text_generator = (el if isinstance(el, str) else str(el) for el in i)
345
+
346
+ with get_pager_file(color=color) as pager:
347
+ for text in itertools.chain(text_generator, "\n"):
348
+ pager.write(text)
349
+
350
+
351
+ @t.overload
352
+ def progressbar(
353
+ *,
354
+ length: int,
355
+ label: str | None = None,
356
+ hidden: bool = False,
357
+ show_eta: bool = True,
358
+ show_percent: bool | None = None,
359
+ show_pos: bool = False,
360
+ fill_char: str = "#",
361
+ empty_char: str = "-",
362
+ bar_template: str = "%(label)s [%(bar)s] %(info)s",
363
+ info_sep: str = " ",
364
+ width: int = 36,
365
+ file: t.TextIO | None = None,
366
+ color: bool | None = None,
367
+ update_min_steps: int = 1,
368
+ ) -> ProgressBar[int]: ...
369
+
370
+
371
+ @t.overload
372
+ def progressbar(
373
+ iterable: cabc.Iterable[V] | None = None,
374
+ length: int | None = None,
375
+ label: str | None = None,
376
+ hidden: bool = False,
377
+ show_eta: bool = True,
378
+ show_percent: bool | None = None,
379
+ show_pos: bool = False,
380
+ item_show_func: t.Callable[[V | None], str | None] | None = None,
381
+ fill_char: str = "#",
382
+ empty_char: str = "-",
383
+ bar_template: str = "%(label)s [%(bar)s] %(info)s",
384
+ info_sep: str = " ",
385
+ width: int = 36,
386
+ file: t.TextIO | None = None,
387
+ color: bool | None = None,
388
+ update_min_steps: int = 1,
389
+ ) -> ProgressBar[V]: ...
390
+
391
+
392
+ def progressbar(
393
+ iterable: cabc.Iterable[V] | None = None,
394
+ length: int | None = None,
395
+ label: str | None = None,
396
+ hidden: bool = False,
397
+ show_eta: bool = True,
398
+ show_percent: bool | None = None,
399
+ show_pos: bool = False,
400
+ item_show_func: t.Callable[[V | None], str | None] | None = None,
401
+ fill_char: str = "#",
402
+ empty_char: str = "-",
403
+ bar_template: str = "%(label)s [%(bar)s] %(info)s",
404
+ info_sep: str = " ",
405
+ width: int = 36,
406
+ file: t.TextIO | None = None,
407
+ color: bool | None = None,
408
+ update_min_steps: int = 1,
409
+ ) -> ProgressBar[V]:
410
+ """This function creates an iterable context manager that can be used
411
+ to iterate over something while showing a progress bar. It will
412
+ either iterate over the `iterable` or `length` items (that are counted
413
+ up). While iteration happens, this function will print a rendered
414
+ progress bar to the given `file` (defaults to stdout) and will attempt
415
+ to calculate remaining time and more. By default, this progress bar
416
+ will not be rendered if the file is not a terminal.
417
+
418
+ The context manager creates the progress bar. When the context
419
+ manager is entered the progress bar is already created. With every
420
+ iteration over the progress bar, the iterable passed to the bar is
421
+ advanced and the bar is updated. When the context manager exits,
422
+ a newline is printed and the progress bar is finalized on screen.
423
+
424
+ Note: The progress bar is currently designed for use cases where the
425
+ total progress can be expected to take at least several seconds.
426
+ Because of this, the ProgressBar class object won't display
427
+ progress that is considered too fast, and progress where the time
428
+ between steps is less than a second.
429
+
430
+ No printing must happen or the progress bar will be unintentionally
431
+ destroyed.
432
+
433
+ Example usage::
434
+
435
+ with progressbar(items) as bar:
436
+ for item in bar:
437
+ do_something_with(item)
438
+
439
+ Alternatively, if no iterable is specified, one can manually update the
440
+ progress bar through the `update()` method instead of directly
441
+ iterating over the progress bar. The update method accepts the number
442
+ of steps to increment the bar with::
443
+
444
+ with progressbar(length=chunks.total_bytes) as bar:
445
+ for chunk in chunks:
446
+ process_chunk(chunk)
447
+ bar.update(chunks.bytes)
448
+
449
+ The ``update()`` method also takes an optional value specifying the
450
+ ``current_item`` at the new position. This is useful when used
451
+ together with ``item_show_func`` to customize the output for each
452
+ manual step::
453
+
454
+ with click.progressbar(
455
+ length=total_size,
456
+ label='Unzipping archive',
457
+ item_show_func=lambda a: a.filename
458
+ ) as bar:
459
+ for archive in zip_file:
460
+ archive.extract()
461
+ bar.update(archive.size, archive)
462
+
463
+ :param iterable: an iterable to iterate over. If not provided the length
464
+ is required.
465
+ :param length: the number of items to iterate over. By default the
466
+ progressbar will attempt to ask the iterator about its
467
+ length, which might or might not work. If an iterable is
468
+ also provided this parameter can be used to override the
469
+ length. If an iterable is not provided the progress bar
470
+ will iterate over a range of that length.
471
+ :param label: the label to show next to the progress bar.
472
+ :param hidden: hide the progressbar. Defaults to ``False``. When no tty is
473
+ detected, it will only print the progressbar label. Setting this to
474
+ ``False`` also disables that.
475
+ :param show_eta: enables or disables the estimated time display. This is
476
+ automatically disabled if the length cannot be
477
+ determined.
478
+ :param show_percent: enables or disables the percentage display. The
479
+ default is `True` if the iterable has a length or
480
+ `False` if not.
481
+ :param show_pos: enables or disables the absolute position display. The
482
+ default is `False`.
483
+ :param item_show_func: A function called with the current item which
484
+ can return a string to show next to the progress bar. If the
485
+ function returns ``None`` nothing is shown. The current item can
486
+ be ``None``, such as when entering and exiting the bar.
487
+ :param fill_char: the character to use to show the filled part of the
488
+ progress bar.
489
+ :param empty_char: the character to use to show the non-filled part of
490
+ the progress bar.
491
+ :param bar_template: the format string to use as template for the bar.
492
+ The parameters in it are ``label`` for the label,
493
+ ``bar`` for the progress bar and ``info`` for the
494
+ info section.
495
+ :param info_sep: the separator between multiple info items (eta etc.)
496
+ :param width: the width of the progress bar in characters, 0 means full
497
+ terminal width
498
+ :param file: The file to write to. If this is not a terminal then
499
+ only the label is printed.
500
+ :param color: controls if the terminal supports ANSI colors or not. The
501
+ default is autodetection. This is only needed if ANSI
502
+ codes are included anywhere in the progress bar output
503
+ which is not the case by default.
504
+ :param update_min_steps: Render only when this many updates have
505
+ completed. This allows tuning for very fast iterators.
506
+
507
+ .. versionadded:: 8.2
508
+ The ``hidden`` argument.
509
+
510
+ .. versionchanged:: 8.0
511
+ Output is shown even if execution time is less than 0.5 seconds.
512
+
513
+ .. versionchanged:: 8.0
514
+ ``item_show_func`` shows the current item, not the previous one.
515
+
516
+ .. versionchanged:: 8.0
517
+ Labels are echoed if the output is not a TTY. Reverts a change
518
+ in 7.0 that removed all output.
519
+
520
+ .. versionadded:: 8.0
521
+ The ``update_min_steps`` parameter.
522
+
523
+ .. versionadded:: 4.0
524
+ The ``color`` parameter and ``update`` method.
525
+
526
+ .. versionadded:: 2.0
527
+ """
528
+ from ._termui_impl import ProgressBar
529
+
530
+ color = resolve_color_default(color)
531
+ return ProgressBar(
532
+ iterable=iterable,
533
+ length=length,
534
+ hidden=hidden,
535
+ show_eta=show_eta,
536
+ show_percent=show_percent,
537
+ show_pos=show_pos,
538
+ item_show_func=item_show_func,
539
+ fill_char=fill_char,
540
+ empty_char=empty_char,
541
+ bar_template=bar_template,
542
+ info_sep=info_sep,
543
+ file=file,
544
+ label=label,
545
+ width=width,
546
+ color=color,
547
+ update_min_steps=update_min_steps,
548
+ )
549
+
550
+
551
+ def clear() -> None:
552
+ """Clears the terminal screen. This will have the effect of clearing
553
+ the whole visible space of the terminal and moving the cursor to the
554
+ top left. This does not do anything if not connected to a terminal.
555
+
556
+ .. versionadded:: 2.0
557
+ """
558
+ if not isatty(sys.stdout):
559
+ return
560
+
561
+ # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor
562
+ echo("\033[2J\033[1;1H", nl=False)
563
+
564
+
565
+ def _interpret_color(color: int | tuple[int, int, int] | str, offset: int = 0) -> str:
566
+ if isinstance(color, int):
567
+ return f"{38 + offset};5;{color:d}"
568
+
569
+ if isinstance(color, (tuple, list)):
570
+ r, g, b = color
571
+ return f"{38 + offset};2;{r:d};{g:d};{b:d}"
572
+
573
+ return str(_ansi_colors[color] + offset)
574
+
575
+
576
+ def style(
577
+ text: t.Any,
578
+ fg: int | tuple[int, int, int] | str | None = None,
579
+ bg: int | tuple[int, int, int] | str | None = None,
580
+ bold: bool | None = None,
581
+ dim: bool | None = None,
582
+ underline: bool | None = None,
583
+ overline: bool | None = None,
584
+ italic: bool | None = None,
585
+ blink: bool | None = None,
586
+ reverse: bool | None = None,
587
+ strikethrough: bool | None = None,
588
+ reset: bool = True,
589
+ ) -> str:
590
+ """Styles a text with ANSI styles and returns the new string. By
591
+ default the styling is self contained which means that at the end
592
+ of the string a reset code is issued. This can be prevented by
593
+ passing ``reset=False``.
594
+
595
+ Examples::
596
+
597
+ click.echo(click.style('Hello World!', fg='green'))
598
+ click.echo(click.style('ATTENTION!', blink=True))
599
+ click.echo(click.style('Some things', reverse=True, fg='cyan'))
600
+ click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))
601
+
602
+ Supported color names:
603
+
604
+ * ``black`` (might be a gray)
605
+ * ``red``
606
+ * ``green``
607
+ * ``yellow`` (might be an orange)
608
+ * ``blue``
609
+ * ``magenta``
610
+ * ``cyan``
611
+ * ``white`` (might be light gray)
612
+ * ``bright_black``
613
+ * ``bright_red``
614
+ * ``bright_green``
615
+ * ``bright_yellow``
616
+ * ``bright_blue``
617
+ * ``bright_magenta``
618
+ * ``bright_cyan``
619
+ * ``bright_white``
620
+ * ``reset`` (reset the color code only)
621
+
622
+ If the terminal supports it, color may also be specified as:
623
+
624
+ - An integer in the interval [0, 255]. The terminal must support
625
+ 8-bit/256-color mode.
626
+ - An RGB tuple of three integers in [0, 255]. The terminal must
627
+ support 24-bit/true-color mode.
628
+
629
+ See https://en.wikipedia.org/wiki/ANSI_color and
630
+ https://gist.github.com/XVilka/8346728 for more information.
631
+
632
+ :param text: the string to style with ansi codes.
633
+ :param fg: if provided this will become the foreground color.
634
+ :param bg: if provided this will become the background color.
635
+ :param bold: if provided this will enable or disable bold mode.
636
+ :param dim: if provided this will enable or disable dim mode. This is
637
+ badly supported.
638
+ :param underline: if provided this will enable or disable underline.
639
+ :param overline: if provided this will enable or disable overline.
640
+ :param italic: if provided this will enable or disable italic.
641
+ :param blink: if provided this will enable or disable blinking.
642
+ :param reverse: if provided this will enable or disable inverse
643
+ rendering (foreground becomes background and the
644
+ other way round).
645
+ :param strikethrough: if provided this will enable or disable
646
+ striking through text.
647
+ :param reset: by default a reset-all code is added at the end of the
648
+ string which means that styles do not carry over. This
649
+ can be disabled to compose styles.
650
+
651
+ .. versionchanged:: 8.0
652
+ A non-string ``message`` is converted to a string.
653
+
654
+ .. versionchanged:: 8.0
655
+ Added support for 256 and RGB color codes.
656
+
657
+ .. versionchanged:: 8.0
658
+ Added the ``strikethrough``, ``italic``, and ``overline``
659
+ parameters.
660
+
661
+ .. versionchanged:: 7.0
662
+ Added support for bright colors.
663
+
664
+ .. versionadded:: 2.0
665
+ """
666
+ if not isinstance(text, str):
667
+ text = str(text)
668
+
669
+ bits = []
670
+
671
+ if fg:
672
+ try:
673
+ bits.append(f"\033[{_interpret_color(fg)}m")
674
+ except KeyError:
675
+ raise TypeError(_("Unknown color {colour!r}").format(colour=fg)) from None
676
+
677
+ if bg:
678
+ try:
679
+ bits.append(f"\033[{_interpret_color(bg, 10)}m")
680
+ except KeyError:
681
+ raise TypeError(_("Unknown color {colour!r}").format(colour=bg)) from None
682
+
683
+ if bold is not None:
684
+ bits.append(f"\033[{1 if bold else 22}m")
685
+ if dim is not None:
686
+ bits.append(f"\033[{2 if dim else 22}m")
687
+ if underline is not None:
688
+ bits.append(f"\033[{4 if underline else 24}m")
689
+ if overline is not None:
690
+ bits.append(f"\033[{53 if overline else 55}m")
691
+ if italic is not None:
692
+ bits.append(f"\033[{3 if italic else 23}m")
693
+ if blink is not None:
694
+ bits.append(f"\033[{5 if blink else 25}m")
695
+ if reverse is not None:
696
+ bits.append(f"\033[{7 if reverse else 27}m")
697
+ if strikethrough is not None:
698
+ bits.append(f"\033[{9 if strikethrough else 29}m")
699
+ bits.append(text)
700
+ if reset:
701
+ bits.append(_ansi_reset_all)
702
+ return "".join(bits)
703
+
704
+
705
+ def unstyle(text: str) -> str:
706
+ """Removes ANSI styling information from a string. Usually it's not
707
+ necessary to use this function as Click's echo function will
708
+ automatically remove styling if necessary.
709
+
710
+ .. versionadded:: 2.0
711
+
712
+ :param text: the text to remove style information from.
713
+ """
714
+ return strip_ansi(text)
715
+
716
+
717
+ def secho(
718
+ message: t.Any | None = None,
719
+ file: t.IO[t.AnyStr] | None = None,
720
+ nl: bool = True,
721
+ err: bool = False,
722
+ color: bool | None = None,
723
+ **styles: t.Any,
724
+ ) -> None:
725
+ """This function combines :func:`echo` and :func:`style` into one
726
+ call. As such the following two calls are the same::
727
+
728
+ click.secho('Hello World!', fg='green')
729
+ click.echo(click.style('Hello World!', fg='green'))
730
+
731
+ All keyword arguments are forwarded to the underlying functions
732
+ depending on which one they go with.
733
+
734
+ Non-string types will be converted to :class:`str`. However,
735
+ :class:`bytes` are passed directly to :meth:`echo` without applying
736
+ style. If you want to style bytes that represent text, call
737
+ :meth:`bytes.decode` first.
738
+
739
+ .. versionchanged:: 8.0
740
+ A non-string ``message`` is converted to a string. Bytes are
741
+ passed through without style applied.
742
+
743
+ .. versionadded:: 2.0
744
+ """
745
+ if message is not None and not isinstance(message, (bytes, bytearray)):
746
+ message = style(message, **styles)
747
+
748
+ return echo(message, file=file, nl=nl, err=err, color=color)
749
+
750
+
751
+ @t.overload
752
+ def edit(
753
+ text: bytes | bytearray,
754
+ editor: str | None = None,
755
+ env: cabc.Mapping[str, str] | None = None,
756
+ require_save: bool = False,
757
+ extension: str = ".txt",
758
+ ) -> bytes | None: ...
759
+
760
+
761
+ @t.overload
762
+ def edit(
763
+ text: str,
764
+ editor: str | None = None,
765
+ env: cabc.Mapping[str, str] | None = None,
766
+ require_save: bool = True,
767
+ extension: str = ".txt",
768
+ ) -> str | None: ...
769
+
770
+
771
+ @t.overload
772
+ def edit(
773
+ text: None = None,
774
+ editor: str | None = None,
775
+ env: cabc.Mapping[str, str] | None = None,
776
+ require_save: bool = True,
777
+ extension: str = ".txt",
778
+ filename: str | cabc.Iterable[str] | None = None,
779
+ ) -> None: ...
780
+
781
+
782
+ def edit(
783
+ text: str | bytes | bytearray | None = None,
784
+ editor: str | None = None,
785
+ env: cabc.Mapping[str, str] | None = None,
786
+ require_save: bool = True,
787
+ extension: str = ".txt",
788
+ filename: str | cabc.Iterable[str] | None = None,
789
+ ) -> str | bytes | bytearray | None:
790
+ r"""Edits the given text in the defined editor. If an editor is given
791
+ (should be the full path to the executable but the regular operating
792
+ system search path is used for finding the executable) it overrides
793
+ the detected editor. Optionally, some environment variables can be
794
+ used. If the editor is closed without changes, `None` is returned. In
795
+ case a file is edited directly the return value is always `None` and
796
+ `require_save` and `extension` are ignored.
797
+
798
+ If the editor cannot be opened a :exc:`UsageError` is raised.
799
+
800
+ Note for Windows: to simplify cross-platform usage, the newlines are
801
+ automatically converted from POSIX to Windows and vice versa. As such,
802
+ the message here will have ``\n`` as newline markers.
803
+
804
+ :param text: the text to edit.
805
+ :param editor: optionally the editor to use. Defaults to automatic
806
+ detection.
807
+ :param env: environment variables to forward to the editor.
808
+ :param require_save: if this is true, then not saving in the editor
809
+ will make the return value become `None`.
810
+ :param extension: the extension to tell the editor about. This defaults
811
+ to `.txt` but changing this might change syntax
812
+ highlighting.
813
+ :param filename: if provided it will edit this file instead of the
814
+ provided text contents. It will not use a temporary
815
+ file as an indirection in that case. If the editor supports
816
+ editing multiple files at once, a sequence of files may be
817
+ passed as well. Invoke `click.file` once per file instead
818
+ if multiple files cannot be managed at once or editing the
819
+ files serially is desired.
820
+
821
+ .. versionchanged:: 8.2.0
822
+ ``filename`` now accepts any ``Iterable[str]`` in addition to a ``str``
823
+ if the ``editor`` supports editing multiple files at once.
824
+
825
+ """
826
+ from ._termui_impl import Editor
827
+
828
+ ed = Editor(editor=editor, env=env, require_save=require_save, extension=extension)
829
+
830
+ if filename is None:
831
+ return ed.edit(text)
832
+
833
+ if isinstance(filename, str):
834
+ filename = (filename,)
835
+
836
+ ed.edit_files(filenames=filename)
837
+ return None
838
+
839
+
840
+ def launch(url: str, wait: bool = False, locate: bool = False) -> int:
841
+ """This function launches the given URL (or filename) in the default
842
+ viewer application for this file type. If this is an executable, it
843
+ might launch the executable in a new session. The return value is
844
+ the exit code of the launched application. Usually, ``0`` indicates
845
+ success.
846
+
847
+ Examples::
848
+
849
+ click.launch('https://click.palletsprojects.com/')
850
+ click.launch('/my/downloaded/file', locate=True)
851
+
852
+ .. versionadded:: 2.0
853
+
854
+ :param url: URL or filename of the thing to launch.
855
+ :param wait: Wait for the program to exit before returning. This
856
+ only works if the launched program blocks. In particular,
857
+ ``xdg-open`` on Linux does not block.
858
+ :param locate: if this is set to `True` then instead of launching the
859
+ application associated with the URL it will attempt to
860
+ launch a file manager with the file located. This
861
+ might have weird effects if the URL does not point to
862
+ the filesystem.
863
+ """
864
+ from ._termui_impl import open_url
865
+
866
+ return open_url(url, wait=wait, locate=locate)
867
+
868
+
869
+ # If this is provided, getchar() calls into this instead. This is used
870
+ # for unittesting purposes.
871
+ _getchar: t.Callable[[bool], str] | None = None
872
+
873
+
874
+ def getchar(echo: bool = False) -> str:
875
+ """Fetches a single character from the terminal and returns it. This
876
+ will always return a unicode character and under certain rare
877
+ circumstances this might return more than one character. The
878
+ situations which more than one character is returned is when for
879
+ whatever reason multiple characters end up in the terminal buffer or
880
+ standard input was not actually a terminal.
881
+
882
+ Note that this will always read from the terminal, even if something
883
+ is piped into the standard input.
884
+
885
+ Note for Windows: in rare cases when typing non-ASCII characters, this
886
+ function might wait for a second character and then return both at once.
887
+ This is because certain Unicode characters look like special-key markers.
888
+
889
+ .. versionadded:: 2.0
890
+
891
+ :param echo: if set to `True`, the character read will also show up on
892
+ the terminal. The default is to not show it.
893
+ """
894
+ global _getchar
895
+
896
+ if _getchar is None:
897
+ from ._termui_impl import getchar as f
898
+
899
+ _getchar = f
900
+
901
+ return _getchar(echo)
902
+
903
+
904
+ def raw_terminal() -> AbstractContextManager[int]:
905
+ from ._termui_impl import raw_terminal as f
906
+
907
+ return f()
908
+
909
+
910
+ def pause(info: str | None = None, err: bool = False) -> None:
911
+ """This command stops execution and waits for the user to press any
912
+ key to continue. This is similar to the Windows batch "pause"
913
+ command. If the program is not run through a terminal, this command
914
+ will instead do nothing.
915
+
916
+ .. versionadded:: 2.0
917
+
918
+ .. versionadded:: 4.0
919
+ Added the `err` parameter.
920
+
921
+ :param info: The message to print before pausing. Defaults to
922
+ ``"Press any key to continue..."``.
923
+ :param err: if set to message goes to ``stderr`` instead of
924
+ ``stdout``, the same as with echo.
925
+ """
926
+ if not isatty(sys.stdin) or not isatty(sys.stdout):
927
+ return
928
+
929
+ if info is None:
930
+ info = _("Press any key to continue...")
931
+
932
+ try:
933
+ if info:
934
+ echo(info, nl=False, err=err)
935
+ try:
936
+ getchar()
937
+ except (KeyboardInterrupt, EOFError):
938
+ pass
939
+ finally:
940
+ if info:
941
+ echo(err=err)
.venv/lib/python3.11/site-packages/click/testing.py ADDED
@@ -0,0 +1,736 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import contextlib
5
+ import io
6
+ import os
7
+ import pdb
8
+ import shlex
9
+ import sys
10
+ import tempfile
11
+ import typing as t
12
+ from types import TracebackType
13
+
14
+ from . import _compat
15
+ from . import formatting
16
+ from . import termui
17
+ from . import utils
18
+ from ._compat import _find_binary_reader
19
+
20
+ if t.TYPE_CHECKING:
21
+ from _typeshed import ReadableBuffer
22
+
23
+ from .core import Command
24
+
25
+ CaptureMode = t.Literal["sys", "fd"]
26
+
27
+
28
+ class EchoingStdin:
29
+ def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:
30
+ self._input = input
31
+ self._output = output
32
+ self._paused = False
33
+
34
+ def __getattr__(self, x: str) -> t.Any:
35
+ return getattr(self._input, x)
36
+
37
+ def _echo(self, rv: bytes) -> bytes:
38
+ if not self._paused:
39
+ self._output.write(rv)
40
+
41
+ return rv
42
+
43
+ def read(self, n: int = -1) -> bytes:
44
+ return self._echo(self._input.read(n))
45
+
46
+ def read1(self, n: int = -1) -> bytes:
47
+ return self._echo(self._input.read1(n)) # type: ignore
48
+
49
+ def readline(self, n: int = -1) -> bytes:
50
+ return self._echo(self._input.readline(n))
51
+
52
+ def readlines(self) -> list[bytes]:
53
+ return [self._echo(x) for x in self._input.readlines()]
54
+
55
+ def __iter__(self) -> cabc.Iterator[bytes]:
56
+ return iter(self._echo(x) for x in self._input)
57
+
58
+ def __repr__(self) -> str:
59
+ return repr(self._input)
60
+
61
+
62
+ @contextlib.contextmanager
63
+ def _pause_echo(stream: EchoingStdin | None) -> cabc.Iterator[None]:
64
+ if stream is None:
65
+ yield
66
+ else:
67
+ stream._paused = True
68
+ yield
69
+ stream._paused = False
70
+
71
+
72
+ class _FDCapture:
73
+ """Redirect a file descriptor to a temporary file for capture.
74
+
75
+ Saves the current target of *targetfd* via :func:`os.dup`, then
76
+ redirects it to a temporary file via :func:`os.dup2`. On
77
+ :meth:`stop`, restores the original ``fd`` and returns the captured
78
+ bytes. Inspired by Pytest's ``FDCapture``.
79
+
80
+ .. versionadded:: 8.4.0
81
+ """
82
+
83
+ def __init__(self, targetfd: int) -> None:
84
+ self._targetfd = targetfd
85
+ self.saved_fd: int = -1
86
+ self._tmpfile: t.BinaryIO | None = None
87
+
88
+ def start(self) -> None:
89
+ self.saved_fd = os.dup(self._targetfd)
90
+ self._tmpfile = tempfile.TemporaryFile(buffering=0)
91
+ os.dup2(self._tmpfile.fileno(), self._targetfd)
92
+
93
+ def stop(self) -> bytes:
94
+ assert self._tmpfile is not None, "_FDCapture.start() was not called"
95
+ os.dup2(self.saved_fd, self._targetfd)
96
+ os.close(self.saved_fd)
97
+ self.saved_fd = -1
98
+ self._tmpfile.seek(0)
99
+ data = self._tmpfile.read()
100
+ self._tmpfile.close()
101
+ self._tmpfile = None
102
+ return data
103
+
104
+
105
+ class BytesIOCopy(io.BytesIO):
106
+ """Patch ``io.BytesIO`` to let the written stream be copied to another.
107
+
108
+ .. versionadded:: 8.2
109
+ """
110
+
111
+ def __init__(self, copy_to: io.BytesIO) -> None:
112
+ super().__init__()
113
+ self.copy_to = copy_to
114
+
115
+ def flush(self) -> None:
116
+ super().flush()
117
+ self.copy_to.flush()
118
+
119
+ def write(self, b: ReadableBuffer) -> int:
120
+ self.copy_to.write(b)
121
+ return super().write(b)
122
+
123
+
124
+ class StreamMixer:
125
+ """Mixes `<stdout>` and `<stderr>` streams.
126
+
127
+ The result is available in the ``output`` attribute.
128
+
129
+ .. versionadded:: 8.2
130
+ """
131
+
132
+ def __init__(self) -> None:
133
+ self.output: io.BytesIO = io.BytesIO()
134
+ self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)
135
+ self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)
136
+
137
+
138
+ class _NamedTextIOWrapper(io.TextIOWrapper):
139
+ """A :class:`~io.TextIOWrapper` with custom ``name`` and ``mode``
140
+ that does not close its underlying buffer.
141
+
142
+ When ``CliRunner`` runs in ``fd`` mode, ``_original_fd`` is patched to
143
+ point at the saved (pre-redirection) ``fd``, so C-level consumers that call
144
+ :meth:`fileno` (like ``faulthandler`` or ``subprocess``) keep working. In
145
+ the default ``sys`` mode ``_original_fd`` stays at ``-1`` and
146
+ :meth:`fileno` raises :exc:`io.UnsupportedOperation`, matching the
147
+ pre-``8.3.3`` behavior.
148
+ """
149
+
150
+ def __init__(
151
+ self,
152
+ buffer: t.BinaryIO,
153
+ name: str,
154
+ mode: str,
155
+ **kwargs: t.Any,
156
+ ) -> None:
157
+ super().__init__(buffer, **kwargs)
158
+ self._name = name
159
+ self._mode = mode
160
+ self._original_fd: int = -1
161
+
162
+ def close(self) -> None:
163
+ """The buffer this object contains belongs to some other object,
164
+ so prevent the default ``__del__`` implementation from closing
165
+ that buffer.
166
+
167
+ .. versionadded:: 8.3.2
168
+ """
169
+
170
+ def fileno(self) -> int:
171
+ """Return the file descriptor of the saved original stream when
172
+ ``CliRunner`` runs in ``fd`` mode. Otherwise delegate to
173
+ :class:`~io.TextIOWrapper`, which raises
174
+ :exc:`io.UnsupportedOperation` for a ``BytesIO``-backed buffer.
175
+ """
176
+ if self._original_fd >= 0:
177
+ return self._original_fd
178
+ return super().fileno()
179
+
180
+ @property
181
+ def name(self) -> str:
182
+ return self._name
183
+
184
+ @property
185
+ def mode(self) -> str:
186
+ return self._mode
187
+
188
+
189
+ def make_input_stream(
190
+ input: str | bytes | t.IO[t.Any] | None, charset: str
191
+ ) -> t.BinaryIO:
192
+ # Is already an input stream.
193
+ if hasattr(input, "read"):
194
+ rv = _find_binary_reader(t.cast("t.IO[t.Any]", input))
195
+
196
+ if rv is not None:
197
+ return rv
198
+
199
+ raise TypeError("Could not find binary reader for input stream.")
200
+
201
+ if input is None:
202
+ input = b""
203
+ elif isinstance(input, str):
204
+ input = input.encode(charset)
205
+
206
+ return io.BytesIO(input)
207
+
208
+
209
+ class Result:
210
+ """Holds the captured result of an invoked CLI script.
211
+
212
+ :param runner: The runner that created the result
213
+ :param stdout_bytes: The standard output as bytes.
214
+ :param stderr_bytes: The standard error as bytes.
215
+ :param output_bytes: A mix of ``stdout_bytes`` and ``stderr_bytes``, as the
216
+ user would see it in its terminal.
217
+ :param return_value: The value returned from the invoked command.
218
+ :param exit_code: The exit code as integer.
219
+ :param exception: The exception that happened if one did.
220
+ :param exc_info: Exception information (exception type, exception instance,
221
+ traceback type).
222
+
223
+ .. versionchanged:: 8.2
224
+ ``stderr_bytes`` no longer optional, ``output_bytes`` introduced and
225
+ ``mix_stderr`` has been removed.
226
+
227
+ .. versionadded:: 8.0
228
+ Added ``return_value``.
229
+ """
230
+
231
+ def __init__(
232
+ self,
233
+ runner: CliRunner,
234
+ stdout_bytes: bytes,
235
+ stderr_bytes: bytes,
236
+ output_bytes: bytes,
237
+ return_value: t.Any,
238
+ exit_code: int,
239
+ exception: BaseException | None,
240
+ exc_info: tuple[type[BaseException], BaseException, TracebackType]
241
+ | None = None,
242
+ ):
243
+ self.runner = runner
244
+ self.stdout_bytes = stdout_bytes
245
+ self.stderr_bytes = stderr_bytes
246
+ self.output_bytes = output_bytes
247
+ self.return_value = return_value
248
+ self.exit_code = exit_code
249
+ self.exception = exception
250
+ self.exc_info = exc_info
251
+
252
+ @property
253
+ def output(self) -> str:
254
+ """The terminal output as unicode string, as the user would see it.
255
+
256
+ .. versionchanged:: 8.2
257
+ No longer a proxy for ``self.stdout``. Now has its own independent stream
258
+ that is mixing `<stdout>` and `<stderr>`, in the order they were written.
259
+ """
260
+ return self.output_bytes.decode(self.runner.charset, "replace").replace(
261
+ "\r\n", "\n"
262
+ )
263
+
264
+ @property
265
+ def stdout(self) -> str:
266
+ """The standard output as unicode string."""
267
+ return self.stdout_bytes.decode(self.runner.charset, "replace").replace(
268
+ "\r\n", "\n"
269
+ )
270
+
271
+ @property
272
+ def stderr(self) -> str:
273
+ """The standard error as unicode string.
274
+
275
+ .. versionchanged:: 8.2
276
+ No longer raise an exception, always returns the `<stderr>` string.
277
+ """
278
+ return self.stderr_bytes.decode(self.runner.charset, "replace").replace(
279
+ "\r\n", "\n"
280
+ )
281
+
282
+ def __repr__(self) -> str:
283
+ exc_str = repr(self.exception) if self.exception else "okay"
284
+ return f"<{type(self).__name__} {exc_str}>"
285
+
286
+
287
+ class CliRunner:
288
+ """The CLI runner provides functionality to invoke a Click command line
289
+ script for unittesting purposes in a isolated environment. This only
290
+ works in single-threaded systems without any concurrency as it changes the
291
+ global interpreter state.
292
+
293
+ :param charset: the character set for the input and output data.
294
+ :param env: a dictionary with environment variables for overriding.
295
+ :param echo_stdin: if this is set to `True`, then reading from `<stdin>` writes
296
+ to `<stdout>`. This is useful for showing examples in
297
+ some circumstances. Note that regular prompts
298
+ will automatically echo the input.
299
+ :param catch_exceptions: Whether to catch any exceptions other than
300
+ ``SystemExit`` when running :meth:`~CliRunner.invoke`.
301
+ :param capture: Selects the output capture strategy. ``sys`` (default)
302
+ captures Python-level writes only and leaves
303
+ :meth:`sys.stdout.fileno` raising :exc:`io.UnsupportedOperation`, so
304
+ user code that calls :func:`os.dup2` on ``sys.stdout.fileno()`` cannot
305
+ clobber the host runner's stdout. ``fd`` redirects file descriptors
306
+ ``1`` and ``2`` via :func:`os.dup2` to a temporary file, also catching
307
+ output from stale stream references, C extensions, and subprocesses.
308
+ ``fd`` is not supported on Windows.
309
+
310
+ .. versionchanged:: 8.4.0
311
+ Added the ``capture`` parameter. The default ``sys`` mode no longer
312
+ exposes the original fd through :meth:`fileno`, reverting the change
313
+ introduced in ``8.3.3`` that broke Pytest's ``fd``-level capture
314
+ teardown. Use ``capture="fd"`` to restore that behavior with proper
315
+ isolation. :issue:`3384`
316
+
317
+ .. versionchanged:: 8.2
318
+ Added the ``catch_exceptions`` parameter.
319
+
320
+ .. versionchanged:: 8.2
321
+ ``mix_stderr`` parameter has been removed.
322
+ """
323
+
324
+ def __init__(
325
+ self,
326
+ charset: str = "utf-8",
327
+ env: cabc.Mapping[str, str | None] | None = None,
328
+ echo_stdin: bool = False,
329
+ catch_exceptions: bool = True,
330
+ capture: CaptureMode = "sys",
331
+ ) -> None:
332
+ if capture not in {"sys", "fd"}:
333
+ raise ValueError(
334
+ f"capture={capture!r} is not valid. Choose from 'sys' or 'fd'."
335
+ )
336
+ if capture == "fd" and sys.platform == "win32":
337
+ raise ValueError(
338
+ f"capture={capture!r} is not supported on Windows. Use 'sys'."
339
+ )
340
+ self.charset = charset
341
+ self.env: cabc.Mapping[str, str | None] = env or {}
342
+ self.echo_stdin = echo_stdin
343
+ self.catch_exceptions = catch_exceptions
344
+ self.capture: CaptureMode = capture
345
+
346
+ def get_default_prog_name(self, cli: Command) -> str:
347
+ """Given a command object it will return the default program name
348
+ for it. The default is the `name` attribute or ``"root"`` if not
349
+ set.
350
+ """
351
+ return cli.name or "root"
352
+
353
+ def make_env(
354
+ self, overrides: cabc.Mapping[str, str | None] | None = None
355
+ ) -> cabc.Mapping[str, str | None]:
356
+ """Returns the environment overrides for invoking a script."""
357
+ rv = dict(self.env)
358
+ if overrides:
359
+ rv.update(overrides)
360
+ return rv
361
+
362
+ @contextlib.contextmanager
363
+ def isolation(
364
+ self,
365
+ input: str | bytes | t.IO[t.Any] | None = None,
366
+ env: cabc.Mapping[str, str | None] | None = None,
367
+ color: bool = False,
368
+ ) -> cabc.Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]:
369
+ """A context manager that sets up the isolation for invoking of a
370
+ command line tool. This sets up `<stdin>` with the given input data
371
+ and `os.environ` with the overrides from the given dictionary.
372
+ This also rebinds some internals in Click to be mocked (like the
373
+ prompt functionality).
374
+
375
+ This is automatically done in the :meth:`invoke` method.
376
+
377
+ :param input: the input stream to put into `sys.stdin`.
378
+ :param env: the environment overrides as dictionary.
379
+ :param color: whether the output should contain color codes. The
380
+ application can still override this explicitly.
381
+
382
+ .. versionadded:: 8.2
383
+ An additional output stream is returned, which is a mix of
384
+ `<stdout>` and `<stderr>` streams.
385
+
386
+ .. versionchanged:: 8.2
387
+ Always returns the `<stderr>` stream.
388
+
389
+ .. versionchanged:: 8.0
390
+ `<stderr>` is opened with ``errors="backslashreplace"``
391
+ instead of the default ``"strict"``.
392
+
393
+ .. versionchanged:: 4.0
394
+ Added the ``color`` parameter.
395
+ """
396
+ bytes_input = make_input_stream(input, self.charset)
397
+ echo_input = None
398
+
399
+ old_stdin = sys.stdin
400
+ old_stdout = sys.stdout
401
+ old_stderr = sys.stderr
402
+ old_forced_width = formatting.FORCED_WIDTH
403
+ formatting.FORCED_WIDTH = 80
404
+
405
+ env = self.make_env(env)
406
+
407
+ stream_mixer = StreamMixer()
408
+
409
+ if self.echo_stdin:
410
+ bytes_input = echo_input = t.cast(
411
+ t.BinaryIO, EchoingStdin(bytes_input, stream_mixer.stdout)
412
+ )
413
+
414
+ sys.stdin = text_input = _NamedTextIOWrapper(
415
+ bytes_input, encoding=self.charset, name="<stdin>", mode="r"
416
+ )
417
+
418
+ if self.echo_stdin:
419
+ # Force unbuffered reads, otherwise TextIOWrapper reads a
420
+ # large chunk which is echoed early.
421
+ text_input._CHUNK_SIZE = 1 # type: ignore
422
+
423
+ sys.stdout = _NamedTextIOWrapper(
424
+ stream_mixer.stdout,
425
+ encoding=self.charset,
426
+ name="<stdout>",
427
+ mode="w",
428
+ )
429
+
430
+ sys.stderr = _NamedTextIOWrapper(
431
+ stream_mixer.stderr,
432
+ encoding=self.charset,
433
+ name="<stderr>",
434
+ mode="w",
435
+ errors="backslashreplace",
436
+ )
437
+
438
+ @_pause_echo(echo_input) # type: ignore
439
+ def visible_input(prompt: str | None = None) -> str:
440
+ sys.stdout.write(prompt or "")
441
+ try:
442
+ val = next(text_input).rstrip("\r\n")
443
+ except StopIteration as e:
444
+ raise EOFError() from e
445
+ sys.stdout.write(f"{val}\n")
446
+ sys.stdout.flush()
447
+ return val
448
+
449
+ @_pause_echo(echo_input) # type: ignore
450
+ def hidden_input(prompt: str | None = None) -> str:
451
+ sys.stdout.write(f"{prompt or ''}\n")
452
+ sys.stdout.flush()
453
+ try:
454
+ return next(text_input).rstrip("\r\n")
455
+ except StopIteration as e:
456
+ raise EOFError() from e
457
+
458
+ @_pause_echo(echo_input) # type: ignore
459
+ def _getchar(echo: bool) -> str:
460
+ char = sys.stdin.read(1)
461
+
462
+ if echo:
463
+ sys.stdout.write(char)
464
+
465
+ sys.stdout.flush()
466
+ return char
467
+
468
+ default_color = color
469
+
470
+ def should_strip_ansi(
471
+ stream: t.IO[t.Any] | None = None, color: bool | None = None
472
+ ) -> bool:
473
+ if color is None:
474
+ return not default_color
475
+ return not color
476
+
477
+ old_visible_prompt_func = termui.visible_prompt_func
478
+ old_hidden_prompt_func = termui.hidden_prompt_func
479
+ old__getchar_func = termui._getchar
480
+ old_should_strip_ansi = utils.should_strip_ansi # type: ignore
481
+ old__compat_should_strip_ansi = _compat.should_strip_ansi
482
+ old_pdb_init = pdb.Pdb.__init__
483
+ termui.visible_prompt_func = visible_input
484
+ termui.hidden_prompt_func = hidden_input
485
+ termui._getchar = _getchar
486
+ utils.should_strip_ansi = should_strip_ansi # type: ignore
487
+ _compat.should_strip_ansi = should_strip_ansi
488
+
489
+ def _patched_pdb_init(
490
+ self: pdb.Pdb,
491
+ completekey: str = "tab",
492
+ stdin: t.IO[str] | None = None,
493
+ stdout: t.IO[str] | None = None,
494
+ **kwargs: t.Any,
495
+ ) -> None:
496
+ """Default ``pdb.Pdb`` to real terminal streams during
497
+ ``CliRunner`` isolation.
498
+
499
+ Without this patch, ``pdb.Pdb.__init__`` inherits from
500
+ ``cmd.Cmd`` which falls back to ``sys.stdin``/``sys.stdout``
501
+ when no explicit streams are provided. During isolation
502
+ those are ``BytesIO``-backed wrappers, so the debugger
503
+ reads from an empty buffer and writes to captured output,
504
+ making interactive debugging impossible.
505
+
506
+ By defaulting to ``sys.__stdin__``/``sys.__stdout__`` (the
507
+ original terminal streams Python preserves regardless of
508
+ redirection), debuggers can interact with the user while
509
+ ``click.echo`` output is still captured normally.
510
+
511
+ This covers ``pdb.set_trace()``, ``breakpoint()``,
512
+ ``pdb.post_mortem()``, and debuggers that subclass
513
+ ``pdb.Pdb`` (ipdb, pdbpp). Explicit ``stdin``/``stdout``
514
+ arguments are honored and not overridden. Debuggers that
515
+ do not subclass ``pdb.Pdb`` (pudb, debugpy) are not
516
+ covered.
517
+ """
518
+ if stdin is None:
519
+ stdin = sys.__stdin__
520
+ if stdout is None:
521
+ stdout = sys.__stdout__
522
+ old_pdb_init(
523
+ self, completekey=completekey, stdin=stdin, stdout=stdout, **kwargs
524
+ )
525
+
526
+ pdb.Pdb.__init__ = _patched_pdb_init # type: ignore[assignment]
527
+
528
+ old_env = {}
529
+ try:
530
+ for key, value in env.items():
531
+ old_env[key] = os.environ.get(key)
532
+ if value is None:
533
+ try:
534
+ del os.environ[key]
535
+ except Exception:
536
+ pass
537
+ else:
538
+ os.environ[key] = value
539
+ yield (stream_mixer.stdout, stream_mixer.stderr, stream_mixer.output)
540
+ finally:
541
+ for key, value in old_env.items():
542
+ if value is None:
543
+ try:
544
+ del os.environ[key]
545
+ except Exception:
546
+ pass
547
+ else:
548
+ os.environ[key] = value
549
+ sys.stdout = old_stdout
550
+ sys.stderr = old_stderr
551
+ sys.stdin = old_stdin
552
+ termui.visible_prompt_func = old_visible_prompt_func
553
+ termui.hidden_prompt_func = old_hidden_prompt_func
554
+ termui._getchar = old__getchar_func
555
+ utils.should_strip_ansi = old_should_strip_ansi # type: ignore
556
+ _compat.should_strip_ansi = old__compat_should_strip_ansi
557
+ formatting.FORCED_WIDTH = old_forced_width
558
+ pdb.Pdb.__init__ = old_pdb_init # type: ignore[method-assign]
559
+
560
+ def invoke(
561
+ self,
562
+ cli: Command,
563
+ args: str | cabc.Sequence[str] | None = None,
564
+ input: str | bytes | t.IO[t.Any] | None = None,
565
+ env: cabc.Mapping[str, str | None] | None = None,
566
+ catch_exceptions: bool | None = None,
567
+ color: bool = False,
568
+ **extra: t.Any,
569
+ ) -> Result:
570
+ """Invokes a command in an isolated environment. The arguments are
571
+ forwarded directly to the command line script, the `extra` keyword
572
+ arguments are passed to the :meth:`~clickpkg.Command.main` function of
573
+ the command.
574
+
575
+ This returns a :class:`Result` object.
576
+
577
+ :param cli: the command to invoke
578
+ :param args: the arguments to invoke. It may be given as an iterable
579
+ or a string. When given as string it will be interpreted
580
+ as a Unix shell command. More details at
581
+ :func:`shlex.split`.
582
+ :param input: the input data for `sys.stdin`.
583
+ :param env: the environment overrides.
584
+ :param catch_exceptions: Whether to catch any other exceptions than
585
+ ``SystemExit``. If :data:`None`, the value
586
+ from :class:`CliRunner` is used.
587
+ :param extra: the keyword arguments to pass to :meth:`main`.
588
+ :param color: whether the output should contain color codes. The
589
+ application can still override this explicitly.
590
+
591
+ .. versionadded:: 8.2
592
+ The result object has the ``output_bytes`` attribute with
593
+ the mix of ``stdout_bytes`` and ``stderr_bytes``, as the user would
594
+ see it in its terminal.
595
+
596
+ .. versionchanged:: 8.2
597
+ The result object always returns the ``stderr_bytes`` stream.
598
+
599
+ .. versionchanged:: 8.0
600
+ The result object has the ``return_value`` attribute with
601
+ the value returned from the invoked command.
602
+
603
+ .. versionchanged:: 4.0
604
+ Added the ``color`` parameter.
605
+
606
+ .. versionchanged:: 3.0
607
+ Added the ``catch_exceptions`` parameter.
608
+
609
+ .. versionchanged:: 3.0
610
+ The result object has the ``exc_info`` attribute with the
611
+ traceback if available.
612
+ """
613
+ exc_info = None
614
+ if catch_exceptions is None:
615
+ catch_exceptions = self.catch_exceptions
616
+
617
+ # Set up fd capture before isolation replaces sys.stdout and sys.stderr.
618
+ cap_out: _FDCapture | None = None
619
+ cap_err: _FDCapture | None = None
620
+
621
+ if self.capture == "fd":
622
+ cap_out = _FDCapture(1)
623
+ cap_err = _FDCapture(2)
624
+ try:
625
+ cap_out.start()
626
+ cap_err.start()
627
+ except OSError:
628
+ cap_out = cap_err = None
629
+
630
+ with self.isolation(input=input, env=env, color=color) as outstreams:
631
+ # Point the captured streams' fileno() at the saved (original)
632
+ # fd so that C-level consumers like faulthandler keep working
633
+ # while fd 1/2 are redirected to the capture tmpfile.
634
+ if cap_out is not None and cap_err is not None:
635
+ sys.stdout._original_fd = cap_out.saved_fd # type: ignore[union-attr]
636
+ sys.stderr._original_fd = cap_err.saved_fd # type: ignore[union-attr]
637
+
638
+ return_value = None
639
+ exception: BaseException | None = None
640
+ exit_code = 0
641
+
642
+ if isinstance(args, str):
643
+ args = shlex.split(args)
644
+
645
+ try:
646
+ prog_name = extra.pop("prog_name")
647
+ except KeyError:
648
+ prog_name = self.get_default_prog_name(cli)
649
+
650
+ try:
651
+ return_value = cli.main(args=args or (), prog_name=prog_name, **extra)
652
+ except SystemExit as e:
653
+ exc_info = sys.exc_info()
654
+ e_code = t.cast("int | t.Any | None", e.code)
655
+
656
+ if e_code is None:
657
+ e_code = 0
658
+
659
+ if e_code != 0:
660
+ exception = e
661
+
662
+ if not isinstance(e_code, int):
663
+ sys.stdout.write(str(e_code))
664
+ sys.stdout.write("\n")
665
+ e_code = 1
666
+
667
+ exit_code = e_code
668
+
669
+ except Exception as e:
670
+ if not catch_exceptions:
671
+ raise
672
+ exception = e
673
+ exit_code = 1
674
+ exc_info = sys.exc_info()
675
+ finally:
676
+ sys.stdout.flush()
677
+ sys.stderr.flush()
678
+
679
+ # Stop fd capture and merge the captured bytes into
680
+ # the stdout/stderr BytesIO streams. BytesIOCopy mirrors
681
+ # those writes into outstreams[2] automatically.
682
+ if cap_out is not None and cap_err is not None:
683
+ fd_out = cap_out.stop()
684
+ fd_err = cap_err.stop()
685
+ if fd_out:
686
+ outstreams[0].write(fd_out)
687
+ if fd_err:
688
+ outstreams[1].write(fd_err)
689
+
690
+ stdout = outstreams[0].getvalue()
691
+ stderr = outstreams[1].getvalue()
692
+ output = outstreams[2].getvalue()
693
+
694
+ return Result(
695
+ runner=self,
696
+ stdout_bytes=stdout,
697
+ stderr_bytes=stderr,
698
+ output_bytes=output,
699
+ return_value=return_value,
700
+ exit_code=exit_code,
701
+ exception=exception,
702
+ exc_info=exc_info, # type: ignore
703
+ )
704
+
705
+ @contextlib.contextmanager
706
+ def isolated_filesystem(
707
+ self, temp_dir: str | os.PathLike[str] | None = None
708
+ ) -> cabc.Iterator[str]:
709
+ """A context manager that creates a temporary directory and
710
+ changes the current working directory to it. This isolates tests
711
+ that affect the contents of the CWD to prevent them from
712
+ interfering with each other.
713
+
714
+ :param temp_dir: Create the temporary directory under this
715
+ directory. If given, the created directory is not removed
716
+ when exiting.
717
+
718
+ .. versionchanged:: 8.0
719
+ Added the ``temp_dir`` parameter.
720
+ """
721
+ cwd = os.getcwd()
722
+ dt = tempfile.mkdtemp(dir=temp_dir)
723
+ os.chdir(dt)
724
+
725
+ try:
726
+ yield dt
727
+ finally:
728
+ os.chdir(cwd)
729
+
730
+ if temp_dir is None:
731
+ import shutil
732
+
733
+ try:
734
+ shutil.rmtree(dt)
735
+ except OSError:
736
+ pass
.venv/lib/python3.11/site-packages/click/types.py ADDED
@@ -0,0 +1,1309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import abc
4
+ import collections.abc as cabc
5
+ import enum
6
+ import os
7
+ import stat
8
+ import sys
9
+ import typing as t
10
+ import uuid
11
+ from datetime import datetime
12
+ from gettext import gettext as _
13
+ from gettext import ngettext
14
+
15
+ from ._compat import _get_argv_encoding
16
+ from ._compat import open_stream
17
+ from .exceptions import BadParameter
18
+ from .utils import format_filename
19
+ from .utils import LazyFile
20
+ from .utils import safecall
21
+
22
+ if t.TYPE_CHECKING:
23
+ import typing_extensions as te
24
+
25
+ from .core import Context
26
+ from .core import Parameter
27
+ from .shell_completion import CompletionItem
28
+
29
+ ParamTypeValue = t.TypeVar("ParamTypeValue")
30
+
31
+
32
+ class ParamTypeInfoDict(t.TypedDict):
33
+ param_type: str
34
+ name: str
35
+
36
+
37
+ class ParamType(t.Generic[ParamTypeValue], abc.ABC):
38
+ """Represents the type of a parameter. Validates and converts values
39
+ from the command line or Python into the correct type.
40
+
41
+ To implement a custom type, subclass and implement at least the
42
+ following:
43
+
44
+ - The :attr:`name` class attribute must be set.
45
+ - Calling an instance of the type with ``None`` must return
46
+ ``None``. This is already implemented by default.
47
+ - :meth:`convert` must convert string values to the correct type.
48
+ - :meth:`convert` must accept values that are already the correct
49
+ type.
50
+ - It must be able to convert a value if the ``ctx`` and ``param``
51
+ arguments are ``None``. This can occur when converting prompt
52
+ input.
53
+
54
+ .. versionchanged:: 8.4.0
55
+ Now a generic abstract base class. Parameterize with the
56
+ converted value type (``ParamType[int]`` for an integer-returning
57
+ type) so that :meth:`convert` and downstream consumers carry the
58
+ narrowed return type.
59
+ """
60
+
61
+ is_composite: t.ClassVar[bool] = False
62
+ arity: t.ClassVar[int] = 1
63
+
64
+ #: the descriptive name of this type
65
+ name: str
66
+
67
+ #: if a list of this type is expected and the value is pulled from a
68
+ #: string environment variable, this is what splits it up. `None`
69
+ #: means any whitespace. For all parameters the general rule is that
70
+ #: whitespace splits them up. The exception are paths and files which
71
+ #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on
72
+ #: Windows).
73
+ envvar_list_splitter: t.ClassVar[str | None] = None
74
+
75
+ def to_info_dict(self) -> ParamTypeInfoDict:
76
+ """Gather information that could be useful for a tool generating
77
+ user-facing documentation.
78
+
79
+ Use :meth:`click.Context.to_info_dict` to traverse the entire
80
+ CLI structure.
81
+
82
+ .. versionadded:: 8.0
83
+ """
84
+ # The class name without the "ParamType" suffix.
85
+ param_type = type(self).__name__.partition("ParamType")[0]
86
+ param_type = param_type.partition("ParameterType")[0]
87
+
88
+ # Custom subclasses might not remember to set a name.
89
+ if hasattr(self, "name"):
90
+ name = self.name
91
+ else:
92
+ name = param_type
93
+
94
+ return {"param_type": param_type, "name": name}
95
+
96
+ def __call__(
97
+ self,
98
+ value: t.Any,
99
+ param: Parameter | None = None,
100
+ ctx: Context | None = None,
101
+ ) -> ParamTypeValue | None:
102
+ if value is not None:
103
+ return self.convert(value, param, ctx)
104
+ return None
105
+
106
+ def get_metavar(self, param: Parameter, ctx: Context) -> str | None:
107
+ """Returns the metavar default for this param if it provides one."""
108
+
109
+ def get_missing_message(self, param: Parameter, ctx: Context | None) -> str | None:
110
+ """Optionally might return extra information about a missing
111
+ parameter.
112
+
113
+ .. versionadded:: 2.0
114
+ """
115
+
116
+ def convert(
117
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
118
+ ) -> ParamTypeValue:
119
+ """Convert the value to the correct type. This is not called if
120
+ the value is ``None`` (the missing value).
121
+
122
+ This must accept string values from the command line, as well as
123
+ values that are already the correct type. It may also convert
124
+ other compatible types.
125
+
126
+ The ``param`` and ``ctx`` arguments may be ``None`` in certain
127
+ situations, such as when converting prompt input.
128
+
129
+ If the value cannot be converted, call :meth:`fail` with a
130
+ descriptive message.
131
+
132
+ :param value: The value to convert.
133
+ :param param: The parameter that is using this type to convert
134
+ its value. May be ``None``.
135
+ :param ctx: The current context that arrived at this value. May
136
+ be ``None``.
137
+ """
138
+ # The default returns the value as-is so subclasses that only customize
139
+ # metadata are not forced to redeclare ``convert``.
140
+ return t.cast("ParamTypeValue", value)
141
+
142
+ def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:
143
+ """Given a value from an environment variable this splits it up
144
+ into small chunks depending on the defined envvar list splitter.
145
+
146
+ If the splitter is set to `None`, which means that whitespace splits,
147
+ then leading and trailing whitespace is ignored. Otherwise, leading
148
+ and trailing splitters usually lead to empty items being included.
149
+ """
150
+ return (rv or "").split(self.envvar_list_splitter)
151
+
152
+ def fail(
153
+ self,
154
+ message: str,
155
+ param: Parameter | None = None,
156
+ ctx: Context | None = None,
157
+ ) -> t.NoReturn:
158
+ """Helper method to fail with an invalid value message."""
159
+ raise BadParameter(message, ctx=ctx, param=param)
160
+
161
+ def shell_complete(
162
+ self, ctx: Context, param: Parameter, incomplete: str
163
+ ) -> list[CompletionItem]:
164
+ """Return a list of
165
+ :class:`~click.shell_completion.CompletionItem` objects for the
166
+ incomplete value. Most types do not provide completions, but
167
+ some do, and this allows custom types to provide custom
168
+ completions as well.
169
+
170
+ :param ctx: Invocation context for this command.
171
+ :param param: The parameter that is requesting completion.
172
+ :param incomplete: Value being completed. May be empty.
173
+
174
+ .. versionadded:: 8.0
175
+ """
176
+ return []
177
+
178
+
179
+ class CompositeParamType(ParamType[ParamTypeValue]):
180
+ is_composite = True
181
+
182
+ @property
183
+ @abc.abstractmethod
184
+ def arity(self) -> int: ... # type: ignore[override]
185
+
186
+
187
+ class FuncParamTypeInfoDict(ParamTypeInfoDict):
188
+ func: t.Callable[[t.Any], t.Any]
189
+
190
+
191
+ class FuncParamType(ParamType[ParamTypeValue]):
192
+ def __init__(self, func: t.Callable[[t.Any], ParamTypeValue]) -> None:
193
+ self.name: str = func.__name__
194
+ self.func = func
195
+
196
+ def to_info_dict(self) -> FuncParamTypeInfoDict:
197
+ return {"func": self.func, **super().to_info_dict()}
198
+
199
+ def convert(
200
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
201
+ ) -> ParamTypeValue:
202
+ try:
203
+ return self.func(value)
204
+ except ValueError as exc:
205
+ message = str(exc)
206
+
207
+ if not message:
208
+ try:
209
+ message = str(value)
210
+ except UnicodeError:
211
+ message = value.decode("utf-8", "replace")
212
+
213
+ self.fail(message, param, ctx)
214
+
215
+
216
+ class UnprocessedParamType(ParamType[t.Any]):
217
+ name = "text"
218
+
219
+ def convert(
220
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
221
+ ) -> t.Any:
222
+ return value
223
+
224
+ def __repr__(self) -> str:
225
+ return "UNPROCESSED"
226
+
227
+
228
+ class StringParamType(ParamType[str]):
229
+ name = "text"
230
+
231
+ def convert(
232
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
233
+ ) -> str:
234
+ if isinstance(value, bytes):
235
+ enc = _get_argv_encoding()
236
+ try:
237
+ value = value.decode(enc)
238
+ except UnicodeError:
239
+ fs_enc = sys.getfilesystemencoding()
240
+ if fs_enc != enc:
241
+ try:
242
+ value = value.decode(fs_enc)
243
+ except UnicodeError:
244
+ value = value.decode("utf-8", "replace")
245
+ else:
246
+ value = value.decode("utf-8", "replace")
247
+ return value # type: ignore[no-any-return]
248
+ return str(value)
249
+
250
+ def __repr__(self) -> str:
251
+ return "STRING"
252
+
253
+
254
+ class ChoiceInfoDict(ParamTypeInfoDict):
255
+ choices: cabc.Sequence[t.Any]
256
+ case_sensitive: bool
257
+
258
+
259
+ class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):
260
+ """The choice type allows a value to be checked against a fixed set
261
+ of supported values.
262
+
263
+ You may pass any iterable value which will be converted to a tuple
264
+ and thus will only be iterated once.
265
+
266
+ The resulting value will always be one of the originally passed choices.
267
+ See :meth:`normalize_choice` for more info on the mapping of strings
268
+ to choices. See :ref:`choice-opts` for an example.
269
+
270
+ :param case_sensitive: Set to false to make choices case
271
+ insensitive. Defaults to true.
272
+
273
+ .. versionchanged:: 8.4.0
274
+ Now generic in the choice value type. Parameterize with the type of
275
+ the choice values (``Choice[HashType]`` for an enum, ``Choice[str]``
276
+ for plain strings) to enable type-checked consumers.
277
+
278
+ .. versionchanged:: 8.2.0
279
+ Non-``str`` ``choices`` are now supported. It can additionally be any
280
+ iterable. Before you were not recommended to pass anything but a list or
281
+ tuple.
282
+
283
+ .. versionadded:: 8.2.0
284
+ Choice normalization can be overridden via :meth:`normalize_choice`.
285
+ """
286
+
287
+ name = "choice"
288
+
289
+ def __init__(
290
+ self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True
291
+ ) -> None:
292
+ self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)
293
+ self.case_sensitive = case_sensitive
294
+
295
+ def to_info_dict(self) -> ChoiceInfoDict:
296
+ return {
297
+ "choices": self.choices,
298
+ "case_sensitive": self.case_sensitive,
299
+ **super().to_info_dict(),
300
+ }
301
+
302
+ def _normalized_mapping(
303
+ self, ctx: Context | None = None
304
+ ) -> cabc.Mapping[ParamTypeValue, str]:
305
+ """
306
+ Returns mapping where keys are the original choices and the values are
307
+ the normalized values that are accepted via the command line.
308
+
309
+ This is a simple wrapper around :meth:`normalize_choice`, use that
310
+ instead which is supported.
311
+ """
312
+ return {
313
+ choice: self.normalize_choice(
314
+ choice=choice,
315
+ ctx=ctx,
316
+ )
317
+ for choice in self.choices
318
+ }
319
+
320
+ def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:
321
+ """
322
+ Normalize a choice value, used to map a passed string to a choice.
323
+ Each choice must have a unique normalized value.
324
+
325
+ By default uses :meth:`Context.token_normalize_func` and if not case
326
+ sensitive, convert it to a casefolded value.
327
+
328
+ .. versionadded:: 8.2.0
329
+ """
330
+ normed_value = choice.name if isinstance(choice, enum.Enum) else str(choice)
331
+
332
+ if ctx is not None and ctx.token_normalize_func is not None:
333
+ normed_value = ctx.token_normalize_func(normed_value)
334
+
335
+ if not self.case_sensitive:
336
+ normed_value = normed_value.casefold()
337
+
338
+ return normed_value
339
+
340
+ def get_metavar(self, param: Parameter, ctx: Context) -> str | None:
341
+ if param.param_type_name == "option" and not param.show_choices: # type: ignore
342
+ choice_metavars = [
343
+ convert_type(type(choice)).name.upper() for choice in self.choices
344
+ ]
345
+ choices_str = "|".join([*dict.fromkeys(choice_metavars)])
346
+ else:
347
+ choices_str = "|".join(
348
+ [str(i) for i in self._normalized_mapping(ctx=ctx).values()]
349
+ )
350
+
351
+ # Use curly braces to indicate a required argument.
352
+ if param.required and param.param_type_name == "argument":
353
+ return f"{{{choices_str}}}"
354
+
355
+ # Use square braces to indicate an option or optional argument.
356
+ return f"[{choices_str}]"
357
+
358
+ def get_missing_message(self, param: Parameter, ctx: Context | None) -> str:
359
+ """
360
+ Message shown when no choice is passed.
361
+
362
+ .. versionchanged:: 8.2.0 Added ``ctx`` argument.
363
+ """
364
+ return _("Choose from:\n\t{choices}").format(
365
+ choices=",\n\t".join(self._normalized_mapping(ctx=ctx).values())
366
+ )
367
+
368
+ def convert(
369
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
370
+ ) -> ParamTypeValue:
371
+ """
372
+ For a given value from the parser, normalize it and find its
373
+ matching normalized value in the list of choices. Then return the
374
+ matched "original" choice.
375
+ """
376
+ normed_value = self.normalize_choice(choice=value, ctx=ctx)
377
+ normalized_mapping = self._normalized_mapping(ctx=ctx)
378
+
379
+ try:
380
+ return next(
381
+ original
382
+ for original, normalized in normalized_mapping.items()
383
+ if normalized == normed_value
384
+ )
385
+ except StopIteration:
386
+ self.fail(
387
+ self.get_invalid_choice_message(value=value, ctx=ctx),
388
+ param=param,
389
+ ctx=ctx,
390
+ )
391
+
392
+ def get_invalid_choice_message(self, value: t.Any, ctx: Context | None) -> str:
393
+ """Get the error message when the given choice is invalid.
394
+
395
+ :param value: The invalid value.
396
+
397
+ .. versionadded:: 8.2
398
+ """
399
+ choices_str = ", ".join(map(repr, self._normalized_mapping(ctx=ctx).values()))
400
+ return ngettext(
401
+ "{value!r} is not {choice}.",
402
+ "{value!r} is not one of {choices}.",
403
+ len(self.choices),
404
+ ).format(value=value, choice=choices_str, choices=choices_str)
405
+
406
+ def __repr__(self) -> str:
407
+ return _("Choice({choices})").format(choices=list(self.choices))
408
+
409
+ def shell_complete(
410
+ self, ctx: Context, param: Parameter, incomplete: str
411
+ ) -> list[CompletionItem]:
412
+ """Complete choices that start with the incomplete value.
413
+
414
+ :param ctx: Invocation context for this command.
415
+ :param param: The parameter that is requesting completion.
416
+ :param incomplete: Value being completed. May be empty.
417
+
418
+ .. versionadded:: 8.0
419
+ """
420
+ from click.shell_completion import CompletionItem
421
+
422
+ str_choices = [self.normalize_choice(choice, ctx) for choice in self.choices]
423
+ if self.case_sensitive:
424
+ matched = (c for c in str_choices if c.startswith(incomplete))
425
+ else:
426
+ incomplete = incomplete.lower()
427
+ matched = (c for c in str_choices if c.lower().startswith(incomplete))
428
+
429
+ return [CompletionItem(c) for c in matched]
430
+
431
+
432
+ class DateTimeInfoDict(ParamTypeInfoDict):
433
+ formats: cabc.Sequence[str]
434
+
435
+
436
+ class DateTime(ParamType[datetime]):
437
+ """The DateTime type converts date strings into `datetime` objects.
438
+
439
+ The format strings which are checked are configurable, but default to some
440
+ common (non-timezone aware) ISO 8601 formats.
441
+
442
+ When specifying *DateTime* formats, you should only pass a list or a tuple.
443
+ Other iterables, like generators, may lead to surprising results.
444
+
445
+ The format strings are processed using ``datetime.strptime``, and this
446
+ consequently defines the format strings which are allowed.
447
+
448
+ Parsing is tried using each format, in order, and the first format which
449
+ parses successfully is used.
450
+
451
+ :param formats: A list or tuple of date format strings, in the order in
452
+ which they should be tried. Defaults to
453
+ ``'%Y-%m-%d'``, ``'%Y-%m-%dT%H:%M:%S'``,
454
+ ``'%Y-%m-%d %H:%M:%S'``.
455
+ """
456
+
457
+ name = "datetime"
458
+
459
+ def __init__(self, formats: cabc.Sequence[str] | None = None):
460
+ self.formats: cabc.Sequence[str] = formats or [
461
+ "%Y-%m-%d",
462
+ "%Y-%m-%dT%H:%M:%S",
463
+ "%Y-%m-%d %H:%M:%S",
464
+ ]
465
+
466
+ def to_info_dict(self) -> DateTimeInfoDict:
467
+ return {"formats": self.formats, **super().to_info_dict()}
468
+
469
+ def get_metavar(self, param: Parameter, ctx: Context) -> str | None:
470
+ return f"[{'|'.join(self.formats)}]"
471
+
472
+ def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:
473
+ try:
474
+ return datetime.strptime(value, format)
475
+ except ValueError:
476
+ return None
477
+
478
+ def convert(
479
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
480
+ ) -> datetime:
481
+ if isinstance(value, datetime):
482
+ return value
483
+
484
+ for format in self.formats:
485
+ converted = self._try_to_convert_date(value, format)
486
+
487
+ if converted is not None:
488
+ return converted
489
+
490
+ formats_str = ", ".join(map(repr, self.formats))
491
+ self.fail(
492
+ ngettext(
493
+ "{value!r} does not match the format {format}.",
494
+ "{value!r} does not match the formats {formats}.",
495
+ len(self.formats),
496
+ ).format(value=value, format=formats_str, formats=formats_str),
497
+ param,
498
+ ctx,
499
+ )
500
+
501
+ def __repr__(self) -> str:
502
+ return "DateTime"
503
+
504
+
505
+ class _NumberParamTypeBase(ParamType[ParamTypeValue]):
506
+ _number_class: t.Callable[[t.Any], ParamTypeValue]
507
+
508
+ def convert(
509
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
510
+ ) -> ParamTypeValue:
511
+ try:
512
+ return self._number_class(value)
513
+ except ValueError:
514
+ self.fail(
515
+ _("{value!r} is not a valid {number_type}.").format(
516
+ value=value, number_type=self.name
517
+ ),
518
+ param,
519
+ ctx,
520
+ )
521
+
522
+
523
+ class NumberRangeInfoDict(ParamTypeInfoDict):
524
+ min: float | None
525
+ max: float | None
526
+ min_open: bool
527
+ max_open: bool
528
+ clamp: bool
529
+
530
+
531
+ class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):
532
+ def __init__(
533
+ self,
534
+ min: float | None = None,
535
+ max: float | None = None,
536
+ min_open: bool = False,
537
+ max_open: bool = False,
538
+ clamp: bool = False,
539
+ ) -> None:
540
+ self.min = min
541
+ self.max = max
542
+ self.min_open = min_open
543
+ self.max_open = max_open
544
+ self.clamp = clamp
545
+
546
+ def to_info_dict(self) -> NumberRangeInfoDict:
547
+ return {
548
+ "min": self.min,
549
+ "max": self.max,
550
+ "min_open": self.min_open,
551
+ "max_open": self.max_open,
552
+ "clamp": self.clamp,
553
+ **super().to_info_dict(),
554
+ }
555
+
556
+ def convert(
557
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
558
+ ) -> ParamTypeValue:
559
+ import operator
560
+
561
+ rv = super().convert(value, param, ctx)
562
+ min = self.min
563
+ max = self.max
564
+ lt_min: bool = min is not None and (
565
+ operator.le if self.min_open else operator.lt
566
+ )(rv, min) # type: ignore[arg-type]
567
+ gt_max: bool = max is not None and (
568
+ operator.ge if self.max_open else operator.gt
569
+ )(rv, max) # type: ignore[arg-type]
570
+
571
+ if self.clamp:
572
+ if min is not None and lt_min:
573
+ return self._clamp(min, 1, self.min_open) # type: ignore[arg-type]
574
+
575
+ if max is not None and gt_max:
576
+ return self._clamp(max, -1, self.max_open) # type: ignore[arg-type]
577
+
578
+ if lt_min or gt_max:
579
+ self.fail(
580
+ _("{value} is not in the range {range}.").format(
581
+ value=rv, range=self._describe_range()
582
+ ),
583
+ param,
584
+ ctx,
585
+ )
586
+
587
+ return rv
588
+
589
+ @abc.abstractmethod
590
+ def _clamp(
591
+ self, bound: ParamTypeValue, dir: t.Literal[1, -1], open: bool
592
+ ) -> ParamTypeValue:
593
+ """Find the valid value to clamp to bound in the given
594
+ direction.
595
+
596
+ :param bound: The boundary value.
597
+ :param dir: 1 or -1 indicating the direction to move.
598
+ :param open: If true, the range does not include the bound.
599
+ """
600
+ ...
601
+
602
+ def _describe_range(self) -> str:
603
+ """Describe the range for use in help text."""
604
+ if self.min is None:
605
+ op = "<" if self.max_open else "<="
606
+ return f"x{op}{self.max}"
607
+
608
+ if self.max is None:
609
+ op = ">" if self.min_open else ">="
610
+ return f"x{op}{self.min}"
611
+
612
+ lop = "<" if self.min_open else "<="
613
+ rop = "<" if self.max_open else "<="
614
+ return f"{self.min}{lop}x{rop}{self.max}"
615
+
616
+ def __repr__(self) -> str:
617
+ clamp = " clamped" if self.clamp else ""
618
+ return f"<{type(self).__name__} {self._describe_range()}{clamp}>"
619
+
620
+
621
+ class IntParamType(_NumberParamTypeBase[int]):
622
+ name = "integer"
623
+ _number_class = int
624
+
625
+ def __repr__(self) -> str:
626
+ return "INT"
627
+
628
+
629
+ class IntRange(_NumberRangeBase[int], IntParamType):
630
+ """Restrict an :data:`click.INT` value to a range of accepted
631
+ values. See :ref:`ranges`.
632
+
633
+ If ``min`` or ``max`` are not passed, any value is accepted in that
634
+ direction. If ``min_open`` or ``max_open`` are enabled, the
635
+ corresponding boundary is not included in the range.
636
+
637
+ If ``clamp`` is enabled, a value outside the range is clamped to the
638
+ boundary instead of failing.
639
+
640
+ .. versionchanged:: 8.0
641
+ Added the ``min_open`` and ``max_open`` parameters.
642
+ """
643
+
644
+ name = "integer range"
645
+
646
+ def _clamp(self, bound: int, dir: t.Literal[1, -1], open: bool) -> int:
647
+ if not open:
648
+ return bound
649
+
650
+ return bound + dir
651
+
652
+
653
+ class FloatParamType(_NumberParamTypeBase[float]):
654
+ name = "float"
655
+ _number_class = float
656
+
657
+ def __repr__(self) -> str:
658
+ return "FLOAT"
659
+
660
+
661
+ class FloatRange(_NumberRangeBase[float], FloatParamType):
662
+ """Restrict a :data:`click.FLOAT` value to a range of accepted
663
+ values. See :ref:`ranges`.
664
+
665
+ If ``min`` or ``max`` are not passed, any value is accepted in that
666
+ direction. If ``min_open`` or ``max_open`` are enabled, the
667
+ corresponding boundary is not included in the range.
668
+
669
+ If ``clamp`` is enabled, a value outside the range is clamped to the
670
+ boundary instead of failing. This is not supported if either
671
+ boundary is marked ``open``.
672
+
673
+ .. versionchanged:: 8.0
674
+ Added the ``min_open`` and ``max_open`` parameters.
675
+ """
676
+
677
+ name = "float range"
678
+
679
+ def __init__(
680
+ self,
681
+ min: float | None = None,
682
+ max: float | None = None,
683
+ min_open: bool = False,
684
+ max_open: bool = False,
685
+ clamp: bool = False,
686
+ ) -> None:
687
+ super().__init__(
688
+ min=min, max=max, min_open=min_open, max_open=max_open, clamp=clamp
689
+ )
690
+
691
+ if (min_open or max_open) and clamp:
692
+ raise TypeError("Clamping is not supported for open bounds.")
693
+
694
+ def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:
695
+ if not open:
696
+ return bound
697
+
698
+ # Could use math.nextafter here, but clamping an
699
+ # open float range doesn't seem to be particularly useful. It's
700
+ # left up to the user to write a callback to do it if needed.
701
+ raise RuntimeError("Clamping is not supported for open bounds.")
702
+
703
+
704
+ class BoolParamType(ParamType[bool]):
705
+ name = "boolean"
706
+
707
+ bool_states: dict[str, bool] = {
708
+ "1": True,
709
+ "0": False,
710
+ "yes": True,
711
+ "no": False,
712
+ "true": True,
713
+ "false": False,
714
+ "on": True,
715
+ "off": False,
716
+ "t": True,
717
+ "f": False,
718
+ "y": True,
719
+ "n": False,
720
+ # Absence of value is considered False.
721
+ "": False,
722
+ }
723
+ """A mapping of string values to boolean states.
724
+
725
+ Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`
726
+ and extends it.
727
+
728
+ .. caution::
729
+ String values are lower-cased, as the ``str_to_bool`` comparison function
730
+ below is case-insensitive.
731
+
732
+ .. warning::
733
+ The mapping is not exhaustive, and does not cover all possible boolean strings
734
+ representations. It will remains as it is to avoid endless bikeshedding.
735
+
736
+ Future work my be considered to make this mapping user-configurable from public
737
+ API.
738
+ """
739
+
740
+ @staticmethod
741
+ def str_to_bool(value: str | bool) -> bool | None:
742
+ """Convert a string to a boolean value.
743
+
744
+ If the value is already a boolean, it is returned as-is. If the value is a
745
+ string, it is stripped of whitespaces and lower-cased, then checked against
746
+ the known boolean states pre-defined in the `BoolParamType.bool_states` mapping
747
+ above.
748
+
749
+ Returns `None` if the value does not match any known boolean state.
750
+ """
751
+ if isinstance(value, bool):
752
+ return value
753
+ return BoolParamType.bool_states.get(value.strip().lower())
754
+
755
+ def convert(
756
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
757
+ ) -> bool:
758
+ normalized = self.str_to_bool(value)
759
+ if normalized is None:
760
+ self.fail(
761
+ _(
762
+ "{value!r} is not a valid boolean. Recognized values: {states}"
763
+ ).format(value=value, states=", ".join(sorted(self.bool_states))),
764
+ param,
765
+ ctx,
766
+ )
767
+ return normalized
768
+
769
+ def __repr__(self) -> str:
770
+ return "BOOL"
771
+
772
+
773
+ class UUIDParameterType(ParamType[uuid.UUID]):
774
+ name = "uuid"
775
+
776
+ def convert(
777
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
778
+ ) -> uuid.UUID:
779
+ if isinstance(value, uuid.UUID):
780
+ return value
781
+
782
+ value = value.strip()
783
+
784
+ try:
785
+ return uuid.UUID(value)
786
+ except ValueError:
787
+ self.fail(
788
+ _("{value!r} is not a valid UUID.").format(value=value), param, ctx
789
+ )
790
+
791
+ def __repr__(self) -> str:
792
+ return "UUID"
793
+
794
+
795
+ class FileInfoDict(ParamTypeInfoDict):
796
+ mode: str
797
+ encoding: str | None
798
+
799
+
800
+ class File(ParamType[t.IO[t.Any]]):
801
+ """Declares a parameter to be a file for reading or writing. The file
802
+ is automatically closed once the context tears down (after the command
803
+ finished working).
804
+
805
+ Files can be opened for reading or writing. The special value ``-``
806
+ indicates stdin or stdout depending on the mode.
807
+
808
+ By default, the file is opened for reading text data, but it can also be
809
+ opened in binary mode or for writing. The encoding parameter can be used
810
+ to force a specific encoding.
811
+
812
+ The `lazy` flag controls if the file should be opened immediately or upon
813
+ first IO. The default is to be non-lazy for standard input and output
814
+ streams as well as files opened for reading, `lazy` otherwise. When opening a
815
+ file lazily for reading, it is still opened temporarily for validation, but
816
+ will not be held open until first IO. lazy is mainly useful when opening
817
+ for writing to avoid creating the file until it is needed.
818
+
819
+ Files can also be opened atomically in which case all writes go into a
820
+ separate file in the same folder and upon completion the file will
821
+ be moved over to the original location. This is useful if a file
822
+ regularly read by other users is modified.
823
+
824
+ See :ref:`file-args` for more information.
825
+
826
+ .. versionchanged:: 2.0
827
+ Added the ``atomic`` parameter.
828
+ """
829
+
830
+ name = "filename"
831
+ envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
832
+
833
+ def __init__(
834
+ self,
835
+ mode: str = "r",
836
+ encoding: str | None = None,
837
+ errors: str | None = "strict",
838
+ lazy: bool | None = None,
839
+ atomic: bool = False,
840
+ ) -> None:
841
+ self.mode = mode
842
+ self.encoding = encoding
843
+ self.errors = errors
844
+ self.lazy = lazy
845
+ self.atomic = atomic
846
+
847
+ def to_info_dict(self) -> FileInfoDict:
848
+ return {
849
+ "mode": self.mode,
850
+ "encoding": self.encoding,
851
+ **super().to_info_dict(),
852
+ }
853
+
854
+ def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:
855
+ if self.lazy is not None:
856
+ return self.lazy
857
+ if os.fspath(value) == "-":
858
+ return False
859
+ elif "w" in self.mode:
860
+ return True
861
+ return False
862
+
863
+ def convert(
864
+ self,
865
+ value: str | os.PathLike[str] | t.IO[t.Any],
866
+ param: Parameter | None,
867
+ ctx: Context | None,
868
+ ) -> t.IO[t.Any]:
869
+ if _is_file_like(value):
870
+ return value
871
+
872
+ value = t.cast("str | os.PathLike[str]", value)
873
+
874
+ try:
875
+ lazy = self.resolve_lazy_flag(value)
876
+
877
+ if lazy:
878
+ lf = LazyFile(
879
+ value, self.mode, self.encoding, self.errors, atomic=self.atomic
880
+ )
881
+
882
+ if ctx is not None:
883
+ ctx.call_on_close(lf.close_intelligently)
884
+
885
+ return t.cast("t.IO[t.Any]", lf)
886
+
887
+ f, should_close = open_stream(
888
+ value, self.mode, self.encoding, self.errors, atomic=self.atomic
889
+ )
890
+
891
+ # If a context is provided, we automatically close the file
892
+ # at the end of the context execution (or flush out). If a
893
+ # context does not exist, it's the caller's responsibility to
894
+ # properly close the file. This for instance happens when the
895
+ # type is used with prompts.
896
+ if ctx is not None:
897
+ if should_close:
898
+ ctx.call_on_close(safecall(f.close))
899
+ else:
900
+ ctx.call_on_close(safecall(f.flush))
901
+
902
+ return f
903
+ except OSError as e:
904
+ self.fail(
905
+ f"'{format_filename(value)}': {e.strerror}",
906
+ param,
907
+ ctx,
908
+ )
909
+
910
+ def shell_complete(
911
+ self, ctx: Context, param: Parameter, incomplete: str
912
+ ) -> list[CompletionItem]:
913
+ """Return a special completion marker that tells the completion
914
+ system to use the shell to provide file path completions.
915
+
916
+ :param ctx: Invocation context for this command.
917
+ :param param: The parameter that is requesting completion.
918
+ :param incomplete: Value being completed. May be empty.
919
+
920
+ .. versionadded:: 8.0
921
+ """
922
+ from click.shell_completion import CompletionItem
923
+
924
+ return [CompletionItem(incomplete, type="file")]
925
+
926
+
927
+ def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:
928
+ return hasattr(value, "read") or hasattr(value, "write")
929
+
930
+
931
+ class PathInfoDict(ParamTypeInfoDict):
932
+ exists: bool
933
+ file_okay: bool
934
+ dir_okay: bool
935
+ writable: bool
936
+ readable: bool
937
+ allow_dash: bool
938
+
939
+
940
+ class Path(ParamType[str | bytes | os.PathLike[str]]):
941
+ """The ``Path`` type is similar to the :class:`File` type, but
942
+ returns the filename instead of an open file. Various checks can be
943
+ enabled to validate the type of file and permissions.
944
+
945
+ :param exists: The file or directory needs to exist for the value to
946
+ be valid. If this is not set to ``True``, and the file does not
947
+ exist, then all further checks are silently skipped.
948
+ :param file_okay: Allow a file as a value.
949
+ :param dir_okay: Allow a directory as a value.
950
+ :param readable: if true, a readable check is performed.
951
+ :param writable: if true, a writable check is performed.
952
+ :param executable: if true, an executable check is performed.
953
+ :param resolve_path: Make the value absolute and resolve any
954
+ symlinks. A ``~`` is not expanded, as this is supposed to be
955
+ done by the shell only.
956
+ :param allow_dash: Allow a single dash as a value, which indicates
957
+ a standard stream (but does not open it). Use
958
+ :func:`~click.open_file` to handle opening this value.
959
+ :param path_type: Convert the incoming path value to this type. If
960
+ ``None``, keep Python's default, which is ``str``. Useful to
961
+ convert to :class:`pathlib.Path`.
962
+
963
+ .. versionchanged:: 8.1
964
+ Added the ``executable`` parameter.
965
+
966
+ .. versionchanged:: 8.0
967
+ Allow passing ``path_type=pathlib.Path``.
968
+
969
+ .. versionchanged:: 6.0
970
+ Added the ``allow_dash`` parameter.
971
+ """
972
+
973
+ envvar_list_splitter: t.ClassVar[str] = os.path.pathsep
974
+
975
+ def __init__(
976
+ self,
977
+ exists: bool = False,
978
+ file_okay: bool = True,
979
+ dir_okay: bool = True,
980
+ writable: bool = False,
981
+ readable: bool = True,
982
+ resolve_path: bool = False,
983
+ allow_dash: bool = False,
984
+ path_type: type[t.Any] | None = None,
985
+ executable: bool = False,
986
+ ):
987
+ self.exists = exists
988
+ self.file_okay = file_okay
989
+ self.dir_okay = dir_okay
990
+ self.readable = readable
991
+ self.writable = writable
992
+ self.executable = executable
993
+ self.resolve_path = resolve_path
994
+ self.allow_dash = allow_dash
995
+ self.type = path_type
996
+
997
+ if self.file_okay and not self.dir_okay:
998
+ self.name: str = _("file")
999
+ elif self.dir_okay and not self.file_okay:
1000
+ self.name = _("directory")
1001
+ else:
1002
+ self.name = _("path")
1003
+
1004
+ def to_info_dict(self) -> PathInfoDict:
1005
+ return {
1006
+ "exists": self.exists,
1007
+ "file_okay": self.file_okay,
1008
+ "dir_okay": self.dir_okay,
1009
+ "writable": self.writable,
1010
+ "readable": self.readable,
1011
+ "allow_dash": self.allow_dash,
1012
+ **super().to_info_dict(),
1013
+ }
1014
+
1015
+ def coerce_path_result(
1016
+ self, value: str | os.PathLike[str]
1017
+ ) -> str | bytes | os.PathLike[str]:
1018
+ if self.type is not None and not isinstance(value, self.type):
1019
+ if self.type is str:
1020
+ return os.fsdecode(value)
1021
+ elif self.type is bytes:
1022
+ return os.fsencode(value)
1023
+ else:
1024
+ return t.cast("os.PathLike[str]", self.type(value))
1025
+
1026
+ return value
1027
+
1028
+ def convert(
1029
+ self,
1030
+ value: str | os.PathLike[str],
1031
+ param: Parameter | None,
1032
+ ctx: Context | None,
1033
+ ) -> str | bytes | os.PathLike[str]:
1034
+ rv = value
1035
+
1036
+ is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")
1037
+
1038
+ if not is_dash:
1039
+ if self.resolve_path:
1040
+ rv = os.path.realpath(rv)
1041
+
1042
+ try:
1043
+ st = os.stat(rv)
1044
+ except OSError:
1045
+ if not self.exists:
1046
+ return self.coerce_path_result(rv)
1047
+ self.fail(
1048
+ _("{name} {filename!r} does not exist.").format(
1049
+ name=self.name.title(), filename=format_filename(value)
1050
+ ),
1051
+ param,
1052
+ ctx,
1053
+ )
1054
+
1055
+ if not self.file_okay and stat.S_ISREG(st.st_mode):
1056
+ self.fail(
1057
+ _("{name} {filename!r} is a file.").format(
1058
+ name=self.name.title(), filename=format_filename(value)
1059
+ ),
1060
+ param,
1061
+ ctx,
1062
+ )
1063
+ if not self.dir_okay and stat.S_ISDIR(st.st_mode):
1064
+ self.fail(
1065
+ _("{name} {filename!r} is a directory.").format(
1066
+ name=self.name.title(), filename=format_filename(value)
1067
+ ),
1068
+ param,
1069
+ ctx,
1070
+ )
1071
+
1072
+ if self.readable and not os.access(rv, os.R_OK):
1073
+ self.fail(
1074
+ _("{name} {filename!r} is not readable.").format(
1075
+ name=self.name.title(), filename=format_filename(value)
1076
+ ),
1077
+ param,
1078
+ ctx,
1079
+ )
1080
+
1081
+ if self.writable and not os.access(rv, os.W_OK):
1082
+ self.fail(
1083
+ _("{name} {filename!r} is not writable.").format(
1084
+ name=self.name.title(), filename=format_filename(value)
1085
+ ),
1086
+ param,
1087
+ ctx,
1088
+ )
1089
+
1090
+ if self.executable and not os.access(value, os.X_OK):
1091
+ self.fail(
1092
+ _("{name} {filename!r} is not executable.").format(
1093
+ name=self.name.title(), filename=format_filename(value)
1094
+ ),
1095
+ param,
1096
+ ctx,
1097
+ )
1098
+
1099
+ return self.coerce_path_result(rv)
1100
+
1101
+ def shell_complete(
1102
+ self, ctx: Context, param: Parameter, incomplete: str
1103
+ ) -> list[CompletionItem]:
1104
+ """Return a special completion marker that tells the completion
1105
+ system to use the shell to provide path completions for only
1106
+ directories or any paths.
1107
+
1108
+ :param ctx: Invocation context for this command.
1109
+ :param param: The parameter that is requesting completion.
1110
+ :param incomplete: Value being completed. May be empty.
1111
+
1112
+ .. versionadded:: 8.0
1113
+ """
1114
+ from click.shell_completion import CompletionItem
1115
+
1116
+ type = "dir" if self.dir_okay and not self.file_okay else "file"
1117
+ return [CompletionItem(incomplete, type=type)]
1118
+
1119
+
1120
+ class TupleInfoDict(ParamTypeInfoDict):
1121
+ types: cabc.Sequence[ParamTypeInfoDict]
1122
+
1123
+
1124
+ class Tuple(CompositeParamType[tuple[t.Any, ...]]):
1125
+ """The default behavior of Click is to apply a type on a value directly.
1126
+ This works well in most cases, except for when `nargs` is set to a fixed
1127
+ count and different types should be used for different items. In this
1128
+ case the :class:`Tuple` type can be used. This type can only be used
1129
+ if `nargs` is set to a fixed number.
1130
+
1131
+ For more information see :ref:`tuple-type`.
1132
+
1133
+ This can be selected by using a Python tuple literal as a type.
1134
+
1135
+ :param types: a list of types that should be used for the tuple items.
1136
+ """
1137
+
1138
+ def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType[t.Any]]) -> None:
1139
+ self.types: cabc.Sequence[ParamType[t.Any]] = [convert_type(ty) for ty in types]
1140
+
1141
+ def to_info_dict(self) -> TupleInfoDict:
1142
+ return {
1143
+ "types": [ty.to_info_dict() for ty in self.types],
1144
+ **super().to_info_dict(),
1145
+ }
1146
+
1147
+ @property
1148
+ def name(self) -> str: # type: ignore[override]
1149
+ return f"<{' '.join(ty.name for ty in self.types)}>"
1150
+
1151
+ @property
1152
+ def arity(self) -> int: # type: ignore[override]
1153
+ return len(self.types)
1154
+
1155
+ def convert(
1156
+ self, value: t.Any, param: Parameter | None, ctx: Context | None
1157
+ ) -> tuple[t.Any, ...]:
1158
+ len_type = len(self.types)
1159
+ len_value = len(value)
1160
+
1161
+ if len_value != len_type:
1162
+ self.fail(
1163
+ ngettext(
1164
+ "{len_type} values are required, but {len_value} was given.",
1165
+ "{len_type} values are required, but {len_value} were given.",
1166
+ len_value,
1167
+ ).format(len_type=len_type, len_value=len_value),
1168
+ param=param,
1169
+ ctx=ctx,
1170
+ )
1171
+
1172
+ return tuple(
1173
+ ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)
1174
+ )
1175
+
1176
+
1177
+ def _guess_type(
1178
+ ty: type[t.Any] | ParamType[t.Any] | None,
1179
+ default: t.Any | None,
1180
+ ) -> type[t.Any] | tuple[type[t.Any], ...] | ParamType[t.Any] | None:
1181
+ """Infer a type from *ty* or *default*.
1182
+
1183
+ Returns *ty* unchanged when it is not ``None``. Otherwise inspects
1184
+ *default* to produce a ``type``, a ``tuple`` of types (for tuple
1185
+ defaults), or ``None``.
1186
+ """
1187
+ if ty is not None:
1188
+ return ty
1189
+
1190
+ if default is None:
1191
+ return None
1192
+
1193
+ if not isinstance(default, (tuple, list)):
1194
+ return type(default)
1195
+
1196
+ # If the default is empty, return None so convert_type falls
1197
+ # through to STRING.
1198
+ if not default:
1199
+ return None
1200
+
1201
+ item = default[0]
1202
+
1203
+ # A sequence of iterables needs to detect the inner types.
1204
+ # Can't call convert_type recursively because that would
1205
+ # incorrectly unwind the tuple to a single type.
1206
+ if isinstance(item, (tuple, list)):
1207
+ return tuple(map(type, item))
1208
+
1209
+ return type(item)
1210
+
1211
+
1212
+ @t.overload
1213
+ def convert_type(ty: None, default: None = None) -> StringParamType: ...
1214
+
1215
+
1216
+ @t.overload
1217
+ def convert_type(
1218
+ ty: type[t.Any] | ParamType[t.Any], default: t.Any | None = None
1219
+ ) -> ParamType[t.Any]: ...
1220
+
1221
+
1222
+ @t.overload
1223
+ def convert_type(
1224
+ ty: t.Any | None, default: t.Any | None = None
1225
+ ) -> ParamType[t.Any]: ...
1226
+
1227
+
1228
+ def convert_type(
1229
+ ty: t.Any | None = None, default: t.Any | None = None
1230
+ ) -> ParamType[t.Any]:
1231
+ """Find the most appropriate :class:`ParamType` for the given Python
1232
+ type. If the type isn't provided, it can be inferred from a default
1233
+ value.
1234
+ """
1235
+ guessed = _guess_type(ty, default)
1236
+ is_guessed = guessed is not ty
1237
+
1238
+ if isinstance(guessed, tuple):
1239
+ return Tuple(guessed)
1240
+
1241
+ if isinstance(guessed, ParamType):
1242
+ return guessed
1243
+
1244
+ if guessed is str or guessed is None:
1245
+ return STRING
1246
+
1247
+ if guessed is int:
1248
+ return INT
1249
+
1250
+ if guessed is float:
1251
+ return FLOAT
1252
+
1253
+ if guessed is bool:
1254
+ return BOOL
1255
+
1256
+ if is_guessed:
1257
+ return STRING
1258
+
1259
+ if __debug__:
1260
+ try:
1261
+ if issubclass(guessed, ParamType):
1262
+ raise AssertionError(
1263
+ f"Attempted to use an uninstantiated parameter type ({guessed})."
1264
+ )
1265
+ except TypeError:
1266
+ # guessed is an instance (correct), so issubclass fails.
1267
+ pass
1268
+
1269
+ return FuncParamType(guessed)
1270
+
1271
+
1272
+ #: A dummy parameter type that just does nothing. From a user's
1273
+ #: perspective this appears to just be the same as `STRING` but
1274
+ #: internally no string conversion takes place if the input was bytes.
1275
+ #: This is usually useful when working with file paths as they can
1276
+ #: appear in bytes and unicode.
1277
+ #:
1278
+ #: For path related uses the :class:`Path` type is a better choice but
1279
+ #: there are situations where an unprocessed type is useful which is why
1280
+ #: it is provided.
1281
+ #:
1282
+ #: .. versionadded:: 4.0
1283
+ UNPROCESSED = UnprocessedParamType()
1284
+
1285
+ #: A unicode string parameter type which is the implicit default. This
1286
+ #: can also be selected by using ``str`` as type.
1287
+ STRING = StringParamType()
1288
+
1289
+ #: An integer parameter. This can also be selected by using ``int`` as
1290
+ #: type.
1291
+ INT = IntParamType()
1292
+
1293
+ #: A floating point value parameter. This can also be selected by using
1294
+ #: ``float`` as type.
1295
+ FLOAT = FloatParamType()
1296
+
1297
+ #: A boolean parameter. This is the default for boolean flags. This can
1298
+ #: also be selected by using ``bool`` as a type.
1299
+ BOOL = BoolParamType()
1300
+
1301
+ #: A UUID parameter.
1302
+ UUID = UUIDParameterType()
1303
+
1304
+
1305
+ class OptionHelpExtra(t.TypedDict, total=False):
1306
+ envvars: tuple[str, ...]
1307
+ default: str
1308
+ range: str
1309
+ required: str
.venv/lib/python3.11/site-packages/click/utils.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections.abc as cabc
4
+ import os
5
+ import re
6
+ import sys
7
+ import typing as t
8
+ from functools import update_wrapper
9
+ from gettext import gettext as _
10
+ from types import ModuleType
11
+ from types import TracebackType
12
+
13
+ from ._compat import _default_text_stderr
14
+ from ._compat import _default_text_stdout
15
+ from ._compat import _find_binary_writer
16
+ from ._compat import auto_wrap_for_ansi
17
+ from ._compat import binary_streams
18
+ from ._compat import open_stream
19
+ from ._compat import should_strip_ansi
20
+ from ._compat import strip_ansi
21
+ from ._compat import text_streams
22
+ from ._compat import WIN
23
+ from .globals import resolve_color_default
24
+
25
+ if t.TYPE_CHECKING:
26
+ import typing_extensions as te
27
+
28
+ P = te.ParamSpec("P")
29
+
30
+ R = t.TypeVar("R")
31
+
32
+
33
+ def _posixify(name: str) -> str:
34
+ return "-".join(name.split()).lower()
35
+
36
+
37
+ def safecall(func: t.Callable[P, R]) -> t.Callable[P, R | None]:
38
+ """Wraps a function so that it swallows exceptions."""
39
+
40
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
41
+ try:
42
+ return func(*args, **kwargs)
43
+ except Exception:
44
+ pass
45
+ return None
46
+
47
+ return update_wrapper(wrapper, func)
48
+
49
+
50
+ def make_str(value: t.Any) -> str:
51
+ """Converts a value into a valid string."""
52
+ if isinstance(value, bytes):
53
+ try:
54
+ return value.decode(sys.getfilesystemencoding())
55
+ except UnicodeError:
56
+ return value.decode("utf-8", "replace")
57
+ return str(value)
58
+
59
+
60
+ def make_default_short_help(help: str, max_length: int = 45) -> str:
61
+ """Returns a condensed version of help string.
62
+
63
+ :meta private:
64
+ """
65
+ # Consider only the first paragraph.
66
+ paragraph_end = help.find("\n\n")
67
+
68
+ if paragraph_end != -1:
69
+ help = help[:paragraph_end]
70
+
71
+ # Collapse newlines, tabs, and spaces.
72
+ words = help.split()
73
+
74
+ if not words:
75
+ return ""
76
+
77
+ # The first paragraph started with a "no rewrap" marker, ignore it.
78
+ if words[0] == "\b":
79
+ words = words[1:]
80
+
81
+ total_length = 0
82
+ last_index = len(words) - 1
83
+
84
+ for i, word in enumerate(words):
85
+ total_length += len(word) + (i > 0)
86
+
87
+ if total_length > max_length: # too long, truncate
88
+ break
89
+
90
+ if word[-1] == ".": # sentence end, truncate without "..."
91
+ return " ".join(words[: i + 1])
92
+
93
+ if total_length == max_length and i != last_index:
94
+ break # not at sentence end, truncate with "..."
95
+ else:
96
+ return " ".join(words) # no truncation needed
97
+
98
+ # Account for the length of the suffix.
99
+ total_length += len("...")
100
+
101
+ # remove words until the length is short enough
102
+ while i > 0:
103
+ total_length -= len(words[i]) + (i > 0)
104
+
105
+ if total_length <= max_length:
106
+ break
107
+
108
+ i -= 1
109
+
110
+ return " ".join(words[:i]) + "..."
111
+
112
+
113
+ class LazyFile:
114
+ """A lazy file works like a regular file but it does not fully open
115
+ the file but it does perform some basic checks early to see if the
116
+ filename parameter does make sense. This is useful for safely opening
117
+ files for writing.
118
+ """
119
+
120
+ name: str
121
+ mode: str
122
+ encoding: str | None
123
+ errors: str | None
124
+ atomic: bool
125
+ _f: t.IO[t.Any] | None
126
+ should_close: bool
127
+
128
+ def __init__(
129
+ self,
130
+ filename: str | os.PathLike[str],
131
+ mode: str = "r",
132
+ encoding: str | None = None,
133
+ errors: str | None = "strict",
134
+ atomic: bool = False,
135
+ ) -> None:
136
+ self.name = os.fspath(filename)
137
+ self.mode = mode
138
+ self.encoding = encoding
139
+ self.errors = errors
140
+ self.atomic = atomic
141
+
142
+ if self.name == "-":
143
+ self._f, self.should_close = open_stream(filename, mode, encoding, errors)
144
+ else:
145
+ if "r" in mode:
146
+ # Open and close the file in case we're opening it for
147
+ # reading so that we can catch at least some errors in
148
+ # some cases early.
149
+ open(filename, mode).close()
150
+ self._f = None
151
+ self.should_close = True
152
+
153
+ def __getattr__(self, name: str) -> t.Any:
154
+ return getattr(self.open(), name)
155
+
156
+ def __repr__(self) -> str:
157
+ if self._f is not None:
158
+ return repr(self._f)
159
+ return f"<unopened file '{format_filename(self.name)}' {self.mode}>"
160
+
161
+ def open(self) -> t.IO[t.Any]:
162
+ """Opens the file if it's not yet open. This call might fail with
163
+ a :exc:`FileError`. Not handling this error will produce an error
164
+ that Click shows.
165
+ """
166
+ if self._f is not None:
167
+ return self._f
168
+ try:
169
+ rv, self.should_close = open_stream(
170
+ self.name, self.mode, self.encoding, self.errors, atomic=self.atomic
171
+ )
172
+ except OSError as e:
173
+ from .exceptions import FileError
174
+
175
+ raise FileError(self.name, hint=e.strerror) from e
176
+ self._f = rv
177
+ return rv
178
+
179
+ def close(self) -> None:
180
+ """Closes the underlying file, no matter what."""
181
+ if self._f is not None:
182
+ self._f.close()
183
+
184
+ def close_intelligently(self) -> None:
185
+ """This function only closes the file if it was opened by the lazy
186
+ file wrapper. For instance this will never close stdin.
187
+ """
188
+ if self.should_close:
189
+ self.close()
190
+
191
+ def __enter__(self) -> LazyFile:
192
+ return self
193
+
194
+ def __exit__(
195
+ self,
196
+ exc_type: type[BaseException] | None,
197
+ exc_value: BaseException | None,
198
+ tb: TracebackType | None,
199
+ ) -> None:
200
+ self.close_intelligently()
201
+
202
+ def __iter__(self) -> cabc.Iterator[t.AnyStr]:
203
+ self.open()
204
+ return iter(self._f) # type: ignore
205
+
206
+
207
+ class KeepOpenFile:
208
+ _file: t.IO[t.Any]
209
+
210
+ def __init__(self, file: t.IO[t.Any]) -> None:
211
+ self._file = file
212
+
213
+ def __getattr__(self, name: str) -> t.Any:
214
+ return getattr(self._file, name)
215
+
216
+ def __enter__(self) -> KeepOpenFile:
217
+ return self
218
+
219
+ def __exit__(
220
+ self,
221
+ exc_type: type[BaseException] | None,
222
+ exc_value: BaseException | None,
223
+ tb: TracebackType | None,
224
+ ) -> None:
225
+ pass
226
+
227
+ def __repr__(self) -> str:
228
+ return repr(self._file)
229
+
230
+ def __iter__(self) -> cabc.Iterator[t.AnyStr]:
231
+ return iter(self._file)
232
+
233
+
234
+ def echo(
235
+ message: object = None,
236
+ file: t.IO[t.Any] | None = None,
237
+ nl: bool = True,
238
+ err: bool = False,
239
+ color: bool | None = None,
240
+ ) -> None:
241
+ """Print a message and newline to stdout or a file. This should be
242
+ used instead of :func:`print` because it provides better support
243
+ for different data, files, and environments.
244
+
245
+ Compared to :func:`print`, this does the following:
246
+
247
+ - Ensures that the output encoding is not misconfigured on Linux.
248
+ - Supports Unicode in the Windows console.
249
+ - Supports writing to binary outputs, and supports writing bytes
250
+ to text outputs.
251
+ - Supports colors and styles on Windows.
252
+ - Removes ANSI color and style codes if the output does not look
253
+ like an interactive terminal.
254
+ - Always flushes the output.
255
+
256
+ :param message: The string or bytes to output. Other objects are
257
+ converted to strings.
258
+ :param file: The file to write to. Defaults to ``stdout``.
259
+ :param err: Write to ``stderr`` instead of ``stdout``.
260
+ :param nl: Print a newline after the message. Enabled by default.
261
+ :param color: Force showing or hiding colors and other styles. By
262
+ default Click will remove color if the output does not look like
263
+ an interactive terminal.
264
+
265
+ .. versionchanged:: 6.0
266
+ Support Unicode output on the Windows console. Click does not
267
+ modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``
268
+ will still not support Unicode.
269
+
270
+ .. versionchanged:: 4.0
271
+ Added the ``color`` parameter.
272
+
273
+ .. versionadded:: 3.0
274
+ Added the ``err`` parameter.
275
+
276
+ .. versionchanged:: 2.0
277
+ Support colors on Windows if colorama is installed.
278
+ """
279
+ if file is None:
280
+ if err:
281
+ file = _default_text_stderr()
282
+ else:
283
+ file = _default_text_stdout()
284
+
285
+ # There are no standard streams attached to write to. For example,
286
+ # pythonw on Windows.
287
+ if file is None:
288
+ return
289
+
290
+ match message:
291
+ case str() | bytes() | bytearray():
292
+ out = message
293
+ case None:
294
+ out = ""
295
+ case _:
296
+ out = str(message)
297
+
298
+ if nl:
299
+ if isinstance(out, str):
300
+ out += "\n"
301
+ else:
302
+ out += b"\n"
303
+
304
+ if not out:
305
+ file.flush()
306
+ return
307
+
308
+ # If there is a message and the value looks like bytes, we manually
309
+ # need to find the binary stream and write the message in there.
310
+ # This is done separately so that most stream types will work as you
311
+ # would expect. Eg: you can write to StringIO for other cases.
312
+ if isinstance(out, (bytes, bytearray)):
313
+ binary_file = _find_binary_writer(file)
314
+ if binary_file is not None:
315
+ file.flush()
316
+ binary_file.write(out)
317
+ binary_file.flush()
318
+ return
319
+
320
+ # ANSI style code support. For no message or bytes, nothing happens.
321
+ # When outputting to a file instead of a terminal, strip codes.
322
+ else:
323
+ color = resolve_color_default(color)
324
+
325
+ if should_strip_ansi(file, color):
326
+ out = strip_ansi(out)
327
+ elif WIN:
328
+ if auto_wrap_for_ansi is not None:
329
+ file = auto_wrap_for_ansi(file, color) # type: ignore
330
+ elif not color:
331
+ out = strip_ansi(out)
332
+
333
+ file.write(out) # type: ignore
334
+ file.flush()
335
+
336
+
337
+ def get_binary_stream(name: t.Literal["stdin", "stdout", "stderr"]) -> t.BinaryIO:
338
+ """Returns a system stream for byte processing.
339
+
340
+ :param name: the name of the stream to open. Valid names are ``'stdin'``,
341
+ ``'stdout'`` and ``'stderr'``
342
+ """
343
+ opener = binary_streams.get(name)
344
+ if opener is None:
345
+ raise TypeError(_("Unknown standard stream '{name}'").format(name=name))
346
+ return opener()
347
+
348
+
349
+ def get_text_stream(
350
+ name: t.Literal["stdin", "stdout", "stderr"],
351
+ encoding: str | None = None,
352
+ errors: str | None = "strict",
353
+ ) -> t.TextIO:
354
+ """Returns a system stream for text processing. This usually returns
355
+ a wrapped stream around a binary stream returned from
356
+ :func:`get_binary_stream` but it also can take shortcuts for already
357
+ correctly configured streams.
358
+
359
+ :param name: the name of the stream to open. Valid names are ``'stdin'``,
360
+ ``'stdout'`` and ``'stderr'``
361
+ :param encoding: overrides the detected default encoding.
362
+ :param errors: overrides the default error mode.
363
+ """
364
+ opener = text_streams.get(name)
365
+ if opener is None:
366
+ raise TypeError(_("Unknown standard stream '{name}'").format(name=name))
367
+ return opener(encoding, errors)
368
+
369
+
370
+ def open_file(
371
+ filename: str | os.PathLike[str],
372
+ mode: str = "r",
373
+ encoding: str | None = None,
374
+ errors: str | None = "strict",
375
+ lazy: bool = False,
376
+ atomic: bool = False,
377
+ ) -> t.IO[t.Any]:
378
+ """Open a file, with extra behavior to handle ``'-'`` to indicate
379
+ a standard stream, lazy open on write, and atomic write. Similar to
380
+ the behavior of the :class:`~click.File` param type.
381
+
382
+ If ``'-'`` is given to open ``stdout`` or ``stdin``, the stream is
383
+ wrapped so that using it in a context manager will not close it.
384
+ This makes it possible to use the function without accidentally
385
+ closing a standard stream:
386
+
387
+ .. code-block:: python
388
+
389
+ with open_file(filename) as f:
390
+ ...
391
+
392
+ :param filename: The name or Path of the file to open, or ``'-'`` for
393
+ ``stdin``/``stdout``.
394
+ :param mode: The mode in which to open the file.
395
+ :param encoding: The encoding to decode or encode a file opened in
396
+ text mode.
397
+ :param errors: The error handling mode.
398
+ :param lazy: Wait to open the file until it is accessed. For read
399
+ mode, the file is temporarily opened to raise access errors
400
+ early, then closed until it is read again.
401
+ :param atomic: Write to a temporary file and replace the given file
402
+ on close.
403
+
404
+ .. versionadded:: 3.0
405
+ """
406
+ if lazy:
407
+ return t.cast(
408
+ "t.IO[t.Any]", LazyFile(filename, mode, encoding, errors, atomic=atomic)
409
+ )
410
+
411
+ f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)
412
+
413
+ if not should_close:
414
+ f = t.cast("t.IO[t.Any]", KeepOpenFile(f))
415
+
416
+ return f
417
+
418
+
419
+ def format_filename(
420
+ filename: str | bytes | os.PathLike[str] | os.PathLike[bytes],
421
+ shorten: bool = False,
422
+ ) -> str:
423
+ """Format a filename as a string for display. Ensures the filename can be
424
+ displayed by replacing any invalid bytes or surrogate escapes in the name
425
+ with the replacement character ``�``.
426
+
427
+ Invalid bytes or surrogate escapes will raise an error when written to a
428
+ stream with ``errors="strict"``. This will typically happen with ``stdout``
429
+ when the locale is something like ``en_GB.UTF-8``.
430
+
431
+ Many scenarios *are* safe to write surrogates though, due to PEP 538 and
432
+ PEP 540, including:
433
+
434
+ - Writing to ``stderr``, which uses ``errors="backslashreplace"``.
435
+ - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens
436
+ stdout and stderr with ``errors="surrogateescape"``.
437
+ - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.
438
+ - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.
439
+ Python opens stdout and stderr with ``errors="surrogateescape"``.
440
+
441
+ :param filename: formats a filename for UI display. This will also convert
442
+ the filename into unicode without failing.
443
+ :param shorten: this optionally shortens the filename to strip of the
444
+ path that leads up to it.
445
+ """
446
+ if shorten:
447
+ filename = os.path.basename(filename)
448
+ else:
449
+ filename = os.fspath(filename)
450
+
451
+ if isinstance(filename, bytes):
452
+ filename = filename.decode(sys.getfilesystemencoding(), "replace")
453
+ else:
454
+ filename = filename.encode("utf-8", "surrogateescape").decode(
455
+ "utf-8", "replace"
456
+ )
457
+
458
+ return filename
459
+
460
+
461
+ def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:
462
+ r"""Returns the config folder for the application. The default behavior
463
+ is to return whatever is most appropriate for the operating system.
464
+
465
+ To give you an idea, for an app called ``"Foo Bar"``, something like
466
+ the following folders could be returned:
467
+
468
+ Mac OS X:
469
+ ``~/Library/Application Support/Foo Bar``
470
+ Mac OS X (POSIX):
471
+ ``~/.foo-bar``
472
+ Unix:
473
+ ``~/.config/foo-bar``
474
+ Unix (POSIX):
475
+ ``~/.foo-bar``
476
+ Windows (roaming):
477
+ ``C:\Users\<user>\AppData\Roaming\Foo Bar``
478
+ Windows (not roaming):
479
+ ``C:\Users\<user>\AppData\Local\Foo Bar``
480
+
481
+ .. versionadded:: 2.0
482
+
483
+ :param app_name: the application name. This should be properly capitalized
484
+ and can contain whitespace.
485
+ :param roaming: controls if the folder should be roaming or not on Windows.
486
+ Has no effect otherwise.
487
+ :param force_posix: if this is set to `True` then on any POSIX system the
488
+ folder will be stored in the home folder with a leading
489
+ dot instead of the XDG config home or darwin's
490
+ application support folder.
491
+ """
492
+ if WIN:
493
+ key = "APPDATA" if roaming else "LOCALAPPDATA"
494
+ folder = os.environ.get(key)
495
+ if folder is None:
496
+ folder = os.path.expanduser("~")
497
+ return os.path.join(folder, app_name)
498
+ if force_posix:
499
+ return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))
500
+ if sys.platform == "darwin":
501
+ return os.path.join(
502
+ os.path.expanduser("~/Library/Application Support"), app_name
503
+ )
504
+ return os.path.join(
505
+ os.environ.get("XDG_CONFIG_HOME", os.path.expanduser("~/.config")),
506
+ _posixify(app_name),
507
+ )
508
+
509
+
510
+ class PacifyFlushWrapper:
511
+ """This wrapper is used to catch and suppress BrokenPipeErrors resulting
512
+ from ``.flush()`` being called on broken pipe during the shutdown/final-GC
513
+ of the Python interpreter. Notably ``.flush()`` is always called on
514
+ ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any
515
+ other cleanup code, and the case where the underlying file is not a broken
516
+ pipe, all calls and attributes are proxied.
517
+ """
518
+
519
+ wrapped: t.IO[t.Any]
520
+
521
+ def __init__(self, wrapped: t.IO[t.Any]) -> None:
522
+ self.wrapped = wrapped
523
+
524
+ def flush(self) -> None:
525
+ try:
526
+ self.wrapped.flush()
527
+ except OSError as e:
528
+ import errno
529
+
530
+ if e.errno != errno.EPIPE:
531
+ raise
532
+
533
+ def __getattr__(self, attr: str) -> t.Any:
534
+ return getattr(self.wrapped, attr)
535
+
536
+
537
+ def _detect_program_name(
538
+ path: str | None = None, _main: ModuleType | None = None
539
+ ) -> str:
540
+ """Determine the command used to run the program, for use in help
541
+ text. If a file or entry point was executed, the file name is
542
+ returned. If ``python -m`` was used to execute a module or package,
543
+ ``python -m name`` is returned.
544
+
545
+ This doesn't try to be too precise, the goal is to give a concise
546
+ name for help text. Files are only shown as their name without the
547
+ path. ``python`` is only shown for modules, and the full path to
548
+ ``sys.executable`` is not shown.
549
+
550
+ :param path: The Python file being executed. Python puts this in
551
+ ``sys.argv[0]``, which is used by default.
552
+ :param _main: The ``__main__`` module. This should only be passed
553
+ during internal testing.
554
+
555
+ .. versionadded:: 8.0
556
+ Based on command args detection in the Werkzeug reloader.
557
+
558
+ :meta private:
559
+ """
560
+ if _main is None:
561
+ _main = sys.modules["__main__"]
562
+
563
+ if not path:
564
+ path = sys.argv[0]
565
+
566
+ # The value of __package__ indicates how Python was called. It may
567
+ # not exist if a setuptools script is installed as an egg. It may be
568
+ # set incorrectly for entry points created with pip on Windows.
569
+ # It is set to "" inside a Shiv or PEX zipapp.
570
+ if getattr(_main, "__package__", None) in {None, ""} or (
571
+ os.name == "nt"
572
+ and _main.__package__ == ""
573
+ and not os.path.exists(path)
574
+ and os.path.exists(f"{path}.exe")
575
+ ):
576
+ # Executed a file, like "python app.py".
577
+ return os.path.basename(path)
578
+
579
+ # Executed a module, like "python -m example".
580
+ # Rewritten by Python from "-m script" to "/path/to/script.py".
581
+ # Need to look at main module to determine how it was executed.
582
+ py_module = t.cast(str, _main.__package__)
583
+ name = os.path.splitext(os.path.basename(path))[0]
584
+
585
+ # A submodule like "example.cli".
586
+ if name != "__main__":
587
+ py_module = f"{py_module}.{name}"
588
+
589
+ return f"python -m {py_module.lstrip('.')}"
590
+
591
+
592
+ def _expand_args(
593
+ args: cabc.Iterable[str],
594
+ *,
595
+ user: bool = True,
596
+ env: bool = True,
597
+ glob_recursive: bool = True,
598
+ ) -> list[str]:
599
+ """Simulate Unix shell expansion with Python functions.
600
+
601
+ See :func:`glob.glob`, :func:`os.path.expanduser`, and
602
+ :func:`os.path.expandvars`.
603
+
604
+ This is intended for use on Windows, where the shell does not do any
605
+ expansion. It may not exactly match what a Unix shell would do.
606
+
607
+ :param args: List of command line arguments to expand.
608
+ :param user: Expand user home directory.
609
+ :param env: Expand environment variables.
610
+ :param glob_recursive: ``**`` matches directories recursively.
611
+
612
+ .. versionchanged:: 8.1
613
+ Invalid glob patterns are treated as empty expansions rather
614
+ than raising an error.
615
+
616
+ .. versionadded:: 8.0
617
+
618
+ :meta private:
619
+ """
620
+ from glob import glob
621
+
622
+ out = []
623
+
624
+ for arg in args:
625
+ if user:
626
+ arg = os.path.expanduser(arg)
627
+
628
+ if env:
629
+ arg = os.path.expandvars(arg)
630
+
631
+ try:
632
+ matches = glob(arg, recursive=glob_recursive)
633
+ except re.error:
634
+ matches = []
635
+
636
+ if not matches:
637
+ out.append(arg)
638
+ else:
639
+ out.extend(matches)
640
+
641
+ return out
.venv/lib/python3.11/site-packages/git/__init__.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
2
+ #
3
+ # This module is part of GitPython and is released under the
4
+ # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
5
+
6
+ # @PydevCodeAnalysisIgnore
7
+
8
+ __all__ = [
9
+ "Actor",
10
+ "AmbiguousObjectName",
11
+ "BadName",
12
+ "BadObject",
13
+ "BadObjectType",
14
+ "BaseIndexEntry",
15
+ "Blob",
16
+ "BlobFilter",
17
+ "BlockingLockFile",
18
+ "CacheError",
19
+ "CheckoutError",
20
+ "CommandError",
21
+ "Commit",
22
+ "Diff",
23
+ "DiffConstants",
24
+ "DiffIndex",
25
+ "Diffable",
26
+ "FetchInfo",
27
+ "Git",
28
+ "GitCmdObjectDB",
29
+ "GitCommandError",
30
+ "GitCommandNotFound",
31
+ "GitConfigParser",
32
+ "GitDB",
33
+ "GitError",
34
+ "HEAD",
35
+ "Head",
36
+ "HookExecutionError",
37
+ "INDEX",
38
+ "IndexEntry",
39
+ "IndexFile",
40
+ "IndexObject",
41
+ "InvalidDBRoot",
42
+ "InvalidGitRepositoryError",
43
+ "List", # Deprecated - import this from `typing` instead.
44
+ "LockFile",
45
+ "NULL_TREE",
46
+ "NoSuchPathError",
47
+ "ODBError",
48
+ "Object",
49
+ "Optional", # Deprecated - import this from `typing` instead.
50
+ "ParseError",
51
+ "PathLike",
52
+ "PushInfo",
53
+ "RefLog",
54
+ "RefLogEntry",
55
+ "Reference",
56
+ "Remote",
57
+ "RemoteProgress",
58
+ "RemoteReference",
59
+ "Repo",
60
+ "RepositoryDirtyError",
61
+ "RootModule",
62
+ "RootUpdateProgress",
63
+ "Sequence", # Deprecated - import from `typing`, or `collections.abc` in 3.9+.
64
+ "StageType",
65
+ "Stats",
66
+ "Submodule",
67
+ "SymbolicReference",
68
+ "TYPE_CHECKING", # Deprecated - import this from `typing` instead.
69
+ "Tag",
70
+ "TagObject",
71
+ "TagReference",
72
+ "Tree",
73
+ "TreeModifier",
74
+ "Tuple", # Deprecated - import this from `typing` instead.
75
+ "Union", # Deprecated - import this from `typing` instead.
76
+ "UnmergedEntriesError",
77
+ "UnsafeOptionError",
78
+ "UnsafeProtocolError",
79
+ "UnsupportedOperation",
80
+ "UpdateProgress",
81
+ "WorkTreeRepositoryUnsupported",
82
+ "refresh",
83
+ "remove_password_if_present",
84
+ "rmtree",
85
+ "safe_decode",
86
+ "to_hex_sha",
87
+ ]
88
+
89
+ __version__ = '3.1.50'
90
+
91
+ from typing import Any, List, Optional, Sequence, TYPE_CHECKING, Tuple, Union
92
+
93
+ if TYPE_CHECKING:
94
+ from types import ModuleType
95
+
96
+ import warnings
97
+
98
+ from gitdb.util import to_hex_sha
99
+
100
+ from git.exc import (
101
+ AmbiguousObjectName,
102
+ BadName,
103
+ BadObject,
104
+ BadObjectType,
105
+ CacheError,
106
+ CheckoutError,
107
+ CommandError,
108
+ GitCommandError,
109
+ GitCommandNotFound,
110
+ GitError,
111
+ HookExecutionError,
112
+ InvalidDBRoot,
113
+ InvalidGitRepositoryError,
114
+ NoSuchPathError,
115
+ ODBError,
116
+ ParseError,
117
+ RepositoryDirtyError,
118
+ UnmergedEntriesError,
119
+ UnsafeOptionError,
120
+ UnsafeProtocolError,
121
+ UnsupportedOperation,
122
+ WorkTreeRepositoryUnsupported,
123
+ )
124
+ from git.types import PathLike
125
+
126
+ try:
127
+ from git.compat import safe_decode # @NoMove
128
+ from git.config import GitConfigParser # @NoMove
129
+ from git.objects import ( # @NoMove
130
+ Blob,
131
+ Commit,
132
+ IndexObject,
133
+ Object,
134
+ RootModule,
135
+ RootUpdateProgress,
136
+ Submodule,
137
+ TagObject,
138
+ Tree,
139
+ TreeModifier,
140
+ UpdateProgress,
141
+ )
142
+ from git.refs import ( # @NoMove
143
+ HEAD,
144
+ Head,
145
+ RefLog,
146
+ RefLogEntry,
147
+ Reference,
148
+ RemoteReference,
149
+ SymbolicReference,
150
+ Tag,
151
+ TagReference,
152
+ )
153
+ from git.diff import ( # @NoMove
154
+ INDEX,
155
+ NULL_TREE,
156
+ Diff,
157
+ DiffConstants,
158
+ DiffIndex,
159
+ Diffable,
160
+ )
161
+ from git.db import GitCmdObjectDB, GitDB # @NoMove
162
+ from git.cmd import Git # @NoMove
163
+ from git.repo import Repo # @NoMove
164
+ from git.remote import FetchInfo, PushInfo, Remote, RemoteProgress # @NoMove
165
+ from git.index import ( # @NoMove
166
+ BaseIndexEntry,
167
+ BlobFilter,
168
+ CheckoutError,
169
+ IndexEntry,
170
+ IndexFile,
171
+ StageType,
172
+ # NOTE: This tells type checkers what util resolves to. We delete it, and it is
173
+ # really resolved by __getattr__, which warns. See below on what to use instead.
174
+ util,
175
+ )
176
+ from git.util import ( # @NoMove
177
+ Actor,
178
+ BlockingLockFile,
179
+ LockFile,
180
+ Stats,
181
+ remove_password_if_present,
182
+ rmtree,
183
+ )
184
+ except GitError as _exc:
185
+ raise ImportError("%s: %s" % (_exc.__class__.__name__, _exc)) from _exc
186
+
187
+
188
+ def _warned_import(message: str, fullname: str) -> "ModuleType":
189
+ import importlib
190
+
191
+ warnings.warn(message, DeprecationWarning, stacklevel=3)
192
+ return importlib.import_module(fullname)
193
+
194
+
195
+ def _getattr(name: str) -> Any:
196
+ # TODO: If __version__ is made dynamic and lazily fetched, put that case right here.
197
+
198
+ if name == "util":
199
+ return _warned_import(
200
+ "The expression `git.util` and the import `from git import util` actually "
201
+ "reference git.index.util, and not the git.util module accessed in "
202
+ '`from git.util import XYZ` or `sys.modules["git.util"]`. This potentially '
203
+ "confusing behavior is currently preserved for compatibility, but may be "
204
+ "changed in the future and should not be relied on.",
205
+ fullname="git.index.util",
206
+ )
207
+
208
+ for names, prefix in (
209
+ ({"head", "log", "reference", "symbolic", "tag"}, "git.refs"),
210
+ ({"base", "fun", "typ"}, "git.index"),
211
+ ):
212
+ if name not in names:
213
+ continue
214
+
215
+ fullname = f"{prefix}.{name}"
216
+
217
+ return _warned_import(
218
+ f"{__name__}.{name} is a private alias of {fullname} and subject to "
219
+ f"immediate removal. Use {fullname} instead.",
220
+ fullname=fullname,
221
+ )
222
+
223
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
224
+
225
+
226
+ if not TYPE_CHECKING:
227
+ # NOTE: The expression `git.util` gives git.index.util and `from git import util`
228
+ # imports git.index.util, NOT git.util. It may not be feasible to change this until
229
+ # the next major version, to avoid breaking code inadvertently relying on it.
230
+ #
231
+ # - If git.index.util *is* what you want, use (or import from) that, to avoid
232
+ # confusion.
233
+ #
234
+ # - To use the "real" git.util module, write `from git.util import ...`, or if
235
+ # necessary access it as `sys.modules["git.util"]`.
236
+ #
237
+ # Note also that `import git.util` technically imports the "real" git.util... but
238
+ # the *expression* `git.util` after doing so is still git.index.util!
239
+ #
240
+ # (This situation differs from that of other indirect-submodule imports that are
241
+ # unambiguously non-public and subject to immediate removal. Here, the public
242
+ # git.util module, though different, makes less discoverable that the expression
243
+ # `git.util` refers to a non-public attribute of the git module.)
244
+ #
245
+ # This had originally come about by a wildcard import. Now that all intended imports
246
+ # are explicit, the intuitive but potentially incompatible binding occurs due to the
247
+ # usual rules for Python submodule bindings. So for now we replace that binding with
248
+ # git.index.util, delete that, and let __getattr__ handle it and issue a warning.
249
+ #
250
+ # For the same runtime behavior, it would be enough to forgo importing util, and
251
+ # delete util as created naturally; __getattr__ would behave the same. But type
252
+ # checkers would not know what util refers to when accessed as an attribute of git.
253
+ del util
254
+
255
+ # This is "hidden" to preserve static checking for undefined/misspelled attributes.
256
+ __getattr__ = _getattr
257
+
258
+ # { Initialize git executable path
259
+
260
+ GIT_OK = None
261
+
262
+
263
+ def refresh(path: Optional[PathLike] = None) -> None:
264
+ """Convenience method for setting the git executable path.
265
+
266
+ :param path:
267
+ Optional path to the Git executable. If not absolute, it is resolved
268
+ immediately, relative to the current directory.
269
+
270
+ :note:
271
+ The `path` parameter is usually omitted and cannot be used to specify a custom
272
+ command whose location is looked up in a path search on each call. See
273
+ :meth:`Git.refresh <git.cmd.Git.refresh>` for details on how to achieve this.
274
+
275
+ :note:
276
+ This calls :meth:`Git.refresh <git.cmd.Git.refresh>` and sets other global
277
+ configuration according to the effect of doing so. As such, this function should
278
+ usually be used instead of using :meth:`Git.refresh <git.cmd.Git.refresh>` or
279
+ :meth:`FetchInfo.refresh <git.remote.FetchInfo.refresh>` directly.
280
+
281
+ :note:
282
+ This function is called automatically, with no arguments, at import time.
283
+ """
284
+ global GIT_OK
285
+ GIT_OK = False
286
+
287
+ if not Git.refresh(path=path):
288
+ return
289
+ if not FetchInfo.refresh(): # noqa: F405
290
+ return # type: ignore[unreachable]
291
+
292
+ GIT_OK = True
293
+
294
+
295
+ try:
296
+ refresh()
297
+ except Exception as _exc:
298
+ raise ImportError("Failed to initialize: {0}".format(_exc)) from _exc
299
+
300
+ # } END initialize git executable path
.venv/lib/python3.11/site-packages/git/cmd.py ADDED
@@ -0,0 +1,1761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
2
+ #
3
+ # This module is part of GitPython and is released under the
4
+ # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
5
+
6
+ from __future__ import annotations
7
+
8
+ __all__ = ["GitMeta", "Git"]
9
+
10
+ import contextlib
11
+ import io
12
+ import itertools
13
+ import logging
14
+ import os
15
+ import re
16
+ import signal
17
+ import subprocess
18
+ from subprocess import DEVNULL, PIPE, Popen
19
+ import sys
20
+ from textwrap import dedent
21
+ import threading
22
+ import warnings
23
+
24
+ from git.compat import defenc, force_bytes, safe_decode
25
+ from git.exc import (
26
+ CommandError,
27
+ GitCommandError,
28
+ GitCommandNotFound,
29
+ UnsafeOptionError,
30
+ UnsafeProtocolError,
31
+ )
32
+ from git.util import (
33
+ cygpath,
34
+ expand_path,
35
+ is_cygwin_git,
36
+ patch_env,
37
+ remove_password_if_present,
38
+ stream_copy,
39
+ )
40
+
41
+ # typing ---------------------------------------------------------------------------
42
+
43
+ from typing import (
44
+ Any,
45
+ AnyStr,
46
+ BinaryIO,
47
+ Callable,
48
+ Dict,
49
+ IO,
50
+ Iterator,
51
+ List,
52
+ Mapping,
53
+ Optional,
54
+ Sequence,
55
+ TYPE_CHECKING,
56
+ TextIO,
57
+ Tuple,
58
+ Union,
59
+ cast,
60
+ overload,
61
+ )
62
+
63
+ if sys.version_info >= (3, 10):
64
+ from typing import TypeAlias
65
+ else:
66
+ from typing_extensions import TypeAlias
67
+
68
+ from git.types import Literal, PathLike, TBD
69
+
70
+ if TYPE_CHECKING:
71
+ from git.diff import DiffIndex
72
+ from git.repo.base import Repo
73
+
74
+ # ---------------------------------------------------------------------------------
75
+
76
+ execute_kwargs = {
77
+ "istream",
78
+ "with_extended_output",
79
+ "with_exceptions",
80
+ "as_process",
81
+ "output_stream",
82
+ "stdout_as_string",
83
+ "kill_after_timeout",
84
+ "with_stdout",
85
+ "universal_newlines",
86
+ "shell",
87
+ "env",
88
+ "max_chunk_size",
89
+ "strip_newline_in_stdout",
90
+ }
91
+
92
+ _logger = logging.getLogger(__name__)
93
+
94
+
95
+ # ==============================================================================
96
+ ## @name Utilities
97
+ # ------------------------------------------------------------------------------
98
+ # Documentation
99
+ ## @{
100
+
101
+
102
+ def handle_process_output(
103
+ process: "Git.AutoInterrupt" | Popen,
104
+ stdout_handler: Union[
105
+ None,
106
+ Callable[[AnyStr], None],
107
+ Callable[[List[AnyStr]], None],
108
+ Callable[[bytes, "Repo", "DiffIndex"], None],
109
+ ],
110
+ stderr_handler: Union[None, Callable[[AnyStr], None], Callable[[List[AnyStr]], None]],
111
+ finalizer: Union[None, Callable[[Union[Popen, "Git.AutoInterrupt"]], None]] = None,
112
+ decode_streams: bool = True,
113
+ kill_after_timeout: Union[None, float] = None,
114
+ ) -> None:
115
+ R"""Register for notifications to learn that process output is ready to read, and
116
+ dispatch lines to the respective line handlers.
117
+
118
+ This function returns once the finalizer returns.
119
+
120
+ :param process:
121
+ :class:`subprocess.Popen` instance.
122
+
123
+ :param stdout_handler:
124
+ f(stdout_line_string), or ``None``.
125
+
126
+ :param stderr_handler:
127
+ f(stderr_line_string), or ``None``.
128
+
129
+ :param finalizer:
130
+ f(proc) - wait for proc to finish.
131
+
132
+ :param decode_streams:
133
+ Assume stdout/stderr streams are binary and decode them before pushing their
134
+ contents to handlers.
135
+
136
+ This defaults to ``True``. Set it to ``False`` if:
137
+
138
+ - ``universal_newlines == True``, as then streams are in text mode, or
139
+ - decoding must happen later, such as for :class:`~git.diff.Diff`\s.
140
+
141
+ :param kill_after_timeout:
142
+ :class:`float` or ``None``, Default = ``None``
143
+
144
+ To specify a timeout in seconds for the git command, after which the process
145
+ should be killed.
146
+ """
147
+
148
+ # Use 2 "pump" threads and wait for both to finish.
149
+ def pump_stream(
150
+ cmdline: List[str],
151
+ name: str,
152
+ stream: Union[BinaryIO, TextIO],
153
+ is_decode: bool,
154
+ handler: Union[None, Callable[[Union[bytes, str]], None]],
155
+ ) -> None:
156
+ try:
157
+ for line in stream:
158
+ if handler:
159
+ if is_decode:
160
+ assert isinstance(line, bytes)
161
+ line_str = line.decode(defenc)
162
+ handler(line_str)
163
+ else:
164
+ handler(line)
165
+
166
+ except Exception as ex:
167
+ _logger.error(f"Pumping {name!r} of cmd({remove_password_if_present(cmdline)}) failed due to: {ex!r}")
168
+ if "I/O operation on closed file" not in str(ex):
169
+ # Only reraise if the error was not due to the stream closing.
170
+ raise CommandError([f"<{name}-pump>"] + remove_password_if_present(cmdline), ex) from ex
171
+ finally:
172
+ stream.close()
173
+
174
+ if hasattr(process, "proc"):
175
+ process = cast("Git.AutoInterrupt", process)
176
+ cmdline: str | Tuple[str, ...] | List[str] = getattr(process.proc, "args", "")
177
+ p_stdout = process.proc.stdout if process.proc else None
178
+ p_stderr = process.proc.stderr if process.proc else None
179
+ else:
180
+ process = cast(Popen, process) # type: ignore[redundant-cast]
181
+ cmdline = getattr(process, "args", "")
182
+ p_stdout = process.stdout
183
+ p_stderr = process.stderr
184
+
185
+ if not isinstance(cmdline, (tuple, list)):
186
+ cmdline = cmdline.split()
187
+
188
+ pumps: List[Tuple[str, IO, Callable[..., None] | None]] = []
189
+ if p_stdout:
190
+ pumps.append(("stdout", p_stdout, stdout_handler))
191
+ if p_stderr:
192
+ pumps.append(("stderr", p_stderr, stderr_handler))
193
+
194
+ threads: List[threading.Thread] = []
195
+
196
+ for name, stream, handler in pumps:
197
+ t = threading.Thread(target=pump_stream, args=(cmdline, name, stream, decode_streams, handler))
198
+ t.daemon = True
199
+ t.start()
200
+ threads.append(t)
201
+
202
+ # FIXME: Why join? Will block if stdin needs feeding...
203
+ for t in threads:
204
+ t.join(timeout=kill_after_timeout)
205
+ if t.is_alive():
206
+ if isinstance(process, Git.AutoInterrupt):
207
+ process._terminate()
208
+ else: # Don't want to deal with the other case.
209
+ raise RuntimeError(
210
+ "Thread join() timed out in cmd.handle_process_output()."
211
+ f" kill_after_timeout={kill_after_timeout} seconds"
212
+ )
213
+ if stderr_handler:
214
+ error_str: Union[str, bytes] = (
215
+ f"error: process killed because it timed out. kill_after_timeout={kill_after_timeout} seconds"
216
+ )
217
+ if not decode_streams and isinstance(p_stderr, BinaryIO):
218
+ # Assume stderr_handler needs binary input.
219
+ error_str = cast(str, error_str)
220
+ error_str = error_str.encode()
221
+ # We ignore typing on the next line because mypy does not like the way
222
+ # we inferred that stderr takes str or bytes.
223
+ stderr_handler(error_str) # type: ignore[arg-type]
224
+
225
+ if finalizer:
226
+ finalizer(process)
227
+
228
+
229
+ safer_popen: Callable[..., Popen]
230
+
231
+ if sys.platform == "win32":
232
+
233
+ def _safer_popen_windows(
234
+ command: Union[str, Sequence[Any]],
235
+ *,
236
+ shell: bool = False,
237
+ env: Optional[Mapping[str, str]] = None,
238
+ **kwargs: Any,
239
+ ) -> Popen:
240
+ """Call :class:`subprocess.Popen` on Windows but don't include a CWD in the
241
+ search.
242
+
243
+ This avoids an untrusted search path condition where a file like ``git.exe`` in
244
+ a malicious repository would be run when GitPython operates on the repository.
245
+ The process using GitPython may have an untrusted repository's working tree as
246
+ its current working directory. Some operations may temporarily change to that
247
+ directory before running a subprocess. In addition, while by default GitPython
248
+ does not run external commands with a shell, it can be made to do so, in which
249
+ case the CWD of the subprocess, which GitPython usually sets to a repository
250
+ working tree, can itself be searched automatically by the shell. This wrapper
251
+ covers all those cases.
252
+
253
+ :note:
254
+ This currently works by setting the
255
+ :envvar:`NoDefaultCurrentDirectoryInExePath` environment variable during
256
+ subprocess creation. It also takes care of passing Windows-specific process
257
+ creation flags, but that is unrelated to path search.
258
+
259
+ :note:
260
+ The current implementation contains a race condition on :attr:`os.environ`.
261
+ GitPython isn't thread-safe, but a program using it on one thread should
262
+ ideally be able to mutate :attr:`os.environ` on another, without
263
+ unpredictable results. See comments in:
264
+ https://github.com/gitpython-developers/GitPython/pull/1650
265
+ """
266
+ # CREATE_NEW_PROCESS_GROUP is needed for some ways of killing it afterwards.
267
+ # https://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal
268
+ # https://docs.python.org/3/library/subprocess.html#subprocess.CREATE_NEW_PROCESS_GROUP
269
+ creationflags = subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
270
+
271
+ # When using a shell, the shell is the direct subprocess, so the variable must
272
+ # be set in its environment, to affect its search behavior.
273
+ if shell:
274
+ # The original may be immutable, or the caller may reuse it. Mutate a copy.
275
+ env = {} if env is None else dict(env)
276
+ env["NoDefaultCurrentDirectoryInExePath"] = "1" # The "1" can be any value.
277
+
278
+ # When not using a shell, the current process does the search in a
279
+ # CreateProcessW API call, so the variable must be set in our environment. With
280
+ # a shell, that's unnecessary if https://github.com/python/cpython/issues/101283
281
+ # is patched. In Python versions where it is unpatched, in the rare case the
282
+ # ComSpec environment variable is unset, the search for the shell itself is
283
+ # unsafe. Setting NoDefaultCurrentDirectoryInExePath in all cases, as done here,
284
+ # is simpler and protects against that. (As above, the "1" can be any value.)
285
+ with patch_env("NoDefaultCurrentDirectoryInExePath", "1"):
286
+ return Popen(
287
+ command,
288
+ shell=shell,
289
+ env=env,
290
+ creationflags=creationflags,
291
+ **kwargs,
292
+ )
293
+
294
+ safer_popen = _safer_popen_windows
295
+ else:
296
+ safer_popen = Popen
297
+
298
+
299
+ def dashify(string: str) -> str:
300
+ return string.replace("_", "-")
301
+
302
+
303
+ def slots_to_dict(self: "Git", exclude: Sequence[str] = ()) -> Dict[str, Any]:
304
+ return {s: getattr(self, s) for s in self.__slots__ if s not in exclude}
305
+
306
+
307
+ def dict_to_slots_and__excluded_are_none(self: object, d: Mapping[str, Any], excluded: Sequence[str] = ()) -> None:
308
+ for k, v in d.items():
309
+ setattr(self, k, v)
310
+ for k in excluded:
311
+ setattr(self, k, None)
312
+
313
+
314
+ ## -- End Utilities -- @}
315
+
316
+
317
+ class _AutoInterrupt:
318
+ """Process wrapper that terminates the wrapped process on finalization.
319
+
320
+ This kills/interrupts the stored process instance once this instance goes out of
321
+ scope. It is used to prevent processes piling up in case iterators stop reading.
322
+
323
+ All attributes are wired through to the contained process object.
324
+
325
+ The wait method is overridden to perform automatic status code checking and possibly
326
+ raise.
327
+ """
328
+
329
+ __slots__ = ("proc", "args", "status")
330
+
331
+ # If this is non-zero it will override any status code during _terminate, used
332
+ # to prevent race conditions in testing.
333
+ _status_code_if_terminate: int = 0
334
+
335
+ def __init__(self, proc: Union[None, subprocess.Popen], args: Any) -> None:
336
+ self.proc = proc
337
+ self.args = args
338
+ self.status: Union[int, None] = None
339
+
340
+ def _terminate(self) -> None:
341
+ """Terminate the underlying process."""
342
+ if self.proc is None:
343
+ return
344
+
345
+ proc = self.proc
346
+ self.proc = None
347
+ if proc.stdin:
348
+ proc.stdin.close()
349
+ if proc.stdout:
350
+ proc.stdout.close()
351
+ if proc.stderr:
352
+ proc.stderr.close()
353
+ # Did the process finish already so we have a return code?
354
+ try:
355
+ if proc.poll() is not None:
356
+ self.status = self._status_code_if_terminate or proc.poll()
357
+ return
358
+ except OSError as ex:
359
+ _logger.info("Ignored error after process had died: %r", ex)
360
+
361
+ # It can be that nothing really exists anymore...
362
+ if os is None or getattr(os, "kill", None) is None:
363
+ return
364
+
365
+ # Try to kill it.
366
+ try:
367
+ proc.terminate()
368
+ status = proc.wait() # Ensure the process goes away.
369
+
370
+ self.status = self._status_code_if_terminate or status
371
+ except (OSError, AttributeError) as ex:
372
+ # On interpreter shutdown (notably on Windows), parts of the stdlib used by
373
+ # subprocess can already be torn down (e.g. `subprocess._winapi` becomes None),
374
+ # which can cause AttributeError during terminate(). In that case, we prefer
375
+ # to silently ignore to avoid noisy "Exception ignored in: __del__" messages.
376
+ _logger.info("Ignored error while terminating process: %r", ex)
377
+ # END exception handling
378
+
379
+ def __del__(self) -> None:
380
+ self._terminate()
381
+
382
+ def __getattr__(self, attr: str) -> Any:
383
+ return getattr(self.proc, attr)
384
+
385
+ # TODO: Bad choice to mimic `proc.wait()` but with different args.
386
+ def wait(self, stderr: Union[None, str, bytes] = b"") -> int:
387
+ """Wait for the process and return its status code.
388
+
389
+ :param stderr:
390
+ Previously read value of stderr, in case stderr is already closed.
391
+
392
+ :warn:
393
+ May deadlock if output or error pipes are used and not handled separately.
394
+
395
+ :raise git.exc.GitCommandError:
396
+ If the return status is not 0.
397
+ """
398
+ if stderr is None:
399
+ stderr_b = b""
400
+ stderr_b = force_bytes(data=stderr, encoding="utf-8")
401
+ status: Union[int, None]
402
+ if self.proc is not None:
403
+ status = self.proc.wait()
404
+ p_stderr = self.proc.stderr
405
+ else: # Assume the underlying proc was killed earlier or never existed.
406
+ status = self.status
407
+ p_stderr = None
408
+
409
+ def read_all_from_possibly_closed_stream(stream: Union[IO[bytes], None]) -> bytes:
410
+ if stream:
411
+ try:
412
+ return stderr_b + force_bytes(stream.read())
413
+ except (OSError, ValueError):
414
+ return stderr_b or b""
415
+ else:
416
+ return stderr_b or b""
417
+
418
+ # END status handling
419
+
420
+ if status != 0:
421
+ errstr = read_all_from_possibly_closed_stream(p_stderr)
422
+ _logger.debug("AutoInterrupt wait stderr: %r" % (errstr,))
423
+ raise GitCommandError(remove_password_if_present(self.args), status, errstr)
424
+ return status
425
+
426
+
427
+ _AutoInterrupt.__name__ = "AutoInterrupt"
428
+ _AutoInterrupt.__qualname__ = "Git.AutoInterrupt"
429
+
430
+
431
+ class _CatFileContentStream:
432
+ """Object representing a sized read-only stream returning the contents of
433
+ an object.
434
+
435
+ This behaves like a stream, but counts the data read and simulates an empty stream
436
+ once our sized content region is empty.
437
+
438
+ If not all data are read to the end of the object's lifetime, we read the rest to
439
+ ensure the underlying stream continues to work.
440
+ """
441
+
442
+ __slots__ = ("_stream", "_nbr", "_size")
443
+
444
+ def __init__(self, size: int, stream: IO[bytes]) -> None:
445
+ self._stream = stream
446
+ self._size = size
447
+ self._nbr = 0 # Number of bytes read.
448
+
449
+ # Special case: If the object is empty, has null bytes, get the final
450
+ # newline right away.
451
+ if size == 0:
452
+ stream.read(1)
453
+ # END handle empty streams
454
+
455
+ def read(self, size: int = -1) -> bytes:
456
+ bytes_left = self._size - self._nbr
457
+ if bytes_left == 0:
458
+ return b""
459
+ if size > -1:
460
+ # Ensure we don't try to read past our limit.
461
+ size = min(bytes_left, size)
462
+ else:
463
+ # They try to read all, make sure it's not more than what remains.
464
+ size = bytes_left
465
+ # END check early depletion
466
+ data = self._stream.read(size)
467
+ self._nbr += len(data)
468
+
469
+ # Check for depletion, read our final byte to make the stream usable by
470
+ # others.
471
+ if self._size - self._nbr == 0:
472
+ self._stream.read(1) # final newline
473
+ # END finish reading
474
+ return data
475
+
476
+ def readline(self, size: int = -1) -> bytes:
477
+ if self._nbr == self._size:
478
+ return b""
479
+
480
+ # Clamp size to lowest allowed value.
481
+ bytes_left = self._size - self._nbr
482
+ if size > -1:
483
+ size = min(bytes_left, size)
484
+ else:
485
+ size = bytes_left
486
+ # END handle size
487
+
488
+ data = self._stream.readline(size)
489
+ self._nbr += len(data)
490
+
491
+ # Handle final byte.
492
+ if self._size - self._nbr == 0:
493
+ self._stream.read(1)
494
+ # END finish reading
495
+
496
+ return data
497
+
498
+ def readlines(self, size: int = -1) -> List[bytes]:
499
+ if self._nbr == self._size:
500
+ return []
501
+
502
+ # Leave all additional logic to our readline method, we just check the size.
503
+ out = []
504
+ nbr = 0
505
+ while True:
506
+ line = self.readline()
507
+ if not line:
508
+ break
509
+ out.append(line)
510
+ if size > -1:
511
+ nbr += len(line)
512
+ if nbr > size:
513
+ break
514
+ # END handle size constraint
515
+ # END readline loop
516
+ return out
517
+
518
+ # skipcq: PYL-E0301
519
+ def __iter__(self) -> "Git.CatFileContentStream":
520
+ return self
521
+
522
+ def __next__(self) -> bytes:
523
+ line = self.readline()
524
+ if not line:
525
+ raise StopIteration
526
+
527
+ return line
528
+
529
+ next = __next__
530
+
531
+ def __del__(self) -> None:
532
+ bytes_left = self._size - self._nbr
533
+ if bytes_left:
534
+ # Read and discard - seeking is impossible within a stream.
535
+ # This includes any terminating newline.
536
+ self._stream.read(bytes_left + 1)
537
+ # END handle incomplete read
538
+
539
+
540
+ _CatFileContentStream.__name__ = "CatFileContentStream"
541
+ _CatFileContentStream.__qualname__ = "Git.CatFileContentStream"
542
+
543
+
544
+ _USE_SHELL_DEFAULT_MESSAGE = (
545
+ "Git.USE_SHELL is deprecated, because only its default value of False is safe. "
546
+ "It will be removed in a future release."
547
+ )
548
+
549
+ _USE_SHELL_DANGER_MESSAGE = (
550
+ "Setting Git.USE_SHELL to True is unsafe and insecure, as the effect of special "
551
+ "shell syntax cannot usually be accounted for. This can result in a command "
552
+ "injection vulnerability and arbitrary code execution. Git.USE_SHELL is deprecated "
553
+ "and will be removed in a future release."
554
+ )
555
+
556
+
557
+ def _warn_use_shell(*, extra_danger: bool) -> None:
558
+ warnings.warn(
559
+ _USE_SHELL_DANGER_MESSAGE if extra_danger else _USE_SHELL_DEFAULT_MESSAGE,
560
+ DeprecationWarning,
561
+ stacklevel=3,
562
+ )
563
+
564
+
565
+ class _GitMeta(type):
566
+ """Metaclass for :class:`Git`.
567
+
568
+ This helps issue :class:`DeprecationWarning` if :attr:`Git.USE_SHELL` is used.
569
+ """
570
+
571
+ def __getattribute(cls, name: str) -> Any:
572
+ if name == "USE_SHELL":
573
+ _warn_use_shell(extra_danger=False)
574
+ return super().__getattribute__(name)
575
+
576
+ def __setattr(cls, name: str, value: Any) -> Any:
577
+ if name == "USE_SHELL":
578
+ _warn_use_shell(extra_danger=value)
579
+ super().__setattr__(name, value)
580
+
581
+ if not TYPE_CHECKING:
582
+ # To preserve static checking for undefined/misspelled attributes while letting
583
+ # the methods' bodies be type-checked, these are defined as non-special methods,
584
+ # then bound to special names out of view of static type checkers. (The original
585
+ # names invoke name mangling (leading "__") to avoid confusion in other scopes.)
586
+ __getattribute__ = __getattribute
587
+ __setattr__ = __setattr
588
+
589
+
590
+ GitMeta = _GitMeta
591
+ """Alias of :class:`Git`'s metaclass, whether it is :class:`type` or a custom metaclass.
592
+
593
+ Whether the :class:`Git` class has the default :class:`type` as its metaclass or uses a
594
+ custom metaclass is not documented and may change at any time. This statically checkable
595
+ metaclass alias is equivalent at runtime to ``type(Git)``. This should almost never be
596
+ used. Code that benefits from it is likely to be remain brittle even if it is used.
597
+
598
+ In view of the :class:`Git` class's intended use and :class:`Git` objects' dynamic
599
+ callable attributes representing git subcommands, it rarely makes sense to inherit from
600
+ :class:`Git` at all. Using :class:`Git` in multiple inheritance can be especially tricky
601
+ to do correctly. Attempting uses of :class:`Git` where its metaclass is relevant, such
602
+ as when a sibling class has an unrelated metaclass and a shared lower bound metaclass
603
+ might have to be introduced to solve a metaclass conflict, is not recommended.
604
+
605
+ :note:
606
+ The correct static type of the :class:`Git` class itself, and any subclasses, is
607
+ ``Type[Git]``. (This can be written as ``type[Git]`` in Python 3.9 later.)
608
+
609
+ :class:`GitMeta` should never be used in any annotation where ``Type[Git]`` is
610
+ intended or otherwise possible to use. This alias is truly only for very rare and
611
+ inherently precarious situations where it is necessary to deal with the metaclass
612
+ explicitly.
613
+ """
614
+
615
+
616
+ class Git(metaclass=_GitMeta):
617
+ """The Git class manages communication with the Git binary.
618
+
619
+ It provides a convenient interface to calling the Git binary, such as in::
620
+
621
+ g = Git( git_dir )
622
+ g.init() # calls 'git init' program
623
+ rval = g.ls_files() # calls 'git ls-files' program
624
+
625
+ Debugging:
626
+
627
+ * Set the :envvar:`GIT_PYTHON_TRACE` environment variable to print each invocation
628
+ of the command to stdout.
629
+ * Set its value to ``full`` to see details about the returned values.
630
+ """
631
+
632
+ __slots__ = (
633
+ "_working_dir",
634
+ "cat_file_all",
635
+ "cat_file_header",
636
+ "_version_info",
637
+ "_version_info_token",
638
+ "_git_options",
639
+ "_persistent_git_options",
640
+ "_environment",
641
+ )
642
+
643
+ _excluded_ = (
644
+ "cat_file_all",
645
+ "cat_file_header",
646
+ "_version_info",
647
+ "_version_info_token",
648
+ )
649
+
650
+ re_unsafe_protocol = re.compile(r"(.+)::.+")
651
+
652
+ def __getstate__(self) -> Dict[str, Any]:
653
+ return slots_to_dict(self, exclude=self._excluded_)
654
+
655
+ def __setstate__(self, d: Dict[str, Any]) -> None:
656
+ dict_to_slots_and__excluded_are_none(self, d, excluded=self._excluded_)
657
+
658
+ # CONFIGURATION
659
+
660
+ git_exec_name = "git"
661
+ """Default git command that should work on Linux, Windows, and other systems."""
662
+
663
+ GIT_PYTHON_TRACE = os.environ.get("GIT_PYTHON_TRACE", False)
664
+ """Enables debugging of GitPython's git commands."""
665
+
666
+ USE_SHELL: bool = False
667
+ """Deprecated. If set to ``True``, a shell will be used when executing git commands.
668
+
669
+ Code that uses ``USE_SHELL = True`` or that passes ``shell=True`` to any GitPython
670
+ functions should be updated to use the default value of ``False`` instead. ``True``
671
+ is unsafe unless the effect of syntax treated specially by the shell is fully
672
+ considered and accounted for, which is not possible under most circumstances. As
673
+ detailed below, it is also no longer needed, even where it had been in the past.
674
+
675
+ It is in many if not most cases a command injection vulnerability for an application
676
+ to set :attr:`USE_SHELL` to ``True``. Any attacker who can cause a specially crafted
677
+ fragment of text to make its way into any part of any argument to any git command
678
+ (including paths, branch names, etc.) can cause the shell to read and write
679
+ arbitrary files and execute arbitrary commands. Innocent input may also accidentally
680
+ contain special shell syntax, leading to inadvertent malfunctions.
681
+
682
+ In addition, how a value of ``True`` interacts with some aspects of GitPython's
683
+ operation is not precisely specified and may change without warning, even before
684
+ GitPython 4.0.0 when :attr:`USE_SHELL` may be removed. This includes:
685
+
686
+ * Whether or how GitPython automatically customizes the shell environment.
687
+
688
+ * Whether, outside of Windows (where :class:`subprocess.Popen` supports lists of
689
+ separate arguments even when ``shell=True``), this can be used with any GitPython
690
+ functionality other than direct calls to the :meth:`execute` method.
691
+
692
+ * Whether any GitPython feature that runs git commands ever attempts to partially
693
+ sanitize data a shell may treat specially. Currently this is not done.
694
+
695
+ Prior to GitPython 2.0.8, this had a narrow purpose in suppressing console windows
696
+ in graphical Windows applications. In 2.0.8 and higher, it provides no benefit, as
697
+ GitPython solves that problem more robustly and safely by using the
698
+ ``CREATE_NO_WINDOW`` process creation flag on Windows.
699
+
700
+ Because Windows path search differs subtly based on whether a shell is used, in rare
701
+ cases changing this from ``True`` to ``False`` may keep an unusual git "executable",
702
+ such as a batch file, from being found. To fix this, set the command name or full
703
+ path in the :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable or pass the
704
+ full path to :func:`git.refresh` (or invoke the script using a ``.exe`` shim).
705
+
706
+ Further reading:
707
+
708
+ * :meth:`Git.execute` (on the ``shell`` parameter).
709
+ * https://github.com/gitpython-developers/GitPython/commit/0d9390866f9ce42870d3116094cd49e0019a970a
710
+ * https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags
711
+ * https://github.com/python/cpython/issues/91558#issuecomment-1100942950
712
+ * https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw
713
+ """
714
+
715
+ _git_exec_env_var = "GIT_PYTHON_GIT_EXECUTABLE"
716
+ _refresh_env_var = "GIT_PYTHON_REFRESH"
717
+
718
+ GIT_PYTHON_GIT_EXECUTABLE = None
719
+ """Provide the full path to the git executable. Otherwise it assumes git is in the
720
+ executable search path.
721
+
722
+ :note:
723
+ The git executable is actually found during the refresh step in the top level
724
+ ``__init__``. It can also be changed by explicitly calling :func:`git.refresh`.
725
+ """
726
+
727
+ _refresh_token = object() # Since None would match an initial _version_info_token.
728
+
729
+ @classmethod
730
+ def refresh(cls, path: Union[None, PathLike] = None) -> bool:
731
+ """Update information about the git executable :class:`Git` objects will use.
732
+
733
+ Called by the :func:`git.refresh` function in the top level ``__init__``.
734
+
735
+ :param path:
736
+ Optional path to the git executable. If not absolute, it is resolved
737
+ immediately, relative to the current directory. (See note below.)
738
+
739
+ :note:
740
+ The top-level :func:`git.refresh` should be preferred because it calls this
741
+ method and may also update other state accordingly.
742
+
743
+ :note:
744
+ There are three different ways to specify the command that refreshing causes
745
+ to be used for git:
746
+
747
+ 1. Pass no `path` argument and do not set the
748
+ :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable. The command
749
+ name ``git`` is used. It is looked up in a path search by the system, in
750
+ each command run (roughly similar to how git is found when running
751
+ ``git`` commands manually). This is usually the desired behavior.
752
+
753
+ 2. Pass no `path` argument but set the :envvar:`GIT_PYTHON_GIT_EXECUTABLE`
754
+ environment variable. The command given as the value of that variable is
755
+ used. This may be a simple command or an arbitrary path. It is looked up
756
+ in each command run. Setting :envvar:`GIT_PYTHON_GIT_EXECUTABLE` to
757
+ ``git`` has the same effect as not setting it.
758
+
759
+ 3. Pass a `path` argument. This path, if not absolute, is immediately
760
+ resolved, relative to the current directory. This resolution occurs at
761
+ the time of the refresh. When git commands are run, they are run using
762
+ that previously resolved path. If a `path` argument is passed, the
763
+ :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable is not
764
+ consulted.
765
+
766
+ :note:
767
+ Refreshing always sets the :attr:`Git.GIT_PYTHON_GIT_EXECUTABLE` class
768
+ attribute, which can be read on the :class:`Git` class or any of its
769
+ instances to check what command is used to run git. This attribute should
770
+ not be confused with the related :envvar:`GIT_PYTHON_GIT_EXECUTABLE`
771
+ environment variable. The class attribute is set no matter how refreshing is
772
+ performed.
773
+ """
774
+ # Discern which path to refresh with.
775
+ if path is not None:
776
+ new_git = os.path.expanduser(path)
777
+ new_git = os.path.abspath(new_git)
778
+ else:
779
+ new_git = os.environ.get(cls._git_exec_env_var, cls.git_exec_name)
780
+
781
+ # Keep track of the old and new git executable path.
782
+ old_git = cls.GIT_PYTHON_GIT_EXECUTABLE
783
+ old_refresh_token = cls._refresh_token
784
+ cls.GIT_PYTHON_GIT_EXECUTABLE = new_git
785
+ cls._refresh_token = object()
786
+
787
+ # Test if the new git executable path is valid. A GitCommandNotFound error is
788
+ # raised by us. A PermissionError is raised if the git executable cannot be
789
+ # executed for whatever reason.
790
+ has_git = False
791
+ try:
792
+ cls().version()
793
+ has_git = True
794
+ except (GitCommandNotFound, PermissionError):
795
+ pass
796
+
797
+ # Warn or raise exception if test failed.
798
+ if not has_git:
799
+ err = (
800
+ dedent(
801
+ """\
802
+ Bad git executable.
803
+ The git executable must be specified in one of the following ways:
804
+ - be included in your $PATH
805
+ - be set via $%s
806
+ - explicitly set via git.refresh(<full-path-to-git-executable>)
807
+ """
808
+ )
809
+ % cls._git_exec_env_var
810
+ )
811
+
812
+ # Revert to whatever the old_git was.
813
+ cls.GIT_PYTHON_GIT_EXECUTABLE = old_git
814
+ cls._refresh_token = old_refresh_token
815
+
816
+ if old_git is None:
817
+ # On the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is None) we only
818
+ # are quiet, warn, or error depending on the GIT_PYTHON_REFRESH value.
819
+
820
+ # Determine what the user wants to happen during the initial refresh. We
821
+ # expect GIT_PYTHON_REFRESH to either be unset or be one of the
822
+ # following values:
823
+ #
824
+ # 0|q|quiet|s|silence|silent|n|none
825
+ # 1|w|warn|warning|l|log
826
+ # 2|r|raise|e|error|exception
827
+
828
+ mode = os.environ.get(cls._refresh_env_var, "raise").lower()
829
+
830
+ quiet = ["quiet", "q", "silence", "s", "silent", "none", "n", "0"]
831
+ warn = ["warn", "w", "warning", "log", "l", "1"]
832
+ error = ["error", "e", "exception", "raise", "r", "2"]
833
+
834
+ if mode in quiet:
835
+ pass
836
+ elif mode in warn or mode in error:
837
+ err = dedent(
838
+ """\
839
+ %s
840
+ All git commands will error until this is rectified.
841
+
842
+ This initial message can be silenced or aggravated in the future by setting the
843
+ $%s environment variable. Use one of the following values:
844
+ - %s: for no message or exception
845
+ - %s: for a warning message (logging level CRITICAL, displayed by default)
846
+ - %s: for a raised exception
847
+
848
+ Example:
849
+ export %s=%s
850
+ """
851
+ ) % (
852
+ err,
853
+ cls._refresh_env_var,
854
+ "|".join(quiet),
855
+ "|".join(warn),
856
+ "|".join(error),
857
+ cls._refresh_env_var,
858
+ quiet[0],
859
+ )
860
+
861
+ if mode in warn:
862
+ _logger.critical(err)
863
+ else:
864
+ raise ImportError(err)
865
+ else:
866
+ err = dedent(
867
+ """\
868
+ %s environment variable has been set but it has been set with an invalid value.
869
+
870
+ Use only the following values:
871
+ - %s: for no message or exception
872
+ - %s: for a warning message (logging level CRITICAL, displayed by default)
873
+ - %s: for a raised exception
874
+ """
875
+ ) % (
876
+ cls._refresh_env_var,
877
+ "|".join(quiet),
878
+ "|".join(warn),
879
+ "|".join(error),
880
+ )
881
+ raise ImportError(err)
882
+
883
+ # We get here if this was the initial refresh and the refresh mode was
884
+ # not error. Go ahead and set the GIT_PYTHON_GIT_EXECUTABLE such that we
885
+ # discern the difference between the first refresh at import time
886
+ # and subsequent calls to git.refresh or this refresh method.
887
+ cls.GIT_PYTHON_GIT_EXECUTABLE = cls.git_exec_name
888
+ else:
889
+ # After the first refresh (when GIT_PYTHON_GIT_EXECUTABLE is no longer
890
+ # None) we raise an exception.
891
+ raise GitCommandNotFound(new_git, err)
892
+
893
+ return has_git
894
+
895
+ @classmethod
896
+ def is_cygwin(cls) -> bool:
897
+ return is_cygwin_git(cls.GIT_PYTHON_GIT_EXECUTABLE)
898
+
899
+ @overload
900
+ @classmethod
901
+ def polish_url(cls, url: str, is_cygwin: Literal[False] = ...) -> str: ...
902
+
903
+ @overload
904
+ @classmethod
905
+ def polish_url(cls, url: str, is_cygwin: Union[None, bool] = None) -> str: ...
906
+
907
+ @classmethod
908
+ def polish_url(cls, url: str, is_cygwin: Union[None, bool] = None) -> PathLike:
909
+ """Remove any backslashes from URLs to be written in config files.
910
+
911
+ Windows might create config files containing paths with backslashes, but git
912
+ stops liking them as it will escape the backslashes. Hence we undo the escaping
913
+ just to be sure.
914
+ """
915
+ if is_cygwin is None:
916
+ is_cygwin = cls.is_cygwin()
917
+
918
+ if is_cygwin:
919
+ url = cygpath(url)
920
+ else:
921
+ url = os.path.expandvars(url)
922
+ if url.startswith("~"):
923
+ url = os.path.expanduser(url)
924
+ url = url.replace("\\\\", "\\").replace("\\", "/")
925
+ return url
926
+
927
+ @classmethod
928
+ def check_unsafe_protocols(cls, url: str) -> None:
929
+ """Check for unsafe protocols.
930
+
931
+ Apart from the usual protocols (http, git, ssh), Git allows "remote helpers"
932
+ that have the form ``<transport>::<address>``. One of these helpers (``ext::``)
933
+ can be used to invoke any arbitrary command.
934
+
935
+ See:
936
+
937
+ - https://git-scm.com/docs/gitremote-helpers
938
+ - https://git-scm.com/docs/git-remote-ext
939
+ """
940
+ match = cls.re_unsafe_protocol.match(url)
941
+ if match:
942
+ protocol = match.group(1)
943
+ raise UnsafeProtocolError(
944
+ f"The `{protocol}::` protocol looks suspicious, use `allow_unsafe_protocols=True` to allow it."
945
+ )
946
+
947
+ @classmethod
948
+ def _canonicalize_option_name(cls, option: str) -> str:
949
+ """Return the option name used for unsafe-option checks.
950
+
951
+ Examples:
952
+ ``"--upload-pack=/tmp/helper"`` -> ``"upload-pack"``
953
+ ``"upload_pack"`` -> ``"upload-pack"``
954
+ ``"--config core.filemode=false"`` -> ``"config"``
955
+ """
956
+ option_name = option.lstrip("-").split("=", 1)[0]
957
+ option_tokens = option_name.split(None, 1)
958
+ if not option_tokens:
959
+ return ""
960
+ return dashify(option_tokens[0])
961
+
962
+ @classmethod
963
+ def check_unsafe_options(cls, options: List[str], unsafe_options: List[str]) -> None:
964
+ """Check for unsafe options.
965
+
966
+ Some options that are passed to ``git <command>`` can be used to execute
967
+ arbitrary commands. These are blocked by default.
968
+ """
969
+ # Options can be of the form `foo`, `--foo`, `--foo bar`, or `--foo=bar`.
970
+ canonical_unsafe_options = {cls._canonicalize_option_name(option): option for option in unsafe_options}
971
+ for option in options:
972
+ unsafe_option = canonical_unsafe_options.get(cls._canonicalize_option_name(option))
973
+ if unsafe_option is not None:
974
+ raise UnsafeOptionError(f"{unsafe_option} is not allowed, use `allow_unsafe_options=True` to allow it.")
975
+
976
+ AutoInterrupt: TypeAlias = _AutoInterrupt
977
+
978
+ CatFileContentStream: TypeAlias = _CatFileContentStream
979
+
980
+ def __init__(self, working_dir: Union[None, PathLike] = None) -> None:
981
+ """Initialize this instance with:
982
+
983
+ :param working_dir:
984
+ Git directory we should work in. If ``None``, we always work in the current
985
+ directory as returned by :func:`os.getcwd`.
986
+ This is meant to be the working tree directory if available, or the
987
+ ``.git`` directory in case of bare repositories.
988
+ """
989
+ super().__init__()
990
+ self._working_dir = expand_path(working_dir)
991
+ self._git_options: Union[List[str], Tuple[str, ...]] = ()
992
+ self._persistent_git_options: List[str] = []
993
+
994
+ # Extra environment variables to pass to git commands
995
+ self._environment: Dict[str, str] = {}
996
+
997
+ # Cached version slots
998
+ self._version_info: Union[Tuple[int, ...], None] = None
999
+ self._version_info_token: object = None
1000
+
1001
+ # Cached command slots
1002
+ self.cat_file_header: Union[None, TBD] = None
1003
+ self.cat_file_all: Union[None, TBD] = None
1004
+
1005
+ def __getattribute__(self, name: str) -> Any:
1006
+ if name == "USE_SHELL":
1007
+ _warn_use_shell(extra_danger=False)
1008
+ return super().__getattribute__(name)
1009
+
1010
+ def __getattr__(self, name: str) -> Any:
1011
+ """A convenience method as it allows to call the command as if it was an object.
1012
+
1013
+ :return:
1014
+ Callable object that will execute call :meth:`_call_process` with your
1015
+ arguments.
1016
+ """
1017
+ if name.startswith("_"):
1018
+ return super().__getattribute__(name)
1019
+ return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
1020
+
1021
+ def set_persistent_git_options(self, **kwargs: Any) -> None:
1022
+ """Specify command line options to the git executable for subsequent
1023
+ subcommand calls.
1024
+
1025
+ :param kwargs:
1026
+ A dict of keyword arguments.
1027
+ These arguments are passed as in :meth:`_call_process`, but will be passed
1028
+ to the git command rather than the subcommand.
1029
+ """
1030
+
1031
+ self._persistent_git_options = self.transform_kwargs(split_single_char_options=True, **kwargs)
1032
+
1033
+ @property
1034
+ def working_dir(self) -> Union[None, PathLike]:
1035
+ """:return: Git directory we are working on"""
1036
+ return self._working_dir
1037
+
1038
+ @property
1039
+ def version_info(self) -> Tuple[int, ...]:
1040
+ """
1041
+ :return: Tuple with integers representing the major, minor and additional
1042
+ version numbers as parsed from :manpage:`git-version(1)`. Up to four fields
1043
+ are used.
1044
+
1045
+ This value is generated on demand and is cached.
1046
+ """
1047
+ # Refreshing is global, but version_info caching is per-instance.
1048
+ refresh_token = self._refresh_token # Copy token in case of concurrent refresh.
1049
+
1050
+ # Use the cached version if obtained after the most recent refresh.
1051
+ if self._version_info_token is refresh_token:
1052
+ assert self._version_info is not None, "Bug: corrupted token-check state"
1053
+ return self._version_info
1054
+
1055
+ # Run "git version" and parse it.
1056
+ process_version = self._call_process("version")
1057
+ version_string = process_version.split(" ")[2]
1058
+ version_fields = version_string.split(".")[:4]
1059
+ leading_numeric_fields = itertools.takewhile(str.isdigit, version_fields)
1060
+ self._version_info = tuple(map(int, leading_numeric_fields))
1061
+
1062
+ # This value will be considered valid until the next refresh.
1063
+ self._version_info_token = refresh_token
1064
+ return self._version_info
1065
+
1066
+ @overload
1067
+ def execute(
1068
+ self,
1069
+ command: Union[str, Sequence[Any]],
1070
+ *,
1071
+ as_process: Literal[True],
1072
+ ) -> "AutoInterrupt": ...
1073
+
1074
+ @overload
1075
+ def execute(
1076
+ self,
1077
+ command: Union[str, Sequence[Any]],
1078
+ *,
1079
+ as_process: Literal[False] = False,
1080
+ stdout_as_string: Literal[True],
1081
+ ) -> Union[str, Tuple[int, str, str]]: ...
1082
+
1083
+ @overload
1084
+ def execute(
1085
+ self,
1086
+ command: Union[str, Sequence[Any]],
1087
+ *,
1088
+ as_process: Literal[False] = False,
1089
+ stdout_as_string: Literal[False] = False,
1090
+ ) -> Union[bytes, Tuple[int, bytes, str]]: ...
1091
+
1092
+ @overload
1093
+ def execute(
1094
+ self,
1095
+ command: Union[str, Sequence[Any]],
1096
+ *,
1097
+ with_extended_output: Literal[False],
1098
+ as_process: Literal[False],
1099
+ stdout_as_string: Literal[True],
1100
+ ) -> str: ...
1101
+
1102
+ @overload
1103
+ def execute(
1104
+ self,
1105
+ command: Union[str, Sequence[Any]],
1106
+ *,
1107
+ with_extended_output: Literal[False],
1108
+ as_process: Literal[False],
1109
+ stdout_as_string: Literal[False],
1110
+ ) -> bytes: ...
1111
+
1112
+ def execute(
1113
+ self,
1114
+ command: Union[str, Sequence[Any]],
1115
+ istream: Union[None, BinaryIO] = None,
1116
+ with_extended_output: bool = False,
1117
+ with_exceptions: bool = True,
1118
+ as_process: bool = False,
1119
+ output_stream: Union[None, BinaryIO] = None,
1120
+ stdout_as_string: bool = True,
1121
+ kill_after_timeout: Union[None, float] = None,
1122
+ with_stdout: bool = True,
1123
+ universal_newlines: bool = False,
1124
+ shell: Union[None, bool] = None,
1125
+ env: Union[None, Mapping[str, str]] = None,
1126
+ max_chunk_size: int = io.DEFAULT_BUFFER_SIZE,
1127
+ strip_newline_in_stdout: bool = True,
1128
+ **subprocess_kwargs: Any,
1129
+ ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], AutoInterrupt]:
1130
+ R"""Handle executing the command, and consume and return the returned
1131
+ information (stdout).
1132
+
1133
+ :param command:
1134
+ The command argument list to execute.
1135
+ It should be a sequence of program arguments, or a string. The
1136
+ program to execute is the first item in the args sequence or string.
1137
+
1138
+ :param istream:
1139
+ Standard input filehandle passed to :class:`subprocess.Popen`.
1140
+
1141
+ :param with_extended_output:
1142
+ Whether to return a (status, stdout, stderr) tuple.
1143
+
1144
+ :param with_exceptions:
1145
+ Whether to raise an exception when git returns a non-zero status.
1146
+
1147
+ :param as_process:
1148
+ Whether to return the created process instance directly from which
1149
+ streams can be read on demand. This will render `with_extended_output`
1150
+ and `with_exceptions` ineffective - the caller will have to deal with
1151
+ the details. It is important to note that the process will be placed
1152
+ into an :class:`AutoInterrupt` wrapper that will interrupt the process
1153
+ once it goes out of scope. If you use the command in iterators, you
1154
+ should pass the whole process instance instead of a single stream.
1155
+
1156
+ :param output_stream:
1157
+ If set to a file-like object, data produced by the git command will be
1158
+ copied to the given stream instead of being returned as a string.
1159
+ This feature only has any effect if `as_process` is ``False``.
1160
+
1161
+ :param stdout_as_string:
1162
+ If ``False``, the command's standard output will be bytes. Otherwise, it
1163
+ will be decoded into a string using the default encoding (usually UTF-8).
1164
+ The latter can fail, if the output contains binary data.
1165
+
1166
+ :param kill_after_timeout:
1167
+ Specifies a timeout in seconds for the git command, after which the process
1168
+ should be killed. This will have no effect if `as_process` is set to
1169
+ ``True``. It is set to ``None`` by default and will let the process run
1170
+ until the timeout is explicitly specified. Uses of this feature should be
1171
+ carefully considered, due to the following limitations:
1172
+
1173
+ 1. This feature is not supported at all on Windows.
1174
+ 2. Effectiveness may vary by operating system. ``ps --ppid`` is used to
1175
+ enumerate child processes, which is available on most GNU/Linux systems
1176
+ but not most others.
1177
+ 3. Deeper descendants do not receive signals, though they may sometimes
1178
+ terminate as a consequence of their parent processes being killed.
1179
+ 4. `kill_after_timeout` uses ``SIGKILL``, which can have negative side
1180
+ effects on a repository. For example, stale locks in case of
1181
+ :manpage:`git-gc(1)` could render the repository incapable of accepting
1182
+ changes until the lock is manually removed.
1183
+
1184
+ :param with_stdout:
1185
+ If ``True``, default ``True``, we open stdout on the created process.
1186
+
1187
+ :param universal_newlines:
1188
+ If ``True``, pipes will be opened as text, and lines are split at all known
1189
+ line endings.
1190
+
1191
+ :param shell:
1192
+ Whether to invoke commands through a shell
1193
+ (see :class:`Popen(..., shell=True) <subprocess.Popen>`).
1194
+ If this is not ``None``, it overrides :attr:`USE_SHELL`.
1195
+
1196
+ Passing ``shell=True`` to this or any other GitPython function should be
1197
+ avoided, as it is unsafe under most circumstances. This is because it is
1198
+ typically not feasible to fully consider and account for the effect of shell
1199
+ expansions, especially when passing ``shell=True`` to other methods that
1200
+ forward it to :meth:`Git.execute`. Passing ``shell=True`` is also no longer
1201
+ needed (nor useful) to work around any known operating system specific
1202
+ issues.
1203
+
1204
+ :param env:
1205
+ A dictionary of environment variables to be passed to
1206
+ :class:`subprocess.Popen`.
1207
+
1208
+ :param max_chunk_size:
1209
+ Maximum number of bytes in one chunk of data passed to the `output_stream`
1210
+ in one invocation of its ``write()`` method. If the given number is not
1211
+ positive then the default value is used.
1212
+
1213
+ :param strip_newline_in_stdout:
1214
+ Whether to strip the trailing ``\n`` of the command stdout.
1215
+
1216
+ :param subprocess_kwargs:
1217
+ Keyword arguments to be passed to :class:`subprocess.Popen`. Please note
1218
+ that some of the valid kwargs are already set by this method; the ones you
1219
+ specify may not be the same ones.
1220
+
1221
+ :return:
1222
+ * str(output), if `extended_output` is ``False`` (Default)
1223
+ * tuple(int(status), str(stdout), str(stderr)),
1224
+ if `extended_output` is ``True``
1225
+
1226
+ If `output_stream` is ``True``, the stdout value will be your output stream:
1227
+
1228
+ * output_stream, if `extended_output` is ``False``
1229
+ * tuple(int(status), output_stream, str(stderr)),
1230
+ if `extended_output` is ``True``
1231
+
1232
+ Note that git is executed with ``LC_MESSAGES="C"`` to ensure consistent
1233
+ output regardless of system language.
1234
+
1235
+ :raise git.exc.GitCommandError:
1236
+
1237
+ :note:
1238
+ If you add additional keyword arguments to the signature of this method, you
1239
+ must update the ``execute_kwargs`` variable housed in this module.
1240
+ """
1241
+ # Remove password for the command if present.
1242
+ redacted_command = remove_password_if_present(command)
1243
+ if self.GIT_PYTHON_TRACE and (self.GIT_PYTHON_TRACE != "full" or as_process):
1244
+ _logger.info(" ".join(redacted_command))
1245
+
1246
+ # Allow the user to have the command executed in their working dir.
1247
+ try:
1248
+ cwd = self._working_dir or os.getcwd() # type: Union[None, str]
1249
+ if not os.access(str(cwd), os.X_OK):
1250
+ cwd = None
1251
+ except FileNotFoundError:
1252
+ cwd = None
1253
+
1254
+ # Start the process.
1255
+ inline_env = env
1256
+ env = os.environ.copy()
1257
+ # Attempt to force all output to plain ASCII English, which is what some parsing
1258
+ # code may expect.
1259
+ # According to https://askubuntu.com/a/311796, we are setting LANGUAGE as well
1260
+ # just to be sure.
1261
+ env["LANGUAGE"] = "C"
1262
+ env["LC_ALL"] = "C"
1263
+ env.update(self._environment)
1264
+ if inline_env is not None:
1265
+ env.update(inline_env)
1266
+
1267
+ if sys.platform == "win32":
1268
+ if kill_after_timeout is not None:
1269
+ raise GitCommandError(
1270
+ redacted_command,
1271
+ '"kill_after_timeout" feature is not supported on Windows.',
1272
+ )
1273
+ cmd_not_found_exception = OSError
1274
+ else:
1275
+ cmd_not_found_exception = FileNotFoundError
1276
+ # END handle
1277
+
1278
+ stdout_sink = PIPE if with_stdout else getattr(subprocess, "DEVNULL", None) or open(os.devnull, "wb")
1279
+ if shell is None:
1280
+ # Get the value of USE_SHELL with no deprecation warning. Do this without
1281
+ # warnings.catch_warnings, to avoid a race condition with application code
1282
+ # configuring warnings. The value could be looked up in type(self).__dict__
1283
+ # or Git.__dict__, but those can break under some circumstances. This works
1284
+ # the same as self.USE_SHELL in more situations; see Git.__getattribute__.
1285
+ shell = super().__getattribute__("USE_SHELL")
1286
+ _logger.debug(
1287
+ "Popen(%s, cwd=%s, stdin=%s, shell=%s, universal_newlines=%s)",
1288
+ redacted_command,
1289
+ cwd,
1290
+ "<valid stream>" if istream else "None",
1291
+ shell,
1292
+ universal_newlines,
1293
+ )
1294
+ try:
1295
+ proc = safer_popen(
1296
+ command,
1297
+ env=env,
1298
+ cwd=cwd,
1299
+ bufsize=-1,
1300
+ stdin=(istream or DEVNULL),
1301
+ stderr=PIPE,
1302
+ stdout=stdout_sink,
1303
+ shell=shell,
1304
+ universal_newlines=universal_newlines,
1305
+ encoding=defenc if universal_newlines else None,
1306
+ **subprocess_kwargs,
1307
+ )
1308
+ except cmd_not_found_exception as err:
1309
+ raise GitCommandNotFound(redacted_command, err) from err
1310
+ else:
1311
+ # Replace with a typeguard for Popen[bytes]?
1312
+ proc.stdout = cast(BinaryIO, proc.stdout)
1313
+ proc.stderr = cast(BinaryIO, proc.stderr)
1314
+
1315
+ if as_process:
1316
+ return self.AutoInterrupt(proc, command)
1317
+
1318
+ if sys.platform != "win32" and kill_after_timeout is not None:
1319
+ # Help mypy figure out this is not None even when used inside communicate().
1320
+ timeout = kill_after_timeout
1321
+
1322
+ def kill_process(pid: int) -> None:
1323
+ """Callback to kill a process.
1324
+
1325
+ This callback implementation would be ineffective and unsafe on Windows.
1326
+ """
1327
+ p = Popen(["ps", "--ppid", str(pid)], stdout=PIPE)
1328
+ child_pids = []
1329
+ if p.stdout is not None:
1330
+ for line in p.stdout:
1331
+ if len(line.split()) > 0:
1332
+ local_pid = (line.split())[0]
1333
+ if local_pid.isdigit():
1334
+ child_pids.append(int(local_pid))
1335
+ try:
1336
+ os.kill(pid, signal.SIGKILL)
1337
+ for child_pid in child_pids:
1338
+ try:
1339
+ os.kill(child_pid, signal.SIGKILL)
1340
+ except OSError:
1341
+ pass
1342
+ # Tell the main routine that the process was killed.
1343
+ kill_check.set()
1344
+ except OSError:
1345
+ # It is possible that the process gets completed in the duration
1346
+ # after timeout happens and before we try to kill the process.
1347
+ pass
1348
+ return
1349
+
1350
+ def communicate() -> Tuple[AnyStr, AnyStr]:
1351
+ watchdog.start()
1352
+ out, err = proc.communicate()
1353
+ watchdog.cancel()
1354
+ if kill_check.is_set():
1355
+ err = 'Timeout: the command "%s" did not complete in %d secs.' % (
1356
+ " ".join(redacted_command),
1357
+ timeout,
1358
+ )
1359
+ if not universal_newlines:
1360
+ err = err.encode(defenc)
1361
+ return out, err
1362
+
1363
+ # END helpers
1364
+
1365
+ kill_check = threading.Event()
1366
+ watchdog = threading.Timer(timeout, kill_process, args=(proc.pid,))
1367
+ else:
1368
+ communicate = proc.communicate
1369
+
1370
+ # Wait for the process to return.
1371
+ status = 0
1372
+ stdout_value: Union[str, bytes] = b""
1373
+ stderr_value: Union[str, bytes] = b""
1374
+ newline = "\n" if universal_newlines else b"\n"
1375
+ try:
1376
+ if output_stream is None:
1377
+ stdout_value, stderr_value = communicate()
1378
+ # Strip trailing "\n".
1379
+ if stdout_value is not None and stdout_value.endswith(newline) and strip_newline_in_stdout: # type: ignore[arg-type]
1380
+ stdout_value = stdout_value[:-1]
1381
+ if stderr_value is not None and stderr_value.endswith(newline): # type: ignore[arg-type]
1382
+ stderr_value = stderr_value[:-1]
1383
+
1384
+ status = proc.returncode
1385
+ else:
1386
+ max_chunk_size = max_chunk_size if max_chunk_size and max_chunk_size > 0 else io.DEFAULT_BUFFER_SIZE
1387
+ if proc.stdout is not None:
1388
+ stream_copy(proc.stdout, output_stream, max_chunk_size)
1389
+ stdout_value = proc.stdout.read()
1390
+ if proc.stderr is not None:
1391
+ stderr_value = proc.stderr.read()
1392
+ # Strip trailing "\n".
1393
+ if stderr_value is not None and stderr_value.endswith(newline): # type: ignore[arg-type]
1394
+ stderr_value = stderr_value[:-1]
1395
+ status = proc.wait()
1396
+ # END stdout handling
1397
+ finally:
1398
+ if proc.stdout is not None:
1399
+ proc.stdout.close()
1400
+ if proc.stderr is not None:
1401
+ proc.stderr.close()
1402
+
1403
+ if self.GIT_PYTHON_TRACE == "full":
1404
+ cmdstr = " ".join(redacted_command)
1405
+
1406
+ def as_text(stdout_value: Union[bytes, str]) -> str:
1407
+ return not output_stream and safe_decode(stdout_value) or "<OUTPUT_STREAM>"
1408
+
1409
+ # END as_text
1410
+
1411
+ if stderr_value:
1412
+ _logger.info(
1413
+ "%s -> %d; stdout: '%s'; stderr: '%s'",
1414
+ cmdstr,
1415
+ status,
1416
+ as_text(stdout_value),
1417
+ safe_decode(stderr_value),
1418
+ )
1419
+ elif stdout_value:
1420
+ _logger.info("%s -> %d; stdout: '%s'", cmdstr, status, as_text(stdout_value))
1421
+ else:
1422
+ _logger.info("%s -> %d", cmdstr, status)
1423
+ # END handle debug printing
1424
+
1425
+ if with_exceptions and status != 0:
1426
+ raise GitCommandError(redacted_command, status, stderr_value, stdout_value)
1427
+
1428
+ if isinstance(stdout_value, bytes) and stdout_as_string: # Could also be output_stream.
1429
+ stdout_value = safe_decode(stdout_value)
1430
+
1431
+ # Allow access to the command's status code.
1432
+ if with_extended_output:
1433
+ return (status, stdout_value, safe_decode(stderr_value))
1434
+ else:
1435
+ return stdout_value
1436
+
1437
+ def environment(self) -> Dict[str, str]:
1438
+ return self._environment
1439
+
1440
+ def update_environment(self, **kwargs: Any) -> Dict[str, Union[str, None]]:
1441
+ """Set environment variables for future git invocations. Return all changed
1442
+ values in a format that can be passed back into this function to revert the
1443
+ changes.
1444
+
1445
+ Examples::
1446
+
1447
+ old_env = self.update_environment(PWD='/tmp')
1448
+ self.update_environment(**old_env)
1449
+
1450
+ :param kwargs:
1451
+ Environment variables to use for git processes.
1452
+
1453
+ :return:
1454
+ Dict that maps environment variables to their old values
1455
+ """
1456
+ old_env = {}
1457
+ for key, value in kwargs.items():
1458
+ # Set value if it is None.
1459
+ if value is not None:
1460
+ old_env[key] = self._environment.get(key)
1461
+ self._environment[key] = value
1462
+ # Remove key from environment if its value is None.
1463
+ elif key in self._environment:
1464
+ old_env[key] = self._environment[key]
1465
+ del self._environment[key]
1466
+ return old_env
1467
+
1468
+ @contextlib.contextmanager
1469
+ def custom_environment(self, **kwargs: Any) -> Iterator[None]:
1470
+ """A context manager around the above :meth:`update_environment` method to
1471
+ restore the environment back to its previous state after operation.
1472
+
1473
+ Examples::
1474
+
1475
+ with self.custom_environment(GIT_SSH='/bin/ssh_wrapper'):
1476
+ repo.remotes.origin.fetch()
1477
+
1478
+ :param kwargs:
1479
+ See :meth:`update_environment`.
1480
+ """
1481
+ old_env = self.update_environment(**kwargs)
1482
+ try:
1483
+ yield
1484
+ finally:
1485
+ self.update_environment(**old_env)
1486
+
1487
+ def transform_kwarg(self, name: str, value: Any, split_single_char_options: bool) -> List[str]:
1488
+ if len(name) == 1:
1489
+ if value is True:
1490
+ return ["-%s" % name]
1491
+ elif value not in (False, None):
1492
+ if split_single_char_options:
1493
+ return ["-%s" % name, "%s" % value]
1494
+ else:
1495
+ return ["-%s%s" % (name, value)]
1496
+ else:
1497
+ if value is True:
1498
+ return ["--%s" % dashify(name)]
1499
+ elif value is not False and value is not None:
1500
+ return ["--%s=%s" % (dashify(name), value)]
1501
+ return []
1502
+
1503
+ def transform_kwargs(self, split_single_char_options: bool = True, **kwargs: Any) -> List[str]:
1504
+ """Transform Python-style kwargs into git command line options."""
1505
+ args = []
1506
+ for k, v in kwargs.items():
1507
+ if isinstance(v, (list, tuple)):
1508
+ for value in v:
1509
+ args += self.transform_kwarg(k, value, split_single_char_options)
1510
+ else:
1511
+ args += self.transform_kwarg(k, v, split_single_char_options)
1512
+ return args
1513
+
1514
+ @classmethod
1515
+ def _unpack_args(cls, arg_list: Sequence[str]) -> List[str]:
1516
+ outlist = []
1517
+ if isinstance(arg_list, (list, tuple)):
1518
+ for arg in arg_list:
1519
+ outlist.extend(cls._unpack_args(arg))
1520
+ else:
1521
+ outlist.append(str(arg_list))
1522
+
1523
+ return outlist
1524
+
1525
+ def __call__(self, **kwargs: Any) -> "Git":
1526
+ """Specify command line options to the git executable for a subcommand call.
1527
+
1528
+ :param kwargs:
1529
+ A dict of keyword arguments.
1530
+ These arguments are passed as in :meth:`_call_process`, but will be passed
1531
+ to the git command rather than the subcommand.
1532
+
1533
+ Examples::
1534
+
1535
+ git(work_tree='/tmp').difftool()
1536
+ """
1537
+ self._git_options = self.transform_kwargs(split_single_char_options=True, **kwargs)
1538
+ return self
1539
+
1540
+ @overload
1541
+ def _call_process(
1542
+ self, method: str, *args: None, **kwargs: None
1543
+ ) -> str: ... # If no args were given, execute the call with all defaults.
1544
+
1545
+ @overload
1546
+ def _call_process(
1547
+ self,
1548
+ method: str,
1549
+ istream: int,
1550
+ as_process: Literal[True],
1551
+ *args: Any,
1552
+ **kwargs: Any,
1553
+ ) -> "Git.AutoInterrupt": ...
1554
+
1555
+ @overload
1556
+ def _call_process(
1557
+ self, method: str, *args: Any, **kwargs: Any
1558
+ ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]: ...
1559
+
1560
+ def _call_process(
1561
+ self, method: str, *args: Any, **kwargs: Any
1562
+ ) -> Union[str, bytes, Tuple[int, Union[str, bytes], str], "Git.AutoInterrupt"]:
1563
+ """Run the given git command with the specified arguments and return the result
1564
+ as a string.
1565
+
1566
+ :param method:
1567
+ The command. Contained ``_`` characters will be converted to hyphens, such
1568
+ as in ``ls_files`` to call ``ls-files``.
1569
+
1570
+ :param args:
1571
+ The list of arguments. If ``None`` is included, it will be pruned.
1572
+ This allows your commands to call git more conveniently, as ``None`` is
1573
+ realized as non-existent.
1574
+
1575
+ :param kwargs:
1576
+ Contains key-values for the following:
1577
+
1578
+ - The :meth:`execute()` kwds, as listed in ``execute_kwargs``.
1579
+ - "Command options" to be converted by :meth:`transform_kwargs`.
1580
+ - The ``insert_kwargs_after`` key which its value must match one of
1581
+ ``*args``.
1582
+
1583
+ It also contains any command options, to be appended after the matched arg.
1584
+
1585
+ Examples::
1586
+
1587
+ git.rev_list('master', max_count=10, header=True)
1588
+
1589
+ turns into::
1590
+
1591
+ git rev-list --max-count=10 --header=master
1592
+
1593
+ :return:
1594
+ Same as :meth:`execute`. If no args are given, used :meth:`execute`'s
1595
+ default (especially ``as_process = False``, ``stdout_as_string = True``) and
1596
+ return :class:`str`.
1597
+ """
1598
+ # Handle optional arguments prior to calling transform_kwargs.
1599
+ # Otherwise these'll end up in args, which is bad.
1600
+ exec_kwargs = {k: v for k, v in kwargs.items() if k in execute_kwargs}
1601
+ opts_kwargs = {k: v for k, v in kwargs.items() if k not in execute_kwargs}
1602
+
1603
+ insert_after_this_arg = opts_kwargs.pop("insert_kwargs_after", None)
1604
+
1605
+ # Prepare the argument list.
1606
+
1607
+ opt_args = self.transform_kwargs(**opts_kwargs)
1608
+ ext_args = self._unpack_args([a for a in args if a is not None])
1609
+
1610
+ if insert_after_this_arg is None:
1611
+ args_list = opt_args + ext_args
1612
+ else:
1613
+ try:
1614
+ index = ext_args.index(insert_after_this_arg)
1615
+ except ValueError as err:
1616
+ raise ValueError(
1617
+ "Couldn't find argument '%s' in args %s to insert cmd options after"
1618
+ % (insert_after_this_arg, str(ext_args))
1619
+ ) from err
1620
+ # END handle error
1621
+ args_list = ext_args[: index + 1] + opt_args + ext_args[index + 1 :]
1622
+ # END handle opts_kwargs
1623
+
1624
+ call = [self.GIT_PYTHON_GIT_EXECUTABLE]
1625
+
1626
+ # Add persistent git options.
1627
+ call.extend(self._persistent_git_options)
1628
+
1629
+ # Add the git options, then reset to empty to avoid side effects.
1630
+ call.extend(self._git_options)
1631
+ self._git_options = ()
1632
+
1633
+ call.append(dashify(method))
1634
+ call.extend(args_list)
1635
+
1636
+ return self.execute(call, **exec_kwargs)
1637
+
1638
+ def _parse_object_header(self, header_line: str) -> Tuple[str, str, int]:
1639
+ """
1640
+ :param header_line:
1641
+ A line of the form::
1642
+
1643
+ <hex_sha> type_string size_as_int
1644
+
1645
+ :return:
1646
+ (hex_sha, type_string, size_as_int)
1647
+
1648
+ :raise ValueError:
1649
+ If the header contains indication for an error due to incorrect input sha.
1650
+ """
1651
+ tokens = header_line.split()
1652
+ if len(tokens) != 3:
1653
+ if not tokens:
1654
+ err_msg = (
1655
+ f"SHA is empty, possible dubious ownership in the repository "
1656
+ f"""at {self._working_dir}.\n If this is unintended run:\n\n """
1657
+ f""" "git config --global --add safe.directory {self._working_dir}" """
1658
+ )
1659
+ raise ValueError(err_msg)
1660
+ else:
1661
+ raise ValueError("SHA %s could not be resolved, git returned: %r" % (tokens[0], header_line.strip()))
1662
+ # END handle actual return value
1663
+ # END error handling
1664
+
1665
+ if len(tokens[0]) != 40:
1666
+ raise ValueError("Failed to parse header: %r" % header_line)
1667
+ return (tokens[0], tokens[1], int(tokens[2]))
1668
+
1669
+ def _prepare_ref(self, ref: AnyStr) -> bytes:
1670
+ # Required for command to separate refs on stdin, as bytes.
1671
+ if isinstance(ref, bytes):
1672
+ # Assume 40 bytes hexsha - bin-to-ascii for some reason returns bytes, not text.
1673
+ refstr: str = ref.decode("ascii")
1674
+ elif not isinstance(ref, str):
1675
+ refstr = str(ref) # Could be ref-object.
1676
+ else:
1677
+ refstr = ref
1678
+
1679
+ if not refstr.endswith("\n"):
1680
+ refstr += "\n"
1681
+ return refstr.encode(defenc)
1682
+
1683
+ def _get_persistent_cmd(self, attr_name: str, cmd_name: str, *args: Any, **kwargs: Any) -> "Git.AutoInterrupt":
1684
+ cur_val = getattr(self, attr_name)
1685
+ if cur_val is not None:
1686
+ return cur_val
1687
+
1688
+ options = {"istream": PIPE, "as_process": True}
1689
+ options.update(kwargs)
1690
+
1691
+ cmd = self._call_process(cmd_name, *args, **options)
1692
+ setattr(self, attr_name, cmd)
1693
+ cmd = cast("Git.AutoInterrupt", cmd)
1694
+ return cmd
1695
+
1696
+ def __get_object_header(self, cmd: "Git.AutoInterrupt", ref: AnyStr) -> Tuple[str, str, int]:
1697
+ if cmd.stdin and cmd.stdout:
1698
+ cmd.stdin.write(self._prepare_ref(ref))
1699
+ cmd.stdin.flush()
1700
+ return self._parse_object_header(cmd.stdout.readline())
1701
+ else:
1702
+ raise ValueError("cmd stdin was empty")
1703
+
1704
+ def get_object_header(self, ref: str) -> Tuple[str, str, int]:
1705
+ """Use this method to quickly examine the type and size of the object behind the
1706
+ given ref.
1707
+
1708
+ :note:
1709
+ The method will only suffer from the costs of command invocation once and
1710
+ reuses the command in subsequent calls.
1711
+
1712
+ :return:
1713
+ (hexsha, type_string, size_as_int)
1714
+ """
1715
+ cmd = self._get_persistent_cmd("cat_file_header", "cat_file", batch_check=True)
1716
+ return self.__get_object_header(cmd, ref)
1717
+
1718
+ def get_object_data(self, ref: str) -> Tuple[str, str, int, bytes]:
1719
+ """Similar to :meth:`get_object_header`, but returns object data as well.
1720
+
1721
+ :return:
1722
+ (hexsha, type_string, size_as_int, data_string)
1723
+
1724
+ :note:
1725
+ Not threadsafe.
1726
+ """
1727
+ hexsha, typename, size, stream = self.stream_object_data(ref)
1728
+ data = stream.read(size)
1729
+ del stream
1730
+ return (hexsha, typename, size, data)
1731
+
1732
+ def stream_object_data(self, ref: str) -> Tuple[str, str, int, "Git.CatFileContentStream"]:
1733
+ """Similar to :meth:`get_object_data`, but returns the data as a stream.
1734
+
1735
+ :return:
1736
+ (hexsha, type_string, size_as_int, stream)
1737
+
1738
+ :note:
1739
+ This method is not threadsafe. You need one independent :class:`Git`
1740
+ instance per thread to be safe!
1741
+ """
1742
+ cmd = self._get_persistent_cmd("cat_file_all", "cat_file", batch=True)
1743
+ hexsha, typename, size = self.__get_object_header(cmd, ref)
1744
+ cmd_stdout = cmd.stdout if cmd.stdout is not None else io.BytesIO()
1745
+ return (hexsha, typename, size, self.CatFileContentStream(size, cmd_stdout))
1746
+
1747
+ def clear_cache(self) -> "Git":
1748
+ """Clear all kinds of internal caches to release resources.
1749
+
1750
+ Currently persistent commands will be interrupted.
1751
+
1752
+ :return:
1753
+ self
1754
+ """
1755
+ for cmd in (self.cat_file_all, self.cat_file_header):
1756
+ if cmd:
1757
+ cmd.__del__()
1758
+
1759
+ self.cat_file_all = None
1760
+ self.cat_file_header = None
1761
+ return self
.venv/lib/python3.11/site-packages/git/compat.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
2
+ #
3
+ # This module is part of GitPython and is released under the
4
+ # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
5
+
6
+ """Utilities to help provide compatibility with Python 3.
7
+
8
+ This module exists for historical reasons. Code outside GitPython may make use of public
9
+ members of this module, but is unlikely to benefit from doing so. GitPython continues to
10
+ use some of these utilities, in some cases for compatibility across different platforms.
11
+ """
12
+
13
+ import locale
14
+ import os
15
+ import sys
16
+ import warnings
17
+
18
+ from gitdb.utils.encoding import force_bytes, force_text # noqa: F401
19
+
20
+ # typing --------------------------------------------------------------------
21
+
22
+ from typing import (
23
+ Any, # noqa: F401
24
+ AnyStr,
25
+ Dict, # noqa: F401
26
+ IO, # noqa: F401
27
+ List,
28
+ Optional,
29
+ TYPE_CHECKING,
30
+ Tuple, # noqa: F401
31
+ Type, # noqa: F401
32
+ Union,
33
+ overload,
34
+ )
35
+
36
+ # ---------------------------------------------------------------------------
37
+
38
+
39
+ _deprecated_platform_aliases = {
40
+ "is_win": os.name == "nt",
41
+ "is_posix": os.name == "posix",
42
+ "is_darwin": sys.platform == "darwin",
43
+ }
44
+
45
+
46
+ def _getattr(name: str) -> Any:
47
+ try:
48
+ value = _deprecated_platform_aliases[name]
49
+ except KeyError:
50
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
51
+
52
+ warnings.warn(
53
+ f"{__name__}.{name} and other is_<platform> aliases are deprecated. "
54
+ "Write the desired os.name or sys.platform check explicitly instead.",
55
+ DeprecationWarning,
56
+ stacklevel=2,
57
+ )
58
+ return value
59
+
60
+
61
+ if not TYPE_CHECKING: # Preserve static checking for undefined/misspelled attributes.
62
+ __getattr__ = _getattr
63
+
64
+
65
+ def __dir__() -> List[str]:
66
+ return [*globals(), *_deprecated_platform_aliases]
67
+
68
+
69
+ is_win: bool
70
+ """Deprecated alias for ``os.name == "nt"`` to check for native Windows.
71
+
72
+ This is deprecated because it is clearer to write out :attr:`os.name` or
73
+ :attr:`sys.platform` checks explicitly, especially in cases where it matters which is
74
+ used.
75
+
76
+ :note:
77
+ ``is_win`` is ``False`` on Cygwin, but is often wrongly assumed ``True``. To detect
78
+ Cygwin, use ``sys.platform == "cygwin"``.
79
+ """
80
+
81
+ is_posix: bool
82
+ """Deprecated alias for ``os.name == "posix"`` to check for Unix-like ("POSIX") systems.
83
+
84
+ This is deprecated because it clearer to write out :attr:`os.name` or
85
+ :attr:`sys.platform` checks explicitly, especially in cases where it matters which is
86
+ used.
87
+
88
+ :note:
89
+ For POSIX systems, more detailed information is available in :attr:`sys.platform`,
90
+ while :attr:`os.name` is always ``"posix"`` on such systems, including macOS
91
+ (Darwin).
92
+ """
93
+
94
+ is_darwin: bool
95
+ """Deprecated alias for ``sys.platform == "darwin"`` to check for macOS (Darwin).
96
+
97
+ This is deprecated because it clearer to write out :attr:`os.name` or
98
+ :attr:`sys.platform` checks explicitly.
99
+
100
+ :note:
101
+ For macOS (Darwin), ``os.name == "posix"`` as in other Unix-like systems, while
102
+ ``sys.platform == "darwin"``.
103
+ """
104
+
105
+ defenc = sys.getfilesystemencoding()
106
+ """The encoding used to convert between Unicode and bytes filenames."""
107
+
108
+
109
+ @overload
110
+ def safe_decode(s: None) -> None: ...
111
+
112
+
113
+ @overload
114
+ def safe_decode(s: AnyStr) -> str: ...
115
+
116
+
117
+ def safe_decode(s: Union[AnyStr, None]) -> Optional[str]:
118
+ """Safely decode a binary string to Unicode."""
119
+ if isinstance(s, str):
120
+ return s
121
+ elif isinstance(s, bytes):
122
+ return s.decode(defenc, "surrogateescape")
123
+ elif s is None:
124
+ return None
125
+ else:
126
+ raise TypeError("Expected bytes or text, but got %r" % (s,))
127
+
128
+
129
+ @overload
130
+ def safe_encode(s: None) -> None: ...
131
+
132
+
133
+ @overload
134
+ def safe_encode(s: AnyStr) -> bytes: ...
135
+
136
+
137
+ def safe_encode(s: Optional[AnyStr]) -> Optional[bytes]:
138
+ """Safely encode a binary string to Unicode."""
139
+ if isinstance(s, str):
140
+ return s.encode(defenc)
141
+ elif isinstance(s, bytes):
142
+ return s
143
+ elif s is None:
144
+ return None
145
+ else:
146
+ raise TypeError("Expected bytes or text, but got %r" % (s,))
147
+
148
+
149
+ @overload
150
+ def win_encode(s: None) -> None: ...
151
+
152
+
153
+ @overload
154
+ def win_encode(s: AnyStr) -> bytes: ...
155
+
156
+
157
+ def win_encode(s: Optional[AnyStr]) -> Optional[bytes]:
158
+ """Encode Unicode strings for process arguments on Windows."""
159
+ if isinstance(s, str):
160
+ return s.encode(locale.getpreferredencoding(False))
161
+ elif isinstance(s, bytes):
162
+ return s
163
+ elif s is not None:
164
+ raise TypeError("Expected bytes or text, but got %r" % (s,))
165
+ return None
.venv/lib/python3.11/site-packages/git/config.py ADDED
@@ -0,0 +1,998 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
2
+ #
3
+ # This module is part of GitPython and is released under the
4
+ # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
5
+
6
+ """Parser for reading and writing configuration files."""
7
+
8
+ __all__ = ["GitConfigParser", "SectionConstraint"]
9
+
10
+ import abc
11
+ import configparser as cp
12
+ import fnmatch
13
+ from functools import wraps
14
+ import inspect
15
+ from io import BufferedReader, IOBase
16
+ import logging
17
+ import os
18
+ import os.path as osp
19
+ import re
20
+ import sys
21
+
22
+ from git.compat import defenc, force_text
23
+ from git.util import LockFile
24
+
25
+ # typing-------------------------------------------------------
26
+
27
+ from typing import (
28
+ Any,
29
+ Callable,
30
+ Generic,
31
+ IO,
32
+ List,
33
+ Dict,
34
+ Sequence,
35
+ TYPE_CHECKING,
36
+ Tuple,
37
+ TypeVar,
38
+ Union,
39
+ cast,
40
+ )
41
+
42
+ from git.types import Lit_config_levels, ConfigLevels_Tup, PathLike, assert_never, _T
43
+
44
+ if TYPE_CHECKING:
45
+ from io import BytesIO
46
+
47
+ from git.repo.base import Repo
48
+
49
+ T_ConfigParser = TypeVar("T_ConfigParser", bound="GitConfigParser")
50
+ T_OMD_value = TypeVar("T_OMD_value", str, bytes, int, float, bool)
51
+
52
+ if sys.version_info[:3] < (3, 7, 2):
53
+ # typing.Ordereddict not added until Python 3.7.2.
54
+ from collections import OrderedDict
55
+
56
+ OrderedDict_OMD = OrderedDict
57
+ else:
58
+ from typing import OrderedDict
59
+
60
+ OrderedDict_OMD = OrderedDict[str, List[T_OMD_value]] # type: ignore[assignment, misc]
61
+
62
+ # -------------------------------------------------------------
63
+
64
+ _logger = logging.getLogger(__name__)
65
+
66
+ CONFIG_LEVELS: ConfigLevels_Tup = ("system", "user", "global", "repository")
67
+ """The configuration level of a configuration file."""
68
+
69
+ CONDITIONAL_INCLUDE_REGEXP = re.compile(r"(?<=includeIf )\"(gitdir|gitdir/i|onbranch|hasconfig:remote\.\*\.url):(.+)\"")
70
+ """Section pattern to detect conditional includes.
71
+
72
+ See: https://git-scm.com/docs/git-config#_conditional_includes
73
+ """
74
+
75
+ UNSAFE_CONFIG_CHARS_RE = re.compile(r"[\r\n\x00]")
76
+ """Characters that cannot be safely written in config names or values."""
77
+
78
+
79
+ class MetaParserBuilder(abc.ABCMeta): # noqa: B024
80
+ """Utility class wrapping base-class methods into decorators that assure read-only
81
+ properties."""
82
+
83
+ def __new__(cls, name: str, bases: Tuple, clsdict: Dict[str, Any]) -> "MetaParserBuilder":
84
+ """Equip all base-class methods with a needs_values decorator, and all non-const
85
+ methods with a :func:`set_dirty_and_flush_changes` decorator in addition to
86
+ that.
87
+ """
88
+ kmm = "_mutating_methods_"
89
+ if kmm in clsdict:
90
+ mutating_methods = clsdict[kmm]
91
+ for base in bases:
92
+ methods = (t for t in inspect.getmembers(base, inspect.isroutine) if not t[0].startswith("_"))
93
+ for method_name, method in methods:
94
+ if method_name in clsdict:
95
+ continue
96
+ method_with_values = needs_values(method)
97
+ if method_name in mutating_methods:
98
+ method_with_values = set_dirty_and_flush_changes(method_with_values)
99
+ # END mutating methods handling
100
+
101
+ clsdict[method_name] = method_with_values
102
+ # END for each name/method pair
103
+ # END for each base
104
+ # END if mutating methods configuration is set
105
+
106
+ new_type = super().__new__(cls, name, bases, clsdict)
107
+ return new_type
108
+
109
+
110
+ def needs_values(func: Callable[..., _T]) -> Callable[..., _T]:
111
+ """Return a method for ensuring we read values (on demand) before we try to access
112
+ them."""
113
+
114
+ @wraps(func)
115
+ def assure_data_present(self: "GitConfigParser", *args: Any, **kwargs: Any) -> _T:
116
+ self.read()
117
+ return func(self, *args, **kwargs)
118
+
119
+ # END wrapper method
120
+ return assure_data_present
121
+
122
+
123
+ def set_dirty_and_flush_changes(non_const_func: Callable[..., _T]) -> Callable[..., _T]:
124
+ """Return a method that checks whether given non constant function may be called.
125
+
126
+ If so, the instance will be set dirty. Additionally, we flush the changes right to
127
+ disk.
128
+ """
129
+
130
+ def flush_changes(self: "GitConfigParser", *args: Any, **kwargs: Any) -> _T:
131
+ rval = non_const_func(self, *args, **kwargs)
132
+ self._dirty = True
133
+ self.write()
134
+ return rval
135
+
136
+ # END wrapper method
137
+ flush_changes.__name__ = non_const_func.__name__
138
+ return flush_changes
139
+
140
+
141
+ class SectionConstraint(Generic[T_ConfigParser]):
142
+ """Constrains a ConfigParser to only option commands which are constrained to
143
+ always use the section we have been initialized with.
144
+
145
+ It supports all ConfigParser methods that operate on an option.
146
+
147
+ :note:
148
+ If used as a context manager, will release the wrapped ConfigParser.
149
+ """
150
+
151
+ __slots__ = ("_config", "_section_name")
152
+
153
+ _valid_attrs_ = (
154
+ "get_value",
155
+ "set_value",
156
+ "get",
157
+ "set",
158
+ "getint",
159
+ "getfloat",
160
+ "getboolean",
161
+ "has_option",
162
+ "remove_section",
163
+ "remove_option",
164
+ "options",
165
+ )
166
+
167
+ def __init__(self, config: T_ConfigParser, section: str) -> None:
168
+ self._config = config
169
+ self._section_name = section
170
+
171
+ def __del__(self) -> None:
172
+ # Yes, for some reason, we have to call it explicitly for it to work in PY3 !
173
+ # Apparently __del__ doesn't get call anymore if refcount becomes 0
174
+ # Ridiculous ... .
175
+ self._config.release()
176
+
177
+ def __getattr__(self, attr: str) -> Any:
178
+ if attr in self._valid_attrs_:
179
+ return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs)
180
+ return super().__getattribute__(attr)
181
+
182
+ def _call_config(self, method: str, *args: Any, **kwargs: Any) -> Any:
183
+ """Call the configuration at the given method which must take a section name as
184
+ first argument."""
185
+ return getattr(self._config, method)(self._section_name, *args, **kwargs)
186
+
187
+ @property
188
+ def config(self) -> T_ConfigParser:
189
+ """return: ConfigParser instance we constrain"""
190
+ return self._config
191
+
192
+ def release(self) -> None:
193
+ """Equivalent to :meth:`GitConfigParser.release`, which is called on our
194
+ underlying parser instance."""
195
+ return self._config.release()
196
+
197
+ def __enter__(self) -> "SectionConstraint[T_ConfigParser]":
198
+ self._config.__enter__()
199
+ return self
200
+
201
+ def __exit__(self, exception_type: str, exception_value: str, traceback: str) -> None:
202
+ self._config.__exit__(exception_type, exception_value, traceback)
203
+
204
+
205
+ class _OMD(OrderedDict_OMD):
206
+ """Ordered multi-dict."""
207
+
208
+ def __setitem__(self, key: str, value: _T) -> None:
209
+ super().__setitem__(key, [value])
210
+
211
+ def add(self, key: str, value: Any) -> None:
212
+ if key not in self:
213
+ super().__setitem__(key, [value])
214
+ return
215
+
216
+ super().__getitem__(key).append(value)
217
+
218
+ def setall(self, key: str, values: List[_T]) -> None:
219
+ super().__setitem__(key, values)
220
+
221
+ def __getitem__(self, key: str) -> Any:
222
+ return super().__getitem__(key)[-1]
223
+
224
+ def getlast(self, key: str) -> Any:
225
+ return super().__getitem__(key)[-1]
226
+
227
+ def setlast(self, key: str, value: Any) -> None:
228
+ if key not in self:
229
+ super().__setitem__(key, [value])
230
+ return
231
+
232
+ prior = super().__getitem__(key)
233
+ prior[-1] = value
234
+
235
+ def get(self, key: str, default: Union[_T, None] = None) -> Union[_T, None]:
236
+ return super().get(key, [default])[-1]
237
+
238
+ def getall(self, key: str) -> List[_T]:
239
+ return super().__getitem__(key)
240
+
241
+ def items(self) -> List[Tuple[str, _T]]: # type: ignore[override]
242
+ """List of (key, last value for key)."""
243
+ return [(k, self[k]) for k in self]
244
+
245
+ def items_all(self) -> List[Tuple[str, List[_T]]]:
246
+ """List of (key, list of values for key)."""
247
+ return [(k, self.getall(k)) for k in self]
248
+
249
+
250
+ def get_config_path(config_level: Lit_config_levels) -> str:
251
+ # We do not support an absolute path of the gitconfig on Windows.
252
+ # Use the global config instead.
253
+ if sys.platform == "win32" and config_level == "system":
254
+ config_level = "global"
255
+
256
+ if config_level == "system":
257
+ return "/etc/gitconfig"
258
+ elif config_level == "user":
259
+ config_home = os.environ.get("XDG_CONFIG_HOME") or osp.join(os.environ.get("HOME", "~"), ".config")
260
+ return osp.normpath(osp.expanduser(osp.join(config_home, "git", "config")))
261
+ elif config_level == "global":
262
+ return osp.normpath(osp.expanduser("~/.gitconfig"))
263
+ elif config_level == "repository":
264
+ raise ValueError("No repo to get repository configuration from. Use Repo._get_config_path")
265
+ else:
266
+ # Should not reach here. Will raise ValueError if does. Static typing will warn
267
+ # about missing elifs.
268
+ assert_never( # type: ignore[unreachable]
269
+ config_level,
270
+ ValueError(f"Invalid configuration level: {config_level!r}"),
271
+ )
272
+
273
+
274
+ class GitConfigParser(cp.RawConfigParser, metaclass=MetaParserBuilder):
275
+ """Implements specifics required to read git style configuration files.
276
+
277
+ This variation behaves much like the :manpage:`git-config(1)` command, such that the
278
+ configuration will be read on demand based on the filepath given during
279
+ initialization.
280
+
281
+ The changes will automatically be written once the instance goes out of scope, but
282
+ can be triggered manually as well.
283
+
284
+ The configuration file will be locked if you intend to change values preventing
285
+ other instances to write concurrently.
286
+
287
+ :note:
288
+ The config is case-sensitive even when queried, hence section and option names
289
+ must match perfectly.
290
+
291
+ :note:
292
+ If used as a context manager, this will release the locked file.
293
+ """
294
+
295
+ # { Configuration
296
+ t_lock = LockFile
297
+ """The lock type determines the type of lock to use in new configuration readers.
298
+
299
+ They must be compatible to the :class:`~git.util.LockFile` interface.
300
+ A suitable alternative would be the :class:`~git.util.BlockingLockFile`.
301
+ """
302
+
303
+ re_comment = re.compile(r"^\s*[#;]")
304
+ # } END configuration
305
+
306
+ optvalueonly_source = r"\s*(?P<option>[^:=\s][^:=]*)"
307
+
308
+ OPTVALUEONLY = re.compile(optvalueonly_source)
309
+
310
+ OPTCRE = re.compile(optvalueonly_source + r"\s*(?P<vi>[:=])\s*" + r"(?P<value>.*)$")
311
+
312
+ del optvalueonly_source
313
+
314
+ _mutating_methods_ = ("add_section", "remove_section", "remove_option", "set")
315
+ """Names of :class:`~configparser.RawConfigParser` methods able to change the
316
+ instance."""
317
+
318
+ def __init__(
319
+ self,
320
+ file_or_files: Union[None, PathLike, "BytesIO", Sequence[Union[PathLike, "BytesIO"]]] = None,
321
+ read_only: bool = True,
322
+ merge_includes: bool = True,
323
+ config_level: Union[Lit_config_levels, None] = None,
324
+ repo: Union["Repo", None] = None,
325
+ ) -> None:
326
+ """Initialize a configuration reader to read the given `file_or_files` and to
327
+ possibly allow changes to it by setting `read_only` False.
328
+
329
+ :param file_or_files:
330
+ A file path or file object, or a sequence of possibly more than one of them.
331
+
332
+ :param read_only:
333
+ If ``True``, the ConfigParser may only read the data, but not change it.
334
+ If ``False``, only a single file path or file object may be given. We will
335
+ write back the changes when they happen, or when the ConfigParser is
336
+ released. This will not happen if other configuration files have been
337
+ included.
338
+
339
+ :param merge_includes:
340
+ If ``True``, we will read files mentioned in ``[include]`` sections and
341
+ merge their contents into ours. This makes it impossible to write back an
342
+ individual configuration file. Thus, if you want to modify a single
343
+ configuration file, turn this off to leave the original dataset unaltered
344
+ when reading it.
345
+
346
+ :param repo:
347
+ Reference to repository to use if ``[includeIf]`` sections are found in
348
+ configuration files.
349
+ """
350
+ cp.RawConfigParser.__init__(self, dict_type=_OMD)
351
+ self._dict: Callable[..., _OMD]
352
+ self._defaults: _OMD
353
+ self._sections: _OMD
354
+
355
+ # Used in Python 3. Needs to stay in sync with sections for underlying
356
+ # implementation to work.
357
+ if not hasattr(self, "_proxies"):
358
+ self._proxies = self._dict()
359
+
360
+ if file_or_files is not None:
361
+ self._file_or_files: Union[PathLike, "BytesIO", Sequence[Union[PathLike, "BytesIO"]]] = file_or_files
362
+ else:
363
+ if config_level is None:
364
+ if read_only:
365
+ self._file_or_files = [
366
+ get_config_path(cast(Lit_config_levels, f)) for f in CONFIG_LEVELS if f != "repository"
367
+ ]
368
+ else:
369
+ raise ValueError("No configuration level or configuration files specified")
370
+ else:
371
+ self._file_or_files = [get_config_path(config_level)]
372
+
373
+ self._read_only = read_only
374
+ self._dirty = False
375
+ self._is_initialized = False
376
+ self._merge_includes = merge_includes
377
+ self._repo = repo
378
+ self._lock: Union["LockFile", None] = None
379
+ self._acquire_lock()
380
+
381
+ def _acquire_lock(self) -> None:
382
+ if not self._read_only:
383
+ if not self._lock:
384
+ if isinstance(self._file_or_files, (str, os.PathLike)):
385
+ file_or_files = self._file_or_files
386
+ elif isinstance(self._file_or_files, (tuple, list, Sequence)):
387
+ raise ValueError(
388
+ "Write-ConfigParsers can operate on a single file only, multiple files have been passed"
389
+ )
390
+ else:
391
+ file_or_files = self._file_or_files.name
392
+
393
+ # END get filename from handle/stream
394
+ # Initialize lock base - we want to write.
395
+ self._lock = self.t_lock(file_or_files)
396
+ # END lock check
397
+
398
+ self._lock._obtain_lock()
399
+ # END read-only check
400
+
401
+ def __del__(self) -> None:
402
+ """Write pending changes if required and release locks."""
403
+ # NOTE: Only consistent in Python 2.
404
+ self.release()
405
+
406
+ def __enter__(self) -> "GitConfigParser":
407
+ self._acquire_lock()
408
+ return self
409
+
410
+ def __exit__(self, *args: Any) -> None:
411
+ self.release()
412
+
413
+ def release(self) -> None:
414
+ """Flush changes and release the configuration write lock. This instance must
415
+ not be used anymore afterwards.
416
+
417
+ In Python 3, it's required to explicitly release locks and flush changes, as
418
+ ``__del__`` is not called deterministically anymore.
419
+ """
420
+ # Checking for the lock here makes sure we do not raise during write()
421
+ # in case an invalid parser was created who could not get a lock.
422
+ if self.read_only or (self._lock and not self._lock._has_lock()):
423
+ return
424
+
425
+ try:
426
+ self.write()
427
+ except IOError:
428
+ _logger.error("Exception during destruction of GitConfigParser", exc_info=True)
429
+ except ReferenceError:
430
+ # This happens in Python 3... and usually means that some state cannot be
431
+ # written as the sections dict cannot be iterated. This usually happens when
432
+ # the interpreter is shutting down. Can it be fixed?
433
+ pass
434
+ finally:
435
+ if self._lock is not None:
436
+ self._lock._release_lock()
437
+
438
+ def optionxform(self, optionstr: str) -> str:
439
+ """Do not transform options in any way when writing."""
440
+ return optionstr
441
+
442
+ def _read(self, fp: Union[BufferedReader, IO[bytes]], fpname: str) -> None:
443
+ """Originally a direct copy of the Python 2.4 version of
444
+ :meth:`RawConfigParser._read <configparser.RawConfigParser._read>`, to ensure it
445
+ uses ordered dicts.
446
+
447
+ The ordering bug was fixed in Python 2.4, and dict itself keeps ordering since
448
+ Python 3.7. This has some other changes, especially that it ignores initial
449
+ whitespace, since git uses tabs. (Big comments are removed to be more compact.)
450
+ """
451
+ cursect = None # None, or a dictionary.
452
+ optname = None
453
+ lineno = 0
454
+ is_multi_line = False
455
+ e = None # None, or an exception.
456
+
457
+ def string_decode(v: str) -> str:
458
+ if v and v.endswith("\\"):
459
+ v = v[:-1]
460
+ # END cut trailing escapes to prevent decode error
461
+
462
+ return v.encode(defenc).decode("unicode_escape")
463
+
464
+ # END string_decode
465
+
466
+ while True:
467
+ # We assume to read binary!
468
+ line = fp.readline().decode(defenc)
469
+ if not line:
470
+ break
471
+ lineno = lineno + 1
472
+ # Comment or blank line?
473
+ if line.strip() == "" or self.re_comment.match(line):
474
+ continue
475
+ if line.split(None, 1)[0].lower() == "rem" and line[0] in "rR":
476
+ # No leading whitespace.
477
+ continue
478
+
479
+ # Is it a section header?
480
+ mo = self.SECTCRE.match(line.strip())
481
+ if not is_multi_line and mo:
482
+ sectname: str = mo.group("header").strip()
483
+ if sectname in self._sections:
484
+ cursect = self._sections[sectname]
485
+ elif sectname == cp.DEFAULTSECT:
486
+ cursect = self._defaults
487
+ else:
488
+ cursect = self._dict((("__name__", sectname),))
489
+ self._sections[sectname] = cursect
490
+ self._proxies[sectname] = None
491
+ # So sections can't start with a continuation line.
492
+ optname = None
493
+ # No section header in the file?
494
+ elif cursect is None:
495
+ raise cp.MissingSectionHeaderError(fpname, lineno, line)
496
+ # An option line?
497
+ elif not is_multi_line:
498
+ mo = self.OPTCRE.match(line)
499
+ if mo:
500
+ # We might just have handled the last line, which could contain a quotation we want to remove.
501
+ optname, vi, optval = mo.group("option", "vi", "value")
502
+ optname = self.optionxform(optname.rstrip())
503
+
504
+ if vi in ("=", ":") and ";" in optval and not optval.strip().startswith('"'):
505
+ pos = optval.find(";")
506
+ if pos != -1 and optval[pos - 1].isspace():
507
+ optval = optval[:pos]
508
+ optval = optval.strip()
509
+
510
+ if len(optval) < 2 or optval[0] != '"':
511
+ # Does not open quoting.
512
+ pass
513
+ elif optval[-1] != '"':
514
+ # Opens quoting and does not close: appears to start multi-line quoting.
515
+ is_multi_line = True
516
+ optval = string_decode(optval[1:])
517
+ elif optval.find("\\", 1, -1) == -1 and optval.find('"', 1, -1) == -1:
518
+ # Opens and closes quoting. Single line, and all we need is quote removal.
519
+ optval = optval[1:-1]
520
+ # TODO: Handle other quoted content, especially well-formed backslash escapes.
521
+
522
+ # Preserves multiple values for duplicate optnames.
523
+ cursect.add(optname, optval)
524
+ else:
525
+ # Check if it's an option with no value - it's just ignored by git.
526
+ if not self.OPTVALUEONLY.match(line):
527
+ if not e:
528
+ e = cp.ParsingError(fpname)
529
+ e.append(lineno, repr(line))
530
+ continue
531
+ else:
532
+ line = line.rstrip()
533
+ if line.endswith('"'):
534
+ is_multi_line = False
535
+ line = line[:-1]
536
+ # END handle quotations
537
+ optval = cursect.getlast(optname)
538
+ cursect.setlast(optname, optval + string_decode(line))
539
+ # END parse section or option
540
+ # END while reading
541
+
542
+ # If any parsing errors occurred, raise an exception.
543
+ if e:
544
+ raise e
545
+
546
+ def _has_includes(self) -> Union[bool, int]:
547
+ return self._merge_includes and len(self._included_paths())
548
+
549
+ def _included_paths(self) -> List[Tuple[str, str]]:
550
+ """List all paths that must be included to configuration.
551
+
552
+ :return:
553
+ The list of paths, where each path is a tuple of (option, value).
554
+ """
555
+
556
+ def _all_items(section: str) -> List[Tuple[str, str]]:
557
+ """Return all (key, value) pairs for a section, including duplicate keys."""
558
+ return [
559
+ (key, value)
560
+ for key, values in self._sections[section].items_all()
561
+ if key != "__name__"
562
+ for value in values
563
+ ]
564
+
565
+ paths = []
566
+
567
+ for section in self.sections():
568
+ if section == "include":
569
+ paths += _all_items(section)
570
+
571
+ match = CONDITIONAL_INCLUDE_REGEXP.search(section)
572
+ if match is None or self._repo is None:
573
+ continue
574
+
575
+ keyword = match.group(1)
576
+ value = match.group(2).strip()
577
+
578
+ if keyword in ["gitdir", "gitdir/i"]:
579
+ value = osp.expanduser(value)
580
+
581
+ if not any(value.startswith(s) for s in ["./", "/"]):
582
+ value = "**/" + value
583
+ if value.endswith("/"):
584
+ value += "**"
585
+
586
+ # Ensure that glob is always case insensitive if required.
587
+ if keyword.endswith("/i"):
588
+ value = re.sub(
589
+ r"[a-zA-Z]",
590
+ lambda m: f"[{m.group().lower()!r}{m.group().upper()!r}]",
591
+ value,
592
+ )
593
+ if self._repo.git_dir:
594
+ if fnmatch.fnmatchcase(os.fspath(self._repo.git_dir), value):
595
+ paths += _all_items(section)
596
+
597
+ elif keyword == "onbranch":
598
+ try:
599
+ branch_name = self._repo.active_branch.name
600
+ except TypeError:
601
+ # Ignore section if active branch cannot be retrieved.
602
+ continue
603
+
604
+ if fnmatch.fnmatchcase(branch_name, value):
605
+ paths += _all_items(section)
606
+ elif keyword == "hasconfig:remote.*.url":
607
+ for remote in self._repo.remotes:
608
+ if fnmatch.fnmatchcase(remote.url, value):
609
+ paths += _all_items(section)
610
+ break
611
+ return paths
612
+
613
+ def read(self) -> None: # type: ignore[override]
614
+ """Read the data stored in the files we have been initialized with.
615
+
616
+ This will ignore files that cannot be read, possibly leaving an empty
617
+ configuration.
618
+
619
+ :raise IOError:
620
+ If a file cannot be handled.
621
+ """
622
+ if self._is_initialized:
623
+ return
624
+ self._is_initialized = True
625
+
626
+ files_to_read: List[Union[PathLike, IO]] = [""]
627
+ if isinstance(self._file_or_files, (str, os.PathLike)):
628
+ # For str or Path, as str is a type of Sequence.
629
+ files_to_read = [self._file_or_files]
630
+ elif not isinstance(self._file_or_files, (tuple, list, Sequence)):
631
+ # Could merge with above isinstance once runtime type known.
632
+ files_to_read = [self._file_or_files]
633
+ else: # For lists or tuples.
634
+ files_to_read = list(self._file_or_files)
635
+ # END ensure we have a copy of the paths to handle
636
+
637
+ seen = set(files_to_read)
638
+ num_read_include_files = 0
639
+ while files_to_read:
640
+ file_path = files_to_read.pop(0)
641
+ file_ok = False
642
+
643
+ if hasattr(file_path, "seek"):
644
+ # Must be a file-object.
645
+ # TODO: Replace cast with assert to narrow type, once sure.
646
+ file_path = cast(IO[bytes], file_path)
647
+ self._read(file_path, file_path.name)
648
+ else:
649
+ try:
650
+ with open(file_path, "rb") as fp:
651
+ file_ok = True
652
+ self._read(fp, fp.name)
653
+ except IOError:
654
+ continue
655
+
656
+ # Read includes and append those that we didn't handle yet. We expect all
657
+ # paths to be normalized and absolute (and will ensure that is the case).
658
+ if self._has_includes():
659
+ for _, include_path in self._included_paths():
660
+ if include_path.startswith("~"):
661
+ include_path = osp.expanduser(include_path)
662
+ if not osp.isabs(include_path):
663
+ if not file_ok:
664
+ continue
665
+ # END ignore relative paths if we don't know the configuration file path
666
+ file_path = cast(PathLike, file_path)
667
+ assert osp.isabs(file_path), "Need absolute paths to be sure our cycle checks will work"
668
+ include_path = osp.join(osp.dirname(file_path), include_path)
669
+ # END make include path absolute
670
+ include_path = osp.normpath(include_path)
671
+ if include_path in seen or not os.access(include_path, os.R_OK):
672
+ continue
673
+ seen.add(include_path)
674
+ # Insert included file to the top to be considered first.
675
+ files_to_read.insert(0, include_path)
676
+ num_read_include_files += 1
677
+ # END each include path in configuration file
678
+ # END handle includes
679
+ # END for each file object to read
680
+
681
+ # If there was no file included, we can safely write back (potentially) the
682
+ # configuration file without altering its meaning.
683
+ if num_read_include_files == 0:
684
+ self._merge_includes = False
685
+
686
+ def _write(self, fp: IO) -> None:
687
+ """Write an .ini-format representation of the configuration state in
688
+ git compatible format."""
689
+
690
+ def write_section(name: str, section_dict: _OMD) -> None:
691
+ fp.write(("[%s]\n" % name).encode(defenc))
692
+
693
+ values: Sequence[str] # Runtime only gets str in tests, but should be whatever _OMD stores.
694
+ v: str
695
+ for key, values in section_dict.items_all():
696
+ if key == "__name__":
697
+ continue
698
+
699
+ for v in values:
700
+ fp.write(("\t%s = %s\n" % (key, self._value_to_string(v).replace("\n", "\n\t"))).encode(defenc))
701
+ # END if key is not __name__
702
+
703
+ # END section writing
704
+
705
+ if self._defaults:
706
+ write_section(cp.DEFAULTSECT, self._defaults)
707
+ value: _OMD
708
+
709
+ for name, value in self._sections.items():
710
+ write_section(name, value)
711
+
712
+ def items(self, section_name: str) -> List[Tuple[str, str]]: # type: ignore[override]
713
+ """:return: list((option, value), ...) pairs of all items in the given section"""
714
+ return [(k, v) for k, v in super().items(section_name) if k != "__name__"]
715
+
716
+ def items_all(self, section_name: str) -> List[Tuple[str, List[str]]]:
717
+ """:return: list((option, [values...]), ...) pairs of all items in the given section"""
718
+ rv = _OMD(self._defaults)
719
+
720
+ for k, vs in self._sections[section_name].items_all():
721
+ if k == "__name__":
722
+ continue
723
+
724
+ if k in rv and rv.getall(k) == vs:
725
+ continue
726
+
727
+ for v in vs:
728
+ rv.add(k, v)
729
+
730
+ return rv.items_all()
731
+
732
+ @needs_values
733
+ def write(self) -> None:
734
+ """Write changes to our file, if there are changes at all.
735
+
736
+ :raise IOError:
737
+ If this is a read-only writer instance or if we could not obtain a file
738
+ lock.
739
+ """
740
+ self._assure_writable("write")
741
+ if not self._dirty:
742
+ return
743
+
744
+ if isinstance(self._file_or_files, (list, tuple)):
745
+ raise AssertionError(
746
+ "Cannot write back if there is not exactly a single file to write to, have %i files"
747
+ % len(self._file_or_files)
748
+ )
749
+ # END assert multiple files
750
+
751
+ if self._has_includes():
752
+ _logger.debug(
753
+ "Skipping write-back of configuration file as include files were merged in."
754
+ + "Set merge_includes=False to prevent this."
755
+ )
756
+ return
757
+ # END stop if we have include files
758
+
759
+ fp = self._file_or_files
760
+
761
+ # We have a physical file on disk, so get a lock.
762
+ is_file_lock = isinstance(fp, (str, os.PathLike, IOBase)) # TODO: Use PathLike (having dropped 3.5).
763
+ if is_file_lock and self._lock is not None: # Else raise error?
764
+ self._lock._obtain_lock()
765
+
766
+ if not hasattr(fp, "seek"):
767
+ fp = cast(PathLike, fp)
768
+ with open(fp, "wb") as fp_open:
769
+ self._write(fp_open)
770
+ else:
771
+ fp = cast("BytesIO", fp)
772
+ fp.seek(0)
773
+ # Make sure we do not overwrite into an existing file.
774
+ if hasattr(fp, "truncate"):
775
+ fp.truncate()
776
+ self._write(fp)
777
+
778
+ def _assure_writable(self, method_name: str) -> None:
779
+ if self.read_only:
780
+ raise IOError("Cannot execute non-constant method %s.%s" % (self, method_name))
781
+
782
+ def add_section(self, section: "cp._SectionName") -> None:
783
+ """Assures added options will stay in order."""
784
+ self._assure_config_name_safe(section, "section")
785
+ return super().add_section(section)
786
+
787
+ @property
788
+ def read_only(self) -> bool:
789
+ """:return: ``True`` if this instance may change the configuration file"""
790
+ return self._read_only
791
+
792
+ # FIXME: Figure out if default or return type can really include bool.
793
+ def get_value(
794
+ self,
795
+ section: str,
796
+ option: str,
797
+ default: Union[int, float, str, bool, None] = None,
798
+ ) -> Union[int, float, str, bool]:
799
+ """Get an option's value.
800
+
801
+ If multiple values are specified for this option in the section, the last one
802
+ specified is returned.
803
+
804
+ :param default:
805
+ If not ``None``, the given default value will be returned in case the option
806
+ did not exist.
807
+
808
+ :return:
809
+ A properly typed value, either int, float or string
810
+
811
+ :raise TypeError:
812
+ In case the value could not be understood.
813
+ Otherwise the exceptions known to the ConfigParser will be raised.
814
+ """
815
+ try:
816
+ valuestr = self.get(section, option)
817
+ except Exception:
818
+ if default is not None:
819
+ return default
820
+ raise
821
+
822
+ return self._string_to_value(valuestr)
823
+
824
+ def get_values(
825
+ self,
826
+ section: str,
827
+ option: str,
828
+ default: Union[int, float, str, bool, None] = None,
829
+ ) -> List[Union[int, float, str, bool]]:
830
+ """Get an option's values.
831
+
832
+ If multiple values are specified for this option in the section, all are
833
+ returned.
834
+
835
+ :param default:
836
+ If not ``None``, a list containing the given default value will be returned
837
+ in case the option did not exist.
838
+
839
+ :return:
840
+ A list of properly typed values, either int, float or string
841
+
842
+ :raise TypeError:
843
+ In case the value could not be understood.
844
+ Otherwise the exceptions known to the ConfigParser will be raised.
845
+ """
846
+ try:
847
+ self.sections()
848
+ lst = self._sections[section].getall(option)
849
+ except Exception:
850
+ if default is not None:
851
+ return [default]
852
+ raise
853
+
854
+ return [self._string_to_value(valuestr) for valuestr in lst]
855
+
856
+ def _string_to_value(self, valuestr: str) -> Union[int, float, str, bool]:
857
+ types = (int, float)
858
+ for numtype in types:
859
+ try:
860
+ val = numtype(valuestr)
861
+ # truncated value ?
862
+ if val != float(valuestr):
863
+ continue
864
+ return val
865
+ except (ValueError, TypeError):
866
+ continue
867
+ # END for each numeric type
868
+
869
+ # Try boolean values as git uses them.
870
+ vl = valuestr.lower()
871
+ if vl == "false":
872
+ return False
873
+ if vl == "true":
874
+ return True
875
+
876
+ if not isinstance(valuestr, str):
877
+ raise TypeError(
878
+ "Invalid value type: only int, long, float and str are allowed",
879
+ valuestr,
880
+ )
881
+
882
+ return valuestr
883
+
884
+ def _value_to_string(self, value: Union[str, bytes, int, float, bool]) -> str:
885
+ if isinstance(value, (int, float, bool)):
886
+ return str(value)
887
+ return force_text(value)
888
+
889
+ def _value_to_string_safe(self, value: Union[str, bytes, int, float, bool]) -> str:
890
+ value_str = self._value_to_string(value)
891
+ if UNSAFE_CONFIG_CHARS_RE.search(value_str):
892
+ raise ValueError("Git config values must not contain CR, LF, or NUL")
893
+ return value_str
894
+
895
+ def _assure_config_name_safe(self, name: "cp._SectionName", label: str) -> None:
896
+ if isinstance(name, str) and UNSAFE_CONFIG_CHARS_RE.search(name):
897
+ raise ValueError("Git config %s names must not contain CR, LF, or NUL" % label)
898
+
899
+ @needs_values
900
+ @set_dirty_and_flush_changes
901
+ def set(
902
+ self,
903
+ section: str,
904
+ option: str,
905
+ value: Union[str, bytes, int, float, bool, None] = None,
906
+ ) -> None:
907
+ self._assure_config_name_safe(section, "section")
908
+ self._assure_config_name_safe(option, "option")
909
+ if value is not None:
910
+ value = self._value_to_string_safe(value)
911
+ return super().set(section, option, value)
912
+
913
+ @needs_values
914
+ @set_dirty_and_flush_changes
915
+ def set_value(self, section: str, option: str, value: Union[str, bytes, int, float, bool]) -> "GitConfigParser":
916
+ """Set the given option in section to the given value.
917
+
918
+ This will create the section if required, and will not throw as opposed to the
919
+ default ConfigParser ``set`` method.
920
+
921
+ :param section:
922
+ Name of the section in which the option resides or should reside.
923
+
924
+ :param option:
925
+ Name of the options whose value to set.
926
+
927
+ :param value:
928
+ Value to set the option to. It must be a string or convertible to a string.
929
+
930
+ :return:
931
+ This instance
932
+ """
933
+ self._assure_config_name_safe(section, "section")
934
+ self._assure_config_name_safe(option, "option")
935
+ value_str = self._value_to_string_safe(value)
936
+ if not self.has_section(section):
937
+ self.add_section(section)
938
+ super().set(section, option, value_str)
939
+ return self
940
+
941
+ @needs_values
942
+ @set_dirty_and_flush_changes
943
+ def add_value(self, section: str, option: str, value: Union[str, bytes, int, float, bool]) -> "GitConfigParser":
944
+ """Add a value for the given option in section.
945
+
946
+ This will create the section if required, and will not throw as opposed to the
947
+ default ConfigParser ``set`` method. The value becomes the new value of the
948
+ option as returned by :meth:`get_value`, and appends to the list of values
949
+ returned by :meth:`get_values`.
950
+
951
+ :param section:
952
+ Name of the section in which the option resides or should reside.
953
+
954
+ :param option:
955
+ Name of the option.
956
+
957
+ :param value:
958
+ Value to add to option. It must be a string or convertible to a string.
959
+
960
+ :return:
961
+ This instance
962
+ """
963
+ self._assure_config_name_safe(section, "section")
964
+ self._assure_config_name_safe(option, "option")
965
+ value_str = self._value_to_string_safe(value)
966
+ if not self.has_section(section):
967
+ self.add_section(section)
968
+ self._sections[section].add(option, value_str)
969
+ return self
970
+
971
+ def rename_section(self, section: str, new_name: str) -> "GitConfigParser":
972
+ """Rename the given section to `new_name`.
973
+
974
+ :raise ValueError:
975
+ If:
976
+
977
+ * `section` doesn't exist.
978
+ * A section with `new_name` does already exist.
979
+
980
+ :return:
981
+ This instance
982
+ """
983
+ if not self.has_section(section):
984
+ raise ValueError("Source section '%s' doesn't exist" % section)
985
+ self._assure_config_name_safe(new_name, "section")
986
+ if self.has_section(new_name):
987
+ raise ValueError("Destination section '%s' already exists" % new_name)
988
+
989
+ super().add_section(new_name)
990
+ new_section = self._sections[new_name]
991
+ for k, vs in self.items_all(section):
992
+ new_section.setall(k, vs)
993
+ # END for each value to copy
994
+
995
+ # This call writes back the changes, which is why we don't have the respective
996
+ # decorator.
997
+ self.remove_section(section)
998
+ return self
.venv/lib/python3.11/site-packages/git/db.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module is part of GitPython and is released under the
2
+ # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
3
+
4
+ """Module with our own gitdb implementation - it uses the git command."""
5
+
6
+ __all__ = ["GitCmdObjectDB", "GitDB"]
7
+
8
+ from gitdb.base import OInfo, OStream
9
+ from gitdb.db import GitDB, LooseObjectDB
10
+ from gitdb.exc import BadObject
11
+
12
+ from git.util import bin_to_hex, hex_to_bin
13
+ from git.exc import GitCommandError
14
+
15
+ # typing-------------------------------------------------
16
+
17
+ from typing import TYPE_CHECKING
18
+
19
+ from git.types import PathLike
20
+
21
+ if TYPE_CHECKING:
22
+ from git.cmd import Git
23
+
24
+ # --------------------------------------------------------
25
+
26
+
27
+ class GitCmdObjectDB(LooseObjectDB):
28
+ """A database representing the default git object store, which includes loose
29
+ objects, pack files and an alternates file.
30
+
31
+ It will create objects only in the loose object database.
32
+ """
33
+
34
+ def __init__(self, root_path: PathLike, git: "Git") -> None:
35
+ """Initialize this instance with the root and a git command."""
36
+ super().__init__(root_path)
37
+ self._git = git
38
+
39
+ def info(self, binsha: bytes) -> OInfo:
40
+ """Get a git object header (using git itself)."""
41
+ hexsha, typename, size = self._git.get_object_header(bin_to_hex(binsha))
42
+ return OInfo(hex_to_bin(hexsha), typename, size)
43
+
44
+ def stream(self, binsha: bytes) -> OStream:
45
+ """Get git object data as a stream supporting ``read()`` (using git itself)."""
46
+ hexsha, typename, size, stream = self._git.stream_object_data(bin_to_hex(binsha))
47
+ return OStream(hex_to_bin(hexsha), typename, size, stream)
48
+
49
+ # { Interface
50
+
51
+ def partial_to_complete_sha_hex(self, partial_hexsha: str) -> bytes:
52
+ """
53
+ :return:
54
+ Full binary 20 byte sha from the given partial hexsha
55
+
56
+ :raise gitdb.exc.AmbiguousObjectName:
57
+
58
+ :raise gitdb.exc.BadObject:
59
+
60
+ :note:
61
+ Currently we only raise :exc:`~gitdb.exc.BadObject` as git does not
62
+ communicate ambiguous objects separately.
63
+ """
64
+ try:
65
+ hexsha, _typename, _size = self._git.get_object_header(partial_hexsha)
66
+ return hex_to_bin(hexsha)
67
+ except (GitCommandError, ValueError) as e:
68
+ raise BadObject(partial_hexsha) from e
69
+ # END handle exceptions
70
+
71
+ # } END interface
.venv/lib/python3.11/site-packages/git/diff.py ADDED
@@ -0,0 +1,776 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
2
+ #
3
+ # This module is part of GitPython and is released under the
4
+ # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
5
+
6
+ __all__ = ["DiffConstants", "NULL_TREE", "INDEX", "Diffable", "DiffIndex", "Diff"]
7
+
8
+ import enum
9
+ import re
10
+ import warnings
11
+
12
+ from git.cmd import handle_process_output
13
+ from git.compat import defenc
14
+ from git.objects.blob import Blob
15
+ from git.objects.util import mode_str_to_int
16
+ from git.util import finalize_process, hex_to_bin
17
+
18
+ # typing ------------------------------------------------------------------
19
+
20
+ from typing import (
21
+ Any,
22
+ Iterator,
23
+ List,
24
+ Match,
25
+ Optional,
26
+ Sequence,
27
+ Tuple,
28
+ TYPE_CHECKING,
29
+ TypeVar,
30
+ Union,
31
+ cast,
32
+ )
33
+ from git.types import PathLike, Literal
34
+
35
+ if TYPE_CHECKING:
36
+ from subprocess import Popen
37
+
38
+ from git.cmd import Git
39
+ from git.objects.base import IndexObject
40
+ from git.objects.commit import Commit
41
+ from git.objects.tree import Tree
42
+ from git.repo.base import Repo
43
+
44
+ Lit_change_type = Literal["A", "D", "C", "M", "R", "T", "U"]
45
+
46
+ # ------------------------------------------------------------------------
47
+
48
+
49
+ @enum.unique
50
+ class DiffConstants(enum.Enum):
51
+ """Special objects for :meth:`Diffable.diff`.
52
+
53
+ See the :meth:`Diffable.diff` method's ``other`` parameter, which accepts various
54
+ values including these.
55
+
56
+ :note:
57
+ These constants are also available as attributes of the :mod:`git.diff` module,
58
+ the :class:`Diffable` class and its subclasses and instances, and the top-level
59
+ :mod:`git` module.
60
+ """
61
+
62
+ NULL_TREE = enum.auto()
63
+ """Stand-in indicating you want to compare against the empty tree in diffs.
64
+
65
+ Also accessible as :const:`git.NULL_TREE`, :const:`git.diff.NULL_TREE`, and
66
+ :const:`Diffable.NULL_TREE`.
67
+ """
68
+
69
+ INDEX = enum.auto()
70
+ """Stand-in indicating you want to diff against the index.
71
+
72
+ Also accessible as :const:`git.INDEX`, :const:`git.diff.INDEX`, and
73
+ :const:`Diffable.INDEX`, as well as :const:`Diffable.Index`. The latter has been
74
+ kept for backward compatibility and made an alias of this, so it may still be used.
75
+ """
76
+
77
+
78
+ NULL_TREE: Literal[DiffConstants.NULL_TREE] = DiffConstants.NULL_TREE
79
+ """Stand-in indicating you want to compare against the empty tree in diffs.
80
+
81
+ See :meth:`Diffable.diff`, which accepts this as a value of its ``other`` parameter.
82
+
83
+ This is an alias of :const:`DiffConstants.NULL_TREE`, which may also be accessed as
84
+ :const:`git.NULL_TREE` and :const:`Diffable.NULL_TREE`.
85
+ """
86
+
87
+ INDEX: Literal[DiffConstants.INDEX] = DiffConstants.INDEX
88
+ """Stand-in indicating you want to diff against the index.
89
+
90
+ See :meth:`Diffable.diff`, which accepts this as a value of its ``other`` parameter.
91
+
92
+ This is an alias of :const:`DiffConstants.INDEX`, which may also be accessed as
93
+ :const:`git.INDEX` and :const:`Diffable.INDEX`, as well as :const:`Diffable.Index`.
94
+ """
95
+
96
+ _octal_byte_re = re.compile(rb"\\([0-9]{3})")
97
+
98
+
99
+ def _octal_repl(matchobj: Match) -> bytes:
100
+ value = matchobj.group(1)
101
+ value = int(value, 8)
102
+ value = bytes(bytearray((value,)))
103
+ return value
104
+
105
+
106
+ def decode_path(path: bytes, has_ab_prefix: bool = True) -> Optional[bytes]:
107
+ if path == b"/dev/null":
108
+ return None
109
+
110
+ if path.startswith(b'"') and path.endswith(b'"'):
111
+ path = path[1:-1].replace(b"\\n", b"\n").replace(b"\\t", b"\t").replace(b'\\"', b'"').replace(b"\\\\", b"\\")
112
+
113
+ path = _octal_byte_re.sub(_octal_repl, path)
114
+
115
+ if has_ab_prefix:
116
+ assert path.startswith(b"a/") or path.startswith(b"b/")
117
+ path = path[2:]
118
+
119
+ return path
120
+
121
+
122
+ class Diffable:
123
+ """Common interface for all objects that can be diffed against another object of
124
+ compatible type.
125
+
126
+ :note:
127
+ Subclasses require a :attr:`repo` member, as it is the case for
128
+ :class:`~git.objects.base.Object` instances. For practical reasons we do not
129
+ derive from :class:`~git.objects.base.Object`.
130
+ """
131
+
132
+ __slots__ = ()
133
+
134
+ repo: "Repo"
135
+ """Repository to operate on. Must be provided by subclass or sibling class."""
136
+
137
+ NULL_TREE = NULL_TREE
138
+ """Stand-in indicating you want to compare against the empty tree in diffs.
139
+
140
+ See the :meth:`diff` method, which accepts this as a value of its ``other``
141
+ parameter.
142
+
143
+ This is the same as :const:`DiffConstants.NULL_TREE`, and may also be accessed as
144
+ :const:`git.NULL_TREE` and :const:`git.diff.NULL_TREE`.
145
+ """
146
+
147
+ INDEX = INDEX
148
+ """Stand-in indicating you want to diff against the index.
149
+
150
+ See the :meth:`diff` method, which accepts this as a value of its ``other``
151
+ parameter.
152
+
153
+ This is the same as :const:`DiffConstants.INDEX`, and may also be accessed as
154
+ :const:`git.INDEX` and :const:`git.diff.INDEX`, as well as :class:`Diffable.INDEX`,
155
+ which is kept for backward compatibility (it is now defined an alias of this).
156
+ """
157
+
158
+ Index = INDEX
159
+ """Stand-in indicating you want to diff against the index
160
+ (same as :const:`~Diffable.INDEX`).
161
+
162
+ This is an alias of :const:`~Diffable.INDEX`, for backward compatibility. See
163
+ :const:`~Diffable.INDEX` and :meth:`diff` for details.
164
+
165
+ :note:
166
+ Although always meant for use as an opaque constant, this was formerly defined
167
+ as a class. Its usage is unchanged, but static type annotations that attempt
168
+ to permit only this object must be changed to avoid new mypy errors. This was
169
+ previously not possible to do, though ``Type[Diffable.Index]`` approximated it.
170
+ It is now possible to do precisely, using ``Literal[DiffConstants.INDEX]``.
171
+ """
172
+
173
+ def _process_diff_args(
174
+ self,
175
+ args: List[Union[PathLike, "Diffable"]],
176
+ ) -> List[Union[PathLike, "Diffable"]]:
177
+ """
178
+ :return:
179
+ Possibly altered version of the given args list.
180
+ This method is called right before git command execution.
181
+ Subclasses can use it to alter the behaviour of the superclass.
182
+ """
183
+ return args
184
+
185
+ def diff(
186
+ self,
187
+ other: Union[DiffConstants, "Tree", "Commit", str, None] = INDEX,
188
+ paths: Union[PathLike, List[PathLike], Tuple[PathLike, ...], None] = None,
189
+ create_patch: bool = False,
190
+ **kwargs: Any,
191
+ ) -> "DiffIndex[Diff]":
192
+ """Create diffs between two items being trees, trees and index or an index and
193
+ the working tree. Detects renames automatically.
194
+
195
+ :param other:
196
+ This the item to compare us with.
197
+
198
+ * If ``None``, we will be compared to the working tree.
199
+
200
+ * If a :class:`~git.types.Tree_ish` or string, it will be compared against
201
+ the respective tree.
202
+
203
+ * If :const:`INDEX`, it will be compared against the index.
204
+
205
+ * If :const:`NULL_TREE`, it will compare against the empty tree.
206
+
207
+ This parameter defaults to :const:`INDEX` (rather than ``None``) so that the
208
+ method will not by default fail on bare repositories.
209
+
210
+ :param paths:
211
+ This a list of paths or a single path to limit the diff to. It will only
212
+ include at least one of the given path or paths.
213
+
214
+ :param create_patch:
215
+ If ``True``, the returned :class:`Diff` contains a detailed patch that if
216
+ applied makes the self to other. Patches are somewhat costly as blobs have
217
+ to be read and diffed.
218
+
219
+ :param kwargs:
220
+ Additional arguments passed to :manpage:`git-diff(1)`, such as ``R=True`` to
221
+ swap both sides of the diff.
222
+
223
+ :return:
224
+ A :class:`DiffIndex` representing the computed diff.
225
+
226
+ :note:
227
+ On a bare repository, `other` needs to be provided as :const:`INDEX`, or as
228
+ an instance of :class:`~git.objects.tree.Tree` or
229
+ :class:`~git.objects.commit.Commit`, or a git command error will occur.
230
+ """
231
+ args: List[Union[PathLike, Diffable]] = []
232
+ args.append("--abbrev=40") # We need full shas.
233
+ args.append("--full-index") # Get full index paths, not only filenames.
234
+
235
+ # Remove default '-M' arg (check for renames) if user is overriding it.
236
+ if not any(x in kwargs for x in ("find_renames", "no_renames", "M")):
237
+ args.append("-M")
238
+
239
+ if create_patch:
240
+ args.append("-p")
241
+ args.append("--no-ext-diff")
242
+ else:
243
+ args.append("--raw")
244
+ args.append("-z")
245
+
246
+ # Ensure we never see colored output.
247
+ # Fixes: https://github.com/gitpython-developers/GitPython/issues/172
248
+ args.append("--no-color")
249
+
250
+ if paths is not None and not isinstance(paths, (tuple, list)):
251
+ paths = [paths]
252
+
253
+ diff_cmd = self.repo.git.diff
254
+ if other is INDEX:
255
+ args.insert(0, "--cached")
256
+ elif other is NULL_TREE:
257
+ args.insert(0, "-r") # Recursive diff-tree.
258
+ args.insert(0, "--root")
259
+ diff_cmd = self.repo.git.diff_tree
260
+ elif other is not None:
261
+ args.insert(0, "-r") # Recursive diff-tree.
262
+ args.insert(0, other)
263
+ diff_cmd = self.repo.git.diff_tree
264
+
265
+ args.insert(0, self)
266
+
267
+ # paths is a list or tuple here, or None.
268
+ if paths:
269
+ args.append("--")
270
+ args.extend(paths)
271
+ # END paths handling
272
+
273
+ kwargs["as_process"] = True
274
+ proc = diff_cmd(*self._process_diff_args(args), **kwargs)
275
+
276
+ diff_method = Diff._index_from_patch_format if create_patch else Diff._index_from_raw_format
277
+ index = diff_method(self.repo, proc)
278
+
279
+ proc.wait()
280
+ return index
281
+
282
+
283
+ T_Diff = TypeVar("T_Diff", bound="Diff")
284
+
285
+
286
+ class DiffIndex(List[T_Diff]):
287
+ R"""An index for diffs, allowing a list of :class:`Diff`\s to be queried by the diff
288
+ properties.
289
+
290
+ The class improves the diff handling convenience.
291
+ """
292
+
293
+ change_type: Sequence[Literal["A", "C", "D", "R", "M", "T"]] = ("A", "C", "D", "R", "M", "T") # noqa: F821
294
+ """Change type invariant identifying possible ways a blob can have changed:
295
+
296
+ * ``A`` = Added
297
+ * ``D`` = Deleted
298
+ * ``R`` = Renamed
299
+ * ``M`` = Modified
300
+ * ``T`` = Changed in the type
301
+ """
302
+
303
+ def iter_change_type(self, change_type: Lit_change_type) -> Iterator[T_Diff]:
304
+ """
305
+ :return:
306
+ Iterator yielding :class:`Diff` instances that match the given `change_type`
307
+
308
+ :param change_type:
309
+ Member of :attr:`DiffIndex.change_type`, namely:
310
+
311
+ * 'A' for added paths
312
+ * 'D' for deleted paths
313
+ * 'R' for renamed paths
314
+ * 'M' for paths with modified data
315
+ * 'T' for changed in the type paths
316
+ """
317
+ if change_type not in self.change_type:
318
+ raise ValueError("Invalid change type: %s" % change_type)
319
+
320
+ for diffidx in self:
321
+ if diffidx.change_type == change_type:
322
+ yield diffidx
323
+ elif change_type == "A" and diffidx.new_file:
324
+ yield diffidx
325
+ elif change_type == "D" and diffidx.deleted_file:
326
+ yield diffidx
327
+ elif change_type == "C" and diffidx.copied_file:
328
+ yield diffidx
329
+ elif change_type == "R" and diffidx.renamed_file:
330
+ yield diffidx
331
+ elif change_type == "M" and diffidx.a_blob and diffidx.b_blob and diffidx.a_blob != diffidx.b_blob:
332
+ yield diffidx
333
+ # END for each diff
334
+
335
+
336
+ class Diff:
337
+ """A Diff contains diff information between two Trees.
338
+
339
+ It contains two sides a and b of the diff. Members are prefixed with "a" and "b"
340
+ respectively to indicate that.
341
+
342
+ Diffs keep information about the changed blob objects, the file mode, renames,
343
+ deletions and new files.
344
+
345
+ There are a few cases where ``None`` has to be expected as member variable value:
346
+
347
+ New File::
348
+
349
+ a_mode is None
350
+ a_blob is None
351
+ a_path is None
352
+
353
+ Deleted File::
354
+
355
+ b_mode is None
356
+ b_blob is None
357
+ b_path is None
358
+
359
+ Working Tree Blobs:
360
+
361
+ When comparing to working trees, the working tree blob will have a null hexsha
362
+ as a corresponding object does not yet exist. The mode will be null as well. The
363
+ path will be available, though.
364
+
365
+ If it is listed in a diff, the working tree version of the file must differ from
366
+ the version in the index or tree, and hence has been modified.
367
+ """
368
+
369
+ # Precompiled regex.
370
+ re_header = re.compile(
371
+ rb"""
372
+ ^diff[ ]--git
373
+ [ ](?P<a_path_fallback>"?[ab]/.+?"?)[ ](?P<b_path_fallback>"?[ab]/.+?"?)\n
374
+ (?:^old[ ]mode[ ](?P<old_mode>\d+)\n
375
+ ^new[ ]mode[ ](?P<new_mode>\d+)(?:\n|$))?
376
+ (?:^similarity[ ]index[ ]\d+%\n
377
+ ^rename[ ]from[ ](?P<rename_from>.*)\n
378
+ ^rename[ ]to[ ](?P<rename_to>.*)(?:\n|$))?
379
+ (?:^new[ ]file[ ]mode[ ](?P<new_file_mode>.+)(?:\n|$))?
380
+ (?:^deleted[ ]file[ ]mode[ ](?P<deleted_file_mode>.+)(?:\n|$))?
381
+ (?:^similarity[ ]index[ ]\d+%\n
382
+ ^copy[ ]from[ ].*\n
383
+ ^copy[ ]to[ ](?P<copied_file_name>.*)(?:\n|$))?
384
+ (?:^index[ ](?P<a_blob_id>[0-9A-Fa-f]+)
385
+ \.\.(?P<b_blob_id>[0-9A-Fa-f]+)[ ]?(?P<b_mode>.+)?(?:\n|$))?
386
+ (?:^---[ ](?P<a_path>[^\t\n\r\f\v]*)[\t\r\f\v]*(?:\n|$))?
387
+ (?:^\+\+\+[ ](?P<b_path>[^\t\n\r\f\v]*)[\t\r\f\v]*(?:\n|$))?
388
+ """,
389
+ re.VERBOSE | re.MULTILINE,
390
+ )
391
+
392
+ # These can be used for comparisons.
393
+ NULL_HEX_SHA = "0" * 40
394
+ NULL_BIN_SHA = b"\0" * 20
395
+
396
+ __slots__ = (
397
+ "a_blob",
398
+ "b_blob",
399
+ "a_mode",
400
+ "b_mode",
401
+ "a_rawpath",
402
+ "b_rawpath",
403
+ "new_file",
404
+ "deleted_file",
405
+ "copied_file",
406
+ "raw_rename_from",
407
+ "raw_rename_to",
408
+ "diff",
409
+ "change_type",
410
+ "score",
411
+ )
412
+
413
+ def __init__(
414
+ self,
415
+ repo: "Repo",
416
+ a_rawpath: Optional[bytes],
417
+ b_rawpath: Optional[bytes],
418
+ a_blob_id: Union[str, bytes, None],
419
+ b_blob_id: Union[str, bytes, None],
420
+ a_mode: Union[bytes, str, None],
421
+ b_mode: Union[bytes, str, None],
422
+ new_file: bool,
423
+ deleted_file: bool,
424
+ copied_file: bool,
425
+ raw_rename_from: Optional[bytes],
426
+ raw_rename_to: Optional[bytes],
427
+ diff: Union[str, bytes, None],
428
+ change_type: Optional[Lit_change_type],
429
+ score: Optional[int],
430
+ ) -> None:
431
+ assert a_rawpath is None or isinstance(a_rawpath, bytes)
432
+ assert b_rawpath is None or isinstance(b_rawpath, bytes)
433
+ self.a_rawpath = a_rawpath
434
+ self.b_rawpath = b_rawpath
435
+
436
+ self.a_mode = mode_str_to_int(a_mode) if a_mode else None
437
+ self.b_mode = mode_str_to_int(b_mode) if b_mode else None
438
+
439
+ # Determine whether this diff references a submodule. If it does then
440
+ # we need to overwrite "repo" to the corresponding submodule's repo instead.
441
+ if repo and a_rawpath:
442
+ for submodule in repo.submodules:
443
+ if submodule.path == a_rawpath.decode(defenc, "replace"):
444
+ if submodule.module_exists():
445
+ repo = submodule.module()
446
+ break
447
+
448
+ self.a_blob: Union["IndexObject", None]
449
+ if a_blob_id is None or a_blob_id == self.NULL_HEX_SHA:
450
+ self.a_blob = None
451
+ else:
452
+ self.a_blob = Blob(repo, hex_to_bin(a_blob_id), mode=self.a_mode, path=self.a_path)
453
+
454
+ self.b_blob: Union["IndexObject", None]
455
+ if b_blob_id is None or b_blob_id == self.NULL_HEX_SHA:
456
+ self.b_blob = None
457
+ else:
458
+ self.b_blob = Blob(repo, hex_to_bin(b_blob_id), mode=self.b_mode, path=self.b_path)
459
+
460
+ self.new_file: bool = new_file
461
+ self.deleted_file: bool = deleted_file
462
+ self.copied_file: bool = copied_file
463
+
464
+ # Be clear and use None instead of empty strings.
465
+ assert raw_rename_from is None or isinstance(raw_rename_from, bytes)
466
+ assert raw_rename_to is None or isinstance(raw_rename_to, bytes)
467
+ self.raw_rename_from = raw_rename_from or None
468
+ self.raw_rename_to = raw_rename_to or None
469
+
470
+ self.diff = diff
471
+ self.change_type: Union[Lit_change_type, None] = change_type
472
+ self.score = score
473
+
474
+ def __eq__(self, other: object) -> bool:
475
+ for name in self.__slots__:
476
+ if getattr(self, name) != getattr(other, name):
477
+ return False
478
+ # END for each name
479
+ return True
480
+
481
+ def __ne__(self, other: object) -> bool:
482
+ return not (self == other)
483
+
484
+ def __hash__(self) -> int:
485
+ return hash(tuple(getattr(self, n) for n in self.__slots__))
486
+
487
+ def __str__(self) -> str:
488
+ h = "%s"
489
+ if self.a_blob:
490
+ h %= self.a_blob.path
491
+ elif self.b_blob:
492
+ h %= self.b_blob.path
493
+
494
+ msg = ""
495
+ line = None
496
+ line_length = 0
497
+ for b, n in zip((self.a_blob, self.b_blob), ("lhs", "rhs")):
498
+ if b:
499
+ line = "\n%s: %o | %s" % (n, b.mode, b.hexsha)
500
+ else:
501
+ line = "\n%s: None" % n
502
+ # END if blob is not None
503
+ line_length = max(len(line), line_length)
504
+ msg += line
505
+ # END for each blob
506
+
507
+ # Add headline.
508
+ h += "\n" + "=" * line_length
509
+
510
+ if self.deleted_file:
511
+ msg += "\nfile deleted in rhs"
512
+ if self.new_file:
513
+ msg += "\nfile added in rhs"
514
+ if self.copied_file:
515
+ msg += "\nfile %r copied from %r" % (self.b_path, self.a_path)
516
+ if self.rename_from:
517
+ msg += "\nfile renamed from %r" % self.rename_from
518
+ if self.rename_to:
519
+ msg += "\nfile renamed to %r" % self.rename_to
520
+ if self.diff:
521
+ msg += "\n---"
522
+ try:
523
+ msg += self.diff.decode(defenc) if isinstance(self.diff, bytes) else self.diff
524
+ except UnicodeDecodeError:
525
+ msg += "OMITTED BINARY DATA"
526
+ # END handle encoding
527
+ msg += "\n---"
528
+ # END diff info
529
+
530
+ return h + msg
531
+
532
+ @property
533
+ def a_path(self) -> Optional[str]:
534
+ return self.a_rawpath.decode(defenc, "replace") if self.a_rawpath else None
535
+
536
+ @property
537
+ def b_path(self) -> Optional[str]:
538
+ return self.b_rawpath.decode(defenc, "replace") if self.b_rawpath else None
539
+
540
+ @property
541
+ def rename_from(self) -> Optional[str]:
542
+ return self.raw_rename_from.decode(defenc, "replace") if self.raw_rename_from else None
543
+
544
+ @property
545
+ def rename_to(self) -> Optional[str]:
546
+ return self.raw_rename_to.decode(defenc, "replace") if self.raw_rename_to else None
547
+
548
+ @property
549
+ def renamed(self) -> bool:
550
+ """Deprecated, use :attr:`renamed_file` instead.
551
+
552
+ :return:
553
+ ``True`` if the blob of our diff has been renamed
554
+
555
+ :note:
556
+ This property is deprecated.
557
+ Please use the :attr:`renamed_file` property instead.
558
+ """
559
+ warnings.warn(
560
+ "Diff.renamed is deprecated, use Diff.renamed_file instead",
561
+ DeprecationWarning,
562
+ stacklevel=2,
563
+ )
564
+ return self.renamed_file
565
+
566
+ @property
567
+ def renamed_file(self) -> bool:
568
+ """:return: ``True`` if the blob of our diff has been renamed"""
569
+ return self.rename_from != self.rename_to
570
+
571
+ @classmethod
572
+ def _pick_best_path(cls, path_match: bytes, rename_match: bytes, path_fallback_match: bytes) -> Optional[bytes]:
573
+ if path_match:
574
+ return decode_path(path_match)
575
+
576
+ if rename_match:
577
+ return decode_path(rename_match, has_ab_prefix=False)
578
+
579
+ if path_fallback_match:
580
+ return decode_path(path_fallback_match)
581
+
582
+ return None
583
+
584
+ @classmethod
585
+ def _index_from_patch_format(cls, repo: "Repo", proc: Union["Popen", "Git.AutoInterrupt"]) -> DiffIndex["Diff"]:
586
+ """Create a new :class:`DiffIndex` from the given process output which must be
587
+ in patch format.
588
+
589
+ :param repo:
590
+ The repository we are operating on.
591
+
592
+ :param proc:
593
+ :manpage:`git-diff(1)` process to read from
594
+ (supports :class:`Git.AutoInterrupt <git.cmd.Git.AutoInterrupt>` wrapper).
595
+
596
+ :return:
597
+ :class:`DiffIndex`
598
+ """
599
+
600
+ # FIXME: Here SLURPING raw, need to re-phrase header-regexes linewise.
601
+ text_list: List[bytes] = []
602
+ handle_process_output(proc, text_list.append, None, finalize_process, decode_streams=False)
603
+
604
+ # For now, we have to bake the stream.
605
+ text = b"".join(text_list)
606
+ index: "DiffIndex" = DiffIndex()
607
+ previous_header: Union[Match[bytes], None] = None
608
+ header: Union[Match[bytes], None] = None
609
+ a_path, b_path = None, None # For mypy.
610
+ a_mode, b_mode = None, None # For mypy.
611
+ for _header in cls.re_header.finditer(text):
612
+ (
613
+ a_path_fallback,
614
+ b_path_fallback,
615
+ old_mode,
616
+ new_mode,
617
+ rename_from,
618
+ rename_to,
619
+ new_file_mode,
620
+ deleted_file_mode,
621
+ copied_file_name,
622
+ a_blob_id,
623
+ b_blob_id,
624
+ b_mode,
625
+ a_path,
626
+ b_path,
627
+ ) = _header.groups()
628
+
629
+ new_file, deleted_file, copied_file = (
630
+ bool(new_file_mode),
631
+ bool(deleted_file_mode),
632
+ bool(copied_file_name),
633
+ )
634
+
635
+ a_path = cls._pick_best_path(a_path, rename_from, a_path_fallback)
636
+ b_path = cls._pick_best_path(b_path, rename_to, b_path_fallback)
637
+
638
+ # Our only means to find the actual text is to see what has not been matched
639
+ # by our regex, and then retro-actively assign it to our index.
640
+ if previous_header is not None:
641
+ index[-1].diff = text[previous_header.end() : _header.start()]
642
+ # END assign actual diff
643
+
644
+ # Make sure the mode is set if the path is set. Otherwise the resulting blob
645
+ # is invalid. We just use the one mode we should have parsed.
646
+ a_mode = old_mode or deleted_file_mode or (a_path and (b_mode or new_mode or new_file_mode))
647
+ b_mode = b_mode or new_mode or new_file_mode or (b_path and a_mode)
648
+ index.append(
649
+ Diff(
650
+ repo,
651
+ a_path,
652
+ b_path,
653
+ a_blob_id and a_blob_id.decode(defenc),
654
+ b_blob_id and b_blob_id.decode(defenc),
655
+ a_mode and a_mode.decode(defenc),
656
+ b_mode and b_mode.decode(defenc),
657
+ new_file,
658
+ deleted_file,
659
+ copied_file,
660
+ rename_from,
661
+ rename_to,
662
+ None,
663
+ None,
664
+ None,
665
+ )
666
+ )
667
+
668
+ previous_header = _header
669
+ header = _header
670
+ # END for each header we parse
671
+ if index and header:
672
+ index[-1].diff = text[header.end() :]
673
+ # END assign last diff
674
+
675
+ return index
676
+
677
+ @staticmethod
678
+ def _handle_diff_line(lines_bytes: bytes, repo: "Repo", index: DiffIndex["Diff"]) -> None:
679
+ lines = lines_bytes.decode(defenc)
680
+
681
+ # Discard everything before the first colon, and the colon itself.
682
+ _, _, lines = lines.partition(":")
683
+
684
+ for line in lines.split("\x00:"):
685
+ if not line:
686
+ # The line data is empty, skip.
687
+ continue
688
+ meta, _, path = line.partition("\x00")
689
+ path = path.rstrip("\x00")
690
+ a_blob_id: Optional[str]
691
+ b_blob_id: Optional[str]
692
+ old_mode, new_mode, a_blob_id, b_blob_id, _change_type = meta.split(None, 4)
693
+ # Change type can be R100
694
+ # R: status letter
695
+ # 100: score (in case of copy and rename)
696
+ change_type: Lit_change_type = cast(Lit_change_type, _change_type[0])
697
+ score_str = "".join(_change_type[1:])
698
+ score = int(score_str) if score_str.isdigit() else None
699
+ path = path.strip("\n")
700
+ a_path = path.encode(defenc)
701
+ b_path = path.encode(defenc)
702
+ deleted_file = False
703
+ new_file = False
704
+ copied_file = False
705
+ rename_from = None
706
+ rename_to = None
707
+
708
+ # NOTE: We cannot conclude from the existence of a blob to change type,
709
+ # as diffs with the working do not have blobs yet.
710
+ if change_type == "D":
711
+ b_blob_id = None # Optional[str]
712
+ deleted_file = True
713
+ elif change_type == "A":
714
+ a_blob_id = None
715
+ new_file = True
716
+ elif change_type == "C":
717
+ copied_file = True
718
+ a_path_str, b_path_str = path.split("\x00", 1)
719
+ a_path = a_path_str.encode(defenc)
720
+ b_path = b_path_str.encode(defenc)
721
+ elif change_type == "R":
722
+ a_path_str, b_path_str = path.split("\x00", 1)
723
+ a_path = a_path_str.encode(defenc)
724
+ b_path = b_path_str.encode(defenc)
725
+ rename_from, rename_to = a_path, b_path
726
+ elif change_type == "T":
727
+ # Nothing to do.
728
+ pass
729
+ # END add/remove handling
730
+
731
+ diff = Diff(
732
+ repo,
733
+ a_path,
734
+ b_path,
735
+ a_blob_id,
736
+ b_blob_id,
737
+ old_mode,
738
+ new_mode,
739
+ new_file,
740
+ deleted_file,
741
+ copied_file,
742
+ rename_from,
743
+ rename_to,
744
+ "",
745
+ change_type,
746
+ score,
747
+ )
748
+ index.append(diff)
749
+
750
+ @classmethod
751
+ def _index_from_raw_format(cls, repo: "Repo", proc: "Popen") -> "DiffIndex[Diff]":
752
+ """Create a new :class:`DiffIndex` from the given process output which must be
753
+ in raw format.
754
+
755
+ :param repo:
756
+ The repository we are operating on.
757
+
758
+ :param proc:
759
+ Process to read output from.
760
+
761
+ :return:
762
+ :class:`DiffIndex`
763
+ """
764
+ # handles
765
+ # :100644 100644 687099101... 37c5e30c8... M .gitignore
766
+
767
+ index: "DiffIndex" = DiffIndex()
768
+ handle_process_output(
769
+ proc,
770
+ lambda byt: cls._handle_diff_line(byt, repo, index),
771
+ None,
772
+ finalize_process,
773
+ decode_streams=False,
774
+ )
775
+
776
+ return index
.venv/lib/python3.11/site-packages/git/exc.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
2
+ #
3
+ # This module is part of GitPython and is released under the
4
+ # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/
5
+
6
+ """Exceptions thrown throughout the git package."""
7
+
8
+ __all__ = [
9
+ # Defined in gitdb.exc:
10
+ "AmbiguousObjectName",
11
+ "BadName",
12
+ "BadObject",
13
+ "BadObjectType",
14
+ "InvalidDBRoot",
15
+ "ODBError",
16
+ "ParseError",
17
+ "UnsupportedOperation",
18
+ # Introduced in this module:
19
+ "GitError",
20
+ "InvalidGitRepositoryError",
21
+ "WorkTreeRepositoryUnsupported",
22
+ "NoSuchPathError",
23
+ "UnsafeProtocolError",
24
+ "UnsafeOptionError",
25
+ "CommandError",
26
+ "GitCommandNotFound",
27
+ "GitCommandError",
28
+ "CheckoutError",
29
+ "CacheError",
30
+ "UnmergedEntriesError",
31
+ "HookExecutionError",
32
+ "RepositoryDirtyError",
33
+ ]
34
+
35
+ from gitdb.exc import (
36
+ AmbiguousObjectName,
37
+ BadName,
38
+ BadObject,
39
+ BadObjectType,
40
+ InvalidDBRoot,
41
+ ODBError,
42
+ ParseError,
43
+ UnsupportedOperation,
44
+ )
45
+
46
+ from git.compat import safe_decode
47
+ from git.util import remove_password_if_present
48
+
49
+ # typing ----------------------------------------------------
50
+
51
+ from typing import List, Sequence, Tuple, TYPE_CHECKING, Union
52
+
53
+ from git.types import PathLike
54
+
55
+ if TYPE_CHECKING:
56
+ from git.repo.base import Repo
57
+
58
+ # ------------------------------------------------------------------
59
+
60
+
61
+ class GitError(Exception):
62
+ """Base class for all package exceptions."""
63
+
64
+
65
+ class InvalidGitRepositoryError(GitError):
66
+ """Thrown if the given repository appears to have an invalid format."""
67
+
68
+
69
+ class WorkTreeRepositoryUnsupported(InvalidGitRepositoryError):
70
+ """Thrown to indicate we can't handle work tree repositories."""
71
+
72
+
73
+ class NoSuchPathError(GitError, OSError):
74
+ """Thrown if a path could not be access by the system."""
75
+
76
+
77
+ class UnsafeProtocolError(GitError):
78
+ """Thrown if unsafe protocols are passed without being explicitly allowed."""
79
+
80
+
81
+ class UnsafeOptionError(GitError):
82
+ """Thrown if unsafe options are passed without being explicitly allowed."""
83
+
84
+
85
+ class CommandError(GitError):
86
+ """Base class for exceptions thrown at every stage of :class:`~subprocess.Popen`
87
+ execution.
88
+
89
+ :param command:
90
+ A non-empty list of argv comprising the command-line.
91
+ """
92
+
93
+ _msg = "Cmd('%s') failed%s"
94
+ """Format string with 2 ``%s`` for ``<cmdline>`` and the rest.
95
+
96
+ For example: ``"'%s' failed%s"``
97
+
98
+ Subclasses may override this attribute, provided it is still in this form.
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ command: Union[List[str], Tuple[str, ...], str],
104
+ status: Union[str, int, None, Exception] = None,
105
+ stderr: Union[bytes, str, None] = None,
106
+ stdout: Union[bytes, str, None] = None,
107
+ ) -> None:
108
+ if not isinstance(command, (tuple, list)):
109
+ command = command.split()
110
+ self.command = remove_password_if_present(command)
111
+ self.status = status
112
+ if status:
113
+ if isinstance(status, Exception):
114
+ status = "%s('%s')" % (type(status).__name__, safe_decode(str(status)))
115
+ else:
116
+ try:
117
+ status = "exit code(%s)" % int(status)
118
+ except (ValueError, TypeError):
119
+ s = safe_decode(str(status))
120
+ status = "'%s'" % s if isinstance(status, str) else s
121
+
122
+ self._cmd = safe_decode(self.command[0])
123
+ self._cmdline = " ".join(safe_decode(i) for i in self.command)
124
+ self._cause = status and " due to: %s" % status or "!"
125
+ stdout_decode = safe_decode(stdout)
126
+ stderr_decode = safe_decode(stderr)
127
+ self.stdout = stdout_decode and "\n stdout: '%s'" % stdout_decode or ""
128
+ self.stderr = stderr_decode and "\n stderr: '%s'" % stderr_decode or ""
129
+
130
+ def __str__(self) -> str:
131
+ return (self._msg + "\n cmdline: %s%s%s") % (
132
+ self._cmd,
133
+ self._cause,
134
+ self._cmdline,
135
+ self.stdout,
136
+ self.stderr,
137
+ )
138
+
139
+
140
+ class GitCommandNotFound(CommandError):
141
+ """Thrown if we cannot find the ``git`` executable in the :envvar:`PATH` or at the
142
+ path given by the :envvar:`GIT_PYTHON_GIT_EXECUTABLE` environment variable."""
143
+
144
+ def __init__(self, command: Union[List[str], Tuple[str], str], cause: Union[str, Exception]) -> None:
145
+ super().__init__(command, cause)
146
+ self._msg = "Cmd('%s') not found%s"
147
+
148
+
149
+ class GitCommandError(CommandError):
150
+ """Thrown if execution of the git command fails with non-zero status code."""
151
+
152
+ def __init__(
153
+ self,
154
+ command: Union[List[str], Tuple[str, ...], str],
155
+ status: Union[str, int, None, Exception] = None,
156
+ stderr: Union[bytes, str, None] = None,
157
+ stdout: Union[bytes, str, None] = None,
158
+ ) -> None:
159
+ super().__init__(command, status, stderr, stdout)
160
+
161
+
162
+ class CheckoutError(GitError):
163
+ """Thrown if a file could not be checked out from the index as it contained
164
+ changes.
165
+
166
+ The :attr:`failed_files` attribute contains a list of relative paths that failed to
167
+ be checked out as they contained changes that did not exist in the index.
168
+
169
+ The :attr:`failed_reasons` attribute contains a string informing about the actual
170
+ cause of the issue.
171
+
172
+ The :attr:`valid_files` attribute contains a list of relative paths to files that
173
+ were checked out successfully and hence match the version stored in the index.
174
+ """
175
+
176
+ def __init__(
177
+ self,
178
+ message: str,
179
+ failed_files: Sequence[PathLike],
180
+ valid_files: Sequence[PathLike],
181
+ failed_reasons: List[str],
182
+ ) -> None:
183
+ Exception.__init__(self, message)
184
+ self.failed_files = failed_files
185
+ self.failed_reasons = failed_reasons
186
+ self.valid_files = valid_files
187
+
188
+ def __str__(self) -> str:
189
+ return Exception.__str__(self) + ":%s" % self.failed_files
190
+
191
+
192
+ class CacheError(GitError):
193
+ """Base for all errors related to the git index, which is called "cache"
194
+ internally."""
195
+
196
+
197
+ class UnmergedEntriesError(CacheError):
198
+ """Thrown if an operation cannot proceed as there are still unmerged
199
+ entries in the cache."""
200
+
201
+
202
+ class HookExecutionError(CommandError):
203
+ """Thrown if a hook exits with a non-zero exit code.
204
+
205
+ This provides access to the exit code and the string returned via standard output.
206
+ """
207
+
208
+ def __init__(
209
+ self,
210
+ command: Union[List[str], Tuple[str, ...], str],
211
+ status: Union[str, int, None, Exception],
212
+ stderr: Union[bytes, str, None] = None,
213
+ stdout: Union[bytes, str, None] = None,
214
+ ) -> None:
215
+ super().__init__(command, status, stderr, stdout)
216
+ self._msg = "Hook('%s') failed%s"
217
+
218
+
219
+ class RepositoryDirtyError(GitError):
220
+ """Thrown whenever an operation on a repository fails as it has uncommitted changes
221
+ that would be overwritten."""
222
+
223
+ def __init__(self, repo: "Repo", message: str) -> None:
224
+ self.repo = repo
225
+ self.message = message
226
+
227
+ def __str__(self) -> str:
228
+ return "Operation cannot be performed on %r: %s" % (self.repo, self.message)