Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/database.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/index.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/locators.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/manifest.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/markers.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/metadata.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/resources.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/version.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/wheel.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/locators.py +1300 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/wheel.py +1053 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_cell_widths.py +451 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_emoji_codes.py +0 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_emoji_replace.py +32 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_inspect.py +210 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_log_render.py +94 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_loop.py +43 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_palettes.py +309 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_pick.py +17 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_ratio.py +160 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_stack.py +16 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_timer.py +19 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_wrap.py +55 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/abc.py +33 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/align.py +312 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/ansi.py +228 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/box.py +483 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/color.py +581 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/columns.py +187 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/console.py +2211 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/containers.py +167 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/control.py +175 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/default_styles.py +183 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/errors.py +34 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/file_proxy.py +54 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/filesize.py +89 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/highlighter.py +147 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/json.py +140 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/jupyter.py +92 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/layout.py +444 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/live_render.py +113 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/logging.py +268 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/measure.py +149 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/padding.py +141 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/pager.py +34 -0
- env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/palette.py +100 -0
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (1.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/compat.cpython-310.pyc
ADDED
Binary file (31.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/database.cpython-310.pyc
ADDED
Binary file (42.9 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/index.cpython-310.pyc
ADDED
Binary file (17.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/locators.cpython-310.pyc
ADDED
Binary file (38.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/manifest.cpython-310.pyc
ADDED
Binary file (10.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/markers.cpython-310.pyc
ADDED
Binary file (5.03 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/metadata.cpython-310.pyc
ADDED
Binary file (26.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/resources.cpython-310.pyc
ADDED
Binary file (11 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/scripts.cpython-310.pyc
ADDED
Binary file (11.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/util.cpython-310.pyc
ADDED
Binary file (51.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/version.cpython-310.pyc
ADDED
Binary file (20.1 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/__pycache__/wheel.cpython-310.pyc
ADDED
Binary file (27.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/locators.py
ADDED
@@ -0,0 +1,1300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
#
|
3 |
+
# Copyright (C) 2012-2015 Vinay Sajip.
|
4 |
+
# Licensed to the Python Software Foundation under a contributor agreement.
|
5 |
+
# See LICENSE.txt and CONTRIBUTORS.txt.
|
6 |
+
#
|
7 |
+
|
8 |
+
import gzip
|
9 |
+
from io import BytesIO
|
10 |
+
import json
|
11 |
+
import logging
|
12 |
+
import os
|
13 |
+
import posixpath
|
14 |
+
import re
|
15 |
+
try:
|
16 |
+
import threading
|
17 |
+
except ImportError: # pragma: no cover
|
18 |
+
import dummy_threading as threading
|
19 |
+
import zlib
|
20 |
+
|
21 |
+
from . import DistlibException
|
22 |
+
from .compat import (urljoin, urlparse, urlunparse, url2pathname, pathname2url,
|
23 |
+
queue, quote, unescape, build_opener,
|
24 |
+
HTTPRedirectHandler as BaseRedirectHandler, text_type,
|
25 |
+
Request, HTTPError, URLError)
|
26 |
+
from .database import Distribution, DistributionPath, make_dist
|
27 |
+
from .metadata import Metadata, MetadataInvalidError
|
28 |
+
from .util import (cached_property, ensure_slash, split_filename, get_project_data,
|
29 |
+
parse_requirement, parse_name_and_version, ServerProxy,
|
30 |
+
normalize_name)
|
31 |
+
from .version import get_scheme, UnsupportedVersionError
|
32 |
+
from .wheel import Wheel, is_compatible
|
33 |
+
|
34 |
+
logger = logging.getLogger(__name__)
|
35 |
+
|
36 |
+
HASHER_HASH = re.compile(r'^(\w+)=([a-f0-9]+)')
|
37 |
+
CHARSET = re.compile(r';\s*charset\s*=\s*(.*)\s*$', re.I)
|
38 |
+
HTML_CONTENT_TYPE = re.compile('text/html|application/x(ht)?ml')
|
39 |
+
DEFAULT_INDEX = 'https://pypi.org/pypi'
|
40 |
+
|
41 |
+
def get_all_distribution_names(url=None):
|
42 |
+
"""
|
43 |
+
Return all distribution names known by an index.
|
44 |
+
:param url: The URL of the index.
|
45 |
+
:return: A list of all known distribution names.
|
46 |
+
"""
|
47 |
+
if url is None:
|
48 |
+
url = DEFAULT_INDEX
|
49 |
+
client = ServerProxy(url, timeout=3.0)
|
50 |
+
try:
|
51 |
+
return client.list_packages()
|
52 |
+
finally:
|
53 |
+
client('close')()
|
54 |
+
|
55 |
+
class RedirectHandler(BaseRedirectHandler):
|
56 |
+
"""
|
57 |
+
A class to work around a bug in some Python 3.2.x releases.
|
58 |
+
"""
|
59 |
+
# There's a bug in the base version for some 3.2.x
|
60 |
+
# (e.g. 3.2.2 on Ubuntu Oneiric). If a Location header
|
61 |
+
# returns e.g. /abc, it bails because it says the scheme ''
|
62 |
+
# is bogus, when actually it should use the request's
|
63 |
+
# URL for the scheme. See Python issue #13696.
|
64 |
+
def http_error_302(self, req, fp, code, msg, headers):
|
65 |
+
# Some servers (incorrectly) return multiple Location headers
|
66 |
+
# (so probably same goes for URI). Use first header.
|
67 |
+
newurl = None
|
68 |
+
for key in ('location', 'uri'):
|
69 |
+
if key in headers:
|
70 |
+
newurl = headers[key]
|
71 |
+
break
|
72 |
+
if newurl is None: # pragma: no cover
|
73 |
+
return
|
74 |
+
urlparts = urlparse(newurl)
|
75 |
+
if urlparts.scheme == '':
|
76 |
+
newurl = urljoin(req.get_full_url(), newurl)
|
77 |
+
if hasattr(headers, 'replace_header'):
|
78 |
+
headers.replace_header(key, newurl)
|
79 |
+
else:
|
80 |
+
headers[key] = newurl
|
81 |
+
return BaseRedirectHandler.http_error_302(self, req, fp, code, msg,
|
82 |
+
headers)
|
83 |
+
|
84 |
+
http_error_301 = http_error_303 = http_error_307 = http_error_302
|
85 |
+
|
86 |
+
class Locator(object):
|
87 |
+
"""
|
88 |
+
A base class for locators - things that locate distributions.
|
89 |
+
"""
|
90 |
+
source_extensions = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz')
|
91 |
+
binary_extensions = ('.egg', '.exe', '.whl')
|
92 |
+
excluded_extensions = ('.pdf',)
|
93 |
+
|
94 |
+
# A list of tags indicating which wheels you want to match. The default
|
95 |
+
# value of None matches against the tags compatible with the running
|
96 |
+
# Python. If you want to match other values, set wheel_tags on a locator
|
97 |
+
# instance to a list of tuples (pyver, abi, arch) which you want to match.
|
98 |
+
wheel_tags = None
|
99 |
+
|
100 |
+
downloadable_extensions = source_extensions + ('.whl',)
|
101 |
+
|
102 |
+
def __init__(self, scheme='default'):
|
103 |
+
"""
|
104 |
+
Initialise an instance.
|
105 |
+
:param scheme: Because locators look for most recent versions, they
|
106 |
+
need to know the version scheme to use. This specifies
|
107 |
+
the current PEP-recommended scheme - use ``'legacy'``
|
108 |
+
if you need to support existing distributions on PyPI.
|
109 |
+
"""
|
110 |
+
self._cache = {}
|
111 |
+
self.scheme = scheme
|
112 |
+
# Because of bugs in some of the handlers on some of the platforms,
|
113 |
+
# we use our own opener rather than just using urlopen.
|
114 |
+
self.opener = build_opener(RedirectHandler())
|
115 |
+
# If get_project() is called from locate(), the matcher instance
|
116 |
+
# is set from the requirement passed to locate(). See issue #18 for
|
117 |
+
# why this can be useful to know.
|
118 |
+
self.matcher = None
|
119 |
+
self.errors = queue.Queue()
|
120 |
+
|
121 |
+
def get_errors(self):
|
122 |
+
"""
|
123 |
+
Return any errors which have occurred.
|
124 |
+
"""
|
125 |
+
result = []
|
126 |
+
while not self.errors.empty(): # pragma: no cover
|
127 |
+
try:
|
128 |
+
e = self.errors.get(False)
|
129 |
+
result.append(e)
|
130 |
+
except self.errors.Empty:
|
131 |
+
continue
|
132 |
+
self.errors.task_done()
|
133 |
+
return result
|
134 |
+
|
135 |
+
def clear_errors(self):
|
136 |
+
"""
|
137 |
+
Clear any errors which may have been logged.
|
138 |
+
"""
|
139 |
+
# Just get the errors and throw them away
|
140 |
+
self.get_errors()
|
141 |
+
|
142 |
+
def clear_cache(self):
|
143 |
+
self._cache.clear()
|
144 |
+
|
145 |
+
def _get_scheme(self):
|
146 |
+
return self._scheme
|
147 |
+
|
148 |
+
def _set_scheme(self, value):
|
149 |
+
self._scheme = value
|
150 |
+
|
151 |
+
scheme = property(_get_scheme, _set_scheme)
|
152 |
+
|
153 |
+
def _get_project(self, name):
|
154 |
+
"""
|
155 |
+
For a given project, get a dictionary mapping available versions to Distribution
|
156 |
+
instances.
|
157 |
+
|
158 |
+
This should be implemented in subclasses.
|
159 |
+
|
160 |
+
If called from a locate() request, self.matcher will be set to a
|
161 |
+
matcher for the requirement to satisfy, otherwise it will be None.
|
162 |
+
"""
|
163 |
+
raise NotImplementedError('Please implement in the subclass')
|
164 |
+
|
165 |
+
def get_distribution_names(self):
|
166 |
+
"""
|
167 |
+
Return all the distribution names known to this locator.
|
168 |
+
"""
|
169 |
+
raise NotImplementedError('Please implement in the subclass')
|
170 |
+
|
171 |
+
def get_project(self, name):
|
172 |
+
"""
|
173 |
+
For a given project, get a dictionary mapping available versions to Distribution
|
174 |
+
instances.
|
175 |
+
|
176 |
+
This calls _get_project to do all the work, and just implements a caching layer on top.
|
177 |
+
"""
|
178 |
+
if self._cache is None: # pragma: no cover
|
179 |
+
result = self._get_project(name)
|
180 |
+
elif name in self._cache:
|
181 |
+
result = self._cache[name]
|
182 |
+
else:
|
183 |
+
self.clear_errors()
|
184 |
+
result = self._get_project(name)
|
185 |
+
self._cache[name] = result
|
186 |
+
return result
|
187 |
+
|
188 |
+
def score_url(self, url):
|
189 |
+
"""
|
190 |
+
Give an url a score which can be used to choose preferred URLs
|
191 |
+
for a given project release.
|
192 |
+
"""
|
193 |
+
t = urlparse(url)
|
194 |
+
basename = posixpath.basename(t.path)
|
195 |
+
compatible = True
|
196 |
+
is_wheel = basename.endswith('.whl')
|
197 |
+
is_downloadable = basename.endswith(self.downloadable_extensions)
|
198 |
+
if is_wheel:
|
199 |
+
compatible = is_compatible(Wheel(basename), self.wheel_tags)
|
200 |
+
return (t.scheme == 'https', 'pypi.org' in t.netloc,
|
201 |
+
is_downloadable, is_wheel, compatible, basename)
|
202 |
+
|
203 |
+
def prefer_url(self, url1, url2):
|
204 |
+
"""
|
205 |
+
Choose one of two URLs where both are candidates for distribution
|
206 |
+
archives for the same version of a distribution (for example,
|
207 |
+
.tar.gz vs. zip).
|
208 |
+
|
209 |
+
The current implementation favours https:// URLs over http://, archives
|
210 |
+
from PyPI over those from other locations, wheel compatibility (if a
|
211 |
+
wheel) and then the archive name.
|
212 |
+
"""
|
213 |
+
result = url2
|
214 |
+
if url1:
|
215 |
+
s1 = self.score_url(url1)
|
216 |
+
s2 = self.score_url(url2)
|
217 |
+
if s1 > s2:
|
218 |
+
result = url1
|
219 |
+
if result != url2:
|
220 |
+
logger.debug('Not replacing %r with %r', url1, url2)
|
221 |
+
else:
|
222 |
+
logger.debug('Replacing %r with %r', url1, url2)
|
223 |
+
return result
|
224 |
+
|
225 |
+
def split_filename(self, filename, project_name):
|
226 |
+
"""
|
227 |
+
Attempt to split a filename in project name, version and Python version.
|
228 |
+
"""
|
229 |
+
return split_filename(filename, project_name)
|
230 |
+
|
231 |
+
def convert_url_to_download_info(self, url, project_name):
|
232 |
+
"""
|
233 |
+
See if a URL is a candidate for a download URL for a project (the URL
|
234 |
+
has typically been scraped from an HTML page).
|
235 |
+
|
236 |
+
If it is, a dictionary is returned with keys "name", "version",
|
237 |
+
"filename" and "url"; otherwise, None is returned.
|
238 |
+
"""
|
239 |
+
def same_project(name1, name2):
|
240 |
+
return normalize_name(name1) == normalize_name(name2)
|
241 |
+
|
242 |
+
result = None
|
243 |
+
scheme, netloc, path, params, query, frag = urlparse(url)
|
244 |
+
if frag.lower().startswith('egg='): # pragma: no cover
|
245 |
+
logger.debug('%s: version hint in fragment: %r',
|
246 |
+
project_name, frag)
|
247 |
+
m = HASHER_HASH.match(frag)
|
248 |
+
if m:
|
249 |
+
algo, digest = m.groups()
|
250 |
+
else:
|
251 |
+
algo, digest = None, None
|
252 |
+
origpath = path
|
253 |
+
if path and path[-1] == '/': # pragma: no cover
|
254 |
+
path = path[:-1]
|
255 |
+
if path.endswith('.whl'):
|
256 |
+
try:
|
257 |
+
wheel = Wheel(path)
|
258 |
+
if not is_compatible(wheel, self.wheel_tags):
|
259 |
+
logger.debug('Wheel not compatible: %s', path)
|
260 |
+
else:
|
261 |
+
if project_name is None:
|
262 |
+
include = True
|
263 |
+
else:
|
264 |
+
include = same_project(wheel.name, project_name)
|
265 |
+
if include:
|
266 |
+
result = {
|
267 |
+
'name': wheel.name,
|
268 |
+
'version': wheel.version,
|
269 |
+
'filename': wheel.filename,
|
270 |
+
'url': urlunparse((scheme, netloc, origpath,
|
271 |
+
params, query, '')),
|
272 |
+
'python-version': ', '.join(
|
273 |
+
['.'.join(list(v[2:])) for v in wheel.pyver]),
|
274 |
+
}
|
275 |
+
except Exception as e: # pragma: no cover
|
276 |
+
logger.warning('invalid path for wheel: %s', path)
|
277 |
+
elif not path.endswith(self.downloadable_extensions): # pragma: no cover
|
278 |
+
logger.debug('Not downloadable: %s', path)
|
279 |
+
else: # downloadable extension
|
280 |
+
path = filename = posixpath.basename(path)
|
281 |
+
for ext in self.downloadable_extensions:
|
282 |
+
if path.endswith(ext):
|
283 |
+
path = path[:-len(ext)]
|
284 |
+
t = self.split_filename(path, project_name)
|
285 |
+
if not t: # pragma: no cover
|
286 |
+
logger.debug('No match for project/version: %s', path)
|
287 |
+
else:
|
288 |
+
name, version, pyver = t
|
289 |
+
if not project_name or same_project(project_name, name):
|
290 |
+
result = {
|
291 |
+
'name': name,
|
292 |
+
'version': version,
|
293 |
+
'filename': filename,
|
294 |
+
'url': urlunparse((scheme, netloc, origpath,
|
295 |
+
params, query, '')),
|
296 |
+
#'packagetype': 'sdist',
|
297 |
+
}
|
298 |
+
if pyver: # pragma: no cover
|
299 |
+
result['python-version'] = pyver
|
300 |
+
break
|
301 |
+
if result and algo:
|
302 |
+
result['%s_digest' % algo] = digest
|
303 |
+
return result
|
304 |
+
|
305 |
+
def _get_digest(self, info):
|
306 |
+
"""
|
307 |
+
Get a digest from a dictionary by looking at a "digests" dictionary
|
308 |
+
or keys of the form 'algo_digest'.
|
309 |
+
|
310 |
+
Returns a 2-tuple (algo, digest) if found, else None. Currently
|
311 |
+
looks only for SHA256, then MD5.
|
312 |
+
"""
|
313 |
+
result = None
|
314 |
+
if 'digests' in info:
|
315 |
+
digests = info['digests']
|
316 |
+
for algo in ('sha256', 'md5'):
|
317 |
+
if algo in digests:
|
318 |
+
result = (algo, digests[algo])
|
319 |
+
break
|
320 |
+
if not result:
|
321 |
+
for algo in ('sha256', 'md5'):
|
322 |
+
key = '%s_digest' % algo
|
323 |
+
if key in info:
|
324 |
+
result = (algo, info[key])
|
325 |
+
break
|
326 |
+
return result
|
327 |
+
|
328 |
+
def _update_version_data(self, result, info):
|
329 |
+
"""
|
330 |
+
Update a result dictionary (the final result from _get_project) with a
|
331 |
+
dictionary for a specific version, which typically holds information
|
332 |
+
gleaned from a filename or URL for an archive for the distribution.
|
333 |
+
"""
|
334 |
+
name = info.pop('name')
|
335 |
+
version = info.pop('version')
|
336 |
+
if version in result:
|
337 |
+
dist = result[version]
|
338 |
+
md = dist.metadata
|
339 |
+
else:
|
340 |
+
dist = make_dist(name, version, scheme=self.scheme)
|
341 |
+
md = dist.metadata
|
342 |
+
dist.digest = digest = self._get_digest(info)
|
343 |
+
url = info['url']
|
344 |
+
result['digests'][url] = digest
|
345 |
+
if md.source_url != info['url']:
|
346 |
+
md.source_url = self.prefer_url(md.source_url, url)
|
347 |
+
result['urls'].setdefault(version, set()).add(url)
|
348 |
+
dist.locator = self
|
349 |
+
result[version] = dist
|
350 |
+
|
351 |
+
def locate(self, requirement, prereleases=False):
|
352 |
+
"""
|
353 |
+
Find the most recent distribution which matches the given
|
354 |
+
requirement.
|
355 |
+
|
356 |
+
:param requirement: A requirement of the form 'foo (1.0)' or perhaps
|
357 |
+
'foo (>= 1.0, < 2.0, != 1.3)'
|
358 |
+
:param prereleases: If ``True``, allow pre-release versions
|
359 |
+
to be located. Otherwise, pre-release versions
|
360 |
+
are not returned.
|
361 |
+
:return: A :class:`Distribution` instance, or ``None`` if no such
|
362 |
+
distribution could be located.
|
363 |
+
"""
|
364 |
+
result = None
|
365 |
+
r = parse_requirement(requirement)
|
366 |
+
if r is None: # pragma: no cover
|
367 |
+
raise DistlibException('Not a valid requirement: %r' % requirement)
|
368 |
+
scheme = get_scheme(self.scheme)
|
369 |
+
self.matcher = matcher = scheme.matcher(r.requirement)
|
370 |
+
logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)
|
371 |
+
versions = self.get_project(r.name)
|
372 |
+
if len(versions) > 2: # urls and digests keys are present
|
373 |
+
# sometimes, versions are invalid
|
374 |
+
slist = []
|
375 |
+
vcls = matcher.version_class
|
376 |
+
for k in versions:
|
377 |
+
if k in ('urls', 'digests'):
|
378 |
+
continue
|
379 |
+
try:
|
380 |
+
if not matcher.match(k):
|
381 |
+
pass # logger.debug('%s did not match %r', matcher, k)
|
382 |
+
else:
|
383 |
+
if prereleases or not vcls(k).is_prerelease:
|
384 |
+
slist.append(k)
|
385 |
+
# else:
|
386 |
+
# logger.debug('skipping pre-release '
|
387 |
+
# 'version %s of %s', k, matcher.name)
|
388 |
+
except Exception: # pragma: no cover
|
389 |
+
logger.warning('error matching %s with %r', matcher, k)
|
390 |
+
pass # slist.append(k)
|
391 |
+
if len(slist) > 1:
|
392 |
+
slist = sorted(slist, key=scheme.key)
|
393 |
+
if slist:
|
394 |
+
logger.debug('sorted list: %s', slist)
|
395 |
+
version = slist[-1]
|
396 |
+
result = versions[version]
|
397 |
+
if result:
|
398 |
+
if r.extras:
|
399 |
+
result.extras = r.extras
|
400 |
+
result.download_urls = versions.get('urls', {}).get(version, set())
|
401 |
+
d = {}
|
402 |
+
sd = versions.get('digests', {})
|
403 |
+
for url in result.download_urls:
|
404 |
+
if url in sd: # pragma: no cover
|
405 |
+
d[url] = sd[url]
|
406 |
+
result.digests = d
|
407 |
+
self.matcher = None
|
408 |
+
return result
|
409 |
+
|
410 |
+
|
411 |
+
class PyPIRPCLocator(Locator):
|
412 |
+
"""
|
413 |
+
This locator uses XML-RPC to locate distributions. It therefore
|
414 |
+
cannot be used with simple mirrors (that only mirror file content).
|
415 |
+
"""
|
416 |
+
def __init__(self, url, **kwargs):
|
417 |
+
"""
|
418 |
+
Initialise an instance.
|
419 |
+
|
420 |
+
:param url: The URL to use for XML-RPC.
|
421 |
+
:param kwargs: Passed to the superclass constructor.
|
422 |
+
"""
|
423 |
+
super(PyPIRPCLocator, self).__init__(**kwargs)
|
424 |
+
self.base_url = url
|
425 |
+
self.client = ServerProxy(url, timeout=3.0)
|
426 |
+
|
427 |
+
def get_distribution_names(self):
|
428 |
+
"""
|
429 |
+
Return all the distribution names known to this locator.
|
430 |
+
"""
|
431 |
+
return set(self.client.list_packages())
|
432 |
+
|
433 |
+
def _get_project(self, name):
|
434 |
+
result = {'urls': {}, 'digests': {}}
|
435 |
+
versions = self.client.package_releases(name, True)
|
436 |
+
for v in versions:
|
437 |
+
urls = self.client.release_urls(name, v)
|
438 |
+
data = self.client.release_data(name, v)
|
439 |
+
metadata = Metadata(scheme=self.scheme)
|
440 |
+
metadata.name = data['name']
|
441 |
+
metadata.version = data['version']
|
442 |
+
metadata.license = data.get('license')
|
443 |
+
metadata.keywords = data.get('keywords', [])
|
444 |
+
metadata.summary = data.get('summary')
|
445 |
+
dist = Distribution(metadata)
|
446 |
+
if urls:
|
447 |
+
info = urls[0]
|
448 |
+
metadata.source_url = info['url']
|
449 |
+
dist.digest = self._get_digest(info)
|
450 |
+
dist.locator = self
|
451 |
+
result[v] = dist
|
452 |
+
for info in urls:
|
453 |
+
url = info['url']
|
454 |
+
digest = self._get_digest(info)
|
455 |
+
result['urls'].setdefault(v, set()).add(url)
|
456 |
+
result['digests'][url] = digest
|
457 |
+
return result
|
458 |
+
|
459 |
+
class PyPIJSONLocator(Locator):
|
460 |
+
"""
|
461 |
+
This locator uses PyPI's JSON interface. It's very limited in functionality
|
462 |
+
and probably not worth using.
|
463 |
+
"""
|
464 |
+
def __init__(self, url, **kwargs):
|
465 |
+
super(PyPIJSONLocator, self).__init__(**kwargs)
|
466 |
+
self.base_url = ensure_slash(url)
|
467 |
+
|
468 |
+
def get_distribution_names(self):
|
469 |
+
"""
|
470 |
+
Return all the distribution names known to this locator.
|
471 |
+
"""
|
472 |
+
raise NotImplementedError('Not available from this locator')
|
473 |
+
|
474 |
+
def _get_project(self, name):
|
475 |
+
result = {'urls': {}, 'digests': {}}
|
476 |
+
url = urljoin(self.base_url, '%s/json' % quote(name))
|
477 |
+
try:
|
478 |
+
resp = self.opener.open(url)
|
479 |
+
data = resp.read().decode() # for now
|
480 |
+
d = json.loads(data)
|
481 |
+
md = Metadata(scheme=self.scheme)
|
482 |
+
data = d['info']
|
483 |
+
md.name = data['name']
|
484 |
+
md.version = data['version']
|
485 |
+
md.license = data.get('license')
|
486 |
+
md.keywords = data.get('keywords', [])
|
487 |
+
md.summary = data.get('summary')
|
488 |
+
dist = Distribution(md)
|
489 |
+
dist.locator = self
|
490 |
+
urls = d['urls']
|
491 |
+
result[md.version] = dist
|
492 |
+
for info in d['urls']:
|
493 |
+
url = info['url']
|
494 |
+
dist.download_urls.add(url)
|
495 |
+
dist.digests[url] = self._get_digest(info)
|
496 |
+
result['urls'].setdefault(md.version, set()).add(url)
|
497 |
+
result['digests'][url] = self._get_digest(info)
|
498 |
+
# Now get other releases
|
499 |
+
for version, infos in d['releases'].items():
|
500 |
+
if version == md.version:
|
501 |
+
continue # already done
|
502 |
+
omd = Metadata(scheme=self.scheme)
|
503 |
+
omd.name = md.name
|
504 |
+
omd.version = version
|
505 |
+
odist = Distribution(omd)
|
506 |
+
odist.locator = self
|
507 |
+
result[version] = odist
|
508 |
+
for info in infos:
|
509 |
+
url = info['url']
|
510 |
+
odist.download_urls.add(url)
|
511 |
+
odist.digests[url] = self._get_digest(info)
|
512 |
+
result['urls'].setdefault(version, set()).add(url)
|
513 |
+
result['digests'][url] = self._get_digest(info)
|
514 |
+
# for info in urls:
|
515 |
+
# md.source_url = info['url']
|
516 |
+
# dist.digest = self._get_digest(info)
|
517 |
+
# dist.locator = self
|
518 |
+
# for info in urls:
|
519 |
+
# url = info['url']
|
520 |
+
# result['urls'].setdefault(md.version, set()).add(url)
|
521 |
+
# result['digests'][url] = self._get_digest(info)
|
522 |
+
except Exception as e:
|
523 |
+
self.errors.put(text_type(e))
|
524 |
+
logger.exception('JSON fetch failed: %s', e)
|
525 |
+
return result
|
526 |
+
|
527 |
+
|
528 |
+
class Page(object):
|
529 |
+
"""
|
530 |
+
This class represents a scraped HTML page.
|
531 |
+
"""
|
532 |
+
# The following slightly hairy-looking regex just looks for the contents of
|
533 |
+
# an anchor link, which has an attribute "href" either immediately preceded
|
534 |
+
# or immediately followed by a "rel" attribute. The attribute values can be
|
535 |
+
# declared with double quotes, single quotes or no quotes - which leads to
|
536 |
+
# the length of the expression.
|
537 |
+
_href = re.compile("""
|
538 |
+
(rel\\s*=\\s*(?:"(?P<rel1>[^"]*)"|'(?P<rel2>[^']*)'|(?P<rel3>[^>\\s\n]*))\\s+)?
|
539 |
+
href\\s*=\\s*(?:"(?P<url1>[^"]*)"|'(?P<url2>[^']*)'|(?P<url3>[^>\\s\n]*))
|
540 |
+
(\\s+rel\\s*=\\s*(?:"(?P<rel4>[^"]*)"|'(?P<rel5>[^']*)'|(?P<rel6>[^>\\s\n]*)))?
|
541 |
+
""", re.I | re.S | re.X)
|
542 |
+
_base = re.compile(r"""<base\s+href\s*=\s*['"]?([^'">]+)""", re.I | re.S)
|
543 |
+
|
544 |
+
def __init__(self, data, url):
|
545 |
+
"""
|
546 |
+
Initialise an instance with the Unicode page contents and the URL they
|
547 |
+
came from.
|
548 |
+
"""
|
549 |
+
self.data = data
|
550 |
+
self.base_url = self.url = url
|
551 |
+
m = self._base.search(self.data)
|
552 |
+
if m:
|
553 |
+
self.base_url = m.group(1)
|
554 |
+
|
555 |
+
_clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\|-]', re.I)
|
556 |
+
|
557 |
+
@cached_property
|
558 |
+
def links(self):
|
559 |
+
"""
|
560 |
+
Return the URLs of all the links on a page together with information
|
561 |
+
about their "rel" attribute, for determining which ones to treat as
|
562 |
+
downloads and which ones to queue for further scraping.
|
563 |
+
"""
|
564 |
+
def clean(url):
|
565 |
+
"Tidy up an URL."
|
566 |
+
scheme, netloc, path, params, query, frag = urlparse(url)
|
567 |
+
return urlunparse((scheme, netloc, quote(path),
|
568 |
+
params, query, frag))
|
569 |
+
|
570 |
+
result = set()
|
571 |
+
for match in self._href.finditer(self.data):
|
572 |
+
d = match.groupdict('')
|
573 |
+
rel = (d['rel1'] or d['rel2'] or d['rel3'] or
|
574 |
+
d['rel4'] or d['rel5'] or d['rel6'])
|
575 |
+
url = d['url1'] or d['url2'] or d['url3']
|
576 |
+
url = urljoin(self.base_url, url)
|
577 |
+
url = unescape(url)
|
578 |
+
url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url)
|
579 |
+
result.add((url, rel))
|
580 |
+
# We sort the result, hoping to bring the most recent versions
|
581 |
+
# to the front
|
582 |
+
result = sorted(result, key=lambda t: t[0], reverse=True)
|
583 |
+
return result
|
584 |
+
|
585 |
+
|
586 |
+
class SimpleScrapingLocator(Locator):
|
587 |
+
"""
|
588 |
+
A locator which scrapes HTML pages to locate downloads for a distribution.
|
589 |
+
This runs multiple threads to do the I/O; performance is at least as good
|
590 |
+
as pip's PackageFinder, which works in an analogous fashion.
|
591 |
+
"""
|
592 |
+
|
593 |
+
# These are used to deal with various Content-Encoding schemes.
|
594 |
+
decoders = {
|
595 |
+
'deflate': zlib.decompress,
|
596 |
+
'gzip': lambda b: gzip.GzipFile(fileobj=BytesIO(b)).read(),
|
597 |
+
'none': lambda b: b,
|
598 |
+
}
|
599 |
+
|
600 |
+
def __init__(self, url, timeout=None, num_workers=10, **kwargs):
|
601 |
+
"""
|
602 |
+
Initialise an instance.
|
603 |
+
:param url: The root URL to use for scraping.
|
604 |
+
:param timeout: The timeout, in seconds, to be applied to requests.
|
605 |
+
This defaults to ``None`` (no timeout specified).
|
606 |
+
:param num_workers: The number of worker threads you want to do I/O,
|
607 |
+
This defaults to 10.
|
608 |
+
:param kwargs: Passed to the superclass.
|
609 |
+
"""
|
610 |
+
super(SimpleScrapingLocator, self).__init__(**kwargs)
|
611 |
+
self.base_url = ensure_slash(url)
|
612 |
+
self.timeout = timeout
|
613 |
+
self._page_cache = {}
|
614 |
+
self._seen = set()
|
615 |
+
self._to_fetch = queue.Queue()
|
616 |
+
self._bad_hosts = set()
|
617 |
+
self.skip_externals = False
|
618 |
+
self.num_workers = num_workers
|
619 |
+
self._lock = threading.RLock()
|
620 |
+
# See issue #45: we need to be resilient when the locator is used
|
621 |
+
# in a thread, e.g. with concurrent.futures. We can't use self._lock
|
622 |
+
# as it is for coordinating our internal threads - the ones created
|
623 |
+
# in _prepare_threads.
|
624 |
+
self._gplock = threading.RLock()
|
625 |
+
self.platform_check = False # See issue #112
|
626 |
+
|
627 |
+
def _prepare_threads(self):
|
628 |
+
"""
|
629 |
+
Threads are created only when get_project is called, and terminate
|
630 |
+
before it returns. They are there primarily to parallelise I/O (i.e.
|
631 |
+
fetching web pages).
|
632 |
+
"""
|
633 |
+
self._threads = []
|
634 |
+
for i in range(self.num_workers):
|
635 |
+
t = threading.Thread(target=self._fetch)
|
636 |
+
t.daemon = True
|
637 |
+
t.start()
|
638 |
+
self._threads.append(t)
|
639 |
+
|
640 |
+
def _wait_threads(self):
|
641 |
+
"""
|
642 |
+
Tell all the threads to terminate (by sending a sentinel value) and
|
643 |
+
wait for them to do so.
|
644 |
+
"""
|
645 |
+
# Note that you need two loops, since you can't say which
|
646 |
+
# thread will get each sentinel
|
647 |
+
for t in self._threads:
|
648 |
+
self._to_fetch.put(None) # sentinel
|
649 |
+
for t in self._threads:
|
650 |
+
t.join()
|
651 |
+
self._threads = []
|
652 |
+
|
653 |
+
def _get_project(self, name):
|
654 |
+
result = {'urls': {}, 'digests': {}}
|
655 |
+
with self._gplock:
|
656 |
+
self.result = result
|
657 |
+
self.project_name = name
|
658 |
+
url = urljoin(self.base_url, '%s/' % quote(name))
|
659 |
+
self._seen.clear()
|
660 |
+
self._page_cache.clear()
|
661 |
+
self._prepare_threads()
|
662 |
+
try:
|
663 |
+
logger.debug('Queueing %s', url)
|
664 |
+
self._to_fetch.put(url)
|
665 |
+
self._to_fetch.join()
|
666 |
+
finally:
|
667 |
+
self._wait_threads()
|
668 |
+
del self.result
|
669 |
+
return result
|
670 |
+
|
671 |
+
platform_dependent = re.compile(r'\b(linux_(i\d86|x86_64|arm\w+)|'
|
672 |
+
r'win(32|_amd64)|macosx_?\d+)\b', re.I)
|
673 |
+
|
674 |
+
def _is_platform_dependent(self, url):
|
675 |
+
"""
|
676 |
+
Does an URL refer to a platform-specific download?
|
677 |
+
"""
|
678 |
+
return self.platform_dependent.search(url)
|
679 |
+
|
680 |
+
def _process_download(self, url):
|
681 |
+
"""
|
682 |
+
See if an URL is a suitable download for a project.
|
683 |
+
|
684 |
+
If it is, register information in the result dictionary (for
|
685 |
+
_get_project) about the specific version it's for.
|
686 |
+
|
687 |
+
Note that the return value isn't actually used other than as a boolean
|
688 |
+
value.
|
689 |
+
"""
|
690 |
+
if self.platform_check and self._is_platform_dependent(url):
|
691 |
+
info = None
|
692 |
+
else:
|
693 |
+
info = self.convert_url_to_download_info(url, self.project_name)
|
694 |
+
logger.debug('process_download: %s -> %s', url, info)
|
695 |
+
if info:
|
696 |
+
with self._lock: # needed because self.result is shared
|
697 |
+
self._update_version_data(self.result, info)
|
698 |
+
return info
|
699 |
+
|
700 |
+
def _should_queue(self, link, referrer, rel):
|
701 |
+
"""
|
702 |
+
Determine whether a link URL from a referring page and with a
|
703 |
+
particular "rel" attribute should be queued for scraping.
|
704 |
+
"""
|
705 |
+
scheme, netloc, path, _, _, _ = urlparse(link)
|
706 |
+
if path.endswith(self.source_extensions + self.binary_extensions +
|
707 |
+
self.excluded_extensions):
|
708 |
+
result = False
|
709 |
+
elif self.skip_externals and not link.startswith(self.base_url):
|
710 |
+
result = False
|
711 |
+
elif not referrer.startswith(self.base_url):
|
712 |
+
result = False
|
713 |
+
elif rel not in ('homepage', 'download'):
|
714 |
+
result = False
|
715 |
+
elif scheme not in ('http', 'https', 'ftp'):
|
716 |
+
result = False
|
717 |
+
elif self._is_platform_dependent(link):
|
718 |
+
result = False
|
719 |
+
else:
|
720 |
+
host = netloc.split(':', 1)[0]
|
721 |
+
if host.lower() == 'localhost':
|
722 |
+
result = False
|
723 |
+
else:
|
724 |
+
result = True
|
725 |
+
logger.debug('should_queue: %s (%s) from %s -> %s', link, rel,
|
726 |
+
referrer, result)
|
727 |
+
return result
|
728 |
+
|
729 |
+
def _fetch(self):
|
730 |
+
"""
|
731 |
+
Get a URL to fetch from the work queue, get the HTML page, examine its
|
732 |
+
links for download candidates and candidates for further scraping.
|
733 |
+
|
734 |
+
This is a handy method to run in a thread.
|
735 |
+
"""
|
736 |
+
while True:
|
737 |
+
url = self._to_fetch.get()
|
738 |
+
try:
|
739 |
+
if url:
|
740 |
+
page = self.get_page(url)
|
741 |
+
if page is None: # e.g. after an error
|
742 |
+
continue
|
743 |
+
for link, rel in page.links:
|
744 |
+
if link not in self._seen:
|
745 |
+
try:
|
746 |
+
self._seen.add(link)
|
747 |
+
if (not self._process_download(link) and
|
748 |
+
self._should_queue(link, url, rel)):
|
749 |
+
logger.debug('Queueing %s from %s', link, url)
|
750 |
+
self._to_fetch.put(link)
|
751 |
+
except MetadataInvalidError: # e.g. invalid versions
|
752 |
+
pass
|
753 |
+
except Exception as e: # pragma: no cover
|
754 |
+
self.errors.put(text_type(e))
|
755 |
+
finally:
|
756 |
+
# always do this, to avoid hangs :-)
|
757 |
+
self._to_fetch.task_done()
|
758 |
+
if not url:
|
759 |
+
#logger.debug('Sentinel seen, quitting.')
|
760 |
+
break
|
761 |
+
|
762 |
+
def get_page(self, url):
|
763 |
+
"""
|
764 |
+
Get the HTML for an URL, possibly from an in-memory cache.
|
765 |
+
|
766 |
+
XXX TODO Note: this cache is never actually cleared. It's assumed that
|
767 |
+
the data won't get stale over the lifetime of a locator instance (not
|
768 |
+
necessarily true for the default_locator).
|
769 |
+
"""
|
770 |
+
# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api
|
771 |
+
scheme, netloc, path, _, _, _ = urlparse(url)
|
772 |
+
if scheme == 'file' and os.path.isdir(url2pathname(path)):
|
773 |
+
url = urljoin(ensure_slash(url), 'index.html')
|
774 |
+
|
775 |
+
if url in self._page_cache:
|
776 |
+
result = self._page_cache[url]
|
777 |
+
logger.debug('Returning %s from cache: %s', url, result)
|
778 |
+
else:
|
779 |
+
host = netloc.split(':', 1)[0]
|
780 |
+
result = None
|
781 |
+
if host in self._bad_hosts:
|
782 |
+
logger.debug('Skipping %s due to bad host %s', url, host)
|
783 |
+
else:
|
784 |
+
req = Request(url, headers={'Accept-encoding': 'identity'})
|
785 |
+
try:
|
786 |
+
logger.debug('Fetching %s', url)
|
787 |
+
resp = self.opener.open(req, timeout=self.timeout)
|
788 |
+
logger.debug('Fetched %s', url)
|
789 |
+
headers = resp.info()
|
790 |
+
content_type = headers.get('Content-Type', '')
|
791 |
+
if HTML_CONTENT_TYPE.match(content_type):
|
792 |
+
final_url = resp.geturl()
|
793 |
+
data = resp.read()
|
794 |
+
encoding = headers.get('Content-Encoding')
|
795 |
+
if encoding:
|
796 |
+
decoder = self.decoders[encoding] # fail if not found
|
797 |
+
data = decoder(data)
|
798 |
+
encoding = 'utf-8'
|
799 |
+
m = CHARSET.search(content_type)
|
800 |
+
if m:
|
801 |
+
encoding = m.group(1)
|
802 |
+
try:
|
803 |
+
data = data.decode(encoding)
|
804 |
+
except UnicodeError: # pragma: no cover
|
805 |
+
data = data.decode('latin-1') # fallback
|
806 |
+
result = Page(data, final_url)
|
807 |
+
self._page_cache[final_url] = result
|
808 |
+
except HTTPError as e:
|
809 |
+
if e.code != 404:
|
810 |
+
logger.exception('Fetch failed: %s: %s', url, e)
|
811 |
+
except URLError as e: # pragma: no cover
|
812 |
+
logger.exception('Fetch failed: %s: %s', url, e)
|
813 |
+
with self._lock:
|
814 |
+
self._bad_hosts.add(host)
|
815 |
+
except Exception as e: # pragma: no cover
|
816 |
+
logger.exception('Fetch failed: %s: %s', url, e)
|
817 |
+
finally:
|
818 |
+
self._page_cache[url] = result # even if None (failure)
|
819 |
+
return result
|
820 |
+
|
821 |
+
_distname_re = re.compile('<a href=[^>]*>([^<]+)<')
|
822 |
+
|
823 |
+
def get_distribution_names(self):
|
824 |
+
"""
|
825 |
+
Return all the distribution names known to this locator.
|
826 |
+
"""
|
827 |
+
result = set()
|
828 |
+
page = self.get_page(self.base_url)
|
829 |
+
if not page:
|
830 |
+
raise DistlibException('Unable to get %s' % self.base_url)
|
831 |
+
for match in self._distname_re.finditer(page.data):
|
832 |
+
result.add(match.group(1))
|
833 |
+
return result
|
834 |
+
|
835 |
+
class DirectoryLocator(Locator):
|
836 |
+
"""
|
837 |
+
This class locates distributions in a directory tree.
|
838 |
+
"""
|
839 |
+
|
840 |
+
def __init__(self, path, **kwargs):
|
841 |
+
"""
|
842 |
+
Initialise an instance.
|
843 |
+
:param path: The root of the directory tree to search.
|
844 |
+
:param kwargs: Passed to the superclass constructor,
|
845 |
+
except for:
|
846 |
+
* recursive - if True (the default), subdirectories are
|
847 |
+
recursed into. If False, only the top-level directory
|
848 |
+
is searched,
|
849 |
+
"""
|
850 |
+
self.recursive = kwargs.pop('recursive', True)
|
851 |
+
super(DirectoryLocator, self).__init__(**kwargs)
|
852 |
+
path = os.path.abspath(path)
|
853 |
+
if not os.path.isdir(path): # pragma: no cover
|
854 |
+
raise DistlibException('Not a directory: %r' % path)
|
855 |
+
self.base_dir = path
|
856 |
+
|
857 |
+
def should_include(self, filename, parent):
|
858 |
+
"""
|
859 |
+
Should a filename be considered as a candidate for a distribution
|
860 |
+
archive? As well as the filename, the directory which contains it
|
861 |
+
is provided, though not used by the current implementation.
|
862 |
+
"""
|
863 |
+
return filename.endswith(self.downloadable_extensions)
|
864 |
+
|
865 |
+
def _get_project(self, name):
|
866 |
+
result = {'urls': {}, 'digests': {}}
|
867 |
+
for root, dirs, files in os.walk(self.base_dir):
|
868 |
+
for fn in files:
|
869 |
+
if self.should_include(fn, root):
|
870 |
+
fn = os.path.join(root, fn)
|
871 |
+
url = urlunparse(('file', '',
|
872 |
+
pathname2url(os.path.abspath(fn)),
|
873 |
+
'', '', ''))
|
874 |
+
info = self.convert_url_to_download_info(url, name)
|
875 |
+
if info:
|
876 |
+
self._update_version_data(result, info)
|
877 |
+
if not self.recursive:
|
878 |
+
break
|
879 |
+
return result
|
880 |
+
|
881 |
+
def get_distribution_names(self):
|
882 |
+
"""
|
883 |
+
Return all the distribution names known to this locator.
|
884 |
+
"""
|
885 |
+
result = set()
|
886 |
+
for root, dirs, files in os.walk(self.base_dir):
|
887 |
+
for fn in files:
|
888 |
+
if self.should_include(fn, root):
|
889 |
+
fn = os.path.join(root, fn)
|
890 |
+
url = urlunparse(('file', '',
|
891 |
+
pathname2url(os.path.abspath(fn)),
|
892 |
+
'', '', ''))
|
893 |
+
info = self.convert_url_to_download_info(url, None)
|
894 |
+
if info:
|
895 |
+
result.add(info['name'])
|
896 |
+
if not self.recursive:
|
897 |
+
break
|
898 |
+
return result
|
899 |
+
|
900 |
+
class JSONLocator(Locator):
|
901 |
+
"""
|
902 |
+
This locator uses special extended metadata (not available on PyPI) and is
|
903 |
+
the basis of performant dependency resolution in distlib. Other locators
|
904 |
+
require archive downloads before dependencies can be determined! As you
|
905 |
+
might imagine, that can be slow.
|
906 |
+
"""
|
907 |
+
def get_distribution_names(self):
|
908 |
+
"""
|
909 |
+
Return all the distribution names known to this locator.
|
910 |
+
"""
|
911 |
+
raise NotImplementedError('Not available from this locator')
|
912 |
+
|
913 |
+
def _get_project(self, name):
|
914 |
+
result = {'urls': {}, 'digests': {}}
|
915 |
+
data = get_project_data(name)
|
916 |
+
if data:
|
917 |
+
for info in data.get('files', []):
|
918 |
+
if info['ptype'] != 'sdist' or info['pyversion'] != 'source':
|
919 |
+
continue
|
920 |
+
# We don't store summary in project metadata as it makes
|
921 |
+
# the data bigger for no benefit during dependency
|
922 |
+
# resolution
|
923 |
+
dist = make_dist(data['name'], info['version'],
|
924 |
+
summary=data.get('summary',
|
925 |
+
'Placeholder for summary'),
|
926 |
+
scheme=self.scheme)
|
927 |
+
md = dist.metadata
|
928 |
+
md.source_url = info['url']
|
929 |
+
# TODO SHA256 digest
|
930 |
+
if 'digest' in info and info['digest']:
|
931 |
+
dist.digest = ('md5', info['digest'])
|
932 |
+
md.dependencies = info.get('requirements', {})
|
933 |
+
dist.exports = info.get('exports', {})
|
934 |
+
result[dist.version] = dist
|
935 |
+
result['urls'].setdefault(dist.version, set()).add(info['url'])
|
936 |
+
return result
|
937 |
+
|
938 |
+
class DistPathLocator(Locator):
|
939 |
+
"""
|
940 |
+
This locator finds installed distributions in a path. It can be useful for
|
941 |
+
adding to an :class:`AggregatingLocator`.
|
942 |
+
"""
|
943 |
+
def __init__(self, distpath, **kwargs):
|
944 |
+
"""
|
945 |
+
Initialise an instance.
|
946 |
+
|
947 |
+
:param distpath: A :class:`DistributionPath` instance to search.
|
948 |
+
"""
|
949 |
+
super(DistPathLocator, self).__init__(**kwargs)
|
950 |
+
assert isinstance(distpath, DistributionPath)
|
951 |
+
self.distpath = distpath
|
952 |
+
|
953 |
+
def _get_project(self, name):
|
954 |
+
dist = self.distpath.get_distribution(name)
|
955 |
+
if dist is None:
|
956 |
+
result = {'urls': {}, 'digests': {}}
|
957 |
+
else:
|
958 |
+
result = {
|
959 |
+
dist.version: dist,
|
960 |
+
'urls': {dist.version: set([dist.source_url])},
|
961 |
+
'digests': {dist.version: set([None])}
|
962 |
+
}
|
963 |
+
return result
|
964 |
+
|
965 |
+
|
966 |
+
class AggregatingLocator(Locator):
|
967 |
+
"""
|
968 |
+
This class allows you to chain and/or merge a list of locators.
|
969 |
+
"""
|
970 |
+
def __init__(self, *locators, **kwargs):
|
971 |
+
"""
|
972 |
+
Initialise an instance.
|
973 |
+
|
974 |
+
:param locators: The list of locators to search.
|
975 |
+
:param kwargs: Passed to the superclass constructor,
|
976 |
+
except for:
|
977 |
+
* merge - if False (the default), the first successful
|
978 |
+
search from any of the locators is returned. If True,
|
979 |
+
the results from all locators are merged (this can be
|
980 |
+
slow).
|
981 |
+
"""
|
982 |
+
self.merge = kwargs.pop('merge', False)
|
983 |
+
self.locators = locators
|
984 |
+
super(AggregatingLocator, self).__init__(**kwargs)
|
985 |
+
|
986 |
+
def clear_cache(self):
|
987 |
+
super(AggregatingLocator, self).clear_cache()
|
988 |
+
for locator in self.locators:
|
989 |
+
locator.clear_cache()
|
990 |
+
|
991 |
+
def _set_scheme(self, value):
|
992 |
+
self._scheme = value
|
993 |
+
for locator in self.locators:
|
994 |
+
locator.scheme = value
|
995 |
+
|
996 |
+
scheme = property(Locator.scheme.fget, _set_scheme)
|
997 |
+
|
998 |
+
def _get_project(self, name):
|
999 |
+
result = {}
|
1000 |
+
for locator in self.locators:
|
1001 |
+
d = locator.get_project(name)
|
1002 |
+
if d:
|
1003 |
+
if self.merge:
|
1004 |
+
files = result.get('urls', {})
|
1005 |
+
digests = result.get('digests', {})
|
1006 |
+
# next line could overwrite result['urls'], result['digests']
|
1007 |
+
result.update(d)
|
1008 |
+
df = result.get('urls')
|
1009 |
+
if files and df:
|
1010 |
+
for k, v in files.items():
|
1011 |
+
if k in df:
|
1012 |
+
df[k] |= v
|
1013 |
+
else:
|
1014 |
+
df[k] = v
|
1015 |
+
dd = result.get('digests')
|
1016 |
+
if digests and dd:
|
1017 |
+
dd.update(digests)
|
1018 |
+
else:
|
1019 |
+
# See issue #18. If any dists are found and we're looking
|
1020 |
+
# for specific constraints, we only return something if
|
1021 |
+
# a match is found. For example, if a DirectoryLocator
|
1022 |
+
# returns just foo (1.0) while we're looking for
|
1023 |
+
# foo (>= 2.0), we'll pretend there was nothing there so
|
1024 |
+
# that subsequent locators can be queried. Otherwise we
|
1025 |
+
# would just return foo (1.0) which would then lead to a
|
1026 |
+
# failure to find foo (>= 2.0), because other locators
|
1027 |
+
# weren't searched. Note that this only matters when
|
1028 |
+
# merge=False.
|
1029 |
+
if self.matcher is None:
|
1030 |
+
found = True
|
1031 |
+
else:
|
1032 |
+
found = False
|
1033 |
+
for k in d:
|
1034 |
+
if self.matcher.match(k):
|
1035 |
+
found = True
|
1036 |
+
break
|
1037 |
+
if found:
|
1038 |
+
result = d
|
1039 |
+
break
|
1040 |
+
return result
|
1041 |
+
|
1042 |
+
def get_distribution_names(self):
|
1043 |
+
"""
|
1044 |
+
Return all the distribution names known to this locator.
|
1045 |
+
"""
|
1046 |
+
result = set()
|
1047 |
+
for locator in self.locators:
|
1048 |
+
try:
|
1049 |
+
result |= locator.get_distribution_names()
|
1050 |
+
except NotImplementedError:
|
1051 |
+
pass
|
1052 |
+
return result
|
1053 |
+
|
1054 |
+
|
1055 |
+
# We use a legacy scheme simply because most of the dists on PyPI use legacy
|
1056 |
+
# versions which don't conform to PEP 426 / PEP 440.
|
1057 |
+
default_locator = AggregatingLocator(
|
1058 |
+
JSONLocator(),
|
1059 |
+
SimpleScrapingLocator('https://pypi.org/simple/',
|
1060 |
+
timeout=3.0),
|
1061 |
+
scheme='legacy')
|
1062 |
+
|
1063 |
+
locate = default_locator.locate
|
1064 |
+
|
1065 |
+
|
1066 |
+
class DependencyFinder(object):
|
1067 |
+
"""
|
1068 |
+
Locate dependencies for distributions.
|
1069 |
+
"""
|
1070 |
+
|
1071 |
+
def __init__(self, locator=None):
|
1072 |
+
"""
|
1073 |
+
Initialise an instance, using the specified locator
|
1074 |
+
to locate distributions.
|
1075 |
+
"""
|
1076 |
+
self.locator = locator or default_locator
|
1077 |
+
self.scheme = get_scheme(self.locator.scheme)
|
1078 |
+
|
1079 |
+
def add_distribution(self, dist):
|
1080 |
+
"""
|
1081 |
+
Add a distribution to the finder. This will update internal information
|
1082 |
+
about who provides what.
|
1083 |
+
:param dist: The distribution to add.
|
1084 |
+
"""
|
1085 |
+
logger.debug('adding distribution %s', dist)
|
1086 |
+
name = dist.key
|
1087 |
+
self.dists_by_name[name] = dist
|
1088 |
+
self.dists[(name, dist.version)] = dist
|
1089 |
+
for p in dist.provides:
|
1090 |
+
name, version = parse_name_and_version(p)
|
1091 |
+
logger.debug('Add to provided: %s, %s, %s', name, version, dist)
|
1092 |
+
self.provided.setdefault(name, set()).add((version, dist))
|
1093 |
+
|
1094 |
+
def remove_distribution(self, dist):
|
1095 |
+
"""
|
1096 |
+
Remove a distribution from the finder. This will update internal
|
1097 |
+
information about who provides what.
|
1098 |
+
:param dist: The distribution to remove.
|
1099 |
+
"""
|
1100 |
+
logger.debug('removing distribution %s', dist)
|
1101 |
+
name = dist.key
|
1102 |
+
del self.dists_by_name[name]
|
1103 |
+
del self.dists[(name, dist.version)]
|
1104 |
+
for p in dist.provides:
|
1105 |
+
name, version = parse_name_and_version(p)
|
1106 |
+
logger.debug('Remove from provided: %s, %s, %s', name, version, dist)
|
1107 |
+
s = self.provided[name]
|
1108 |
+
s.remove((version, dist))
|
1109 |
+
if not s:
|
1110 |
+
del self.provided[name]
|
1111 |
+
|
1112 |
+
def get_matcher(self, reqt):
|
1113 |
+
"""
|
1114 |
+
Get a version matcher for a requirement.
|
1115 |
+
:param reqt: The requirement
|
1116 |
+
:type reqt: str
|
1117 |
+
:return: A version matcher (an instance of
|
1118 |
+
:class:`distlib.version.Matcher`).
|
1119 |
+
"""
|
1120 |
+
try:
|
1121 |
+
matcher = self.scheme.matcher(reqt)
|
1122 |
+
except UnsupportedVersionError: # pragma: no cover
|
1123 |
+
# XXX compat-mode if cannot read the version
|
1124 |
+
name = reqt.split()[0]
|
1125 |
+
matcher = self.scheme.matcher(name)
|
1126 |
+
return matcher
|
1127 |
+
|
1128 |
+
def find_providers(self, reqt):
|
1129 |
+
"""
|
1130 |
+
Find the distributions which can fulfill a requirement.
|
1131 |
+
|
1132 |
+
:param reqt: The requirement.
|
1133 |
+
:type reqt: str
|
1134 |
+
:return: A set of distribution which can fulfill the requirement.
|
1135 |
+
"""
|
1136 |
+
matcher = self.get_matcher(reqt)
|
1137 |
+
name = matcher.key # case-insensitive
|
1138 |
+
result = set()
|
1139 |
+
provided = self.provided
|
1140 |
+
if name in provided:
|
1141 |
+
for version, provider in provided[name]:
|
1142 |
+
try:
|
1143 |
+
match = matcher.match(version)
|
1144 |
+
except UnsupportedVersionError:
|
1145 |
+
match = False
|
1146 |
+
|
1147 |
+
if match:
|
1148 |
+
result.add(provider)
|
1149 |
+
break
|
1150 |
+
return result
|
1151 |
+
|
1152 |
+
def try_to_replace(self, provider, other, problems):
|
1153 |
+
"""
|
1154 |
+
Attempt to replace one provider with another. This is typically used
|
1155 |
+
when resolving dependencies from multiple sources, e.g. A requires
|
1156 |
+
(B >= 1.0) while C requires (B >= 1.1).
|
1157 |
+
|
1158 |
+
For successful replacement, ``provider`` must meet all the requirements
|
1159 |
+
which ``other`` fulfills.
|
1160 |
+
|
1161 |
+
:param provider: The provider we are trying to replace with.
|
1162 |
+
:param other: The provider we're trying to replace.
|
1163 |
+
:param problems: If False is returned, this will contain what
|
1164 |
+
problems prevented replacement. This is currently
|
1165 |
+
a tuple of the literal string 'cantreplace',
|
1166 |
+
``provider``, ``other`` and the set of requirements
|
1167 |
+
that ``provider`` couldn't fulfill.
|
1168 |
+
:return: True if we can replace ``other`` with ``provider``, else
|
1169 |
+
False.
|
1170 |
+
"""
|
1171 |
+
rlist = self.reqts[other]
|
1172 |
+
unmatched = set()
|
1173 |
+
for s in rlist:
|
1174 |
+
matcher = self.get_matcher(s)
|
1175 |
+
if not matcher.match(provider.version):
|
1176 |
+
unmatched.add(s)
|
1177 |
+
if unmatched:
|
1178 |
+
# can't replace other with provider
|
1179 |
+
problems.add(('cantreplace', provider, other,
|
1180 |
+
frozenset(unmatched)))
|
1181 |
+
result = False
|
1182 |
+
else:
|
1183 |
+
# can replace other with provider
|
1184 |
+
self.remove_distribution(other)
|
1185 |
+
del self.reqts[other]
|
1186 |
+
for s in rlist:
|
1187 |
+
self.reqts.setdefault(provider, set()).add(s)
|
1188 |
+
self.add_distribution(provider)
|
1189 |
+
result = True
|
1190 |
+
return result
|
1191 |
+
|
1192 |
+
def find(self, requirement, meta_extras=None, prereleases=False):
|
1193 |
+
"""
|
1194 |
+
Find a distribution and all distributions it depends on.
|
1195 |
+
|
1196 |
+
:param requirement: The requirement specifying the distribution to
|
1197 |
+
find, or a Distribution instance.
|
1198 |
+
:param meta_extras: A list of meta extras such as :test:, :build: and
|
1199 |
+
so on.
|
1200 |
+
:param prereleases: If ``True``, allow pre-release versions to be
|
1201 |
+
returned - otherwise, don't return prereleases
|
1202 |
+
unless they're all that's available.
|
1203 |
+
|
1204 |
+
Return a set of :class:`Distribution` instances and a set of
|
1205 |
+
problems.
|
1206 |
+
|
1207 |
+
The distributions returned should be such that they have the
|
1208 |
+
:attr:`required` attribute set to ``True`` if they were
|
1209 |
+
from the ``requirement`` passed to ``find()``, and they have the
|
1210 |
+
:attr:`build_time_dependency` attribute set to ``True`` unless they
|
1211 |
+
are post-installation dependencies of the ``requirement``.
|
1212 |
+
|
1213 |
+
The problems should be a tuple consisting of the string
|
1214 |
+
``'unsatisfied'`` and the requirement which couldn't be satisfied
|
1215 |
+
by any distribution known to the locator.
|
1216 |
+
"""
|
1217 |
+
|
1218 |
+
self.provided = {}
|
1219 |
+
self.dists = {}
|
1220 |
+
self.dists_by_name = {}
|
1221 |
+
self.reqts = {}
|
1222 |
+
|
1223 |
+
meta_extras = set(meta_extras or [])
|
1224 |
+
if ':*:' in meta_extras:
|
1225 |
+
meta_extras.remove(':*:')
|
1226 |
+
# :meta: and :run: are implicitly included
|
1227 |
+
meta_extras |= set([':test:', ':build:', ':dev:'])
|
1228 |
+
|
1229 |
+
if isinstance(requirement, Distribution):
|
1230 |
+
dist = odist = requirement
|
1231 |
+
logger.debug('passed %s as requirement', odist)
|
1232 |
+
else:
|
1233 |
+
dist = odist = self.locator.locate(requirement,
|
1234 |
+
prereleases=prereleases)
|
1235 |
+
if dist is None:
|
1236 |
+
raise DistlibException('Unable to locate %r' % requirement)
|
1237 |
+
logger.debug('located %s', odist)
|
1238 |
+
dist.requested = True
|
1239 |
+
problems = set()
|
1240 |
+
todo = set([dist])
|
1241 |
+
install_dists = set([odist])
|
1242 |
+
while todo:
|
1243 |
+
dist = todo.pop()
|
1244 |
+
name = dist.key # case-insensitive
|
1245 |
+
if name not in self.dists_by_name:
|
1246 |
+
self.add_distribution(dist)
|
1247 |
+
else:
|
1248 |
+
#import pdb; pdb.set_trace()
|
1249 |
+
other = self.dists_by_name[name]
|
1250 |
+
if other != dist:
|
1251 |
+
self.try_to_replace(dist, other, problems)
|
1252 |
+
|
1253 |
+
ireqts = dist.run_requires | dist.meta_requires
|
1254 |
+
sreqts = dist.build_requires
|
1255 |
+
ereqts = set()
|
1256 |
+
if meta_extras and dist in install_dists:
|
1257 |
+
for key in ('test', 'build', 'dev'):
|
1258 |
+
e = ':%s:' % key
|
1259 |
+
if e in meta_extras:
|
1260 |
+
ereqts |= getattr(dist, '%s_requires' % key)
|
1261 |
+
all_reqts = ireqts | sreqts | ereqts
|
1262 |
+
for r in all_reqts:
|
1263 |
+
providers = self.find_providers(r)
|
1264 |
+
if not providers:
|
1265 |
+
logger.debug('No providers found for %r', r)
|
1266 |
+
provider = self.locator.locate(r, prereleases=prereleases)
|
1267 |
+
# If no provider is found and we didn't consider
|
1268 |
+
# prereleases, consider them now.
|
1269 |
+
if provider is None and not prereleases:
|
1270 |
+
provider = self.locator.locate(r, prereleases=True)
|
1271 |
+
if provider is None:
|
1272 |
+
logger.debug('Cannot satisfy %r', r)
|
1273 |
+
problems.add(('unsatisfied', r))
|
1274 |
+
else:
|
1275 |
+
n, v = provider.key, provider.version
|
1276 |
+
if (n, v) not in self.dists:
|
1277 |
+
todo.add(provider)
|
1278 |
+
providers.add(provider)
|
1279 |
+
if r in ireqts and dist in install_dists:
|
1280 |
+
install_dists.add(provider)
|
1281 |
+
logger.debug('Adding %s to install_dists',
|
1282 |
+
provider.name_and_version)
|
1283 |
+
for p in providers:
|
1284 |
+
name = p.key
|
1285 |
+
if name not in self.dists_by_name:
|
1286 |
+
self.reqts.setdefault(p, set()).add(r)
|
1287 |
+
else:
|
1288 |
+
other = self.dists_by_name[name]
|
1289 |
+
if other != p:
|
1290 |
+
# see if other can be replaced by p
|
1291 |
+
self.try_to_replace(p, other, problems)
|
1292 |
+
|
1293 |
+
dists = set(self.dists.values())
|
1294 |
+
for dist in dists:
|
1295 |
+
dist.build_time_dependency = dist not in install_dists
|
1296 |
+
if dist.build_time_dependency:
|
1297 |
+
logger.debug('%s is a build-time dependency only.',
|
1298 |
+
dist.name_and_version)
|
1299 |
+
logger.debug('find done for %s', odist)
|
1300 |
+
return dists, problems
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/distlib/wheel.py
ADDED
@@ -0,0 +1,1053 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
#
|
3 |
+
# Copyright (C) 2013-2020 Vinay Sajip.
|
4 |
+
# Licensed to the Python Software Foundation under a contributor agreement.
|
5 |
+
# See LICENSE.txt and CONTRIBUTORS.txt.
|
6 |
+
#
|
7 |
+
from __future__ import unicode_literals
|
8 |
+
|
9 |
+
import base64
|
10 |
+
import codecs
|
11 |
+
import datetime
|
12 |
+
from email import message_from_file
|
13 |
+
import hashlib
|
14 |
+
import imp
|
15 |
+
import json
|
16 |
+
import logging
|
17 |
+
import os
|
18 |
+
import posixpath
|
19 |
+
import re
|
20 |
+
import shutil
|
21 |
+
import sys
|
22 |
+
import tempfile
|
23 |
+
import zipfile
|
24 |
+
|
25 |
+
from . import __version__, DistlibException
|
26 |
+
from .compat import sysconfig, ZipFile, fsdecode, text_type, filter
|
27 |
+
from .database import InstalledDistribution
|
28 |
+
from .metadata import (Metadata, METADATA_FILENAME, WHEEL_METADATA_FILENAME,
|
29 |
+
LEGACY_METADATA_FILENAME)
|
30 |
+
from .util import (FileOperator, convert_path, CSVReader, CSVWriter, Cache,
|
31 |
+
cached_property, get_cache_base, read_exports, tempdir,
|
32 |
+
get_platform)
|
33 |
+
from .version import NormalizedVersion, UnsupportedVersionError
|
34 |
+
|
35 |
+
logger = logging.getLogger(__name__)
|
36 |
+
|
37 |
+
cache = None # created when needed
|
38 |
+
|
39 |
+
if hasattr(sys, 'pypy_version_info'): # pragma: no cover
|
40 |
+
IMP_PREFIX = 'pp'
|
41 |
+
elif sys.platform.startswith('java'): # pragma: no cover
|
42 |
+
IMP_PREFIX = 'jy'
|
43 |
+
elif sys.platform == 'cli': # pragma: no cover
|
44 |
+
IMP_PREFIX = 'ip'
|
45 |
+
else:
|
46 |
+
IMP_PREFIX = 'cp'
|
47 |
+
|
48 |
+
VER_SUFFIX = sysconfig.get_config_var('py_version_nodot')
|
49 |
+
if not VER_SUFFIX: # pragma: no cover
|
50 |
+
VER_SUFFIX = '%s%s' % sys.version_info[:2]
|
51 |
+
PYVER = 'py' + VER_SUFFIX
|
52 |
+
IMPVER = IMP_PREFIX + VER_SUFFIX
|
53 |
+
|
54 |
+
ARCH = get_platform().replace('-', '_').replace('.', '_')
|
55 |
+
|
56 |
+
ABI = sysconfig.get_config_var('SOABI')
|
57 |
+
if ABI and ABI.startswith('cpython-'):
|
58 |
+
ABI = ABI.replace('cpython-', 'cp').split('-')[0]
|
59 |
+
else:
|
60 |
+
def _derive_abi():
|
61 |
+
parts = ['cp', VER_SUFFIX]
|
62 |
+
if sysconfig.get_config_var('Py_DEBUG'):
|
63 |
+
parts.append('d')
|
64 |
+
if sysconfig.get_config_var('WITH_PYMALLOC'):
|
65 |
+
parts.append('m')
|
66 |
+
if sysconfig.get_config_var('Py_UNICODE_SIZE') == 4:
|
67 |
+
parts.append('u')
|
68 |
+
return ''.join(parts)
|
69 |
+
ABI = _derive_abi()
|
70 |
+
del _derive_abi
|
71 |
+
|
72 |
+
FILENAME_RE = re.compile(r'''
|
73 |
+
(?P<nm>[^-]+)
|
74 |
+
-(?P<vn>\d+[^-]*)
|
75 |
+
(-(?P<bn>\d+[^-]*))?
|
76 |
+
-(?P<py>\w+\d+(\.\w+\d+)*)
|
77 |
+
-(?P<bi>\w+)
|
78 |
+
-(?P<ar>\w+(\.\w+)*)
|
79 |
+
\.whl$
|
80 |
+
''', re.IGNORECASE | re.VERBOSE)
|
81 |
+
|
82 |
+
NAME_VERSION_RE = re.compile(r'''
|
83 |
+
(?P<nm>[^-]+)
|
84 |
+
-(?P<vn>\d+[^-]*)
|
85 |
+
(-(?P<bn>\d+[^-]*))?$
|
86 |
+
''', re.IGNORECASE | re.VERBOSE)
|
87 |
+
|
88 |
+
SHEBANG_RE = re.compile(br'\s*#![^\r\n]*')
|
89 |
+
SHEBANG_DETAIL_RE = re.compile(br'^(\s*#!("[^"]+"|\S+))\s+(.*)$')
|
90 |
+
SHEBANG_PYTHON = b'#!python'
|
91 |
+
SHEBANG_PYTHONW = b'#!pythonw'
|
92 |
+
|
93 |
+
if os.sep == '/':
|
94 |
+
to_posix = lambda o: o
|
95 |
+
else:
|
96 |
+
to_posix = lambda o: o.replace(os.sep, '/')
|
97 |
+
|
98 |
+
|
99 |
+
class Mounter(object):
|
100 |
+
def __init__(self):
|
101 |
+
self.impure_wheels = {}
|
102 |
+
self.libs = {}
|
103 |
+
|
104 |
+
def add(self, pathname, extensions):
|
105 |
+
self.impure_wheels[pathname] = extensions
|
106 |
+
self.libs.update(extensions)
|
107 |
+
|
108 |
+
def remove(self, pathname):
|
109 |
+
extensions = self.impure_wheels.pop(pathname)
|
110 |
+
for k, v in extensions:
|
111 |
+
if k in self.libs:
|
112 |
+
del self.libs[k]
|
113 |
+
|
114 |
+
def find_module(self, fullname, path=None):
|
115 |
+
if fullname in self.libs:
|
116 |
+
result = self
|
117 |
+
else:
|
118 |
+
result = None
|
119 |
+
return result
|
120 |
+
|
121 |
+
def load_module(self, fullname):
|
122 |
+
if fullname in sys.modules:
|
123 |
+
result = sys.modules[fullname]
|
124 |
+
else:
|
125 |
+
if fullname not in self.libs:
|
126 |
+
raise ImportError('unable to find extension for %s' % fullname)
|
127 |
+
result = imp.load_dynamic(fullname, self.libs[fullname])
|
128 |
+
result.__loader__ = self
|
129 |
+
parts = fullname.rsplit('.', 1)
|
130 |
+
if len(parts) > 1:
|
131 |
+
result.__package__ = parts[0]
|
132 |
+
return result
|
133 |
+
|
134 |
+
_hook = Mounter()
|
135 |
+
|
136 |
+
|
137 |
+
class Wheel(object):
|
138 |
+
"""
|
139 |
+
Class to build and install from Wheel files (PEP 427).
|
140 |
+
"""
|
141 |
+
|
142 |
+
wheel_version = (1, 1)
|
143 |
+
hash_kind = 'sha256'
|
144 |
+
|
145 |
+
def __init__(self, filename=None, sign=False, verify=False):
|
146 |
+
"""
|
147 |
+
Initialise an instance using a (valid) filename.
|
148 |
+
"""
|
149 |
+
self.sign = sign
|
150 |
+
self.should_verify = verify
|
151 |
+
self.buildver = ''
|
152 |
+
self.pyver = [PYVER]
|
153 |
+
self.abi = ['none']
|
154 |
+
self.arch = ['any']
|
155 |
+
self.dirname = os.getcwd()
|
156 |
+
if filename is None:
|
157 |
+
self.name = 'dummy'
|
158 |
+
self.version = '0.1'
|
159 |
+
self._filename = self.filename
|
160 |
+
else:
|
161 |
+
m = NAME_VERSION_RE.match(filename)
|
162 |
+
if m:
|
163 |
+
info = m.groupdict('')
|
164 |
+
self.name = info['nm']
|
165 |
+
# Reinstate the local version separator
|
166 |
+
self.version = info['vn'].replace('_', '-')
|
167 |
+
self.buildver = info['bn']
|
168 |
+
self._filename = self.filename
|
169 |
+
else:
|
170 |
+
dirname, filename = os.path.split(filename)
|
171 |
+
m = FILENAME_RE.match(filename)
|
172 |
+
if not m:
|
173 |
+
raise DistlibException('Invalid name or '
|
174 |
+
'filename: %r' % filename)
|
175 |
+
if dirname:
|
176 |
+
self.dirname = os.path.abspath(dirname)
|
177 |
+
self._filename = filename
|
178 |
+
info = m.groupdict('')
|
179 |
+
self.name = info['nm']
|
180 |
+
self.version = info['vn']
|
181 |
+
self.buildver = info['bn']
|
182 |
+
self.pyver = info['py'].split('.')
|
183 |
+
self.abi = info['bi'].split('.')
|
184 |
+
self.arch = info['ar'].split('.')
|
185 |
+
|
186 |
+
@property
|
187 |
+
def filename(self):
|
188 |
+
"""
|
189 |
+
Build and return a filename from the various components.
|
190 |
+
"""
|
191 |
+
if self.buildver:
|
192 |
+
buildver = '-' + self.buildver
|
193 |
+
else:
|
194 |
+
buildver = ''
|
195 |
+
pyver = '.'.join(self.pyver)
|
196 |
+
abi = '.'.join(self.abi)
|
197 |
+
arch = '.'.join(self.arch)
|
198 |
+
# replace - with _ as a local version separator
|
199 |
+
version = self.version.replace('-', '_')
|
200 |
+
return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,
|
201 |
+
pyver, abi, arch)
|
202 |
+
|
203 |
+
@property
|
204 |
+
def exists(self):
|
205 |
+
path = os.path.join(self.dirname, self.filename)
|
206 |
+
return os.path.isfile(path)
|
207 |
+
|
208 |
+
@property
|
209 |
+
def tags(self):
|
210 |
+
for pyver in self.pyver:
|
211 |
+
for abi in self.abi:
|
212 |
+
for arch in self.arch:
|
213 |
+
yield pyver, abi, arch
|
214 |
+
|
215 |
+
@cached_property
|
216 |
+
def metadata(self):
|
217 |
+
pathname = os.path.join(self.dirname, self.filename)
|
218 |
+
name_ver = '%s-%s' % (self.name, self.version)
|
219 |
+
info_dir = '%s.dist-info' % name_ver
|
220 |
+
wrapper = codecs.getreader('utf-8')
|
221 |
+
with ZipFile(pathname, 'r') as zf:
|
222 |
+
wheel_metadata = self.get_wheel_metadata(zf)
|
223 |
+
wv = wheel_metadata['Wheel-Version'].split('.', 1)
|
224 |
+
file_version = tuple([int(i) for i in wv])
|
225 |
+
# if file_version < (1, 1):
|
226 |
+
# fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME,
|
227 |
+
# LEGACY_METADATA_FILENAME]
|
228 |
+
# else:
|
229 |
+
# fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME]
|
230 |
+
fns = [WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME]
|
231 |
+
result = None
|
232 |
+
for fn in fns:
|
233 |
+
try:
|
234 |
+
metadata_filename = posixpath.join(info_dir, fn)
|
235 |
+
with zf.open(metadata_filename) as bf:
|
236 |
+
wf = wrapper(bf)
|
237 |
+
result = Metadata(fileobj=wf)
|
238 |
+
if result:
|
239 |
+
break
|
240 |
+
except KeyError:
|
241 |
+
pass
|
242 |
+
if not result:
|
243 |
+
raise ValueError('Invalid wheel, because metadata is '
|
244 |
+
'missing: looked in %s' % ', '.join(fns))
|
245 |
+
return result
|
246 |
+
|
247 |
+
def get_wheel_metadata(self, zf):
|
248 |
+
name_ver = '%s-%s' % (self.name, self.version)
|
249 |
+
info_dir = '%s.dist-info' % name_ver
|
250 |
+
metadata_filename = posixpath.join(info_dir, 'WHEEL')
|
251 |
+
with zf.open(metadata_filename) as bf:
|
252 |
+
wf = codecs.getreader('utf-8')(bf)
|
253 |
+
message = message_from_file(wf)
|
254 |
+
return dict(message)
|
255 |
+
|
256 |
+
@cached_property
|
257 |
+
def info(self):
|
258 |
+
pathname = os.path.join(self.dirname, self.filename)
|
259 |
+
with ZipFile(pathname, 'r') as zf:
|
260 |
+
result = self.get_wheel_metadata(zf)
|
261 |
+
return result
|
262 |
+
|
263 |
+
def process_shebang(self, data):
|
264 |
+
m = SHEBANG_RE.match(data)
|
265 |
+
if m:
|
266 |
+
end = m.end()
|
267 |
+
shebang, data_after_shebang = data[:end], data[end:]
|
268 |
+
# Preserve any arguments after the interpreter
|
269 |
+
if b'pythonw' in shebang.lower():
|
270 |
+
shebang_python = SHEBANG_PYTHONW
|
271 |
+
else:
|
272 |
+
shebang_python = SHEBANG_PYTHON
|
273 |
+
m = SHEBANG_DETAIL_RE.match(shebang)
|
274 |
+
if m:
|
275 |
+
args = b' ' + m.groups()[-1]
|
276 |
+
else:
|
277 |
+
args = b''
|
278 |
+
shebang = shebang_python + args
|
279 |
+
data = shebang + data_after_shebang
|
280 |
+
else:
|
281 |
+
cr = data.find(b'\r')
|
282 |
+
lf = data.find(b'\n')
|
283 |
+
if cr < 0 or cr > lf:
|
284 |
+
term = b'\n'
|
285 |
+
else:
|
286 |
+
if data[cr:cr + 2] == b'\r\n':
|
287 |
+
term = b'\r\n'
|
288 |
+
else:
|
289 |
+
term = b'\r'
|
290 |
+
data = SHEBANG_PYTHON + term + data
|
291 |
+
return data
|
292 |
+
|
293 |
+
def get_hash(self, data, hash_kind=None):
|
294 |
+
if hash_kind is None:
|
295 |
+
hash_kind = self.hash_kind
|
296 |
+
try:
|
297 |
+
hasher = getattr(hashlib, hash_kind)
|
298 |
+
except AttributeError:
|
299 |
+
raise DistlibException('Unsupported hash algorithm: %r' % hash_kind)
|
300 |
+
result = hasher(data).digest()
|
301 |
+
result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii')
|
302 |
+
return hash_kind, result
|
303 |
+
|
304 |
+
def write_record(self, records, record_path, base):
|
305 |
+
records = list(records) # make a copy, as mutated
|
306 |
+
p = to_posix(os.path.relpath(record_path, base))
|
307 |
+
records.append((p, '', ''))
|
308 |
+
with CSVWriter(record_path) as writer:
|
309 |
+
for row in records:
|
310 |
+
writer.writerow(row)
|
311 |
+
|
312 |
+
def write_records(self, info, libdir, archive_paths):
|
313 |
+
records = []
|
314 |
+
distinfo, info_dir = info
|
315 |
+
hasher = getattr(hashlib, self.hash_kind)
|
316 |
+
for ap, p in archive_paths:
|
317 |
+
with open(p, 'rb') as f:
|
318 |
+
data = f.read()
|
319 |
+
digest = '%s=%s' % self.get_hash(data)
|
320 |
+
size = os.path.getsize(p)
|
321 |
+
records.append((ap, digest, size))
|
322 |
+
|
323 |
+
p = os.path.join(distinfo, 'RECORD')
|
324 |
+
self.write_record(records, p, libdir)
|
325 |
+
ap = to_posix(os.path.join(info_dir, 'RECORD'))
|
326 |
+
archive_paths.append((ap, p))
|
327 |
+
|
328 |
+
def build_zip(self, pathname, archive_paths):
|
329 |
+
with ZipFile(pathname, 'w', zipfile.ZIP_DEFLATED) as zf:
|
330 |
+
for ap, p in archive_paths:
|
331 |
+
logger.debug('Wrote %s to %s in wheel', p, ap)
|
332 |
+
zf.write(p, ap)
|
333 |
+
|
334 |
+
def build(self, paths, tags=None, wheel_version=None):
|
335 |
+
"""
|
336 |
+
Build a wheel from files in specified paths, and use any specified tags
|
337 |
+
when determining the name of the wheel.
|
338 |
+
"""
|
339 |
+
if tags is None:
|
340 |
+
tags = {}
|
341 |
+
|
342 |
+
libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0]
|
343 |
+
if libkey == 'platlib':
|
344 |
+
is_pure = 'false'
|
345 |
+
default_pyver = [IMPVER]
|
346 |
+
default_abi = [ABI]
|
347 |
+
default_arch = [ARCH]
|
348 |
+
else:
|
349 |
+
is_pure = 'true'
|
350 |
+
default_pyver = [PYVER]
|
351 |
+
default_abi = ['none']
|
352 |
+
default_arch = ['any']
|
353 |
+
|
354 |
+
self.pyver = tags.get('pyver', default_pyver)
|
355 |
+
self.abi = tags.get('abi', default_abi)
|
356 |
+
self.arch = tags.get('arch', default_arch)
|
357 |
+
|
358 |
+
libdir = paths[libkey]
|
359 |
+
|
360 |
+
name_ver = '%s-%s' % (self.name, self.version)
|
361 |
+
data_dir = '%s.data' % name_ver
|
362 |
+
info_dir = '%s.dist-info' % name_ver
|
363 |
+
|
364 |
+
archive_paths = []
|
365 |
+
|
366 |
+
# First, stuff which is not in site-packages
|
367 |
+
for key in ('data', 'headers', 'scripts'):
|
368 |
+
if key not in paths:
|
369 |
+
continue
|
370 |
+
path = paths[key]
|
371 |
+
if os.path.isdir(path):
|
372 |
+
for root, dirs, files in os.walk(path):
|
373 |
+
for fn in files:
|
374 |
+
p = fsdecode(os.path.join(root, fn))
|
375 |
+
rp = os.path.relpath(p, path)
|
376 |
+
ap = to_posix(os.path.join(data_dir, key, rp))
|
377 |
+
archive_paths.append((ap, p))
|
378 |
+
if key == 'scripts' and not p.endswith('.exe'):
|
379 |
+
with open(p, 'rb') as f:
|
380 |
+
data = f.read()
|
381 |
+
data = self.process_shebang(data)
|
382 |
+
with open(p, 'wb') as f:
|
383 |
+
f.write(data)
|
384 |
+
|
385 |
+
# Now, stuff which is in site-packages, other than the
|
386 |
+
# distinfo stuff.
|
387 |
+
path = libdir
|
388 |
+
distinfo = None
|
389 |
+
for root, dirs, files in os.walk(path):
|
390 |
+
if root == path:
|
391 |
+
# At the top level only, save distinfo for later
|
392 |
+
# and skip it for now
|
393 |
+
for i, dn in enumerate(dirs):
|
394 |
+
dn = fsdecode(dn)
|
395 |
+
if dn.endswith('.dist-info'):
|
396 |
+
distinfo = os.path.join(root, dn)
|
397 |
+
del dirs[i]
|
398 |
+
break
|
399 |
+
assert distinfo, '.dist-info directory expected, not found'
|
400 |
+
|
401 |
+
for fn in files:
|
402 |
+
# comment out next suite to leave .pyc files in
|
403 |
+
if fsdecode(fn).endswith(('.pyc', '.pyo')):
|
404 |
+
continue
|
405 |
+
p = os.path.join(root, fn)
|
406 |
+
rp = to_posix(os.path.relpath(p, path))
|
407 |
+
archive_paths.append((rp, p))
|
408 |
+
|
409 |
+
# Now distinfo. Assumed to be flat, i.e. os.listdir is enough.
|
410 |
+
files = os.listdir(distinfo)
|
411 |
+
for fn in files:
|
412 |
+
if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'):
|
413 |
+
p = fsdecode(os.path.join(distinfo, fn))
|
414 |
+
ap = to_posix(os.path.join(info_dir, fn))
|
415 |
+
archive_paths.append((ap, p))
|
416 |
+
|
417 |
+
wheel_metadata = [
|
418 |
+
'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version),
|
419 |
+
'Generator: distlib %s' % __version__,
|
420 |
+
'Root-Is-Purelib: %s' % is_pure,
|
421 |
+
]
|
422 |
+
for pyver, abi, arch in self.tags:
|
423 |
+
wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch))
|
424 |
+
p = os.path.join(distinfo, 'WHEEL')
|
425 |
+
with open(p, 'w') as f:
|
426 |
+
f.write('\n'.join(wheel_metadata))
|
427 |
+
ap = to_posix(os.path.join(info_dir, 'WHEEL'))
|
428 |
+
archive_paths.append((ap, p))
|
429 |
+
|
430 |
+
# sort the entries by archive path. Not needed by any spec, but it
|
431 |
+
# keeps the archive listing and RECORD tidier than they would otherwise
|
432 |
+
# be. Use the number of path segments to keep directory entries together,
|
433 |
+
# and keep the dist-info stuff at the end.
|
434 |
+
def sorter(t):
|
435 |
+
ap = t[0]
|
436 |
+
n = ap.count('/')
|
437 |
+
if '.dist-info' in ap:
|
438 |
+
n += 10000
|
439 |
+
return (n, ap)
|
440 |
+
archive_paths = sorted(archive_paths, key=sorter)
|
441 |
+
|
442 |
+
# Now, at last, RECORD.
|
443 |
+
# Paths in here are archive paths - nothing else makes sense.
|
444 |
+
self.write_records((distinfo, info_dir), libdir, archive_paths)
|
445 |
+
# Now, ready to build the zip file
|
446 |
+
pathname = os.path.join(self.dirname, self.filename)
|
447 |
+
self.build_zip(pathname, archive_paths)
|
448 |
+
return pathname
|
449 |
+
|
450 |
+
def skip_entry(self, arcname):
|
451 |
+
"""
|
452 |
+
Determine whether an archive entry should be skipped when verifying
|
453 |
+
or installing.
|
454 |
+
"""
|
455 |
+
# The signature file won't be in RECORD,
|
456 |
+
# and we don't currently don't do anything with it
|
457 |
+
# We also skip directories, as they won't be in RECORD
|
458 |
+
# either. See:
|
459 |
+
#
|
460 |
+
# https://github.com/pypa/wheel/issues/294
|
461 |
+
# https://github.com/pypa/wheel/issues/287
|
462 |
+
# https://github.com/pypa/wheel/pull/289
|
463 |
+
#
|
464 |
+
return arcname.endswith(('/', '/RECORD.jws'))
|
465 |
+
|
466 |
+
def install(self, paths, maker, **kwargs):
|
467 |
+
"""
|
468 |
+
Install a wheel to the specified paths. If kwarg ``warner`` is
|
469 |
+
specified, it should be a callable, which will be called with two
|
470 |
+
tuples indicating the wheel version of this software and the wheel
|
471 |
+
version in the file, if there is a discrepancy in the versions.
|
472 |
+
This can be used to issue any warnings to raise any exceptions.
|
473 |
+
If kwarg ``lib_only`` is True, only the purelib/platlib files are
|
474 |
+
installed, and the headers, scripts, data and dist-info metadata are
|
475 |
+
not written. If kwarg ``bytecode_hashed_invalidation`` is True, written
|
476 |
+
bytecode will try to use file-hash based invalidation (PEP-552) on
|
477 |
+
supported interpreter versions (CPython 2.7+).
|
478 |
+
|
479 |
+
The return value is a :class:`InstalledDistribution` instance unless
|
480 |
+
``options.lib_only`` is True, in which case the return value is ``None``.
|
481 |
+
"""
|
482 |
+
|
483 |
+
dry_run = maker.dry_run
|
484 |
+
warner = kwargs.get('warner')
|
485 |
+
lib_only = kwargs.get('lib_only', False)
|
486 |
+
bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False)
|
487 |
+
|
488 |
+
pathname = os.path.join(self.dirname, self.filename)
|
489 |
+
name_ver = '%s-%s' % (self.name, self.version)
|
490 |
+
data_dir = '%s.data' % name_ver
|
491 |
+
info_dir = '%s.dist-info' % name_ver
|
492 |
+
|
493 |
+
metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)
|
494 |
+
wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
|
495 |
+
record_name = posixpath.join(info_dir, 'RECORD')
|
496 |
+
|
497 |
+
wrapper = codecs.getreader('utf-8')
|
498 |
+
|
499 |
+
with ZipFile(pathname, 'r') as zf:
|
500 |
+
with zf.open(wheel_metadata_name) as bwf:
|
501 |
+
wf = wrapper(bwf)
|
502 |
+
message = message_from_file(wf)
|
503 |
+
wv = message['Wheel-Version'].split('.', 1)
|
504 |
+
file_version = tuple([int(i) for i in wv])
|
505 |
+
if (file_version != self.wheel_version) and warner:
|
506 |
+
warner(self.wheel_version, file_version)
|
507 |
+
|
508 |
+
if message['Root-Is-Purelib'] == 'true':
|
509 |
+
libdir = paths['purelib']
|
510 |
+
else:
|
511 |
+
libdir = paths['platlib']
|
512 |
+
|
513 |
+
records = {}
|
514 |
+
with zf.open(record_name) as bf:
|
515 |
+
with CSVReader(stream=bf) as reader:
|
516 |
+
for row in reader:
|
517 |
+
p = row[0]
|
518 |
+
records[p] = row
|
519 |
+
|
520 |
+
data_pfx = posixpath.join(data_dir, '')
|
521 |
+
info_pfx = posixpath.join(info_dir, '')
|
522 |
+
script_pfx = posixpath.join(data_dir, 'scripts', '')
|
523 |
+
|
524 |
+
# make a new instance rather than a copy of maker's,
|
525 |
+
# as we mutate it
|
526 |
+
fileop = FileOperator(dry_run=dry_run)
|
527 |
+
fileop.record = True # so we can rollback if needed
|
528 |
+
|
529 |
+
bc = not sys.dont_write_bytecode # Double negatives. Lovely!
|
530 |
+
|
531 |
+
outfiles = [] # for RECORD writing
|
532 |
+
|
533 |
+
# for script copying/shebang processing
|
534 |
+
workdir = tempfile.mkdtemp()
|
535 |
+
# set target dir later
|
536 |
+
# we default add_launchers to False, as the
|
537 |
+
# Python Launcher should be used instead
|
538 |
+
maker.source_dir = workdir
|
539 |
+
maker.target_dir = None
|
540 |
+
try:
|
541 |
+
for zinfo in zf.infolist():
|
542 |
+
arcname = zinfo.filename
|
543 |
+
if isinstance(arcname, text_type):
|
544 |
+
u_arcname = arcname
|
545 |
+
else:
|
546 |
+
u_arcname = arcname.decode('utf-8')
|
547 |
+
if self.skip_entry(u_arcname):
|
548 |
+
continue
|
549 |
+
row = records[u_arcname]
|
550 |
+
if row[2] and str(zinfo.file_size) != row[2]:
|
551 |
+
raise DistlibException('size mismatch for '
|
552 |
+
'%s' % u_arcname)
|
553 |
+
if row[1]:
|
554 |
+
kind, value = row[1].split('=', 1)
|
555 |
+
with zf.open(arcname) as bf:
|
556 |
+
data = bf.read()
|
557 |
+
_, digest = self.get_hash(data, kind)
|
558 |
+
if digest != value:
|
559 |
+
raise DistlibException('digest mismatch for '
|
560 |
+
'%s' % arcname)
|
561 |
+
|
562 |
+
if lib_only and u_arcname.startswith((info_pfx, data_pfx)):
|
563 |
+
logger.debug('lib_only: skipping %s', u_arcname)
|
564 |
+
continue
|
565 |
+
is_script = (u_arcname.startswith(script_pfx)
|
566 |
+
and not u_arcname.endswith('.exe'))
|
567 |
+
|
568 |
+
if u_arcname.startswith(data_pfx):
|
569 |
+
_, where, rp = u_arcname.split('/', 2)
|
570 |
+
outfile = os.path.join(paths[where], convert_path(rp))
|
571 |
+
else:
|
572 |
+
# meant for site-packages.
|
573 |
+
if u_arcname in (wheel_metadata_name, record_name):
|
574 |
+
continue
|
575 |
+
outfile = os.path.join(libdir, convert_path(u_arcname))
|
576 |
+
if not is_script:
|
577 |
+
with zf.open(arcname) as bf:
|
578 |
+
fileop.copy_stream(bf, outfile)
|
579 |
+
# Issue #147: permission bits aren't preserved. Using
|
580 |
+
# zf.extract(zinfo, libdir) should have worked, but didn't,
|
581 |
+
# see https://www.thetopsites.net/article/53834422.shtml
|
582 |
+
# So ... manually preserve permission bits as given in zinfo
|
583 |
+
if os.name == 'posix':
|
584 |
+
# just set the normal permission bits
|
585 |
+
os.chmod(outfile, (zinfo.external_attr >> 16) & 0x1FF)
|
586 |
+
outfiles.append(outfile)
|
587 |
+
# Double check the digest of the written file
|
588 |
+
if not dry_run and row[1]:
|
589 |
+
with open(outfile, 'rb') as bf:
|
590 |
+
data = bf.read()
|
591 |
+
_, newdigest = self.get_hash(data, kind)
|
592 |
+
if newdigest != digest:
|
593 |
+
raise DistlibException('digest mismatch '
|
594 |
+
'on write for '
|
595 |
+
'%s' % outfile)
|
596 |
+
if bc and outfile.endswith('.py'):
|
597 |
+
try:
|
598 |
+
pyc = fileop.byte_compile(outfile,
|
599 |
+
hashed_invalidation=bc_hashed_invalidation)
|
600 |
+
outfiles.append(pyc)
|
601 |
+
except Exception:
|
602 |
+
# Don't give up if byte-compilation fails,
|
603 |
+
# but log it and perhaps warn the user
|
604 |
+
logger.warning('Byte-compilation failed',
|
605 |
+
exc_info=True)
|
606 |
+
else:
|
607 |
+
fn = os.path.basename(convert_path(arcname))
|
608 |
+
workname = os.path.join(workdir, fn)
|
609 |
+
with zf.open(arcname) as bf:
|
610 |
+
fileop.copy_stream(bf, workname)
|
611 |
+
|
612 |
+
dn, fn = os.path.split(outfile)
|
613 |
+
maker.target_dir = dn
|
614 |
+
filenames = maker.make(fn)
|
615 |
+
fileop.set_executable_mode(filenames)
|
616 |
+
outfiles.extend(filenames)
|
617 |
+
|
618 |
+
if lib_only:
|
619 |
+
logger.debug('lib_only: returning None')
|
620 |
+
dist = None
|
621 |
+
else:
|
622 |
+
# Generate scripts
|
623 |
+
|
624 |
+
# Try to get pydist.json so we can see if there are
|
625 |
+
# any commands to generate. If this fails (e.g. because
|
626 |
+
# of a legacy wheel), log a warning but don't give up.
|
627 |
+
commands = None
|
628 |
+
file_version = self.info['Wheel-Version']
|
629 |
+
if file_version == '1.0':
|
630 |
+
# Use legacy info
|
631 |
+
ep = posixpath.join(info_dir, 'entry_points.txt')
|
632 |
+
try:
|
633 |
+
with zf.open(ep) as bwf:
|
634 |
+
epdata = read_exports(bwf)
|
635 |
+
commands = {}
|
636 |
+
for key in ('console', 'gui'):
|
637 |
+
k = '%s_scripts' % key
|
638 |
+
if k in epdata:
|
639 |
+
commands['wrap_%s' % key] = d = {}
|
640 |
+
for v in epdata[k].values():
|
641 |
+
s = '%s:%s' % (v.prefix, v.suffix)
|
642 |
+
if v.flags:
|
643 |
+
s += ' [%s]' % ','.join(v.flags)
|
644 |
+
d[v.name] = s
|
645 |
+
except Exception:
|
646 |
+
logger.warning('Unable to read legacy script '
|
647 |
+
'metadata, so cannot generate '
|
648 |
+
'scripts')
|
649 |
+
else:
|
650 |
+
try:
|
651 |
+
with zf.open(metadata_name) as bwf:
|
652 |
+
wf = wrapper(bwf)
|
653 |
+
commands = json.load(wf).get('extensions')
|
654 |
+
if commands:
|
655 |
+
commands = commands.get('python.commands')
|
656 |
+
except Exception:
|
657 |
+
logger.warning('Unable to read JSON metadata, so '
|
658 |
+
'cannot generate scripts')
|
659 |
+
if commands:
|
660 |
+
console_scripts = commands.get('wrap_console', {})
|
661 |
+
gui_scripts = commands.get('wrap_gui', {})
|
662 |
+
if console_scripts or gui_scripts:
|
663 |
+
script_dir = paths.get('scripts', '')
|
664 |
+
if not os.path.isdir(script_dir):
|
665 |
+
raise ValueError('Valid script path not '
|
666 |
+
'specified')
|
667 |
+
maker.target_dir = script_dir
|
668 |
+
for k, v in console_scripts.items():
|
669 |
+
script = '%s = %s' % (k, v)
|
670 |
+
filenames = maker.make(script)
|
671 |
+
fileop.set_executable_mode(filenames)
|
672 |
+
|
673 |
+
if gui_scripts:
|
674 |
+
options = {'gui': True }
|
675 |
+
for k, v in gui_scripts.items():
|
676 |
+
script = '%s = %s' % (k, v)
|
677 |
+
filenames = maker.make(script, options)
|
678 |
+
fileop.set_executable_mode(filenames)
|
679 |
+
|
680 |
+
p = os.path.join(libdir, info_dir)
|
681 |
+
dist = InstalledDistribution(p)
|
682 |
+
|
683 |
+
# Write SHARED
|
684 |
+
paths = dict(paths) # don't change passed in dict
|
685 |
+
del paths['purelib']
|
686 |
+
del paths['platlib']
|
687 |
+
paths['lib'] = libdir
|
688 |
+
p = dist.write_shared_locations(paths, dry_run)
|
689 |
+
if p:
|
690 |
+
outfiles.append(p)
|
691 |
+
|
692 |
+
# Write RECORD
|
693 |
+
dist.write_installed_files(outfiles, paths['prefix'],
|
694 |
+
dry_run)
|
695 |
+
return dist
|
696 |
+
except Exception: # pragma: no cover
|
697 |
+
logger.exception('installation failed.')
|
698 |
+
fileop.rollback()
|
699 |
+
raise
|
700 |
+
finally:
|
701 |
+
shutil.rmtree(workdir)
|
702 |
+
|
703 |
+
def _get_dylib_cache(self):
|
704 |
+
global cache
|
705 |
+
if cache is None:
|
706 |
+
# Use native string to avoid issues on 2.x: see Python #20140.
|
707 |
+
base = os.path.join(get_cache_base(), str('dylib-cache'),
|
708 |
+
'%s.%s' % sys.version_info[:2])
|
709 |
+
cache = Cache(base)
|
710 |
+
return cache
|
711 |
+
|
712 |
+
def _get_extensions(self):
|
713 |
+
pathname = os.path.join(self.dirname, self.filename)
|
714 |
+
name_ver = '%s-%s' % (self.name, self.version)
|
715 |
+
info_dir = '%s.dist-info' % name_ver
|
716 |
+
arcname = posixpath.join(info_dir, 'EXTENSIONS')
|
717 |
+
wrapper = codecs.getreader('utf-8')
|
718 |
+
result = []
|
719 |
+
with ZipFile(pathname, 'r') as zf:
|
720 |
+
try:
|
721 |
+
with zf.open(arcname) as bf:
|
722 |
+
wf = wrapper(bf)
|
723 |
+
extensions = json.load(wf)
|
724 |
+
cache = self._get_dylib_cache()
|
725 |
+
prefix = cache.prefix_to_dir(pathname)
|
726 |
+
cache_base = os.path.join(cache.base, prefix)
|
727 |
+
if not os.path.isdir(cache_base):
|
728 |
+
os.makedirs(cache_base)
|
729 |
+
for name, relpath in extensions.items():
|
730 |
+
dest = os.path.join(cache_base, convert_path(relpath))
|
731 |
+
if not os.path.exists(dest):
|
732 |
+
extract = True
|
733 |
+
else:
|
734 |
+
file_time = os.stat(dest).st_mtime
|
735 |
+
file_time = datetime.datetime.fromtimestamp(file_time)
|
736 |
+
info = zf.getinfo(relpath)
|
737 |
+
wheel_time = datetime.datetime(*info.date_time)
|
738 |
+
extract = wheel_time > file_time
|
739 |
+
if extract:
|
740 |
+
zf.extract(relpath, cache_base)
|
741 |
+
result.append((name, dest))
|
742 |
+
except KeyError:
|
743 |
+
pass
|
744 |
+
return result
|
745 |
+
|
746 |
+
def is_compatible(self):
|
747 |
+
"""
|
748 |
+
Determine if a wheel is compatible with the running system.
|
749 |
+
"""
|
750 |
+
return is_compatible(self)
|
751 |
+
|
752 |
+
def is_mountable(self):
|
753 |
+
"""
|
754 |
+
Determine if a wheel is asserted as mountable by its metadata.
|
755 |
+
"""
|
756 |
+
return True # for now - metadata details TBD
|
757 |
+
|
758 |
+
def mount(self, append=False):
|
759 |
+
pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
|
760 |
+
if not self.is_compatible():
|
761 |
+
msg = 'Wheel %s not compatible with this Python.' % pathname
|
762 |
+
raise DistlibException(msg)
|
763 |
+
if not self.is_mountable():
|
764 |
+
msg = 'Wheel %s is marked as not mountable.' % pathname
|
765 |
+
raise DistlibException(msg)
|
766 |
+
if pathname in sys.path:
|
767 |
+
logger.debug('%s already in path', pathname)
|
768 |
+
else:
|
769 |
+
if append:
|
770 |
+
sys.path.append(pathname)
|
771 |
+
else:
|
772 |
+
sys.path.insert(0, pathname)
|
773 |
+
extensions = self._get_extensions()
|
774 |
+
if extensions:
|
775 |
+
if _hook not in sys.meta_path:
|
776 |
+
sys.meta_path.append(_hook)
|
777 |
+
_hook.add(pathname, extensions)
|
778 |
+
|
779 |
+
def unmount(self):
|
780 |
+
pathname = os.path.abspath(os.path.join(self.dirname, self.filename))
|
781 |
+
if pathname not in sys.path:
|
782 |
+
logger.debug('%s not in path', pathname)
|
783 |
+
else:
|
784 |
+
sys.path.remove(pathname)
|
785 |
+
if pathname in _hook.impure_wheels:
|
786 |
+
_hook.remove(pathname)
|
787 |
+
if not _hook.impure_wheels:
|
788 |
+
if _hook in sys.meta_path:
|
789 |
+
sys.meta_path.remove(_hook)
|
790 |
+
|
791 |
+
def verify(self):
|
792 |
+
pathname = os.path.join(self.dirname, self.filename)
|
793 |
+
name_ver = '%s-%s' % (self.name, self.version)
|
794 |
+
data_dir = '%s.data' % name_ver
|
795 |
+
info_dir = '%s.dist-info' % name_ver
|
796 |
+
|
797 |
+
metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)
|
798 |
+
wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')
|
799 |
+
record_name = posixpath.join(info_dir, 'RECORD')
|
800 |
+
|
801 |
+
wrapper = codecs.getreader('utf-8')
|
802 |
+
|
803 |
+
with ZipFile(pathname, 'r') as zf:
|
804 |
+
with zf.open(wheel_metadata_name) as bwf:
|
805 |
+
wf = wrapper(bwf)
|
806 |
+
message = message_from_file(wf)
|
807 |
+
wv = message['Wheel-Version'].split('.', 1)
|
808 |
+
file_version = tuple([int(i) for i in wv])
|
809 |
+
# TODO version verification
|
810 |
+
|
811 |
+
records = {}
|
812 |
+
with zf.open(record_name) as bf:
|
813 |
+
with CSVReader(stream=bf) as reader:
|
814 |
+
for row in reader:
|
815 |
+
p = row[0]
|
816 |
+
records[p] = row
|
817 |
+
|
818 |
+
for zinfo in zf.infolist():
|
819 |
+
arcname = zinfo.filename
|
820 |
+
if isinstance(arcname, text_type):
|
821 |
+
u_arcname = arcname
|
822 |
+
else:
|
823 |
+
u_arcname = arcname.decode('utf-8')
|
824 |
+
# See issue #115: some wheels have .. in their entries, but
|
825 |
+
# in the filename ... e.g. __main__..py ! So the check is
|
826 |
+
# updated to look for .. in the directory portions
|
827 |
+
p = u_arcname.split('/')
|
828 |
+
if '..' in p:
|
829 |
+
raise DistlibException('invalid entry in '
|
830 |
+
'wheel: %r' % u_arcname)
|
831 |
+
|
832 |
+
if self.skip_entry(u_arcname):
|
833 |
+
continue
|
834 |
+
row = records[u_arcname]
|
835 |
+
if row[2] and str(zinfo.file_size) != row[2]:
|
836 |
+
raise DistlibException('size mismatch for '
|
837 |
+
'%s' % u_arcname)
|
838 |
+
if row[1]:
|
839 |
+
kind, value = row[1].split('=', 1)
|
840 |
+
with zf.open(arcname) as bf:
|
841 |
+
data = bf.read()
|
842 |
+
_, digest = self.get_hash(data, kind)
|
843 |
+
if digest != value:
|
844 |
+
raise DistlibException('digest mismatch for '
|
845 |
+
'%s' % arcname)
|
846 |
+
|
847 |
+
def update(self, modifier, dest_dir=None, **kwargs):
|
848 |
+
"""
|
849 |
+
Update the contents of a wheel in a generic way. The modifier should
|
850 |
+
be a callable which expects a dictionary argument: its keys are
|
851 |
+
archive-entry paths, and its values are absolute filesystem paths
|
852 |
+
where the contents the corresponding archive entries can be found. The
|
853 |
+
modifier is free to change the contents of the files pointed to, add
|
854 |
+
new entries and remove entries, before returning. This method will
|
855 |
+
extract the entire contents of the wheel to a temporary location, call
|
856 |
+
the modifier, and then use the passed (and possibly updated)
|
857 |
+
dictionary to write a new wheel. If ``dest_dir`` is specified, the new
|
858 |
+
wheel is written there -- otherwise, the original wheel is overwritten.
|
859 |
+
|
860 |
+
The modifier should return True if it updated the wheel, else False.
|
861 |
+
This method returns the same value the modifier returns.
|
862 |
+
"""
|
863 |
+
|
864 |
+
def get_version(path_map, info_dir):
|
865 |
+
version = path = None
|
866 |
+
key = '%s/%s' % (info_dir, LEGACY_METADATA_FILENAME)
|
867 |
+
if key not in path_map:
|
868 |
+
key = '%s/PKG-INFO' % info_dir
|
869 |
+
if key in path_map:
|
870 |
+
path = path_map[key]
|
871 |
+
version = Metadata(path=path).version
|
872 |
+
return version, path
|
873 |
+
|
874 |
+
def update_version(version, path):
|
875 |
+
updated = None
|
876 |
+
try:
|
877 |
+
v = NormalizedVersion(version)
|
878 |
+
i = version.find('-')
|
879 |
+
if i < 0:
|
880 |
+
updated = '%s+1' % version
|
881 |
+
else:
|
882 |
+
parts = [int(s) for s in version[i + 1:].split('.')]
|
883 |
+
parts[-1] += 1
|
884 |
+
updated = '%s+%s' % (version[:i],
|
885 |
+
'.'.join(str(i) for i in parts))
|
886 |
+
except UnsupportedVersionError:
|
887 |
+
logger.debug('Cannot update non-compliant (PEP-440) '
|
888 |
+
'version %r', version)
|
889 |
+
if updated:
|
890 |
+
md = Metadata(path=path)
|
891 |
+
md.version = updated
|
892 |
+
legacy = path.endswith(LEGACY_METADATA_FILENAME)
|
893 |
+
md.write(path=path, legacy=legacy)
|
894 |
+
logger.debug('Version updated from %r to %r', version,
|
895 |
+
updated)
|
896 |
+
|
897 |
+
pathname = os.path.join(self.dirname, self.filename)
|
898 |
+
name_ver = '%s-%s' % (self.name, self.version)
|
899 |
+
info_dir = '%s.dist-info' % name_ver
|
900 |
+
record_name = posixpath.join(info_dir, 'RECORD')
|
901 |
+
with tempdir() as workdir:
|
902 |
+
with ZipFile(pathname, 'r') as zf:
|
903 |
+
path_map = {}
|
904 |
+
for zinfo in zf.infolist():
|
905 |
+
arcname = zinfo.filename
|
906 |
+
if isinstance(arcname, text_type):
|
907 |
+
u_arcname = arcname
|
908 |
+
else:
|
909 |
+
u_arcname = arcname.decode('utf-8')
|
910 |
+
if u_arcname == record_name:
|
911 |
+
continue
|
912 |
+
if '..' in u_arcname:
|
913 |
+
raise DistlibException('invalid entry in '
|
914 |
+
'wheel: %r' % u_arcname)
|
915 |
+
zf.extract(zinfo, workdir)
|
916 |
+
path = os.path.join(workdir, convert_path(u_arcname))
|
917 |
+
path_map[u_arcname] = path
|
918 |
+
|
919 |
+
# Remember the version.
|
920 |
+
original_version, _ = get_version(path_map, info_dir)
|
921 |
+
# Files extracted. Call the modifier.
|
922 |
+
modified = modifier(path_map, **kwargs)
|
923 |
+
if modified:
|
924 |
+
# Something changed - need to build a new wheel.
|
925 |
+
current_version, path = get_version(path_map, info_dir)
|
926 |
+
if current_version and (current_version == original_version):
|
927 |
+
# Add or update local version to signify changes.
|
928 |
+
update_version(current_version, path)
|
929 |
+
# Decide where the new wheel goes.
|
930 |
+
if dest_dir is None:
|
931 |
+
fd, newpath = tempfile.mkstemp(suffix='.whl',
|
932 |
+
prefix='wheel-update-',
|
933 |
+
dir=workdir)
|
934 |
+
os.close(fd)
|
935 |
+
else:
|
936 |
+
if not os.path.isdir(dest_dir):
|
937 |
+
raise DistlibException('Not a directory: %r' % dest_dir)
|
938 |
+
newpath = os.path.join(dest_dir, self.filename)
|
939 |
+
archive_paths = list(path_map.items())
|
940 |
+
distinfo = os.path.join(workdir, info_dir)
|
941 |
+
info = distinfo, info_dir
|
942 |
+
self.write_records(info, workdir, archive_paths)
|
943 |
+
self.build_zip(newpath, archive_paths)
|
944 |
+
if dest_dir is None:
|
945 |
+
shutil.copyfile(newpath, pathname)
|
946 |
+
return modified
|
947 |
+
|
948 |
+
def _get_glibc_version():
|
949 |
+
import platform
|
950 |
+
ver = platform.libc_ver()
|
951 |
+
result = []
|
952 |
+
if ver[0] == 'glibc':
|
953 |
+
for s in ver[1].split('.'):
|
954 |
+
result.append(int(s) if s.isdigit() else 0)
|
955 |
+
result = tuple(result)
|
956 |
+
return result
|
957 |
+
|
958 |
+
def compatible_tags():
|
959 |
+
"""
|
960 |
+
Return (pyver, abi, arch) tuples compatible with this Python.
|
961 |
+
"""
|
962 |
+
versions = [VER_SUFFIX]
|
963 |
+
major = VER_SUFFIX[0]
|
964 |
+
for minor in range(sys.version_info[1] - 1, - 1, -1):
|
965 |
+
versions.append(''.join([major, str(minor)]))
|
966 |
+
|
967 |
+
abis = []
|
968 |
+
for suffix, _, _ in imp.get_suffixes():
|
969 |
+
if suffix.startswith('.abi'):
|
970 |
+
abis.append(suffix.split('.', 2)[1])
|
971 |
+
abis.sort()
|
972 |
+
if ABI != 'none':
|
973 |
+
abis.insert(0, ABI)
|
974 |
+
abis.append('none')
|
975 |
+
result = []
|
976 |
+
|
977 |
+
arches = [ARCH]
|
978 |
+
if sys.platform == 'darwin':
|
979 |
+
m = re.match(r'(\w+)_(\d+)_(\d+)_(\w+)$', ARCH)
|
980 |
+
if m:
|
981 |
+
name, major, minor, arch = m.groups()
|
982 |
+
minor = int(minor)
|
983 |
+
matches = [arch]
|
984 |
+
if arch in ('i386', 'ppc'):
|
985 |
+
matches.append('fat')
|
986 |
+
if arch in ('i386', 'ppc', 'x86_64'):
|
987 |
+
matches.append('fat3')
|
988 |
+
if arch in ('ppc64', 'x86_64'):
|
989 |
+
matches.append('fat64')
|
990 |
+
if arch in ('i386', 'x86_64'):
|
991 |
+
matches.append('intel')
|
992 |
+
if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'):
|
993 |
+
matches.append('universal')
|
994 |
+
while minor >= 0:
|
995 |
+
for match in matches:
|
996 |
+
s = '%s_%s_%s_%s' % (name, major, minor, match)
|
997 |
+
if s != ARCH: # already there
|
998 |
+
arches.append(s)
|
999 |
+
minor -= 1
|
1000 |
+
|
1001 |
+
# Most specific - our Python version, ABI and arch
|
1002 |
+
for abi in abis:
|
1003 |
+
for arch in arches:
|
1004 |
+
result.append((''.join((IMP_PREFIX, versions[0])), abi, arch))
|
1005 |
+
# manylinux
|
1006 |
+
if abi != 'none' and sys.platform.startswith('linux'):
|
1007 |
+
arch = arch.replace('linux_', '')
|
1008 |
+
parts = _get_glibc_version()
|
1009 |
+
if len(parts) == 2:
|
1010 |
+
if parts >= (2, 5):
|
1011 |
+
result.append((''.join((IMP_PREFIX, versions[0])), abi,
|
1012 |
+
'manylinux1_%s' % arch))
|
1013 |
+
if parts >= (2, 12):
|
1014 |
+
result.append((''.join((IMP_PREFIX, versions[0])), abi,
|
1015 |
+
'manylinux2010_%s' % arch))
|
1016 |
+
if parts >= (2, 17):
|
1017 |
+
result.append((''.join((IMP_PREFIX, versions[0])), abi,
|
1018 |
+
'manylinux2014_%s' % arch))
|
1019 |
+
result.append((''.join((IMP_PREFIX, versions[0])), abi,
|
1020 |
+
'manylinux_%s_%s_%s' % (parts[0], parts[1],
|
1021 |
+
arch)))
|
1022 |
+
|
1023 |
+
# where no ABI / arch dependency, but IMP_PREFIX dependency
|
1024 |
+
for i, version in enumerate(versions):
|
1025 |
+
result.append((''.join((IMP_PREFIX, version)), 'none', 'any'))
|
1026 |
+
if i == 0:
|
1027 |
+
result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any'))
|
1028 |
+
|
1029 |
+
# no IMP_PREFIX, ABI or arch dependency
|
1030 |
+
for i, version in enumerate(versions):
|
1031 |
+
result.append((''.join(('py', version)), 'none', 'any'))
|
1032 |
+
if i == 0:
|
1033 |
+
result.append((''.join(('py', version[0])), 'none', 'any'))
|
1034 |
+
|
1035 |
+
return set(result)
|
1036 |
+
|
1037 |
+
|
1038 |
+
COMPATIBLE_TAGS = compatible_tags()
|
1039 |
+
|
1040 |
+
del compatible_tags
|
1041 |
+
|
1042 |
+
|
1043 |
+
def is_compatible(wheel, tags=None):
|
1044 |
+
if not isinstance(wheel, Wheel):
|
1045 |
+
wheel = Wheel(wheel) # assume it's a filename
|
1046 |
+
result = False
|
1047 |
+
if tags is None:
|
1048 |
+
tags = COMPATIBLE_TAGS
|
1049 |
+
for ver, abi, arch in tags:
|
1050 |
+
if ver in wheel.pyver and abi in wheel.abi and arch in wheel.arch:
|
1051 |
+
result = True
|
1052 |
+
break
|
1053 |
+
return result
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_cell_widths.py
ADDED
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Auto generated by make_terminal_widths.py
|
2 |
+
|
3 |
+
CELL_WIDTHS = [
|
4 |
+
(0, 0, 0),
|
5 |
+
(1, 31, -1),
|
6 |
+
(127, 159, -1),
|
7 |
+
(768, 879, 0),
|
8 |
+
(1155, 1161, 0),
|
9 |
+
(1425, 1469, 0),
|
10 |
+
(1471, 1471, 0),
|
11 |
+
(1473, 1474, 0),
|
12 |
+
(1476, 1477, 0),
|
13 |
+
(1479, 1479, 0),
|
14 |
+
(1552, 1562, 0),
|
15 |
+
(1611, 1631, 0),
|
16 |
+
(1648, 1648, 0),
|
17 |
+
(1750, 1756, 0),
|
18 |
+
(1759, 1764, 0),
|
19 |
+
(1767, 1768, 0),
|
20 |
+
(1770, 1773, 0),
|
21 |
+
(1809, 1809, 0),
|
22 |
+
(1840, 1866, 0),
|
23 |
+
(1958, 1968, 0),
|
24 |
+
(2027, 2035, 0),
|
25 |
+
(2045, 2045, 0),
|
26 |
+
(2070, 2073, 0),
|
27 |
+
(2075, 2083, 0),
|
28 |
+
(2085, 2087, 0),
|
29 |
+
(2089, 2093, 0),
|
30 |
+
(2137, 2139, 0),
|
31 |
+
(2259, 2273, 0),
|
32 |
+
(2275, 2306, 0),
|
33 |
+
(2362, 2362, 0),
|
34 |
+
(2364, 2364, 0),
|
35 |
+
(2369, 2376, 0),
|
36 |
+
(2381, 2381, 0),
|
37 |
+
(2385, 2391, 0),
|
38 |
+
(2402, 2403, 0),
|
39 |
+
(2433, 2433, 0),
|
40 |
+
(2492, 2492, 0),
|
41 |
+
(2497, 2500, 0),
|
42 |
+
(2509, 2509, 0),
|
43 |
+
(2530, 2531, 0),
|
44 |
+
(2558, 2558, 0),
|
45 |
+
(2561, 2562, 0),
|
46 |
+
(2620, 2620, 0),
|
47 |
+
(2625, 2626, 0),
|
48 |
+
(2631, 2632, 0),
|
49 |
+
(2635, 2637, 0),
|
50 |
+
(2641, 2641, 0),
|
51 |
+
(2672, 2673, 0),
|
52 |
+
(2677, 2677, 0),
|
53 |
+
(2689, 2690, 0),
|
54 |
+
(2748, 2748, 0),
|
55 |
+
(2753, 2757, 0),
|
56 |
+
(2759, 2760, 0),
|
57 |
+
(2765, 2765, 0),
|
58 |
+
(2786, 2787, 0),
|
59 |
+
(2810, 2815, 0),
|
60 |
+
(2817, 2817, 0),
|
61 |
+
(2876, 2876, 0),
|
62 |
+
(2879, 2879, 0),
|
63 |
+
(2881, 2884, 0),
|
64 |
+
(2893, 2893, 0),
|
65 |
+
(2901, 2902, 0),
|
66 |
+
(2914, 2915, 0),
|
67 |
+
(2946, 2946, 0),
|
68 |
+
(3008, 3008, 0),
|
69 |
+
(3021, 3021, 0),
|
70 |
+
(3072, 3072, 0),
|
71 |
+
(3076, 3076, 0),
|
72 |
+
(3134, 3136, 0),
|
73 |
+
(3142, 3144, 0),
|
74 |
+
(3146, 3149, 0),
|
75 |
+
(3157, 3158, 0),
|
76 |
+
(3170, 3171, 0),
|
77 |
+
(3201, 3201, 0),
|
78 |
+
(3260, 3260, 0),
|
79 |
+
(3263, 3263, 0),
|
80 |
+
(3270, 3270, 0),
|
81 |
+
(3276, 3277, 0),
|
82 |
+
(3298, 3299, 0),
|
83 |
+
(3328, 3329, 0),
|
84 |
+
(3387, 3388, 0),
|
85 |
+
(3393, 3396, 0),
|
86 |
+
(3405, 3405, 0),
|
87 |
+
(3426, 3427, 0),
|
88 |
+
(3457, 3457, 0),
|
89 |
+
(3530, 3530, 0),
|
90 |
+
(3538, 3540, 0),
|
91 |
+
(3542, 3542, 0),
|
92 |
+
(3633, 3633, 0),
|
93 |
+
(3636, 3642, 0),
|
94 |
+
(3655, 3662, 0),
|
95 |
+
(3761, 3761, 0),
|
96 |
+
(3764, 3772, 0),
|
97 |
+
(3784, 3789, 0),
|
98 |
+
(3864, 3865, 0),
|
99 |
+
(3893, 3893, 0),
|
100 |
+
(3895, 3895, 0),
|
101 |
+
(3897, 3897, 0),
|
102 |
+
(3953, 3966, 0),
|
103 |
+
(3968, 3972, 0),
|
104 |
+
(3974, 3975, 0),
|
105 |
+
(3981, 3991, 0),
|
106 |
+
(3993, 4028, 0),
|
107 |
+
(4038, 4038, 0),
|
108 |
+
(4141, 4144, 0),
|
109 |
+
(4146, 4151, 0),
|
110 |
+
(4153, 4154, 0),
|
111 |
+
(4157, 4158, 0),
|
112 |
+
(4184, 4185, 0),
|
113 |
+
(4190, 4192, 0),
|
114 |
+
(4209, 4212, 0),
|
115 |
+
(4226, 4226, 0),
|
116 |
+
(4229, 4230, 0),
|
117 |
+
(4237, 4237, 0),
|
118 |
+
(4253, 4253, 0),
|
119 |
+
(4352, 4447, 2),
|
120 |
+
(4957, 4959, 0),
|
121 |
+
(5906, 5908, 0),
|
122 |
+
(5938, 5940, 0),
|
123 |
+
(5970, 5971, 0),
|
124 |
+
(6002, 6003, 0),
|
125 |
+
(6068, 6069, 0),
|
126 |
+
(6071, 6077, 0),
|
127 |
+
(6086, 6086, 0),
|
128 |
+
(6089, 6099, 0),
|
129 |
+
(6109, 6109, 0),
|
130 |
+
(6155, 6157, 0),
|
131 |
+
(6277, 6278, 0),
|
132 |
+
(6313, 6313, 0),
|
133 |
+
(6432, 6434, 0),
|
134 |
+
(6439, 6440, 0),
|
135 |
+
(6450, 6450, 0),
|
136 |
+
(6457, 6459, 0),
|
137 |
+
(6679, 6680, 0),
|
138 |
+
(6683, 6683, 0),
|
139 |
+
(6742, 6742, 0),
|
140 |
+
(6744, 6750, 0),
|
141 |
+
(6752, 6752, 0),
|
142 |
+
(6754, 6754, 0),
|
143 |
+
(6757, 6764, 0),
|
144 |
+
(6771, 6780, 0),
|
145 |
+
(6783, 6783, 0),
|
146 |
+
(6832, 6848, 0),
|
147 |
+
(6912, 6915, 0),
|
148 |
+
(6964, 6964, 0),
|
149 |
+
(6966, 6970, 0),
|
150 |
+
(6972, 6972, 0),
|
151 |
+
(6978, 6978, 0),
|
152 |
+
(7019, 7027, 0),
|
153 |
+
(7040, 7041, 0),
|
154 |
+
(7074, 7077, 0),
|
155 |
+
(7080, 7081, 0),
|
156 |
+
(7083, 7085, 0),
|
157 |
+
(7142, 7142, 0),
|
158 |
+
(7144, 7145, 0),
|
159 |
+
(7149, 7149, 0),
|
160 |
+
(7151, 7153, 0),
|
161 |
+
(7212, 7219, 0),
|
162 |
+
(7222, 7223, 0),
|
163 |
+
(7376, 7378, 0),
|
164 |
+
(7380, 7392, 0),
|
165 |
+
(7394, 7400, 0),
|
166 |
+
(7405, 7405, 0),
|
167 |
+
(7412, 7412, 0),
|
168 |
+
(7416, 7417, 0),
|
169 |
+
(7616, 7673, 0),
|
170 |
+
(7675, 7679, 0),
|
171 |
+
(8203, 8207, 0),
|
172 |
+
(8232, 8238, 0),
|
173 |
+
(8288, 8291, 0),
|
174 |
+
(8400, 8432, 0),
|
175 |
+
(8986, 8987, 2),
|
176 |
+
(9001, 9002, 2),
|
177 |
+
(9193, 9196, 2),
|
178 |
+
(9200, 9200, 2),
|
179 |
+
(9203, 9203, 2),
|
180 |
+
(9725, 9726, 2),
|
181 |
+
(9748, 9749, 2),
|
182 |
+
(9800, 9811, 2),
|
183 |
+
(9855, 9855, 2),
|
184 |
+
(9875, 9875, 2),
|
185 |
+
(9889, 9889, 2),
|
186 |
+
(9898, 9899, 2),
|
187 |
+
(9917, 9918, 2),
|
188 |
+
(9924, 9925, 2),
|
189 |
+
(9934, 9934, 2),
|
190 |
+
(9940, 9940, 2),
|
191 |
+
(9962, 9962, 2),
|
192 |
+
(9970, 9971, 2),
|
193 |
+
(9973, 9973, 2),
|
194 |
+
(9978, 9978, 2),
|
195 |
+
(9981, 9981, 2),
|
196 |
+
(9989, 9989, 2),
|
197 |
+
(9994, 9995, 2),
|
198 |
+
(10024, 10024, 2),
|
199 |
+
(10060, 10060, 2),
|
200 |
+
(10062, 10062, 2),
|
201 |
+
(10067, 10069, 2),
|
202 |
+
(10071, 10071, 2),
|
203 |
+
(10133, 10135, 2),
|
204 |
+
(10160, 10160, 2),
|
205 |
+
(10175, 10175, 2),
|
206 |
+
(11035, 11036, 2),
|
207 |
+
(11088, 11088, 2),
|
208 |
+
(11093, 11093, 2),
|
209 |
+
(11503, 11505, 0),
|
210 |
+
(11647, 11647, 0),
|
211 |
+
(11744, 11775, 0),
|
212 |
+
(11904, 11929, 2),
|
213 |
+
(11931, 12019, 2),
|
214 |
+
(12032, 12245, 2),
|
215 |
+
(12272, 12283, 2),
|
216 |
+
(12288, 12329, 2),
|
217 |
+
(12330, 12333, 0),
|
218 |
+
(12334, 12350, 2),
|
219 |
+
(12353, 12438, 2),
|
220 |
+
(12441, 12442, 0),
|
221 |
+
(12443, 12543, 2),
|
222 |
+
(12549, 12591, 2),
|
223 |
+
(12593, 12686, 2),
|
224 |
+
(12688, 12771, 2),
|
225 |
+
(12784, 12830, 2),
|
226 |
+
(12832, 12871, 2),
|
227 |
+
(12880, 19903, 2),
|
228 |
+
(19968, 42124, 2),
|
229 |
+
(42128, 42182, 2),
|
230 |
+
(42607, 42610, 0),
|
231 |
+
(42612, 42621, 0),
|
232 |
+
(42654, 42655, 0),
|
233 |
+
(42736, 42737, 0),
|
234 |
+
(43010, 43010, 0),
|
235 |
+
(43014, 43014, 0),
|
236 |
+
(43019, 43019, 0),
|
237 |
+
(43045, 43046, 0),
|
238 |
+
(43052, 43052, 0),
|
239 |
+
(43204, 43205, 0),
|
240 |
+
(43232, 43249, 0),
|
241 |
+
(43263, 43263, 0),
|
242 |
+
(43302, 43309, 0),
|
243 |
+
(43335, 43345, 0),
|
244 |
+
(43360, 43388, 2),
|
245 |
+
(43392, 43394, 0),
|
246 |
+
(43443, 43443, 0),
|
247 |
+
(43446, 43449, 0),
|
248 |
+
(43452, 43453, 0),
|
249 |
+
(43493, 43493, 0),
|
250 |
+
(43561, 43566, 0),
|
251 |
+
(43569, 43570, 0),
|
252 |
+
(43573, 43574, 0),
|
253 |
+
(43587, 43587, 0),
|
254 |
+
(43596, 43596, 0),
|
255 |
+
(43644, 43644, 0),
|
256 |
+
(43696, 43696, 0),
|
257 |
+
(43698, 43700, 0),
|
258 |
+
(43703, 43704, 0),
|
259 |
+
(43710, 43711, 0),
|
260 |
+
(43713, 43713, 0),
|
261 |
+
(43756, 43757, 0),
|
262 |
+
(43766, 43766, 0),
|
263 |
+
(44005, 44005, 0),
|
264 |
+
(44008, 44008, 0),
|
265 |
+
(44013, 44013, 0),
|
266 |
+
(44032, 55203, 2),
|
267 |
+
(63744, 64255, 2),
|
268 |
+
(64286, 64286, 0),
|
269 |
+
(65024, 65039, 0),
|
270 |
+
(65040, 65049, 2),
|
271 |
+
(65056, 65071, 0),
|
272 |
+
(65072, 65106, 2),
|
273 |
+
(65108, 65126, 2),
|
274 |
+
(65128, 65131, 2),
|
275 |
+
(65281, 65376, 2),
|
276 |
+
(65504, 65510, 2),
|
277 |
+
(66045, 66045, 0),
|
278 |
+
(66272, 66272, 0),
|
279 |
+
(66422, 66426, 0),
|
280 |
+
(68097, 68099, 0),
|
281 |
+
(68101, 68102, 0),
|
282 |
+
(68108, 68111, 0),
|
283 |
+
(68152, 68154, 0),
|
284 |
+
(68159, 68159, 0),
|
285 |
+
(68325, 68326, 0),
|
286 |
+
(68900, 68903, 0),
|
287 |
+
(69291, 69292, 0),
|
288 |
+
(69446, 69456, 0),
|
289 |
+
(69633, 69633, 0),
|
290 |
+
(69688, 69702, 0),
|
291 |
+
(69759, 69761, 0),
|
292 |
+
(69811, 69814, 0),
|
293 |
+
(69817, 69818, 0),
|
294 |
+
(69888, 69890, 0),
|
295 |
+
(69927, 69931, 0),
|
296 |
+
(69933, 69940, 0),
|
297 |
+
(70003, 70003, 0),
|
298 |
+
(70016, 70017, 0),
|
299 |
+
(70070, 70078, 0),
|
300 |
+
(70089, 70092, 0),
|
301 |
+
(70095, 70095, 0),
|
302 |
+
(70191, 70193, 0),
|
303 |
+
(70196, 70196, 0),
|
304 |
+
(70198, 70199, 0),
|
305 |
+
(70206, 70206, 0),
|
306 |
+
(70367, 70367, 0),
|
307 |
+
(70371, 70378, 0),
|
308 |
+
(70400, 70401, 0),
|
309 |
+
(70459, 70460, 0),
|
310 |
+
(70464, 70464, 0),
|
311 |
+
(70502, 70508, 0),
|
312 |
+
(70512, 70516, 0),
|
313 |
+
(70712, 70719, 0),
|
314 |
+
(70722, 70724, 0),
|
315 |
+
(70726, 70726, 0),
|
316 |
+
(70750, 70750, 0),
|
317 |
+
(70835, 70840, 0),
|
318 |
+
(70842, 70842, 0),
|
319 |
+
(70847, 70848, 0),
|
320 |
+
(70850, 70851, 0),
|
321 |
+
(71090, 71093, 0),
|
322 |
+
(71100, 71101, 0),
|
323 |
+
(71103, 71104, 0),
|
324 |
+
(71132, 71133, 0),
|
325 |
+
(71219, 71226, 0),
|
326 |
+
(71229, 71229, 0),
|
327 |
+
(71231, 71232, 0),
|
328 |
+
(71339, 71339, 0),
|
329 |
+
(71341, 71341, 0),
|
330 |
+
(71344, 71349, 0),
|
331 |
+
(71351, 71351, 0),
|
332 |
+
(71453, 71455, 0),
|
333 |
+
(71458, 71461, 0),
|
334 |
+
(71463, 71467, 0),
|
335 |
+
(71727, 71735, 0),
|
336 |
+
(71737, 71738, 0),
|
337 |
+
(71995, 71996, 0),
|
338 |
+
(71998, 71998, 0),
|
339 |
+
(72003, 72003, 0),
|
340 |
+
(72148, 72151, 0),
|
341 |
+
(72154, 72155, 0),
|
342 |
+
(72160, 72160, 0),
|
343 |
+
(72193, 72202, 0),
|
344 |
+
(72243, 72248, 0),
|
345 |
+
(72251, 72254, 0),
|
346 |
+
(72263, 72263, 0),
|
347 |
+
(72273, 72278, 0),
|
348 |
+
(72281, 72283, 0),
|
349 |
+
(72330, 72342, 0),
|
350 |
+
(72344, 72345, 0),
|
351 |
+
(72752, 72758, 0),
|
352 |
+
(72760, 72765, 0),
|
353 |
+
(72767, 72767, 0),
|
354 |
+
(72850, 72871, 0),
|
355 |
+
(72874, 72880, 0),
|
356 |
+
(72882, 72883, 0),
|
357 |
+
(72885, 72886, 0),
|
358 |
+
(73009, 73014, 0),
|
359 |
+
(73018, 73018, 0),
|
360 |
+
(73020, 73021, 0),
|
361 |
+
(73023, 73029, 0),
|
362 |
+
(73031, 73031, 0),
|
363 |
+
(73104, 73105, 0),
|
364 |
+
(73109, 73109, 0),
|
365 |
+
(73111, 73111, 0),
|
366 |
+
(73459, 73460, 0),
|
367 |
+
(92912, 92916, 0),
|
368 |
+
(92976, 92982, 0),
|
369 |
+
(94031, 94031, 0),
|
370 |
+
(94095, 94098, 0),
|
371 |
+
(94176, 94179, 2),
|
372 |
+
(94180, 94180, 0),
|
373 |
+
(94192, 94193, 2),
|
374 |
+
(94208, 100343, 2),
|
375 |
+
(100352, 101589, 2),
|
376 |
+
(101632, 101640, 2),
|
377 |
+
(110592, 110878, 2),
|
378 |
+
(110928, 110930, 2),
|
379 |
+
(110948, 110951, 2),
|
380 |
+
(110960, 111355, 2),
|
381 |
+
(113821, 113822, 0),
|
382 |
+
(119143, 119145, 0),
|
383 |
+
(119163, 119170, 0),
|
384 |
+
(119173, 119179, 0),
|
385 |
+
(119210, 119213, 0),
|
386 |
+
(119362, 119364, 0),
|
387 |
+
(121344, 121398, 0),
|
388 |
+
(121403, 121452, 0),
|
389 |
+
(121461, 121461, 0),
|
390 |
+
(121476, 121476, 0),
|
391 |
+
(121499, 121503, 0),
|
392 |
+
(121505, 121519, 0),
|
393 |
+
(122880, 122886, 0),
|
394 |
+
(122888, 122904, 0),
|
395 |
+
(122907, 122913, 0),
|
396 |
+
(122915, 122916, 0),
|
397 |
+
(122918, 122922, 0),
|
398 |
+
(123184, 123190, 0),
|
399 |
+
(123628, 123631, 0),
|
400 |
+
(125136, 125142, 0),
|
401 |
+
(125252, 125258, 0),
|
402 |
+
(126980, 126980, 2),
|
403 |
+
(127183, 127183, 2),
|
404 |
+
(127374, 127374, 2),
|
405 |
+
(127377, 127386, 2),
|
406 |
+
(127488, 127490, 2),
|
407 |
+
(127504, 127547, 2),
|
408 |
+
(127552, 127560, 2),
|
409 |
+
(127568, 127569, 2),
|
410 |
+
(127584, 127589, 2),
|
411 |
+
(127744, 127776, 2),
|
412 |
+
(127789, 127797, 2),
|
413 |
+
(127799, 127868, 2),
|
414 |
+
(127870, 127891, 2),
|
415 |
+
(127904, 127946, 2),
|
416 |
+
(127951, 127955, 2),
|
417 |
+
(127968, 127984, 2),
|
418 |
+
(127988, 127988, 2),
|
419 |
+
(127992, 128062, 2),
|
420 |
+
(128064, 128064, 2),
|
421 |
+
(128066, 128252, 2),
|
422 |
+
(128255, 128317, 2),
|
423 |
+
(128331, 128334, 2),
|
424 |
+
(128336, 128359, 2),
|
425 |
+
(128378, 128378, 2),
|
426 |
+
(128405, 128406, 2),
|
427 |
+
(128420, 128420, 2),
|
428 |
+
(128507, 128591, 2),
|
429 |
+
(128640, 128709, 2),
|
430 |
+
(128716, 128716, 2),
|
431 |
+
(128720, 128722, 2),
|
432 |
+
(128725, 128727, 2),
|
433 |
+
(128747, 128748, 2),
|
434 |
+
(128756, 128764, 2),
|
435 |
+
(128992, 129003, 2),
|
436 |
+
(129292, 129338, 2),
|
437 |
+
(129340, 129349, 2),
|
438 |
+
(129351, 129400, 2),
|
439 |
+
(129402, 129483, 2),
|
440 |
+
(129485, 129535, 2),
|
441 |
+
(129648, 129652, 2),
|
442 |
+
(129656, 129658, 2),
|
443 |
+
(129664, 129670, 2),
|
444 |
+
(129680, 129704, 2),
|
445 |
+
(129712, 129718, 2),
|
446 |
+
(129728, 129730, 2),
|
447 |
+
(129744, 129750, 2),
|
448 |
+
(131072, 196605, 2),
|
449 |
+
(196608, 262141, 2),
|
450 |
+
(917760, 917999, 0),
|
451 |
+
]
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_emoji_codes.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_emoji_replace.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Callable, Match, Optional
|
2 |
+
import re
|
3 |
+
|
4 |
+
from ._emoji_codes import EMOJI
|
5 |
+
|
6 |
+
|
7 |
+
_ReStringMatch = Match[str] # regex match object
|
8 |
+
_ReSubCallable = Callable[[_ReStringMatch], str] # Callable invoked by re.sub
|
9 |
+
_EmojiSubMethod = Callable[[_ReSubCallable, str], str] # Sub method of a compiled re
|
10 |
+
|
11 |
+
|
12 |
+
def _emoji_replace(
|
13 |
+
text: str,
|
14 |
+
default_variant: Optional[str] = None,
|
15 |
+
_emoji_sub: _EmojiSubMethod = re.compile(r"(:(\S*?)(?:(?:\-)(emoji|text))?:)").sub,
|
16 |
+
) -> str:
|
17 |
+
"""Replace emoji code in text."""
|
18 |
+
get_emoji = EMOJI.__getitem__
|
19 |
+
variants = {"text": "\uFE0E", "emoji": "\uFE0F"}
|
20 |
+
get_variant = variants.get
|
21 |
+
default_variant_code = variants.get(default_variant, "") if default_variant else ""
|
22 |
+
|
23 |
+
def do_replace(match: Match[str]) -> str:
|
24 |
+
emoji_code, emoji_name, variant = match.groups()
|
25 |
+
try:
|
26 |
+
return get_emoji(emoji_name.lower()) + get_variant(
|
27 |
+
variant, default_variant_code
|
28 |
+
)
|
29 |
+
except KeyError:
|
30 |
+
return emoji_code
|
31 |
+
|
32 |
+
return _emoji_sub(do_replace, text)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_inspect.py
ADDED
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import absolute_import
|
2 |
+
|
3 |
+
from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature
|
4 |
+
from typing import Any, Iterable, Optional, Tuple
|
5 |
+
|
6 |
+
from .console import RenderableType, Group
|
7 |
+
from .highlighter import ReprHighlighter
|
8 |
+
from .jupyter import JupyterMixin
|
9 |
+
from .panel import Panel
|
10 |
+
from .pretty import Pretty
|
11 |
+
from .table import Table
|
12 |
+
from .text import Text, TextType
|
13 |
+
|
14 |
+
|
15 |
+
def _first_paragraph(doc: str) -> str:
|
16 |
+
"""Get the first paragraph from a docstring."""
|
17 |
+
paragraph, _, _ = doc.partition("\n\n")
|
18 |
+
return paragraph
|
19 |
+
|
20 |
+
|
21 |
+
def _reformat_doc(doc: str) -> str:
|
22 |
+
"""Reformat docstring."""
|
23 |
+
doc = cleandoc(doc).strip()
|
24 |
+
return doc
|
25 |
+
|
26 |
+
|
27 |
+
class Inspect(JupyterMixin):
|
28 |
+
"""A renderable to inspect any Python Object.
|
29 |
+
|
30 |
+
Args:
|
31 |
+
obj (Any): An object to inspect.
|
32 |
+
title (str, optional): Title to display over inspect result, or None use type. Defaults to None.
|
33 |
+
help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.
|
34 |
+
methods (bool, optional): Enable inspection of callables. Defaults to False.
|
35 |
+
docs (bool, optional): Also render doc strings. Defaults to True.
|
36 |
+
private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.
|
37 |
+
dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.
|
38 |
+
sort (bool, optional): Sort attributes alphabetically. Defaults to True.
|
39 |
+
all (bool, optional): Show all attributes. Defaults to False.
|
40 |
+
value (bool, optional): Pretty print value of object. Defaults to True.
|
41 |
+
"""
|
42 |
+
|
43 |
+
def __init__(
|
44 |
+
self,
|
45 |
+
obj: Any,
|
46 |
+
*,
|
47 |
+
title: Optional[TextType] = None,
|
48 |
+
help: bool = False,
|
49 |
+
methods: bool = False,
|
50 |
+
docs: bool = True,
|
51 |
+
private: bool = False,
|
52 |
+
dunder: bool = False,
|
53 |
+
sort: bool = True,
|
54 |
+
all: bool = True,
|
55 |
+
value: bool = True,
|
56 |
+
) -> None:
|
57 |
+
self.highlighter = ReprHighlighter()
|
58 |
+
self.obj = obj
|
59 |
+
self.title = title or self._make_title(obj)
|
60 |
+
if all:
|
61 |
+
methods = private = dunder = True
|
62 |
+
self.help = help
|
63 |
+
self.methods = methods
|
64 |
+
self.docs = docs or help
|
65 |
+
self.private = private or dunder
|
66 |
+
self.dunder = dunder
|
67 |
+
self.sort = sort
|
68 |
+
self.value = value
|
69 |
+
|
70 |
+
def _make_title(self, obj: Any) -> Text:
|
71 |
+
"""Make a default title."""
|
72 |
+
title_str = (
|
73 |
+
str(obj)
|
74 |
+
if (isclass(obj) or callable(obj) or ismodule(obj))
|
75 |
+
else str(type(obj))
|
76 |
+
)
|
77 |
+
title_text = self.highlighter(title_str)
|
78 |
+
return title_text
|
79 |
+
|
80 |
+
def __rich__(self) -> Panel:
|
81 |
+
return Panel.fit(
|
82 |
+
Group(*self._render()),
|
83 |
+
title=self.title,
|
84 |
+
border_style="scope.border",
|
85 |
+
padding=(0, 1),
|
86 |
+
)
|
87 |
+
|
88 |
+
def _get_signature(self, name: str, obj: Any) -> Optional[Text]:
|
89 |
+
"""Get a signature for a callable."""
|
90 |
+
try:
|
91 |
+
_signature = str(signature(obj)) + ":"
|
92 |
+
except ValueError:
|
93 |
+
_signature = "(...)"
|
94 |
+
except TypeError:
|
95 |
+
return None
|
96 |
+
|
97 |
+
source_filename: Optional[str] = None
|
98 |
+
try:
|
99 |
+
source_filename = getfile(obj)
|
100 |
+
except TypeError:
|
101 |
+
pass
|
102 |
+
|
103 |
+
callable_name = Text(name, style="inspect.callable")
|
104 |
+
if source_filename:
|
105 |
+
callable_name.stylize(f"link file://{source_filename}")
|
106 |
+
signature_text = self.highlighter(_signature)
|
107 |
+
|
108 |
+
qualname = name or getattr(obj, "__qualname__", name)
|
109 |
+
qual_signature = Text.assemble(
|
110 |
+
("def ", "inspect.def"), (qualname, "inspect.callable"), signature_text
|
111 |
+
)
|
112 |
+
|
113 |
+
return qual_signature
|
114 |
+
|
115 |
+
def _render(self) -> Iterable[RenderableType]:
|
116 |
+
"""Render object."""
|
117 |
+
|
118 |
+
def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:
|
119 |
+
key, (_error, value) = item
|
120 |
+
return (callable(value), key.strip("_").lower())
|
121 |
+
|
122 |
+
def safe_getattr(attr_name: str) -> Tuple[Any, Any]:
|
123 |
+
"""Get attribute or any exception."""
|
124 |
+
try:
|
125 |
+
return (None, getattr(obj, attr_name))
|
126 |
+
except Exception as error:
|
127 |
+
return (error, None)
|
128 |
+
|
129 |
+
obj = self.obj
|
130 |
+
keys = dir(obj)
|
131 |
+
total_items = len(keys)
|
132 |
+
if not self.dunder:
|
133 |
+
keys = [key for key in keys if not key.startswith("__")]
|
134 |
+
if not self.private:
|
135 |
+
keys = [key for key in keys if not key.startswith("_")]
|
136 |
+
not_shown_count = total_items - len(keys)
|
137 |
+
items = [(key, safe_getattr(key)) for key in keys]
|
138 |
+
if self.sort:
|
139 |
+
items.sort(key=sort_items)
|
140 |
+
|
141 |
+
items_table = Table.grid(padding=(0, 1), expand=False)
|
142 |
+
items_table.add_column(justify="right")
|
143 |
+
add_row = items_table.add_row
|
144 |
+
highlighter = self.highlighter
|
145 |
+
|
146 |
+
if callable(obj):
|
147 |
+
signature = self._get_signature("", obj)
|
148 |
+
if signature is not None:
|
149 |
+
yield signature
|
150 |
+
yield ""
|
151 |
+
|
152 |
+
if self.docs:
|
153 |
+
_doc = getdoc(obj)
|
154 |
+
if _doc is not None:
|
155 |
+
if not self.help:
|
156 |
+
_doc = _first_paragraph(_doc)
|
157 |
+
doc_text = Text(_reformat_doc(_doc), style="inspect.help")
|
158 |
+
doc_text = highlighter(doc_text)
|
159 |
+
yield doc_text
|
160 |
+
yield ""
|
161 |
+
|
162 |
+
if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):
|
163 |
+
yield Panel(
|
164 |
+
Pretty(obj, indent_guides=True, max_length=10, max_string=60),
|
165 |
+
border_style="inspect.value.border",
|
166 |
+
)
|
167 |
+
yield ""
|
168 |
+
|
169 |
+
for key, (error, value) in items:
|
170 |
+
key_text = Text.assemble(
|
171 |
+
(
|
172 |
+
key,
|
173 |
+
"inspect.attr.dunder" if key.startswith("__") else "inspect.attr",
|
174 |
+
),
|
175 |
+
(" =", "inspect.equals"),
|
176 |
+
)
|
177 |
+
if error is not None:
|
178 |
+
warning = key_text.copy()
|
179 |
+
warning.stylize("inspect.error")
|
180 |
+
add_row(warning, highlighter(repr(error)))
|
181 |
+
continue
|
182 |
+
|
183 |
+
if callable(value):
|
184 |
+
if not self.methods:
|
185 |
+
continue
|
186 |
+
|
187 |
+
_signature_text = self._get_signature(key, value)
|
188 |
+
if _signature_text is None:
|
189 |
+
add_row(key_text, Pretty(value, highlighter=highlighter))
|
190 |
+
else:
|
191 |
+
if self.docs:
|
192 |
+
docs = getdoc(value)
|
193 |
+
if docs is not None:
|
194 |
+
_doc = _reformat_doc(str(docs))
|
195 |
+
if not self.help:
|
196 |
+
_doc = _first_paragraph(_doc)
|
197 |
+
_signature_text.append("\n" if "\n" in _doc else " ")
|
198 |
+
doc = highlighter(_doc)
|
199 |
+
doc.stylize("inspect.doc")
|
200 |
+
_signature_text.append(doc)
|
201 |
+
|
202 |
+
add_row(key_text, _signature_text)
|
203 |
+
else:
|
204 |
+
add_row(key_text, Pretty(value, highlighter=highlighter))
|
205 |
+
if items_table.row_count:
|
206 |
+
yield items_table
|
207 |
+
else:
|
208 |
+
yield Text.from_markup(
|
209 |
+
f"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options."
|
210 |
+
)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_log_render.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
from typing import Iterable, List, Optional, TYPE_CHECKING, Union, Callable
|
3 |
+
|
4 |
+
|
5 |
+
from .text import Text, TextType
|
6 |
+
|
7 |
+
if TYPE_CHECKING:
|
8 |
+
from .console import Console, ConsoleRenderable, RenderableType
|
9 |
+
from .table import Table
|
10 |
+
|
11 |
+
FormatTimeCallable = Callable[[datetime], Text]
|
12 |
+
|
13 |
+
|
14 |
+
class LogRender:
|
15 |
+
def __init__(
|
16 |
+
self,
|
17 |
+
show_time: bool = True,
|
18 |
+
show_level: bool = False,
|
19 |
+
show_path: bool = True,
|
20 |
+
time_format: Union[str, FormatTimeCallable] = "[%x %X]",
|
21 |
+
omit_repeated_times: bool = True,
|
22 |
+
level_width: Optional[int] = 8,
|
23 |
+
) -> None:
|
24 |
+
self.show_time = show_time
|
25 |
+
self.show_level = show_level
|
26 |
+
self.show_path = show_path
|
27 |
+
self.time_format = time_format
|
28 |
+
self.omit_repeated_times = omit_repeated_times
|
29 |
+
self.level_width = level_width
|
30 |
+
self._last_time: Optional[Text] = None
|
31 |
+
|
32 |
+
def __call__(
|
33 |
+
self,
|
34 |
+
console: "Console",
|
35 |
+
renderables: Iterable["ConsoleRenderable"],
|
36 |
+
log_time: Optional[datetime] = None,
|
37 |
+
time_format: Optional[Union[str, FormatTimeCallable]] = None,
|
38 |
+
level: TextType = "",
|
39 |
+
path: Optional[str] = None,
|
40 |
+
line_no: Optional[int] = None,
|
41 |
+
link_path: Optional[str] = None,
|
42 |
+
) -> "Table":
|
43 |
+
from .containers import Renderables
|
44 |
+
from .table import Table
|
45 |
+
|
46 |
+
output = Table.grid(padding=(0, 1))
|
47 |
+
output.expand = True
|
48 |
+
if self.show_time:
|
49 |
+
output.add_column(style="log.time")
|
50 |
+
if self.show_level:
|
51 |
+
output.add_column(style="log.level", width=self.level_width)
|
52 |
+
output.add_column(ratio=1, style="log.message", overflow="fold")
|
53 |
+
if self.show_path and path:
|
54 |
+
output.add_column(style="log.path")
|
55 |
+
row: List["RenderableType"] = []
|
56 |
+
if self.show_time:
|
57 |
+
log_time = log_time or console.get_datetime()
|
58 |
+
time_format = time_format or self.time_format
|
59 |
+
if callable(time_format):
|
60 |
+
log_time_display = time_format(log_time)
|
61 |
+
else:
|
62 |
+
log_time_display = Text(log_time.strftime(time_format))
|
63 |
+
if log_time_display == self._last_time and self.omit_repeated_times:
|
64 |
+
row.append(Text(" " * len(log_time_display)))
|
65 |
+
else:
|
66 |
+
row.append(log_time_display)
|
67 |
+
self._last_time = log_time_display
|
68 |
+
if self.show_level:
|
69 |
+
row.append(level)
|
70 |
+
|
71 |
+
row.append(Renderables(renderables))
|
72 |
+
if self.show_path and path:
|
73 |
+
path_text = Text()
|
74 |
+
path_text.append(
|
75 |
+
path, style=f"link file://{link_path}" if link_path else ""
|
76 |
+
)
|
77 |
+
if line_no:
|
78 |
+
path_text.append(":")
|
79 |
+
path_text.append(
|
80 |
+
f"{line_no}",
|
81 |
+
style=f"link file://{link_path}#{line_no}" if link_path else "",
|
82 |
+
)
|
83 |
+
row.append(path_text)
|
84 |
+
|
85 |
+
output.add_row(*row)
|
86 |
+
return output
|
87 |
+
|
88 |
+
|
89 |
+
if __name__ == "__main__": # pragma: no cover
|
90 |
+
from pip._vendor.rich.console import Console
|
91 |
+
|
92 |
+
c = Console()
|
93 |
+
c.print("[on blue]Hello", justify="right")
|
94 |
+
c.log("[on blue]hello", justify="right")
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_loop.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Iterable, Tuple, TypeVar
|
2 |
+
|
3 |
+
T = TypeVar("T")
|
4 |
+
|
5 |
+
|
6 |
+
def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
|
7 |
+
"""Iterate and generate a tuple with a flag for first value."""
|
8 |
+
iter_values = iter(values)
|
9 |
+
try:
|
10 |
+
value = next(iter_values)
|
11 |
+
except StopIteration:
|
12 |
+
return
|
13 |
+
yield True, value
|
14 |
+
for value in iter_values:
|
15 |
+
yield False, value
|
16 |
+
|
17 |
+
|
18 |
+
def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
|
19 |
+
"""Iterate and generate a tuple with a flag for last value."""
|
20 |
+
iter_values = iter(values)
|
21 |
+
try:
|
22 |
+
previous_value = next(iter_values)
|
23 |
+
except StopIteration:
|
24 |
+
return
|
25 |
+
for value in iter_values:
|
26 |
+
yield False, previous_value
|
27 |
+
previous_value = value
|
28 |
+
yield True, previous_value
|
29 |
+
|
30 |
+
|
31 |
+
def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
|
32 |
+
"""Iterate and generate a tuple with a flag for first and last value."""
|
33 |
+
iter_values = iter(values)
|
34 |
+
try:
|
35 |
+
previous_value = next(iter_values)
|
36 |
+
except StopIteration:
|
37 |
+
return
|
38 |
+
first = True
|
39 |
+
for value in iter_values:
|
40 |
+
yield first, False, previous_value
|
41 |
+
first = False
|
42 |
+
previous_value = value
|
43 |
+
yield first, True, previous_value
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_palettes.py
ADDED
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .palette import Palette
|
2 |
+
|
3 |
+
|
4 |
+
# Taken from https://en.wikipedia.org/wiki/ANSI_escape_code (Windows 10 column)
|
5 |
+
WINDOWS_PALETTE = Palette(
|
6 |
+
[
|
7 |
+
(12, 12, 12),
|
8 |
+
(197, 15, 31),
|
9 |
+
(19, 161, 14),
|
10 |
+
(193, 156, 0),
|
11 |
+
(0, 55, 218),
|
12 |
+
(136, 23, 152),
|
13 |
+
(58, 150, 221),
|
14 |
+
(204, 204, 204),
|
15 |
+
(118, 118, 118),
|
16 |
+
(231, 72, 86),
|
17 |
+
(22, 198, 12),
|
18 |
+
(249, 241, 165),
|
19 |
+
(59, 120, 255),
|
20 |
+
(180, 0, 158),
|
21 |
+
(97, 214, 214),
|
22 |
+
(242, 242, 242),
|
23 |
+
]
|
24 |
+
)
|
25 |
+
|
26 |
+
# # The standard ansi colors (including bright variants)
|
27 |
+
STANDARD_PALETTE = Palette(
|
28 |
+
[
|
29 |
+
(0, 0, 0),
|
30 |
+
(170, 0, 0),
|
31 |
+
(0, 170, 0),
|
32 |
+
(170, 85, 0),
|
33 |
+
(0, 0, 170),
|
34 |
+
(170, 0, 170),
|
35 |
+
(0, 170, 170),
|
36 |
+
(170, 170, 170),
|
37 |
+
(85, 85, 85),
|
38 |
+
(255, 85, 85),
|
39 |
+
(85, 255, 85),
|
40 |
+
(255, 255, 85),
|
41 |
+
(85, 85, 255),
|
42 |
+
(255, 85, 255),
|
43 |
+
(85, 255, 255),
|
44 |
+
(255, 255, 255),
|
45 |
+
]
|
46 |
+
)
|
47 |
+
|
48 |
+
|
49 |
+
# The 256 color palette
|
50 |
+
EIGHT_BIT_PALETTE = Palette(
|
51 |
+
[
|
52 |
+
(0, 0, 0),
|
53 |
+
(128, 0, 0),
|
54 |
+
(0, 128, 0),
|
55 |
+
(128, 128, 0),
|
56 |
+
(0, 0, 128),
|
57 |
+
(128, 0, 128),
|
58 |
+
(0, 128, 128),
|
59 |
+
(192, 192, 192),
|
60 |
+
(128, 128, 128),
|
61 |
+
(255, 0, 0),
|
62 |
+
(0, 255, 0),
|
63 |
+
(255, 255, 0),
|
64 |
+
(0, 0, 255),
|
65 |
+
(255, 0, 255),
|
66 |
+
(0, 255, 255),
|
67 |
+
(255, 255, 255),
|
68 |
+
(0, 0, 0),
|
69 |
+
(0, 0, 95),
|
70 |
+
(0, 0, 135),
|
71 |
+
(0, 0, 175),
|
72 |
+
(0, 0, 215),
|
73 |
+
(0, 0, 255),
|
74 |
+
(0, 95, 0),
|
75 |
+
(0, 95, 95),
|
76 |
+
(0, 95, 135),
|
77 |
+
(0, 95, 175),
|
78 |
+
(0, 95, 215),
|
79 |
+
(0, 95, 255),
|
80 |
+
(0, 135, 0),
|
81 |
+
(0, 135, 95),
|
82 |
+
(0, 135, 135),
|
83 |
+
(0, 135, 175),
|
84 |
+
(0, 135, 215),
|
85 |
+
(0, 135, 255),
|
86 |
+
(0, 175, 0),
|
87 |
+
(0, 175, 95),
|
88 |
+
(0, 175, 135),
|
89 |
+
(0, 175, 175),
|
90 |
+
(0, 175, 215),
|
91 |
+
(0, 175, 255),
|
92 |
+
(0, 215, 0),
|
93 |
+
(0, 215, 95),
|
94 |
+
(0, 215, 135),
|
95 |
+
(0, 215, 175),
|
96 |
+
(0, 215, 215),
|
97 |
+
(0, 215, 255),
|
98 |
+
(0, 255, 0),
|
99 |
+
(0, 255, 95),
|
100 |
+
(0, 255, 135),
|
101 |
+
(0, 255, 175),
|
102 |
+
(0, 255, 215),
|
103 |
+
(0, 255, 255),
|
104 |
+
(95, 0, 0),
|
105 |
+
(95, 0, 95),
|
106 |
+
(95, 0, 135),
|
107 |
+
(95, 0, 175),
|
108 |
+
(95, 0, 215),
|
109 |
+
(95, 0, 255),
|
110 |
+
(95, 95, 0),
|
111 |
+
(95, 95, 95),
|
112 |
+
(95, 95, 135),
|
113 |
+
(95, 95, 175),
|
114 |
+
(95, 95, 215),
|
115 |
+
(95, 95, 255),
|
116 |
+
(95, 135, 0),
|
117 |
+
(95, 135, 95),
|
118 |
+
(95, 135, 135),
|
119 |
+
(95, 135, 175),
|
120 |
+
(95, 135, 215),
|
121 |
+
(95, 135, 255),
|
122 |
+
(95, 175, 0),
|
123 |
+
(95, 175, 95),
|
124 |
+
(95, 175, 135),
|
125 |
+
(95, 175, 175),
|
126 |
+
(95, 175, 215),
|
127 |
+
(95, 175, 255),
|
128 |
+
(95, 215, 0),
|
129 |
+
(95, 215, 95),
|
130 |
+
(95, 215, 135),
|
131 |
+
(95, 215, 175),
|
132 |
+
(95, 215, 215),
|
133 |
+
(95, 215, 255),
|
134 |
+
(95, 255, 0),
|
135 |
+
(95, 255, 95),
|
136 |
+
(95, 255, 135),
|
137 |
+
(95, 255, 175),
|
138 |
+
(95, 255, 215),
|
139 |
+
(95, 255, 255),
|
140 |
+
(135, 0, 0),
|
141 |
+
(135, 0, 95),
|
142 |
+
(135, 0, 135),
|
143 |
+
(135, 0, 175),
|
144 |
+
(135, 0, 215),
|
145 |
+
(135, 0, 255),
|
146 |
+
(135, 95, 0),
|
147 |
+
(135, 95, 95),
|
148 |
+
(135, 95, 135),
|
149 |
+
(135, 95, 175),
|
150 |
+
(135, 95, 215),
|
151 |
+
(135, 95, 255),
|
152 |
+
(135, 135, 0),
|
153 |
+
(135, 135, 95),
|
154 |
+
(135, 135, 135),
|
155 |
+
(135, 135, 175),
|
156 |
+
(135, 135, 215),
|
157 |
+
(135, 135, 255),
|
158 |
+
(135, 175, 0),
|
159 |
+
(135, 175, 95),
|
160 |
+
(135, 175, 135),
|
161 |
+
(135, 175, 175),
|
162 |
+
(135, 175, 215),
|
163 |
+
(135, 175, 255),
|
164 |
+
(135, 215, 0),
|
165 |
+
(135, 215, 95),
|
166 |
+
(135, 215, 135),
|
167 |
+
(135, 215, 175),
|
168 |
+
(135, 215, 215),
|
169 |
+
(135, 215, 255),
|
170 |
+
(135, 255, 0),
|
171 |
+
(135, 255, 95),
|
172 |
+
(135, 255, 135),
|
173 |
+
(135, 255, 175),
|
174 |
+
(135, 255, 215),
|
175 |
+
(135, 255, 255),
|
176 |
+
(175, 0, 0),
|
177 |
+
(175, 0, 95),
|
178 |
+
(175, 0, 135),
|
179 |
+
(175, 0, 175),
|
180 |
+
(175, 0, 215),
|
181 |
+
(175, 0, 255),
|
182 |
+
(175, 95, 0),
|
183 |
+
(175, 95, 95),
|
184 |
+
(175, 95, 135),
|
185 |
+
(175, 95, 175),
|
186 |
+
(175, 95, 215),
|
187 |
+
(175, 95, 255),
|
188 |
+
(175, 135, 0),
|
189 |
+
(175, 135, 95),
|
190 |
+
(175, 135, 135),
|
191 |
+
(175, 135, 175),
|
192 |
+
(175, 135, 215),
|
193 |
+
(175, 135, 255),
|
194 |
+
(175, 175, 0),
|
195 |
+
(175, 175, 95),
|
196 |
+
(175, 175, 135),
|
197 |
+
(175, 175, 175),
|
198 |
+
(175, 175, 215),
|
199 |
+
(175, 175, 255),
|
200 |
+
(175, 215, 0),
|
201 |
+
(175, 215, 95),
|
202 |
+
(175, 215, 135),
|
203 |
+
(175, 215, 175),
|
204 |
+
(175, 215, 215),
|
205 |
+
(175, 215, 255),
|
206 |
+
(175, 255, 0),
|
207 |
+
(175, 255, 95),
|
208 |
+
(175, 255, 135),
|
209 |
+
(175, 255, 175),
|
210 |
+
(175, 255, 215),
|
211 |
+
(175, 255, 255),
|
212 |
+
(215, 0, 0),
|
213 |
+
(215, 0, 95),
|
214 |
+
(215, 0, 135),
|
215 |
+
(215, 0, 175),
|
216 |
+
(215, 0, 215),
|
217 |
+
(215, 0, 255),
|
218 |
+
(215, 95, 0),
|
219 |
+
(215, 95, 95),
|
220 |
+
(215, 95, 135),
|
221 |
+
(215, 95, 175),
|
222 |
+
(215, 95, 215),
|
223 |
+
(215, 95, 255),
|
224 |
+
(215, 135, 0),
|
225 |
+
(215, 135, 95),
|
226 |
+
(215, 135, 135),
|
227 |
+
(215, 135, 175),
|
228 |
+
(215, 135, 215),
|
229 |
+
(215, 135, 255),
|
230 |
+
(215, 175, 0),
|
231 |
+
(215, 175, 95),
|
232 |
+
(215, 175, 135),
|
233 |
+
(215, 175, 175),
|
234 |
+
(215, 175, 215),
|
235 |
+
(215, 175, 255),
|
236 |
+
(215, 215, 0),
|
237 |
+
(215, 215, 95),
|
238 |
+
(215, 215, 135),
|
239 |
+
(215, 215, 175),
|
240 |
+
(215, 215, 215),
|
241 |
+
(215, 215, 255),
|
242 |
+
(215, 255, 0),
|
243 |
+
(215, 255, 95),
|
244 |
+
(215, 255, 135),
|
245 |
+
(215, 255, 175),
|
246 |
+
(215, 255, 215),
|
247 |
+
(215, 255, 255),
|
248 |
+
(255, 0, 0),
|
249 |
+
(255, 0, 95),
|
250 |
+
(255, 0, 135),
|
251 |
+
(255, 0, 175),
|
252 |
+
(255, 0, 215),
|
253 |
+
(255, 0, 255),
|
254 |
+
(255, 95, 0),
|
255 |
+
(255, 95, 95),
|
256 |
+
(255, 95, 135),
|
257 |
+
(255, 95, 175),
|
258 |
+
(255, 95, 215),
|
259 |
+
(255, 95, 255),
|
260 |
+
(255, 135, 0),
|
261 |
+
(255, 135, 95),
|
262 |
+
(255, 135, 135),
|
263 |
+
(255, 135, 175),
|
264 |
+
(255, 135, 215),
|
265 |
+
(255, 135, 255),
|
266 |
+
(255, 175, 0),
|
267 |
+
(255, 175, 95),
|
268 |
+
(255, 175, 135),
|
269 |
+
(255, 175, 175),
|
270 |
+
(255, 175, 215),
|
271 |
+
(255, 175, 255),
|
272 |
+
(255, 215, 0),
|
273 |
+
(255, 215, 95),
|
274 |
+
(255, 215, 135),
|
275 |
+
(255, 215, 175),
|
276 |
+
(255, 215, 215),
|
277 |
+
(255, 215, 255),
|
278 |
+
(255, 255, 0),
|
279 |
+
(255, 255, 95),
|
280 |
+
(255, 255, 135),
|
281 |
+
(255, 255, 175),
|
282 |
+
(255, 255, 215),
|
283 |
+
(255, 255, 255),
|
284 |
+
(8, 8, 8),
|
285 |
+
(18, 18, 18),
|
286 |
+
(28, 28, 28),
|
287 |
+
(38, 38, 38),
|
288 |
+
(48, 48, 48),
|
289 |
+
(58, 58, 58),
|
290 |
+
(68, 68, 68),
|
291 |
+
(78, 78, 78),
|
292 |
+
(88, 88, 88),
|
293 |
+
(98, 98, 98),
|
294 |
+
(108, 108, 108),
|
295 |
+
(118, 118, 118),
|
296 |
+
(128, 128, 128),
|
297 |
+
(138, 138, 138),
|
298 |
+
(148, 148, 148),
|
299 |
+
(158, 158, 158),
|
300 |
+
(168, 168, 168),
|
301 |
+
(178, 178, 178),
|
302 |
+
(188, 188, 188),
|
303 |
+
(198, 198, 198),
|
304 |
+
(208, 208, 208),
|
305 |
+
(218, 218, 218),
|
306 |
+
(228, 228, 228),
|
307 |
+
(238, 238, 238),
|
308 |
+
]
|
309 |
+
)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_pick.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional
|
2 |
+
|
3 |
+
|
4 |
+
def pick_bool(*values: Optional[bool]) -> bool:
|
5 |
+
"""Pick the first non-none bool or return the last value.
|
6 |
+
|
7 |
+
Args:
|
8 |
+
*values (bool): Any number of boolean or None values.
|
9 |
+
|
10 |
+
Returns:
|
11 |
+
bool: First non-none boolean.
|
12 |
+
"""
|
13 |
+
assert values, "1 or more values required"
|
14 |
+
for value in values:
|
15 |
+
if value is not None:
|
16 |
+
return value
|
17 |
+
return bool(value)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_ratio.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from fractions import Fraction
|
3 |
+
from math import ceil
|
4 |
+
from typing import cast, List, Optional, Sequence
|
5 |
+
|
6 |
+
if sys.version_info >= (3, 8):
|
7 |
+
from typing import Protocol
|
8 |
+
else:
|
9 |
+
from pip._vendor.typing_extensions import Protocol # pragma: no cover
|
10 |
+
|
11 |
+
|
12 |
+
class Edge(Protocol):
|
13 |
+
"""Any object that defines an edge (such as Layout)."""
|
14 |
+
|
15 |
+
size: Optional[int] = None
|
16 |
+
ratio: int = 1
|
17 |
+
minimum_size: int = 1
|
18 |
+
|
19 |
+
|
20 |
+
def ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]:
|
21 |
+
"""Divide total space to satisfy size, ratio, and minimum_size, constraints.
|
22 |
+
|
23 |
+
The returned list of integers should add up to total in most cases, unless it is
|
24 |
+
impossible to satisfy all the constraints. For instance, if there are two edges
|
25 |
+
with a minimum size of 20 each and `total` is 30 then the returned list will be
|
26 |
+
greater than total. In practice, this would mean that a Layout object would
|
27 |
+
clip the rows that would overflow the screen height.
|
28 |
+
|
29 |
+
Args:
|
30 |
+
total (int): Total number of characters.
|
31 |
+
edges (List[Edge]): Edges within total space.
|
32 |
+
|
33 |
+
Returns:
|
34 |
+
List[int]: Number of characters for each edge.
|
35 |
+
"""
|
36 |
+
# Size of edge or None for yet to be determined
|
37 |
+
sizes = [(edge.size or None) for edge in edges]
|
38 |
+
|
39 |
+
_Fraction = Fraction
|
40 |
+
|
41 |
+
# While any edges haven't been calculated
|
42 |
+
while None in sizes:
|
43 |
+
# Get flexible edges and index to map these back on to sizes list
|
44 |
+
flexible_edges = [
|
45 |
+
(index, edge)
|
46 |
+
for index, (size, edge) in enumerate(zip(sizes, edges))
|
47 |
+
if size is None
|
48 |
+
]
|
49 |
+
# Remaining space in total
|
50 |
+
remaining = total - sum(size or 0 for size in sizes)
|
51 |
+
if remaining <= 0:
|
52 |
+
# No room for flexible edges
|
53 |
+
return [
|
54 |
+
((edge.minimum_size or 1) if size is None else size)
|
55 |
+
for size, edge in zip(sizes, edges)
|
56 |
+
]
|
57 |
+
# Calculate number of characters in a ratio portion
|
58 |
+
portion = _Fraction(
|
59 |
+
remaining, sum((edge.ratio or 1) for _, edge in flexible_edges)
|
60 |
+
)
|
61 |
+
|
62 |
+
# If any edges will be less than their minimum, replace size with the minimum
|
63 |
+
for index, edge in flexible_edges:
|
64 |
+
if portion * edge.ratio <= edge.minimum_size:
|
65 |
+
sizes[index] = edge.minimum_size
|
66 |
+
# New fixed size will invalidate calculations, so we need to repeat the process
|
67 |
+
break
|
68 |
+
else:
|
69 |
+
# Distribute flexible space and compensate for rounding error
|
70 |
+
# Since edge sizes can only be integers we need to add the remainder
|
71 |
+
# to the following line
|
72 |
+
remainder = _Fraction(0)
|
73 |
+
for index, edge in flexible_edges:
|
74 |
+
size, remainder = divmod(portion * edge.ratio + remainder, 1)
|
75 |
+
sizes[index] = size
|
76 |
+
break
|
77 |
+
# Sizes now contains integers only
|
78 |
+
return cast(List[int], sizes)
|
79 |
+
|
80 |
+
|
81 |
+
def ratio_reduce(
|
82 |
+
total: int, ratios: List[int], maximums: List[int], values: List[int]
|
83 |
+
) -> List[int]:
|
84 |
+
"""Divide an integer total in to parts based on ratios.
|
85 |
+
|
86 |
+
Args:
|
87 |
+
total (int): The total to divide.
|
88 |
+
ratios (List[int]): A list of integer ratios.
|
89 |
+
maximums (List[int]): List of maximums values for each slot.
|
90 |
+
values (List[int]): List of values
|
91 |
+
|
92 |
+
Returns:
|
93 |
+
List[int]: A list of integers guaranteed to sum to total.
|
94 |
+
"""
|
95 |
+
ratios = [ratio if _max else 0 for ratio, _max in zip(ratios, maximums)]
|
96 |
+
total_ratio = sum(ratios)
|
97 |
+
if not total_ratio:
|
98 |
+
return values[:]
|
99 |
+
total_remaining = total
|
100 |
+
result: List[int] = []
|
101 |
+
append = result.append
|
102 |
+
for ratio, maximum, value in zip(ratios, maximums, values):
|
103 |
+
if ratio and total_ratio > 0:
|
104 |
+
distributed = min(maximum, round(ratio * total_remaining / total_ratio))
|
105 |
+
append(value - distributed)
|
106 |
+
total_remaining -= distributed
|
107 |
+
total_ratio -= ratio
|
108 |
+
else:
|
109 |
+
append(value)
|
110 |
+
return result
|
111 |
+
|
112 |
+
|
113 |
+
def ratio_distribute(
|
114 |
+
total: int, ratios: List[int], minimums: Optional[List[int]] = None
|
115 |
+
) -> List[int]:
|
116 |
+
"""Distribute an integer total in to parts based on ratios.
|
117 |
+
|
118 |
+
Args:
|
119 |
+
total (int): The total to divide.
|
120 |
+
ratios (List[int]): A list of integer ratios.
|
121 |
+
minimums (List[int]): List of minimum values for each slot.
|
122 |
+
|
123 |
+
Returns:
|
124 |
+
List[int]: A list of integers guaranteed to sum to total.
|
125 |
+
"""
|
126 |
+
if minimums:
|
127 |
+
ratios = [ratio if _min else 0 for ratio, _min in zip(ratios, minimums)]
|
128 |
+
total_ratio = sum(ratios)
|
129 |
+
assert total_ratio > 0, "Sum of ratios must be > 0"
|
130 |
+
|
131 |
+
total_remaining = total
|
132 |
+
distributed_total: List[int] = []
|
133 |
+
append = distributed_total.append
|
134 |
+
if minimums is None:
|
135 |
+
_minimums = [0] * len(ratios)
|
136 |
+
else:
|
137 |
+
_minimums = minimums
|
138 |
+
for ratio, minimum in zip(ratios, _minimums):
|
139 |
+
if total_ratio > 0:
|
140 |
+
distributed = max(minimum, ceil(ratio * total_remaining / total_ratio))
|
141 |
+
else:
|
142 |
+
distributed = total_remaining
|
143 |
+
append(distributed)
|
144 |
+
total_ratio -= ratio
|
145 |
+
total_remaining -= distributed
|
146 |
+
return distributed_total
|
147 |
+
|
148 |
+
|
149 |
+
if __name__ == "__main__":
|
150 |
+
from dataclasses import dataclass
|
151 |
+
|
152 |
+
@dataclass
|
153 |
+
class E:
|
154 |
+
|
155 |
+
size: Optional[int] = None
|
156 |
+
ratio: int = 1
|
157 |
+
minimum_size: int = 1
|
158 |
+
|
159 |
+
resolved = ratio_resolve(110, [E(None, 1, 1), E(None, 1, 1), E(None, 1, 1)])
|
160 |
+
print(sum(resolved))
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_stack.py
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List, TypeVar
|
2 |
+
|
3 |
+
T = TypeVar("T")
|
4 |
+
|
5 |
+
|
6 |
+
class Stack(List[T]):
|
7 |
+
"""A small shim over builtin list."""
|
8 |
+
|
9 |
+
@property
|
10 |
+
def top(self) -> T:
|
11 |
+
"""Get top of stack."""
|
12 |
+
return self[-1]
|
13 |
+
|
14 |
+
def push(self, item: T) -> None:
|
15 |
+
"""Push an item on to the stack (append in stack nomenclature)."""
|
16 |
+
self.append(item)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_timer.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Timer context manager, only used in debug.
|
3 |
+
|
4 |
+
"""
|
5 |
+
|
6 |
+
from time import time
|
7 |
+
|
8 |
+
import contextlib
|
9 |
+
from typing import Generator
|
10 |
+
|
11 |
+
|
12 |
+
@contextlib.contextmanager
|
13 |
+
def timer(subject: str = "time") -> Generator[None, None, None]:
|
14 |
+
"""print the elapsed time. (only used in debugging)"""
|
15 |
+
start = time()
|
16 |
+
yield
|
17 |
+
elapsed = time() - start
|
18 |
+
elapsed_ms = elapsed * 1000
|
19 |
+
print(f"{subject} elapsed {elapsed_ms:.1f}ms")
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/_wrap.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from typing import Iterable, List, Tuple
|
3 |
+
|
4 |
+
from .cells import cell_len, chop_cells
|
5 |
+
from ._loop import loop_last
|
6 |
+
|
7 |
+
re_word = re.compile(r"\s*\S+\s*")
|
8 |
+
|
9 |
+
|
10 |
+
def words(text: str) -> Iterable[Tuple[int, int, str]]:
|
11 |
+
position = 0
|
12 |
+
word_match = re_word.match(text, position)
|
13 |
+
while word_match is not None:
|
14 |
+
start, end = word_match.span()
|
15 |
+
word = word_match.group(0)
|
16 |
+
yield start, end, word
|
17 |
+
word_match = re_word.match(text, end)
|
18 |
+
|
19 |
+
|
20 |
+
def divide_line(text: str, width: int, fold: bool = True) -> List[int]:
|
21 |
+
divides: List[int] = []
|
22 |
+
append = divides.append
|
23 |
+
line_position = 0
|
24 |
+
_cell_len = cell_len
|
25 |
+
for start, _end, word in words(text):
|
26 |
+
word_length = _cell_len(word.rstrip())
|
27 |
+
if line_position + word_length > width:
|
28 |
+
if word_length > width:
|
29 |
+
if fold:
|
30 |
+
for last, line in loop_last(
|
31 |
+
chop_cells(word, width, position=line_position)
|
32 |
+
):
|
33 |
+
if last:
|
34 |
+
line_position = _cell_len(line)
|
35 |
+
else:
|
36 |
+
start += len(line)
|
37 |
+
append(start)
|
38 |
+
else:
|
39 |
+
if start:
|
40 |
+
append(start)
|
41 |
+
line_position = _cell_len(word)
|
42 |
+
elif line_position and start:
|
43 |
+
append(start)
|
44 |
+
line_position = _cell_len(word)
|
45 |
+
else:
|
46 |
+
line_position += _cell_len(word)
|
47 |
+
return divides
|
48 |
+
|
49 |
+
|
50 |
+
if __name__ == "__main__": # pragma: no cover
|
51 |
+
from .console import Console
|
52 |
+
|
53 |
+
console = Console(width=10)
|
54 |
+
console.print("12345 abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ 12345")
|
55 |
+
print(chop_cells("abcdefghijklmnopqrstuvwxyz", 10, position=2))
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/abc.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import ABC
|
2 |
+
|
3 |
+
|
4 |
+
class RichRenderable(ABC):
|
5 |
+
"""An abstract base class for Rich renderables.
|
6 |
+
|
7 |
+
Note that there is no need to extend this class, the intended use is to check if an
|
8 |
+
object supports the Rich renderable protocol. For example::
|
9 |
+
|
10 |
+
if isinstance(my_object, RichRenderable):
|
11 |
+
console.print(my_object)
|
12 |
+
|
13 |
+
"""
|
14 |
+
|
15 |
+
@classmethod
|
16 |
+
def __subclasshook__(cls, other: type) -> bool:
|
17 |
+
"""Check if this class supports the rich render protocol."""
|
18 |
+
return hasattr(other, "__rich_console__") or hasattr(other, "__rich__")
|
19 |
+
|
20 |
+
|
21 |
+
if __name__ == "__main__": # pragma: no cover
|
22 |
+
from pip._vendor.rich.text import Text
|
23 |
+
|
24 |
+
t = Text()
|
25 |
+
print(isinstance(Text, RichRenderable))
|
26 |
+
print(isinstance(t, RichRenderable))
|
27 |
+
|
28 |
+
class Foo:
|
29 |
+
pass
|
30 |
+
|
31 |
+
f = Foo()
|
32 |
+
print(isinstance(f, RichRenderable))
|
33 |
+
print(isinstance("", RichRenderable))
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/align.py
ADDED
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from itertools import chain
|
3 |
+
from typing import TYPE_CHECKING, Iterable, Optional
|
4 |
+
|
5 |
+
if sys.version_info >= (3, 8):
|
6 |
+
from typing import Literal
|
7 |
+
else:
|
8 |
+
from pip._vendor.typing_extensions import Literal # pragma: no cover
|
9 |
+
|
10 |
+
from .constrain import Constrain
|
11 |
+
from .jupyter import JupyterMixin
|
12 |
+
from .measure import Measurement
|
13 |
+
from .segment import Segment
|
14 |
+
from .style import StyleType
|
15 |
+
|
16 |
+
if TYPE_CHECKING:
|
17 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
18 |
+
|
19 |
+
AlignMethod = Literal["left", "center", "right"]
|
20 |
+
VerticalAlignMethod = Literal["top", "middle", "bottom"]
|
21 |
+
AlignValues = AlignMethod # TODO: deprecate AlignValues
|
22 |
+
|
23 |
+
|
24 |
+
class Align(JupyterMixin):
|
25 |
+
"""Align a renderable by adding spaces if necessary.
|
26 |
+
|
27 |
+
Args:
|
28 |
+
renderable (RenderableType): A console renderable.
|
29 |
+
align (AlignMethod): One of "left", "center", or "right""
|
30 |
+
style (StyleType, optional): An optional style to apply to the background.
|
31 |
+
vertical (Optional[VerticalAlginMethod], optional): Optional vertical align, one of "top", "middle", or "bottom". Defaults to None.
|
32 |
+
pad (bool, optional): Pad the right with spaces. Defaults to True.
|
33 |
+
width (int, optional): Restrict contents to given width, or None to use default width. Defaults to None.
|
34 |
+
height (int, optional): Set height of align renderable, or None to fit to contents. Defaults to None.
|
35 |
+
|
36 |
+
Raises:
|
37 |
+
ValueError: if ``align`` is not one of the expected values.
|
38 |
+
"""
|
39 |
+
|
40 |
+
def __init__(
|
41 |
+
self,
|
42 |
+
renderable: "RenderableType",
|
43 |
+
align: AlignMethod = "left",
|
44 |
+
style: Optional[StyleType] = None,
|
45 |
+
*,
|
46 |
+
vertical: Optional[VerticalAlignMethod] = None,
|
47 |
+
pad: bool = True,
|
48 |
+
width: Optional[int] = None,
|
49 |
+
height: Optional[int] = None,
|
50 |
+
) -> None:
|
51 |
+
if align not in ("left", "center", "right"):
|
52 |
+
raise ValueError(
|
53 |
+
f'invalid value for align, expected "left", "center", or "right" (not {align!r})'
|
54 |
+
)
|
55 |
+
if vertical is not None and vertical not in ("top", "middle", "bottom"):
|
56 |
+
raise ValueError(
|
57 |
+
f'invalid value for vertical, expected "top", "middle", or "bottom" (not {vertical!r})'
|
58 |
+
)
|
59 |
+
self.renderable = renderable
|
60 |
+
self.align = align
|
61 |
+
self.style = style
|
62 |
+
self.vertical = vertical
|
63 |
+
self.pad = pad
|
64 |
+
self.width = width
|
65 |
+
self.height = height
|
66 |
+
|
67 |
+
def __repr__(self) -> str:
|
68 |
+
return f"Align({self.renderable!r}, {self.align!r})"
|
69 |
+
|
70 |
+
@classmethod
|
71 |
+
def left(
|
72 |
+
cls,
|
73 |
+
renderable: "RenderableType",
|
74 |
+
style: Optional[StyleType] = None,
|
75 |
+
*,
|
76 |
+
vertical: Optional[VerticalAlignMethod] = None,
|
77 |
+
pad: bool = True,
|
78 |
+
width: Optional[int] = None,
|
79 |
+
height: Optional[int] = None,
|
80 |
+
) -> "Align":
|
81 |
+
"""Align a renderable to the left."""
|
82 |
+
return cls(
|
83 |
+
renderable,
|
84 |
+
"left",
|
85 |
+
style=style,
|
86 |
+
vertical=vertical,
|
87 |
+
pad=pad,
|
88 |
+
width=width,
|
89 |
+
height=height,
|
90 |
+
)
|
91 |
+
|
92 |
+
@classmethod
|
93 |
+
def center(
|
94 |
+
cls,
|
95 |
+
renderable: "RenderableType",
|
96 |
+
style: Optional[StyleType] = None,
|
97 |
+
*,
|
98 |
+
vertical: Optional[VerticalAlignMethod] = None,
|
99 |
+
pad: bool = True,
|
100 |
+
width: Optional[int] = None,
|
101 |
+
height: Optional[int] = None,
|
102 |
+
) -> "Align":
|
103 |
+
"""Align a renderable to the center."""
|
104 |
+
return cls(
|
105 |
+
renderable,
|
106 |
+
"center",
|
107 |
+
style=style,
|
108 |
+
vertical=vertical,
|
109 |
+
pad=pad,
|
110 |
+
width=width,
|
111 |
+
height=height,
|
112 |
+
)
|
113 |
+
|
114 |
+
@classmethod
|
115 |
+
def right(
|
116 |
+
cls,
|
117 |
+
renderable: "RenderableType",
|
118 |
+
style: Optional[StyleType] = None,
|
119 |
+
*,
|
120 |
+
vertical: Optional[VerticalAlignMethod] = None,
|
121 |
+
pad: bool = True,
|
122 |
+
width: Optional[int] = None,
|
123 |
+
height: Optional[int] = None,
|
124 |
+
) -> "Align":
|
125 |
+
"""Align a renderable to the right."""
|
126 |
+
return cls(
|
127 |
+
renderable,
|
128 |
+
"right",
|
129 |
+
style=style,
|
130 |
+
vertical=vertical,
|
131 |
+
pad=pad,
|
132 |
+
width=width,
|
133 |
+
height=height,
|
134 |
+
)
|
135 |
+
|
136 |
+
def __rich_console__(
|
137 |
+
self, console: "Console", options: "ConsoleOptions"
|
138 |
+
) -> "RenderResult":
|
139 |
+
align = self.align
|
140 |
+
width = console.measure(self.renderable, options=options).maximum
|
141 |
+
rendered = console.render(
|
142 |
+
Constrain(
|
143 |
+
self.renderable, width if self.width is None else min(width, self.width)
|
144 |
+
),
|
145 |
+
options.update(height=None),
|
146 |
+
)
|
147 |
+
lines = list(Segment.split_lines(rendered))
|
148 |
+
width, height = Segment.get_shape(lines)
|
149 |
+
lines = Segment.set_shape(lines, width, height)
|
150 |
+
new_line = Segment.line()
|
151 |
+
excess_space = options.max_width - width
|
152 |
+
style = console.get_style(self.style) if self.style is not None else None
|
153 |
+
|
154 |
+
def generate_segments() -> Iterable[Segment]:
|
155 |
+
if excess_space <= 0:
|
156 |
+
# Exact fit
|
157 |
+
for line in lines:
|
158 |
+
yield from line
|
159 |
+
yield new_line
|
160 |
+
|
161 |
+
elif align == "left":
|
162 |
+
# Pad on the right
|
163 |
+
pad = Segment(" " * excess_space, style) if self.pad else None
|
164 |
+
for line in lines:
|
165 |
+
yield from line
|
166 |
+
if pad:
|
167 |
+
yield pad
|
168 |
+
yield new_line
|
169 |
+
|
170 |
+
elif align == "center":
|
171 |
+
# Pad left and right
|
172 |
+
left = excess_space // 2
|
173 |
+
pad = Segment(" " * left, style)
|
174 |
+
pad_right = (
|
175 |
+
Segment(" " * (excess_space - left), style) if self.pad else None
|
176 |
+
)
|
177 |
+
for line in lines:
|
178 |
+
if left:
|
179 |
+
yield pad
|
180 |
+
yield from line
|
181 |
+
if pad_right:
|
182 |
+
yield pad_right
|
183 |
+
yield new_line
|
184 |
+
|
185 |
+
elif align == "right":
|
186 |
+
# Padding on left
|
187 |
+
pad = Segment(" " * excess_space, style)
|
188 |
+
for line in lines:
|
189 |
+
yield pad
|
190 |
+
yield from line
|
191 |
+
yield new_line
|
192 |
+
|
193 |
+
blank_line = (
|
194 |
+
Segment(f"{' ' * (self.width or options.max_width)}\n", style)
|
195 |
+
if self.pad
|
196 |
+
else Segment("\n")
|
197 |
+
)
|
198 |
+
|
199 |
+
def blank_lines(count: int) -> Iterable[Segment]:
|
200 |
+
if count > 0:
|
201 |
+
for _ in range(count):
|
202 |
+
yield blank_line
|
203 |
+
|
204 |
+
vertical_height = self.height or options.height
|
205 |
+
iter_segments: Iterable[Segment]
|
206 |
+
if self.vertical and vertical_height is not None:
|
207 |
+
if self.vertical == "top":
|
208 |
+
bottom_space = vertical_height - height
|
209 |
+
iter_segments = chain(generate_segments(), blank_lines(bottom_space))
|
210 |
+
elif self.vertical == "middle":
|
211 |
+
top_space = (vertical_height - height) // 2
|
212 |
+
bottom_space = vertical_height - top_space - height
|
213 |
+
iter_segments = chain(
|
214 |
+
blank_lines(top_space),
|
215 |
+
generate_segments(),
|
216 |
+
blank_lines(bottom_space),
|
217 |
+
)
|
218 |
+
else: # self.vertical == "bottom":
|
219 |
+
top_space = vertical_height - height
|
220 |
+
iter_segments = chain(blank_lines(top_space), generate_segments())
|
221 |
+
else:
|
222 |
+
iter_segments = generate_segments()
|
223 |
+
if self.style:
|
224 |
+
style = console.get_style(self.style)
|
225 |
+
iter_segments = Segment.apply_style(iter_segments, style)
|
226 |
+
yield from iter_segments
|
227 |
+
|
228 |
+
def __rich_measure__(
|
229 |
+
self, console: "Console", options: "ConsoleOptions"
|
230 |
+
) -> Measurement:
|
231 |
+
measurement = Measurement.get(console, options, self.renderable)
|
232 |
+
return measurement
|
233 |
+
|
234 |
+
|
235 |
+
class VerticalCenter(JupyterMixin):
|
236 |
+
"""Vertically aligns a renderable.
|
237 |
+
|
238 |
+
Warn:
|
239 |
+
This class is deprecated and may be removed in a future version. Use Align class with
|
240 |
+
`vertical="middle"`.
|
241 |
+
|
242 |
+
Args:
|
243 |
+
renderable (RenderableType): A renderable object.
|
244 |
+
"""
|
245 |
+
|
246 |
+
def __init__(
|
247 |
+
self,
|
248 |
+
renderable: "RenderableType",
|
249 |
+
style: Optional[StyleType] = None,
|
250 |
+
) -> None:
|
251 |
+
self.renderable = renderable
|
252 |
+
self.style = style
|
253 |
+
|
254 |
+
def __repr__(self) -> str:
|
255 |
+
return f"VerticalCenter({self.renderable!r})"
|
256 |
+
|
257 |
+
def __rich_console__(
|
258 |
+
self, console: "Console", options: "ConsoleOptions"
|
259 |
+
) -> "RenderResult":
|
260 |
+
style = console.get_style(self.style) if self.style is not None else None
|
261 |
+
lines = console.render_lines(
|
262 |
+
self.renderable, options.update(height=None), pad=False
|
263 |
+
)
|
264 |
+
width, _height = Segment.get_shape(lines)
|
265 |
+
new_line = Segment.line()
|
266 |
+
height = options.height or options.size.height
|
267 |
+
top_space = (height - len(lines)) // 2
|
268 |
+
bottom_space = height - top_space - len(lines)
|
269 |
+
blank_line = Segment(f"{' ' * width}", style)
|
270 |
+
|
271 |
+
def blank_lines(count: int) -> Iterable[Segment]:
|
272 |
+
for _ in range(count):
|
273 |
+
yield blank_line
|
274 |
+
yield new_line
|
275 |
+
|
276 |
+
if top_space > 0:
|
277 |
+
yield from blank_lines(top_space)
|
278 |
+
for line in lines:
|
279 |
+
yield from line
|
280 |
+
yield new_line
|
281 |
+
if bottom_space > 0:
|
282 |
+
yield from blank_lines(bottom_space)
|
283 |
+
|
284 |
+
def __rich_measure__(
|
285 |
+
self, console: "Console", options: "ConsoleOptions"
|
286 |
+
) -> Measurement:
|
287 |
+
measurement = Measurement.get(console, options, self.renderable)
|
288 |
+
return measurement
|
289 |
+
|
290 |
+
|
291 |
+
if __name__ == "__main__": # pragma: no cover
|
292 |
+
from pip._vendor.rich.console import Console, Group
|
293 |
+
from pip._vendor.rich.highlighter import ReprHighlighter
|
294 |
+
from pip._vendor.rich.panel import Panel
|
295 |
+
|
296 |
+
highlighter = ReprHighlighter()
|
297 |
+
console = Console()
|
298 |
+
|
299 |
+
panel = Panel(
|
300 |
+
Group(
|
301 |
+
Align.left(highlighter("align='left'")),
|
302 |
+
Align.center(highlighter("align='center'")),
|
303 |
+
Align.right(highlighter("align='right'")),
|
304 |
+
),
|
305 |
+
width=60,
|
306 |
+
style="on dark_blue",
|
307 |
+
title="Algin",
|
308 |
+
)
|
309 |
+
|
310 |
+
console.print(
|
311 |
+
Align.center(panel, vertical="middle", style="on red", height=console.height)
|
312 |
+
)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/ansi.py
ADDED
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from contextlib import suppress
|
2 |
+
import re
|
3 |
+
from typing import Iterable, NamedTuple
|
4 |
+
|
5 |
+
from .color import Color
|
6 |
+
from .style import Style
|
7 |
+
from .text import Text
|
8 |
+
|
9 |
+
re_ansi = re.compile(r"(?:\x1b\[(.*?)m)|(?:\x1b\](.*?)\x1b\\)")
|
10 |
+
re_csi = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
|
11 |
+
|
12 |
+
|
13 |
+
class _AnsiToken(NamedTuple):
|
14 |
+
"""Result of ansi tokenized string."""
|
15 |
+
|
16 |
+
plain: str = ""
|
17 |
+
sgr: str = ""
|
18 |
+
osc: str = ""
|
19 |
+
|
20 |
+
|
21 |
+
def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]:
|
22 |
+
"""Tokenize a string in to plain text and ANSI codes.
|
23 |
+
|
24 |
+
Args:
|
25 |
+
ansi_text (str): A String containing ANSI codes.
|
26 |
+
|
27 |
+
Yields:
|
28 |
+
AnsiToken: A named tuple of (plain, sgr, osc)
|
29 |
+
"""
|
30 |
+
|
31 |
+
def remove_csi(ansi_text: str) -> str:
|
32 |
+
"""Remove unknown CSI sequences."""
|
33 |
+
return re_csi.sub("", ansi_text)
|
34 |
+
|
35 |
+
position = 0
|
36 |
+
for match in re_ansi.finditer(ansi_text):
|
37 |
+
start, end = match.span(0)
|
38 |
+
sgr, osc = match.groups()
|
39 |
+
if start > position:
|
40 |
+
yield _AnsiToken(remove_csi(ansi_text[position:start]))
|
41 |
+
yield _AnsiToken("", sgr, osc)
|
42 |
+
position = end
|
43 |
+
if position < len(ansi_text):
|
44 |
+
yield _AnsiToken(remove_csi(ansi_text[position:]))
|
45 |
+
|
46 |
+
|
47 |
+
SGR_STYLE_MAP = {
|
48 |
+
1: "bold",
|
49 |
+
2: "dim",
|
50 |
+
3: "italic",
|
51 |
+
4: "underline",
|
52 |
+
5: "blink",
|
53 |
+
6: "blink2",
|
54 |
+
7: "reverse",
|
55 |
+
8: "conceal",
|
56 |
+
9: "strike",
|
57 |
+
21: "underline2",
|
58 |
+
22: "not dim not bold",
|
59 |
+
23: "not italic",
|
60 |
+
24: "not underline",
|
61 |
+
25: "not blink",
|
62 |
+
26: "not blink2",
|
63 |
+
27: "not reverse",
|
64 |
+
28: "not conceal",
|
65 |
+
29: "not strike",
|
66 |
+
30: "color(0)",
|
67 |
+
31: "color(1)",
|
68 |
+
32: "color(2)",
|
69 |
+
33: "color(3)",
|
70 |
+
34: "color(4)",
|
71 |
+
35: "color(5)",
|
72 |
+
36: "color(6)",
|
73 |
+
37: "color(7)",
|
74 |
+
39: "default",
|
75 |
+
40: "on color(0)",
|
76 |
+
41: "on color(1)",
|
77 |
+
42: "on color(2)",
|
78 |
+
43: "on color(3)",
|
79 |
+
44: "on color(4)",
|
80 |
+
45: "on color(5)",
|
81 |
+
46: "on color(6)",
|
82 |
+
47: "on color(7)",
|
83 |
+
49: "on default",
|
84 |
+
51: "frame",
|
85 |
+
52: "encircle",
|
86 |
+
53: "overline",
|
87 |
+
54: "not frame not encircle",
|
88 |
+
55: "not overline",
|
89 |
+
90: "color(8)",
|
90 |
+
91: "color(9)",
|
91 |
+
92: "color(10)",
|
92 |
+
93: "color(11)",
|
93 |
+
94: "color(12)",
|
94 |
+
95: "color(13)",
|
95 |
+
96: "color(14)",
|
96 |
+
97: "color(15)",
|
97 |
+
100: "on color(8)",
|
98 |
+
101: "on color(9)",
|
99 |
+
102: "on color(10)",
|
100 |
+
103: "on color(11)",
|
101 |
+
104: "on color(12)",
|
102 |
+
105: "on color(13)",
|
103 |
+
106: "on color(14)",
|
104 |
+
107: "on color(15)",
|
105 |
+
}
|
106 |
+
|
107 |
+
|
108 |
+
class AnsiDecoder:
|
109 |
+
"""Translate ANSI code in to styled Text."""
|
110 |
+
|
111 |
+
def __init__(self) -> None:
|
112 |
+
self.style = Style.null()
|
113 |
+
|
114 |
+
def decode(self, terminal_text: str) -> Iterable[Text]:
|
115 |
+
"""Decode ANSI codes in an interable of lines.
|
116 |
+
|
117 |
+
Args:
|
118 |
+
lines (Iterable[str]): An iterable of lines of terminal output.
|
119 |
+
|
120 |
+
Yields:
|
121 |
+
Text: Marked up Text.
|
122 |
+
"""
|
123 |
+
for line in terminal_text.splitlines():
|
124 |
+
yield self.decode_line(line)
|
125 |
+
|
126 |
+
def decode_line(self, line: str) -> Text:
|
127 |
+
"""Decode a line containing ansi codes.
|
128 |
+
|
129 |
+
Args:
|
130 |
+
line (str): A line of terminal output.
|
131 |
+
|
132 |
+
Returns:
|
133 |
+
Text: A Text instance marked up according to ansi codes.
|
134 |
+
"""
|
135 |
+
from_ansi = Color.from_ansi
|
136 |
+
from_rgb = Color.from_rgb
|
137 |
+
_Style = Style
|
138 |
+
text = Text()
|
139 |
+
append = text.append
|
140 |
+
line = line.rsplit("\r", 1)[-1]
|
141 |
+
for token in _ansi_tokenize(line):
|
142 |
+
plain_text, sgr, osc = token
|
143 |
+
if plain_text:
|
144 |
+
append(plain_text, self.style or None)
|
145 |
+
elif osc:
|
146 |
+
if osc.startswith("8;"):
|
147 |
+
_params, semicolon, link = osc[2:].partition(";")
|
148 |
+
if semicolon:
|
149 |
+
self.style = self.style.update_link(link or None)
|
150 |
+
elif sgr:
|
151 |
+
# Translate in to semi-colon separated codes
|
152 |
+
# Ignore invalid codes, because we want to be lenient
|
153 |
+
codes = [
|
154 |
+
min(255, int(_code)) for _code in sgr.split(";") if _code.isdigit()
|
155 |
+
]
|
156 |
+
iter_codes = iter(codes)
|
157 |
+
for code in iter_codes:
|
158 |
+
if code == 0:
|
159 |
+
# reset
|
160 |
+
self.style = _Style.null()
|
161 |
+
elif code in SGR_STYLE_MAP:
|
162 |
+
# styles
|
163 |
+
self.style += _Style.parse(SGR_STYLE_MAP[code])
|
164 |
+
elif code == 38:
|
165 |
+
# Foreground
|
166 |
+
with suppress(StopIteration):
|
167 |
+
color_type = next(iter_codes)
|
168 |
+
if color_type == 5:
|
169 |
+
self.style += _Style.from_color(
|
170 |
+
from_ansi(next(iter_codes))
|
171 |
+
)
|
172 |
+
elif color_type == 2:
|
173 |
+
self.style += _Style.from_color(
|
174 |
+
from_rgb(
|
175 |
+
next(iter_codes),
|
176 |
+
next(iter_codes),
|
177 |
+
next(iter_codes),
|
178 |
+
)
|
179 |
+
)
|
180 |
+
elif code == 48:
|
181 |
+
# Background
|
182 |
+
with suppress(StopIteration):
|
183 |
+
color_type = next(iter_codes)
|
184 |
+
if color_type == 5:
|
185 |
+
self.style += _Style.from_color(
|
186 |
+
None, from_ansi(next(iter_codes))
|
187 |
+
)
|
188 |
+
elif color_type == 2:
|
189 |
+
self.style += _Style.from_color(
|
190 |
+
None,
|
191 |
+
from_rgb(
|
192 |
+
next(iter_codes),
|
193 |
+
next(iter_codes),
|
194 |
+
next(iter_codes),
|
195 |
+
),
|
196 |
+
)
|
197 |
+
|
198 |
+
return text
|
199 |
+
|
200 |
+
|
201 |
+
if __name__ == "__main__": # pragma: no cover
|
202 |
+
import pty
|
203 |
+
import io
|
204 |
+
import os
|
205 |
+
import sys
|
206 |
+
|
207 |
+
decoder = AnsiDecoder()
|
208 |
+
|
209 |
+
stdout = io.BytesIO()
|
210 |
+
|
211 |
+
def read(fd: int) -> bytes:
|
212 |
+
data = os.read(fd, 1024)
|
213 |
+
stdout.write(data)
|
214 |
+
return data
|
215 |
+
|
216 |
+
pty.spawn(sys.argv[1:], read)
|
217 |
+
|
218 |
+
from .console import Console
|
219 |
+
|
220 |
+
console = Console(record=True)
|
221 |
+
|
222 |
+
stdout_result = stdout.getvalue().decode("utf-8")
|
223 |
+
print(stdout_result)
|
224 |
+
|
225 |
+
for line in decoder.decode(stdout_result):
|
226 |
+
console.print(line)
|
227 |
+
|
228 |
+
console.save_html("stdout.html")
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/box.py
ADDED
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from typing import TYPE_CHECKING, Iterable, List
|
3 |
+
|
4 |
+
if sys.version_info >= (3, 8):
|
5 |
+
from typing import Literal
|
6 |
+
else:
|
7 |
+
from pip._vendor.typing_extensions import Literal # pragma: no cover
|
8 |
+
|
9 |
+
|
10 |
+
from ._loop import loop_last
|
11 |
+
|
12 |
+
if TYPE_CHECKING:
|
13 |
+
from pip._vendor.rich.console import ConsoleOptions
|
14 |
+
|
15 |
+
|
16 |
+
class Box:
|
17 |
+
"""Defines characters to render boxes.
|
18 |
+
|
19 |
+
┌─┬┐ top
|
20 |
+
│ ││ head
|
21 |
+
├─┼┤ head_row
|
22 |
+
│ ││ mid
|
23 |
+
├─┼┤ row
|
24 |
+
├─┼┤ foot_row
|
25 |
+
│ ││ foot
|
26 |
+
└─┴┘ bottom
|
27 |
+
|
28 |
+
Args:
|
29 |
+
box (str): Characters making up box.
|
30 |
+
ascii (bool, optional): True if this box uses ascii characters only. Default is False.
|
31 |
+
"""
|
32 |
+
|
33 |
+
def __init__(self, box: str, *, ascii: bool = False) -> None:
|
34 |
+
self._box = box
|
35 |
+
self.ascii = ascii
|
36 |
+
line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines()
|
37 |
+
# top
|
38 |
+
self.top_left, self.top, self.top_divider, self.top_right = iter(line1)
|
39 |
+
# head
|
40 |
+
self.head_left, _, self.head_vertical, self.head_right = iter(line2)
|
41 |
+
# head_row
|
42 |
+
(
|
43 |
+
self.head_row_left,
|
44 |
+
self.head_row_horizontal,
|
45 |
+
self.head_row_cross,
|
46 |
+
self.head_row_right,
|
47 |
+
) = iter(line3)
|
48 |
+
|
49 |
+
# mid
|
50 |
+
self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4)
|
51 |
+
# row
|
52 |
+
self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5)
|
53 |
+
# foot_row
|
54 |
+
(
|
55 |
+
self.foot_row_left,
|
56 |
+
self.foot_row_horizontal,
|
57 |
+
self.foot_row_cross,
|
58 |
+
self.foot_row_right,
|
59 |
+
) = iter(line6)
|
60 |
+
# foot
|
61 |
+
self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7)
|
62 |
+
# bottom
|
63 |
+
self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter(
|
64 |
+
line8
|
65 |
+
)
|
66 |
+
|
67 |
+
def __repr__(self) -> str:
|
68 |
+
return "Box(...)"
|
69 |
+
|
70 |
+
def __str__(self) -> str:
|
71 |
+
return self._box
|
72 |
+
|
73 |
+
def substitute(self, options: "ConsoleOptions", safe: bool = True) -> "Box":
|
74 |
+
"""Substitute this box for another if it won't render due to platform issues.
|
75 |
+
|
76 |
+
Args:
|
77 |
+
options (ConsoleOptions): Console options used in rendering.
|
78 |
+
safe (bool, optional): Substitute this for another Box if there are known problems
|
79 |
+
displaying on the platform (currently only relevant on Windows). Default is True.
|
80 |
+
|
81 |
+
Returns:
|
82 |
+
Box: A different Box or the same Box.
|
83 |
+
"""
|
84 |
+
box = self
|
85 |
+
if options.legacy_windows and safe:
|
86 |
+
box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box)
|
87 |
+
if options.ascii_only and not box.ascii:
|
88 |
+
box = ASCII
|
89 |
+
return box
|
90 |
+
|
91 |
+
def get_top(self, widths: Iterable[int]) -> str:
|
92 |
+
"""Get the top of a simple box.
|
93 |
+
|
94 |
+
Args:
|
95 |
+
widths (List[int]): Widths of columns.
|
96 |
+
|
97 |
+
Returns:
|
98 |
+
str: A string of box characters.
|
99 |
+
"""
|
100 |
+
|
101 |
+
parts: List[str] = []
|
102 |
+
append = parts.append
|
103 |
+
append(self.top_left)
|
104 |
+
for last, width in loop_last(widths):
|
105 |
+
append(self.top * width)
|
106 |
+
if not last:
|
107 |
+
append(self.top_divider)
|
108 |
+
append(self.top_right)
|
109 |
+
return "".join(parts)
|
110 |
+
|
111 |
+
def get_row(
|
112 |
+
self,
|
113 |
+
widths: Iterable[int],
|
114 |
+
level: Literal["head", "row", "foot", "mid"] = "row",
|
115 |
+
edge: bool = True,
|
116 |
+
) -> str:
|
117 |
+
"""Get the top of a simple box.
|
118 |
+
|
119 |
+
Args:
|
120 |
+
width (List[int]): Widths of columns.
|
121 |
+
|
122 |
+
Returns:
|
123 |
+
str: A string of box characters.
|
124 |
+
"""
|
125 |
+
if level == "head":
|
126 |
+
left = self.head_row_left
|
127 |
+
horizontal = self.head_row_horizontal
|
128 |
+
cross = self.head_row_cross
|
129 |
+
right = self.head_row_right
|
130 |
+
elif level == "row":
|
131 |
+
left = self.row_left
|
132 |
+
horizontal = self.row_horizontal
|
133 |
+
cross = self.row_cross
|
134 |
+
right = self.row_right
|
135 |
+
elif level == "mid":
|
136 |
+
left = self.mid_left
|
137 |
+
horizontal = " "
|
138 |
+
cross = self.mid_vertical
|
139 |
+
right = self.mid_right
|
140 |
+
elif level == "foot":
|
141 |
+
left = self.foot_row_left
|
142 |
+
horizontal = self.foot_row_horizontal
|
143 |
+
cross = self.foot_row_cross
|
144 |
+
right = self.foot_row_right
|
145 |
+
else:
|
146 |
+
raise ValueError("level must be 'head', 'row' or 'foot'")
|
147 |
+
|
148 |
+
parts: List[str] = []
|
149 |
+
append = parts.append
|
150 |
+
if edge:
|
151 |
+
append(left)
|
152 |
+
for last, width in loop_last(widths):
|
153 |
+
append(horizontal * width)
|
154 |
+
if not last:
|
155 |
+
append(cross)
|
156 |
+
if edge:
|
157 |
+
append(right)
|
158 |
+
return "".join(parts)
|
159 |
+
|
160 |
+
def get_bottom(self, widths: Iterable[int]) -> str:
|
161 |
+
"""Get the bottom of a simple box.
|
162 |
+
|
163 |
+
Args:
|
164 |
+
widths (List[int]): Widths of columns.
|
165 |
+
|
166 |
+
Returns:
|
167 |
+
str: A string of box characters.
|
168 |
+
"""
|
169 |
+
|
170 |
+
parts: List[str] = []
|
171 |
+
append = parts.append
|
172 |
+
append(self.bottom_left)
|
173 |
+
for last, width in loop_last(widths):
|
174 |
+
append(self.bottom * width)
|
175 |
+
if not last:
|
176 |
+
append(self.bottom_divider)
|
177 |
+
append(self.bottom_right)
|
178 |
+
return "".join(parts)
|
179 |
+
|
180 |
+
|
181 |
+
ASCII: Box = Box(
|
182 |
+
"""\
|
183 |
+
+--+
|
184 |
+
| ||
|
185 |
+
|-+|
|
186 |
+
| ||
|
187 |
+
|-+|
|
188 |
+
|-+|
|
189 |
+
| ||
|
190 |
+
+--+
|
191 |
+
""",
|
192 |
+
ascii=True,
|
193 |
+
)
|
194 |
+
|
195 |
+
ASCII2: Box = Box(
|
196 |
+
"""\
|
197 |
+
+-++
|
198 |
+
| ||
|
199 |
+
+-++
|
200 |
+
| ||
|
201 |
+
+-++
|
202 |
+
+-++
|
203 |
+
| ||
|
204 |
+
+-++
|
205 |
+
""",
|
206 |
+
ascii=True,
|
207 |
+
)
|
208 |
+
|
209 |
+
ASCII_DOUBLE_HEAD: Box = Box(
|
210 |
+
"""\
|
211 |
+
+-++
|
212 |
+
| ||
|
213 |
+
+=++
|
214 |
+
| ||
|
215 |
+
+-++
|
216 |
+
+-++
|
217 |
+
| ||
|
218 |
+
+-++
|
219 |
+
""",
|
220 |
+
ascii=True,
|
221 |
+
)
|
222 |
+
|
223 |
+
SQUARE: Box = Box(
|
224 |
+
"""\
|
225 |
+
┌─┬┐
|
226 |
+
│ ││
|
227 |
+
├─┼┤
|
228 |
+
│ ││
|
229 |
+
├─┼┤
|
230 |
+
├─┼┤
|
231 |
+
│ ││
|
232 |
+
└─┴┘
|
233 |
+
"""
|
234 |
+
)
|
235 |
+
|
236 |
+
SQUARE_DOUBLE_HEAD: Box = Box(
|
237 |
+
"""\
|
238 |
+
┌─┬┐
|
239 |
+
│ ││
|
240 |
+
╞═╪╡
|
241 |
+
│ ││
|
242 |
+
├─┼┤
|
243 |
+
├─┼┤
|
244 |
+
│ ││
|
245 |
+
└─┴┘
|
246 |
+
"""
|
247 |
+
)
|
248 |
+
|
249 |
+
MINIMAL: Box = Box(
|
250 |
+
"""\
|
251 |
+
╷
|
252 |
+
│
|
253 |
+
╶─┼╴
|
254 |
+
│
|
255 |
+
╶─┼╴
|
256 |
+
╶─┼╴
|
257 |
+
│
|
258 |
+
╵
|
259 |
+
"""
|
260 |
+
)
|
261 |
+
|
262 |
+
|
263 |
+
MINIMAL_HEAVY_HEAD: Box = Box(
|
264 |
+
"""\
|
265 |
+
╷
|
266 |
+
│
|
267 |
+
╺━┿╸
|
268 |
+
│
|
269 |
+
╶─┼╴
|
270 |
+
╶─┼╴
|
271 |
+
│
|
272 |
+
╵
|
273 |
+
"""
|
274 |
+
)
|
275 |
+
|
276 |
+
MINIMAL_DOUBLE_HEAD: Box = Box(
|
277 |
+
"""\
|
278 |
+
╷
|
279 |
+
│
|
280 |
+
═╪
|
281 |
+
│
|
282 |
+
─┼
|
283 |
+
─┼
|
284 |
+
│
|
285 |
+
╵
|
286 |
+
"""
|
287 |
+
)
|
288 |
+
|
289 |
+
|
290 |
+
SIMPLE: Box = Box(
|
291 |
+
"""\
|
292 |
+
|
293 |
+
|
294 |
+
──
|
295 |
+
|
296 |
+
|
297 |
+
──
|
298 |
+
|
299 |
+
|
300 |
+
"""
|
301 |
+
)
|
302 |
+
|
303 |
+
SIMPLE_HEAD: Box = Box(
|
304 |
+
"""\
|
305 |
+
|
306 |
+
|
307 |
+
──
|
308 |
+
|
309 |
+
|
310 |
+
|
311 |
+
|
312 |
+
|
313 |
+
"""
|
314 |
+
)
|
315 |
+
|
316 |
+
|
317 |
+
SIMPLE_HEAVY: Box = Box(
|
318 |
+
"""\
|
319 |
+
|
320 |
+
|
321 |
+
━━
|
322 |
+
|
323 |
+
|
324 |
+
━━
|
325 |
+
|
326 |
+
|
327 |
+
"""
|
328 |
+
)
|
329 |
+
|
330 |
+
|
331 |
+
HORIZONTALS: Box = Box(
|
332 |
+
"""\
|
333 |
+
──
|
334 |
+
|
335 |
+
──
|
336 |
+
|
337 |
+
──
|
338 |
+
──
|
339 |
+
|
340 |
+
──
|
341 |
+
"""
|
342 |
+
)
|
343 |
+
|
344 |
+
ROUNDED: Box = Box(
|
345 |
+
"""\
|
346 |
+
╭─┬╮
|
347 |
+
│ ││
|
348 |
+
├─┼┤
|
349 |
+
│ ││
|
350 |
+
├─┼┤
|
351 |
+
├─┼┤
|
352 |
+
│ ││
|
353 |
+
╰─┴╯
|
354 |
+
"""
|
355 |
+
)
|
356 |
+
|
357 |
+
HEAVY: Box = Box(
|
358 |
+
"""\
|
359 |
+
┏━┳┓
|
360 |
+
┃ ┃┃
|
361 |
+
┣━╋┫
|
362 |
+
┃ ┃┃
|
363 |
+
┣━╋┫
|
364 |
+
┣━╋┫
|
365 |
+
┃ ┃┃
|
366 |
+
┗━┻┛
|
367 |
+
"""
|
368 |
+
)
|
369 |
+
|
370 |
+
HEAVY_EDGE: Box = Box(
|
371 |
+
"""\
|
372 |
+
┏━┯┓
|
373 |
+
┃ │┃
|
374 |
+
┠─┼┨
|
375 |
+
┃ │┃
|
376 |
+
┠─┼┨
|
377 |
+
┠─┼┨
|
378 |
+
┃ │┃
|
379 |
+
┗━┷┛
|
380 |
+
"""
|
381 |
+
)
|
382 |
+
|
383 |
+
HEAVY_HEAD: Box = Box(
|
384 |
+
"""\
|
385 |
+
┏━┳┓
|
386 |
+
┃ ┃┃
|
387 |
+
┡━╇┩
|
388 |
+
│ ││
|
389 |
+
├─┼┤
|
390 |
+
├─┼┤
|
391 |
+
│ ││
|
392 |
+
└─┴┘
|
393 |
+
"""
|
394 |
+
)
|
395 |
+
|
396 |
+
DOUBLE: Box = Box(
|
397 |
+
"""\
|
398 |
+
╔═╦╗
|
399 |
+
║ ║║
|
400 |
+
╠═╬╣
|
401 |
+
║ ║║
|
402 |
+
╠═╬╣
|
403 |
+
╠═╬╣
|
404 |
+
║ ║║
|
405 |
+
╚═╩╝
|
406 |
+
"""
|
407 |
+
)
|
408 |
+
|
409 |
+
DOUBLE_EDGE: Box = Box(
|
410 |
+
"""\
|
411 |
+
╔═╤╗
|
412 |
+
║ │║
|
413 |
+
╟─┼╢
|
414 |
+
║ │║
|
415 |
+
╟─┼╢
|
416 |
+
╟─┼╢
|
417 |
+
║ │║
|
418 |
+
╚═╧╝
|
419 |
+
"""
|
420 |
+
)
|
421 |
+
|
422 |
+
# Map Boxes that don't render with raster fonts on to equivalent that do
|
423 |
+
LEGACY_WINDOWS_SUBSTITUTIONS = {
|
424 |
+
ROUNDED: SQUARE,
|
425 |
+
MINIMAL_HEAVY_HEAD: MINIMAL,
|
426 |
+
SIMPLE_HEAVY: SIMPLE,
|
427 |
+
HEAVY: SQUARE,
|
428 |
+
HEAVY_EDGE: SQUARE,
|
429 |
+
HEAVY_HEAD: SQUARE,
|
430 |
+
}
|
431 |
+
|
432 |
+
|
433 |
+
if __name__ == "__main__": # pragma: no cover
|
434 |
+
|
435 |
+
from pip._vendor.rich.columns import Columns
|
436 |
+
from pip._vendor.rich.panel import Panel
|
437 |
+
|
438 |
+
from . import box as box
|
439 |
+
from .console import Console
|
440 |
+
from .table import Table
|
441 |
+
from .text import Text
|
442 |
+
|
443 |
+
console = Console(record=True)
|
444 |
+
|
445 |
+
BOXES = [
|
446 |
+
"ASCII",
|
447 |
+
"ASCII2",
|
448 |
+
"ASCII_DOUBLE_HEAD",
|
449 |
+
"SQUARE",
|
450 |
+
"SQUARE_DOUBLE_HEAD",
|
451 |
+
"MINIMAL",
|
452 |
+
"MINIMAL_HEAVY_HEAD",
|
453 |
+
"MINIMAL_DOUBLE_HEAD",
|
454 |
+
"SIMPLE",
|
455 |
+
"SIMPLE_HEAD",
|
456 |
+
"SIMPLE_HEAVY",
|
457 |
+
"HORIZONTALS",
|
458 |
+
"ROUNDED",
|
459 |
+
"HEAVY",
|
460 |
+
"HEAVY_EDGE",
|
461 |
+
"HEAVY_HEAD",
|
462 |
+
"DOUBLE",
|
463 |
+
"DOUBLE_EDGE",
|
464 |
+
]
|
465 |
+
|
466 |
+
console.print(Panel("[bold green]Box Constants", style="green"), justify="center")
|
467 |
+
console.print()
|
468 |
+
|
469 |
+
columns = Columns(expand=True, padding=2)
|
470 |
+
for box_name in sorted(BOXES):
|
471 |
+
table = Table(
|
472 |
+
show_footer=True, style="dim", border_style="not dim", expand=True
|
473 |
+
)
|
474 |
+
table.add_column("Header 1", "Footer 1")
|
475 |
+
table.add_column("Header 2", "Footer 2")
|
476 |
+
table.add_row("Cell", "Cell")
|
477 |
+
table.add_row("Cell", "Cell")
|
478 |
+
table.box = getattr(box, box_name)
|
479 |
+
table.title = Text(f"box.{box_name}", style="magenta")
|
480 |
+
columns.add_renderable(table)
|
481 |
+
console.print(columns)
|
482 |
+
|
483 |
+
# console.save_html("box.html", inline_styles=True)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/color.py
ADDED
@@ -0,0 +1,581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import platform
|
2 |
+
import re
|
3 |
+
from colorsys import rgb_to_hls
|
4 |
+
from enum import IntEnum
|
5 |
+
from functools import lru_cache
|
6 |
+
from typing import TYPE_CHECKING, NamedTuple, Optional, Tuple
|
7 |
+
|
8 |
+
from ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE
|
9 |
+
from .color_triplet import ColorTriplet
|
10 |
+
from .repr import rich_repr, Result
|
11 |
+
from .terminal_theme import DEFAULT_TERMINAL_THEME
|
12 |
+
|
13 |
+
if TYPE_CHECKING: # pragma: no cover
|
14 |
+
from .terminal_theme import TerminalTheme
|
15 |
+
from .text import Text
|
16 |
+
|
17 |
+
|
18 |
+
WINDOWS = platform.system() == "Windows"
|
19 |
+
|
20 |
+
|
21 |
+
class ColorSystem(IntEnum):
|
22 |
+
"""One of the 3 color system supported by terminals."""
|
23 |
+
|
24 |
+
STANDARD = 1
|
25 |
+
EIGHT_BIT = 2
|
26 |
+
TRUECOLOR = 3
|
27 |
+
WINDOWS = 4
|
28 |
+
|
29 |
+
def __repr__(self) -> str:
|
30 |
+
return f"ColorSystem.{self.name}"
|
31 |
+
|
32 |
+
|
33 |
+
class ColorType(IntEnum):
|
34 |
+
"""Type of color stored in Color class."""
|
35 |
+
|
36 |
+
DEFAULT = 0
|
37 |
+
STANDARD = 1
|
38 |
+
EIGHT_BIT = 2
|
39 |
+
TRUECOLOR = 3
|
40 |
+
WINDOWS = 4
|
41 |
+
|
42 |
+
def __repr__(self) -> str:
|
43 |
+
return f"ColorType.{self.name}"
|
44 |
+
|
45 |
+
|
46 |
+
ANSI_COLOR_NAMES = {
|
47 |
+
"black": 0,
|
48 |
+
"red": 1,
|
49 |
+
"green": 2,
|
50 |
+
"yellow": 3,
|
51 |
+
"blue": 4,
|
52 |
+
"magenta": 5,
|
53 |
+
"cyan": 6,
|
54 |
+
"white": 7,
|
55 |
+
"bright_black": 8,
|
56 |
+
"bright_red": 9,
|
57 |
+
"bright_green": 10,
|
58 |
+
"bright_yellow": 11,
|
59 |
+
"bright_blue": 12,
|
60 |
+
"bright_magenta": 13,
|
61 |
+
"bright_cyan": 14,
|
62 |
+
"bright_white": 15,
|
63 |
+
"grey0": 16,
|
64 |
+
"navy_blue": 17,
|
65 |
+
"dark_blue": 18,
|
66 |
+
"blue3": 20,
|
67 |
+
"blue1": 21,
|
68 |
+
"dark_green": 22,
|
69 |
+
"deep_sky_blue4": 25,
|
70 |
+
"dodger_blue3": 26,
|
71 |
+
"dodger_blue2": 27,
|
72 |
+
"green4": 28,
|
73 |
+
"spring_green4": 29,
|
74 |
+
"turquoise4": 30,
|
75 |
+
"deep_sky_blue3": 32,
|
76 |
+
"dodger_blue1": 33,
|
77 |
+
"green3": 40,
|
78 |
+
"spring_green3": 41,
|
79 |
+
"dark_cyan": 36,
|
80 |
+
"light_sea_green": 37,
|
81 |
+
"deep_sky_blue2": 38,
|
82 |
+
"deep_sky_blue1": 39,
|
83 |
+
"spring_green2": 47,
|
84 |
+
"cyan3": 43,
|
85 |
+
"dark_turquoise": 44,
|
86 |
+
"turquoise2": 45,
|
87 |
+
"green1": 46,
|
88 |
+
"spring_green1": 48,
|
89 |
+
"medium_spring_green": 49,
|
90 |
+
"cyan2": 50,
|
91 |
+
"cyan1": 51,
|
92 |
+
"dark_red": 88,
|
93 |
+
"deep_pink4": 125,
|
94 |
+
"purple4": 55,
|
95 |
+
"purple3": 56,
|
96 |
+
"blue_violet": 57,
|
97 |
+
"orange4": 94,
|
98 |
+
"grey37": 59,
|
99 |
+
"medium_purple4": 60,
|
100 |
+
"slate_blue3": 62,
|
101 |
+
"royal_blue1": 63,
|
102 |
+
"chartreuse4": 64,
|
103 |
+
"dark_sea_green4": 71,
|
104 |
+
"pale_turquoise4": 66,
|
105 |
+
"steel_blue": 67,
|
106 |
+
"steel_blue3": 68,
|
107 |
+
"cornflower_blue": 69,
|
108 |
+
"chartreuse3": 76,
|
109 |
+
"cadet_blue": 73,
|
110 |
+
"sky_blue3": 74,
|
111 |
+
"steel_blue1": 81,
|
112 |
+
"pale_green3": 114,
|
113 |
+
"sea_green3": 78,
|
114 |
+
"aquamarine3": 79,
|
115 |
+
"medium_turquoise": 80,
|
116 |
+
"chartreuse2": 112,
|
117 |
+
"sea_green2": 83,
|
118 |
+
"sea_green1": 85,
|
119 |
+
"aquamarine1": 122,
|
120 |
+
"dark_slate_gray2": 87,
|
121 |
+
"dark_magenta": 91,
|
122 |
+
"dark_violet": 128,
|
123 |
+
"purple": 129,
|
124 |
+
"light_pink4": 95,
|
125 |
+
"plum4": 96,
|
126 |
+
"medium_purple3": 98,
|
127 |
+
"slate_blue1": 99,
|
128 |
+
"yellow4": 106,
|
129 |
+
"wheat4": 101,
|
130 |
+
"grey53": 102,
|
131 |
+
"light_slate_grey": 103,
|
132 |
+
"medium_purple": 104,
|
133 |
+
"light_slate_blue": 105,
|
134 |
+
"dark_olive_green3": 149,
|
135 |
+
"dark_sea_green": 108,
|
136 |
+
"light_sky_blue3": 110,
|
137 |
+
"sky_blue2": 111,
|
138 |
+
"dark_sea_green3": 150,
|
139 |
+
"dark_slate_gray3": 116,
|
140 |
+
"sky_blue1": 117,
|
141 |
+
"chartreuse1": 118,
|
142 |
+
"light_green": 120,
|
143 |
+
"pale_green1": 156,
|
144 |
+
"dark_slate_gray1": 123,
|
145 |
+
"red3": 160,
|
146 |
+
"medium_violet_red": 126,
|
147 |
+
"magenta3": 164,
|
148 |
+
"dark_orange3": 166,
|
149 |
+
"indian_red": 167,
|
150 |
+
"hot_pink3": 168,
|
151 |
+
"medium_orchid3": 133,
|
152 |
+
"medium_orchid": 134,
|
153 |
+
"medium_purple2": 140,
|
154 |
+
"dark_goldenrod": 136,
|
155 |
+
"light_salmon3": 173,
|
156 |
+
"rosy_brown": 138,
|
157 |
+
"grey63": 139,
|
158 |
+
"medium_purple1": 141,
|
159 |
+
"gold3": 178,
|
160 |
+
"dark_khaki": 143,
|
161 |
+
"navajo_white3": 144,
|
162 |
+
"grey69": 145,
|
163 |
+
"light_steel_blue3": 146,
|
164 |
+
"light_steel_blue": 147,
|
165 |
+
"yellow3": 184,
|
166 |
+
"dark_sea_green2": 157,
|
167 |
+
"light_cyan3": 152,
|
168 |
+
"light_sky_blue1": 153,
|
169 |
+
"green_yellow": 154,
|
170 |
+
"dark_olive_green2": 155,
|
171 |
+
"dark_sea_green1": 193,
|
172 |
+
"pale_turquoise1": 159,
|
173 |
+
"deep_pink3": 162,
|
174 |
+
"magenta2": 200,
|
175 |
+
"hot_pink2": 169,
|
176 |
+
"orchid": 170,
|
177 |
+
"medium_orchid1": 207,
|
178 |
+
"orange3": 172,
|
179 |
+
"light_pink3": 174,
|
180 |
+
"pink3": 175,
|
181 |
+
"plum3": 176,
|
182 |
+
"violet": 177,
|
183 |
+
"light_goldenrod3": 179,
|
184 |
+
"tan": 180,
|
185 |
+
"misty_rose3": 181,
|
186 |
+
"thistle3": 182,
|
187 |
+
"plum2": 183,
|
188 |
+
"khaki3": 185,
|
189 |
+
"light_goldenrod2": 222,
|
190 |
+
"light_yellow3": 187,
|
191 |
+
"grey84": 188,
|
192 |
+
"light_steel_blue1": 189,
|
193 |
+
"yellow2": 190,
|
194 |
+
"dark_olive_green1": 192,
|
195 |
+
"honeydew2": 194,
|
196 |
+
"light_cyan1": 195,
|
197 |
+
"red1": 196,
|
198 |
+
"deep_pink2": 197,
|
199 |
+
"deep_pink1": 199,
|
200 |
+
"magenta1": 201,
|
201 |
+
"orange_red1": 202,
|
202 |
+
"indian_red1": 204,
|
203 |
+
"hot_pink": 206,
|
204 |
+
"dark_orange": 208,
|
205 |
+
"salmon1": 209,
|
206 |
+
"light_coral": 210,
|
207 |
+
"pale_violet_red1": 211,
|
208 |
+
"orchid2": 212,
|
209 |
+
"orchid1": 213,
|
210 |
+
"orange1": 214,
|
211 |
+
"sandy_brown": 215,
|
212 |
+
"light_salmon1": 216,
|
213 |
+
"light_pink1": 217,
|
214 |
+
"pink1": 218,
|
215 |
+
"plum1": 219,
|
216 |
+
"gold1": 220,
|
217 |
+
"navajo_white1": 223,
|
218 |
+
"misty_rose1": 224,
|
219 |
+
"thistle1": 225,
|
220 |
+
"yellow1": 226,
|
221 |
+
"light_goldenrod1": 227,
|
222 |
+
"khaki1": 228,
|
223 |
+
"wheat1": 229,
|
224 |
+
"cornsilk1": 230,
|
225 |
+
"grey100": 231,
|
226 |
+
"grey3": 232,
|
227 |
+
"grey7": 233,
|
228 |
+
"grey11": 234,
|
229 |
+
"grey15": 235,
|
230 |
+
"grey19": 236,
|
231 |
+
"grey23": 237,
|
232 |
+
"grey27": 238,
|
233 |
+
"grey30": 239,
|
234 |
+
"grey35": 240,
|
235 |
+
"grey39": 241,
|
236 |
+
"grey42": 242,
|
237 |
+
"grey46": 243,
|
238 |
+
"grey50": 244,
|
239 |
+
"grey54": 245,
|
240 |
+
"grey58": 246,
|
241 |
+
"grey62": 247,
|
242 |
+
"grey66": 248,
|
243 |
+
"grey70": 249,
|
244 |
+
"grey74": 250,
|
245 |
+
"grey78": 251,
|
246 |
+
"grey82": 252,
|
247 |
+
"grey85": 253,
|
248 |
+
"grey89": 254,
|
249 |
+
"grey93": 255,
|
250 |
+
}
|
251 |
+
|
252 |
+
|
253 |
+
class ColorParseError(Exception):
|
254 |
+
"""The color could not be parsed."""
|
255 |
+
|
256 |
+
|
257 |
+
RE_COLOR = re.compile(
|
258 |
+
r"""^
|
259 |
+
\#([0-9a-f]{6})$|
|
260 |
+
color\(([0-9]{1,3})\)$|
|
261 |
+
rgb\(([\d\s,]+)\)$
|
262 |
+
""",
|
263 |
+
re.VERBOSE,
|
264 |
+
)
|
265 |
+
|
266 |
+
|
267 |
+
@rich_repr
|
268 |
+
class Color(NamedTuple):
|
269 |
+
"""Terminal color definition."""
|
270 |
+
|
271 |
+
name: str
|
272 |
+
"""The name of the color (typically the input to Color.parse)."""
|
273 |
+
type: ColorType
|
274 |
+
"""The type of the color."""
|
275 |
+
number: Optional[int] = None
|
276 |
+
"""The color number, if a standard color, or None."""
|
277 |
+
triplet: Optional[ColorTriplet] = None
|
278 |
+
"""A triplet of color components, if an RGB color."""
|
279 |
+
|
280 |
+
def __rich__(self) -> "Text":
|
281 |
+
"""Dispays the actual color if Rich printed."""
|
282 |
+
from .text import Text
|
283 |
+
from .style import Style
|
284 |
+
|
285 |
+
return Text.assemble(
|
286 |
+
f"<color {self.name!r} ({self.type.name.lower()})",
|
287 |
+
("⬤", Style(color=self)),
|
288 |
+
" >",
|
289 |
+
)
|
290 |
+
|
291 |
+
def __rich_repr__(self) -> Result:
|
292 |
+
yield self.name
|
293 |
+
yield self.type
|
294 |
+
yield "number", self.number, None
|
295 |
+
yield "triplet", self.triplet, None
|
296 |
+
|
297 |
+
@property
|
298 |
+
def system(self) -> ColorSystem:
|
299 |
+
"""Get the native color system for this color."""
|
300 |
+
if self.type == ColorType.DEFAULT:
|
301 |
+
return ColorSystem.STANDARD
|
302 |
+
return ColorSystem(int(self.type))
|
303 |
+
|
304 |
+
@property
|
305 |
+
def is_system_defined(self) -> bool:
|
306 |
+
"""Check if the color is ultimately defined by the system."""
|
307 |
+
return self.system not in (ColorSystem.EIGHT_BIT, ColorSystem.TRUECOLOR)
|
308 |
+
|
309 |
+
@property
|
310 |
+
def is_default(self) -> bool:
|
311 |
+
"""Check if the color is a default color."""
|
312 |
+
return self.type == ColorType.DEFAULT
|
313 |
+
|
314 |
+
def get_truecolor(
|
315 |
+
self, theme: Optional["TerminalTheme"] = None, foreground: bool = True
|
316 |
+
) -> ColorTriplet:
|
317 |
+
"""Get an equivalent color triplet for this color.
|
318 |
+
|
319 |
+
Args:
|
320 |
+
theme (TerminalTheme, optional): Optional terminal theme, or None to use default. Defaults to None.
|
321 |
+
foreground (bool, optional): True for a foreground color, or False for background. Defaults to True.
|
322 |
+
|
323 |
+
Returns:
|
324 |
+
ColorTriplet: A color triplet containing RGB components.
|
325 |
+
"""
|
326 |
+
|
327 |
+
if theme is None:
|
328 |
+
theme = DEFAULT_TERMINAL_THEME
|
329 |
+
if self.type == ColorType.TRUECOLOR:
|
330 |
+
assert self.triplet is not None
|
331 |
+
return self.triplet
|
332 |
+
elif self.type == ColorType.EIGHT_BIT:
|
333 |
+
assert self.number is not None
|
334 |
+
return EIGHT_BIT_PALETTE[self.number]
|
335 |
+
elif self.type == ColorType.STANDARD:
|
336 |
+
assert self.number is not None
|
337 |
+
return theme.ansi_colors[self.number]
|
338 |
+
elif self.type == ColorType.WINDOWS:
|
339 |
+
assert self.number is not None
|
340 |
+
return WINDOWS_PALETTE[self.number]
|
341 |
+
else: # self.type == ColorType.DEFAULT:
|
342 |
+
assert self.number is None
|
343 |
+
return theme.foreground_color if foreground else theme.background_color
|
344 |
+
|
345 |
+
@classmethod
|
346 |
+
def from_ansi(cls, number: int) -> "Color":
|
347 |
+
"""Create a Color number from it's 8-bit ansi number.
|
348 |
+
|
349 |
+
Args:
|
350 |
+
number (int): A number between 0-255 inclusive.
|
351 |
+
|
352 |
+
Returns:
|
353 |
+
Color: A new Color instance.
|
354 |
+
"""
|
355 |
+
return cls(
|
356 |
+
name=f"color({number})",
|
357 |
+
type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),
|
358 |
+
number=number,
|
359 |
+
)
|
360 |
+
|
361 |
+
@classmethod
|
362 |
+
def from_triplet(cls, triplet: "ColorTriplet") -> "Color":
|
363 |
+
"""Create a truecolor RGB color from a triplet of values.
|
364 |
+
|
365 |
+
Args:
|
366 |
+
triplet (ColorTriplet): A color triplet containing red, green and blue components.
|
367 |
+
|
368 |
+
Returns:
|
369 |
+
Color: A new color object.
|
370 |
+
"""
|
371 |
+
return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet)
|
372 |
+
|
373 |
+
@classmethod
|
374 |
+
def from_rgb(cls, red: float, green: float, blue: float) -> "Color":
|
375 |
+
"""Create a truecolor from three color components in the range(0->255).
|
376 |
+
|
377 |
+
Args:
|
378 |
+
red (float): Red component in range 0-255.
|
379 |
+
green (float): Green component in range 0-255.
|
380 |
+
blue (float): Blue component in range 0-255.
|
381 |
+
|
382 |
+
Returns:
|
383 |
+
Color: A new color object.
|
384 |
+
"""
|
385 |
+
return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue)))
|
386 |
+
|
387 |
+
@classmethod
|
388 |
+
def default(cls) -> "Color":
|
389 |
+
"""Get a Color instance representing the default color.
|
390 |
+
|
391 |
+
Returns:
|
392 |
+
Color: Default color.
|
393 |
+
"""
|
394 |
+
return cls(name="default", type=ColorType.DEFAULT)
|
395 |
+
|
396 |
+
@classmethod
|
397 |
+
@lru_cache(maxsize=1024)
|
398 |
+
def parse(cls, color: str) -> "Color":
|
399 |
+
"""Parse a color definition."""
|
400 |
+
original_color = color
|
401 |
+
color = color.lower().strip()
|
402 |
+
|
403 |
+
if color == "default":
|
404 |
+
return cls(color, type=ColorType.DEFAULT)
|
405 |
+
|
406 |
+
color_number = ANSI_COLOR_NAMES.get(color)
|
407 |
+
if color_number is not None:
|
408 |
+
return cls(
|
409 |
+
color,
|
410 |
+
type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT),
|
411 |
+
number=color_number,
|
412 |
+
)
|
413 |
+
|
414 |
+
color_match = RE_COLOR.match(color)
|
415 |
+
if color_match is None:
|
416 |
+
raise ColorParseError(f"{original_color!r} is not a valid color")
|
417 |
+
|
418 |
+
color_24, color_8, color_rgb = color_match.groups()
|
419 |
+
if color_24:
|
420 |
+
triplet = ColorTriplet(
|
421 |
+
int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16)
|
422 |
+
)
|
423 |
+
return cls(color, ColorType.TRUECOLOR, triplet=triplet)
|
424 |
+
|
425 |
+
elif color_8:
|
426 |
+
number = int(color_8)
|
427 |
+
if number > 255:
|
428 |
+
raise ColorParseError(f"color number must be <= 255 in {color!r}")
|
429 |
+
return cls(
|
430 |
+
color,
|
431 |
+
type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),
|
432 |
+
number=number,
|
433 |
+
)
|
434 |
+
|
435 |
+
else: # color_rgb:
|
436 |
+
components = color_rgb.split(",")
|
437 |
+
if len(components) != 3:
|
438 |
+
raise ColorParseError(
|
439 |
+
f"expected three components in {original_color!r}"
|
440 |
+
)
|
441 |
+
red, green, blue = components
|
442 |
+
triplet = ColorTriplet(int(red), int(green), int(blue))
|
443 |
+
if not all(component <= 255 for component in triplet):
|
444 |
+
raise ColorParseError(
|
445 |
+
f"color components must be <= 255 in {original_color!r}"
|
446 |
+
)
|
447 |
+
return cls(color, ColorType.TRUECOLOR, triplet=triplet)
|
448 |
+
|
449 |
+
@lru_cache(maxsize=1024)
|
450 |
+
def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]:
|
451 |
+
"""Get the ANSI escape codes for this color."""
|
452 |
+
_type = self.type
|
453 |
+
if _type == ColorType.DEFAULT:
|
454 |
+
return ("39" if foreground else "49",)
|
455 |
+
|
456 |
+
elif _type == ColorType.WINDOWS:
|
457 |
+
number = self.number
|
458 |
+
assert number is not None
|
459 |
+
fore, back = (30, 40) if number < 8 else (82, 92)
|
460 |
+
return (str(fore + number if foreground else back + number),)
|
461 |
+
|
462 |
+
elif _type == ColorType.STANDARD:
|
463 |
+
number = self.number
|
464 |
+
assert number is not None
|
465 |
+
fore, back = (30, 40) if number < 8 else (82, 92)
|
466 |
+
return (str(fore + number if foreground else back + number),)
|
467 |
+
|
468 |
+
elif _type == ColorType.EIGHT_BIT:
|
469 |
+
assert self.number is not None
|
470 |
+
return ("38" if foreground else "48", "5", str(self.number))
|
471 |
+
|
472 |
+
else: # self.standard == ColorStandard.TRUECOLOR:
|
473 |
+
assert self.triplet is not None
|
474 |
+
red, green, blue = self.triplet
|
475 |
+
return ("38" if foreground else "48", "2", str(red), str(green), str(blue))
|
476 |
+
|
477 |
+
@lru_cache(maxsize=1024)
|
478 |
+
def downgrade(self, system: ColorSystem) -> "Color":
|
479 |
+
"""Downgrade a color system to a system with fewer colors."""
|
480 |
+
|
481 |
+
if self.type in [ColorType.DEFAULT, system]:
|
482 |
+
return self
|
483 |
+
# Convert to 8-bit color from truecolor color
|
484 |
+
if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:
|
485 |
+
assert self.triplet is not None
|
486 |
+
red, green, blue = self.triplet.normalized
|
487 |
+
_h, l, s = rgb_to_hls(red, green, blue)
|
488 |
+
# If saturation is under 10% assume it is grayscale
|
489 |
+
if s < 0.1:
|
490 |
+
gray = round(l * 25.0)
|
491 |
+
if gray == 0:
|
492 |
+
color_number = 16
|
493 |
+
elif gray == 25:
|
494 |
+
color_number = 231
|
495 |
+
else:
|
496 |
+
color_number = 231 + gray
|
497 |
+
return Color(self.name, ColorType.EIGHT_BIT, number=color_number)
|
498 |
+
|
499 |
+
color_number = (
|
500 |
+
16 + 36 * round(red * 5.0) + 6 * round(green * 5.0) + round(blue * 5.0)
|
501 |
+
)
|
502 |
+
return Color(self.name, ColorType.EIGHT_BIT, number=color_number)
|
503 |
+
|
504 |
+
# Convert to standard from truecolor or 8-bit
|
505 |
+
elif system == ColorSystem.STANDARD:
|
506 |
+
if self.system == ColorSystem.TRUECOLOR:
|
507 |
+
assert self.triplet is not None
|
508 |
+
triplet = self.triplet
|
509 |
+
else: # self.system == ColorSystem.EIGHT_BIT
|
510 |
+
assert self.number is not None
|
511 |
+
triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])
|
512 |
+
|
513 |
+
color_number = STANDARD_PALETTE.match(triplet)
|
514 |
+
return Color(self.name, ColorType.STANDARD, number=color_number)
|
515 |
+
|
516 |
+
elif system == ColorSystem.WINDOWS:
|
517 |
+
if self.system == ColorSystem.TRUECOLOR:
|
518 |
+
assert self.triplet is not None
|
519 |
+
triplet = self.triplet
|
520 |
+
else: # self.system == ColorSystem.EIGHT_BIT
|
521 |
+
assert self.number is not None
|
522 |
+
if self.number < 16:
|
523 |
+
return Color(self.name, ColorType.WINDOWS, number=self.number)
|
524 |
+
triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])
|
525 |
+
|
526 |
+
color_number = WINDOWS_PALETTE.match(triplet)
|
527 |
+
return Color(self.name, ColorType.WINDOWS, number=color_number)
|
528 |
+
|
529 |
+
return self
|
530 |
+
|
531 |
+
|
532 |
+
def parse_rgb_hex(hex_color: str) -> ColorTriplet:
|
533 |
+
"""Parse six hex characters in to RGB triplet."""
|
534 |
+
assert len(hex_color) == 6, "must be 6 characters"
|
535 |
+
color = ColorTriplet(
|
536 |
+
int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)
|
537 |
+
)
|
538 |
+
return color
|
539 |
+
|
540 |
+
|
541 |
+
def blend_rgb(
|
542 |
+
color1: ColorTriplet, color2: ColorTriplet, cross_fade: float = 0.5
|
543 |
+
) -> ColorTriplet:
|
544 |
+
"""Blend one RGB color in to another."""
|
545 |
+
r1, g1, b1 = color1
|
546 |
+
r2, g2, b2 = color2
|
547 |
+
new_color = ColorTriplet(
|
548 |
+
int(r1 + (r2 - r1) * cross_fade),
|
549 |
+
int(g1 + (g2 - g1) * cross_fade),
|
550 |
+
int(b1 + (b2 - b1) * cross_fade),
|
551 |
+
)
|
552 |
+
return new_color
|
553 |
+
|
554 |
+
|
555 |
+
if __name__ == "__main__": # pragma: no cover
|
556 |
+
|
557 |
+
from .console import Console
|
558 |
+
from .table import Table
|
559 |
+
from .text import Text
|
560 |
+
|
561 |
+
console = Console()
|
562 |
+
|
563 |
+
table = Table(show_footer=False, show_edge=True)
|
564 |
+
table.add_column("Color", width=10, overflow="ellipsis")
|
565 |
+
table.add_column("Number", justify="right", style="yellow")
|
566 |
+
table.add_column("Name", style="green")
|
567 |
+
table.add_column("Hex", style="blue")
|
568 |
+
table.add_column("RGB", style="magenta")
|
569 |
+
|
570 |
+
colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items())
|
571 |
+
for color_number, name in colors:
|
572 |
+
color_cell = Text(" " * 10, style=f"on {name}")
|
573 |
+
if color_number < 16:
|
574 |
+
table.add_row(color_cell, f"{color_number}", Text(f'"{name}"'))
|
575 |
+
else:
|
576 |
+
color = EIGHT_BIT_PALETTE[color_number] # type: ignore
|
577 |
+
table.add_row(
|
578 |
+
color_cell, str(color_number), Text(f'"{name}"'), color.hex, color.rgb
|
579 |
+
)
|
580 |
+
|
581 |
+
console.print(table)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/columns.py
ADDED
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import defaultdict
|
2 |
+
from itertools import chain
|
3 |
+
from operator import itemgetter
|
4 |
+
from typing import Dict, Iterable, List, Optional, Tuple
|
5 |
+
|
6 |
+
from .align import Align, AlignMethod
|
7 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
8 |
+
from .constrain import Constrain
|
9 |
+
from .measure import Measurement
|
10 |
+
from .padding import Padding, PaddingDimensions
|
11 |
+
from .table import Table
|
12 |
+
from .text import TextType
|
13 |
+
from .jupyter import JupyterMixin
|
14 |
+
|
15 |
+
|
16 |
+
class Columns(JupyterMixin):
|
17 |
+
"""Display renderables in neat columns.
|
18 |
+
|
19 |
+
Args:
|
20 |
+
renderables (Iterable[RenderableType]): Any number of Rich renderables (including str).
|
21 |
+
width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None.
|
22 |
+
padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1).
|
23 |
+
expand (bool, optional): Expand columns to full width. Defaults to False.
|
24 |
+
equal (bool, optional): Arrange in to equal sized columns. Defaults to False.
|
25 |
+
column_first (bool, optional): Align items from top to bottom (rather than left to right). Defaults to False.
|
26 |
+
right_to_left (bool, optional): Start column from right hand side. Defaults to False.
|
27 |
+
align (str, optional): Align value ("left", "right", or "center") or None for default. Defaults to None.
|
28 |
+
title (TextType, optional): Optional title for Columns.
|
29 |
+
"""
|
30 |
+
|
31 |
+
def __init__(
|
32 |
+
self,
|
33 |
+
renderables: Optional[Iterable[RenderableType]] = None,
|
34 |
+
padding: PaddingDimensions = (0, 1),
|
35 |
+
*,
|
36 |
+
width: Optional[int] = None,
|
37 |
+
expand: bool = False,
|
38 |
+
equal: bool = False,
|
39 |
+
column_first: bool = False,
|
40 |
+
right_to_left: bool = False,
|
41 |
+
align: Optional[AlignMethod] = None,
|
42 |
+
title: Optional[TextType] = None,
|
43 |
+
) -> None:
|
44 |
+
self.renderables = list(renderables or [])
|
45 |
+
self.width = width
|
46 |
+
self.padding = padding
|
47 |
+
self.expand = expand
|
48 |
+
self.equal = equal
|
49 |
+
self.column_first = column_first
|
50 |
+
self.right_to_left = right_to_left
|
51 |
+
self.align: Optional[AlignMethod] = align
|
52 |
+
self.title = title
|
53 |
+
|
54 |
+
def add_renderable(self, renderable: RenderableType) -> None:
|
55 |
+
"""Add a renderable to the columns.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
renderable (RenderableType): Any renderable object.
|
59 |
+
"""
|
60 |
+
self.renderables.append(renderable)
|
61 |
+
|
62 |
+
def __rich_console__(
|
63 |
+
self, console: Console, options: ConsoleOptions
|
64 |
+
) -> RenderResult:
|
65 |
+
render_str = console.render_str
|
66 |
+
renderables = [
|
67 |
+
render_str(renderable) if isinstance(renderable, str) else renderable
|
68 |
+
for renderable in self.renderables
|
69 |
+
]
|
70 |
+
if not renderables:
|
71 |
+
return
|
72 |
+
_top, right, _bottom, left = Padding.unpack(self.padding)
|
73 |
+
width_padding = max(left, right)
|
74 |
+
max_width = options.max_width
|
75 |
+
widths: Dict[int, int] = defaultdict(int)
|
76 |
+
column_count = len(renderables)
|
77 |
+
|
78 |
+
get_measurement = Measurement.get
|
79 |
+
renderable_widths = [
|
80 |
+
get_measurement(console, options, renderable).maximum
|
81 |
+
for renderable in renderables
|
82 |
+
]
|
83 |
+
if self.equal:
|
84 |
+
renderable_widths = [max(renderable_widths)] * len(renderable_widths)
|
85 |
+
|
86 |
+
def iter_renderables(
|
87 |
+
column_count: int,
|
88 |
+
) -> Iterable[Tuple[int, Optional[RenderableType]]]:
|
89 |
+
item_count = len(renderables)
|
90 |
+
if self.column_first:
|
91 |
+
width_renderables = list(zip(renderable_widths, renderables))
|
92 |
+
|
93 |
+
column_lengths: List[int] = [item_count // column_count] * column_count
|
94 |
+
for col_no in range(item_count % column_count):
|
95 |
+
column_lengths[col_no] += 1
|
96 |
+
|
97 |
+
row_count = (item_count + column_count - 1) // column_count
|
98 |
+
cells = [[-1] * column_count for _ in range(row_count)]
|
99 |
+
row = col = 0
|
100 |
+
for index in range(item_count):
|
101 |
+
cells[row][col] = index
|
102 |
+
column_lengths[col] -= 1
|
103 |
+
if column_lengths[col]:
|
104 |
+
row += 1
|
105 |
+
else:
|
106 |
+
col += 1
|
107 |
+
row = 0
|
108 |
+
for index in chain.from_iterable(cells):
|
109 |
+
if index == -1:
|
110 |
+
break
|
111 |
+
yield width_renderables[index]
|
112 |
+
else:
|
113 |
+
yield from zip(renderable_widths, renderables)
|
114 |
+
# Pad odd elements with spaces
|
115 |
+
if item_count % column_count:
|
116 |
+
for _ in range(column_count - (item_count % column_count)):
|
117 |
+
yield 0, None
|
118 |
+
|
119 |
+
table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False)
|
120 |
+
table.expand = self.expand
|
121 |
+
table.title = self.title
|
122 |
+
|
123 |
+
if self.width is not None:
|
124 |
+
column_count = (max_width) // (self.width + width_padding)
|
125 |
+
for _ in range(column_count):
|
126 |
+
table.add_column(width=self.width)
|
127 |
+
else:
|
128 |
+
while column_count > 1:
|
129 |
+
widths.clear()
|
130 |
+
column_no = 0
|
131 |
+
for renderable_width, _ in iter_renderables(column_count):
|
132 |
+
widths[column_no] = max(widths[column_no], renderable_width)
|
133 |
+
total_width = sum(widths.values()) + width_padding * (
|
134 |
+
len(widths) - 1
|
135 |
+
)
|
136 |
+
if total_width > max_width:
|
137 |
+
column_count = len(widths) - 1
|
138 |
+
break
|
139 |
+
else:
|
140 |
+
column_no = (column_no + 1) % column_count
|
141 |
+
else:
|
142 |
+
break
|
143 |
+
|
144 |
+
get_renderable = itemgetter(1)
|
145 |
+
_renderables = [
|
146 |
+
get_renderable(_renderable)
|
147 |
+
for _renderable in iter_renderables(column_count)
|
148 |
+
]
|
149 |
+
if self.equal:
|
150 |
+
_renderables = [
|
151 |
+
None
|
152 |
+
if renderable is None
|
153 |
+
else Constrain(renderable, renderable_widths[0])
|
154 |
+
for renderable in _renderables
|
155 |
+
]
|
156 |
+
if self.align:
|
157 |
+
align = self.align
|
158 |
+
_Align = Align
|
159 |
+
_renderables = [
|
160 |
+
None if renderable is None else _Align(renderable, align)
|
161 |
+
for renderable in _renderables
|
162 |
+
]
|
163 |
+
|
164 |
+
right_to_left = self.right_to_left
|
165 |
+
add_row = table.add_row
|
166 |
+
for start in range(0, len(_renderables), column_count):
|
167 |
+
row = _renderables[start : start + column_count]
|
168 |
+
if right_to_left:
|
169 |
+
row = row[::-1]
|
170 |
+
add_row(*row)
|
171 |
+
yield table
|
172 |
+
|
173 |
+
|
174 |
+
if __name__ == "__main__": # pragma: no cover
|
175 |
+
import os
|
176 |
+
|
177 |
+
console = Console()
|
178 |
+
|
179 |
+
files = [f"{i} {s}" for i, s in enumerate(sorted(os.listdir()))]
|
180 |
+
columns = Columns(files, padding=(0, 1), expand=False, equal=False)
|
181 |
+
console.print(columns)
|
182 |
+
console.rule()
|
183 |
+
columns.column_first = True
|
184 |
+
console.print(columns)
|
185 |
+
columns.right_to_left = True
|
186 |
+
console.rule()
|
187 |
+
console.print(columns)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/console.py
ADDED
@@ -0,0 +1,2211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import inspect
|
2 |
+
import os
|
3 |
+
import platform
|
4 |
+
import sys
|
5 |
+
import threading
|
6 |
+
from abc import ABC, abstractmethod
|
7 |
+
from dataclasses import dataclass, field
|
8 |
+
from datetime import datetime
|
9 |
+
from functools import wraps
|
10 |
+
from getpass import getpass
|
11 |
+
from html import escape
|
12 |
+
from inspect import isclass
|
13 |
+
from itertools import islice
|
14 |
+
from threading import RLock
|
15 |
+
from time import monotonic
|
16 |
+
from types import FrameType, ModuleType, TracebackType
|
17 |
+
from typing import (
|
18 |
+
IO,
|
19 |
+
TYPE_CHECKING,
|
20 |
+
Any,
|
21 |
+
Callable,
|
22 |
+
Dict,
|
23 |
+
Iterable,
|
24 |
+
List,
|
25 |
+
Mapping,
|
26 |
+
NamedTuple,
|
27 |
+
Optional,
|
28 |
+
TextIO,
|
29 |
+
Tuple,
|
30 |
+
Type,
|
31 |
+
Union,
|
32 |
+
cast,
|
33 |
+
)
|
34 |
+
|
35 |
+
if sys.version_info >= (3, 8):
|
36 |
+
from typing import Literal, Protocol, runtime_checkable
|
37 |
+
else:
|
38 |
+
from pip._vendor.typing_extensions import (
|
39 |
+
Literal,
|
40 |
+
Protocol,
|
41 |
+
runtime_checkable,
|
42 |
+
) # pragma: no cover
|
43 |
+
|
44 |
+
from . import errors, themes
|
45 |
+
from ._emoji_replace import _emoji_replace
|
46 |
+
from ._log_render import FormatTimeCallable, LogRender
|
47 |
+
from .align import Align, AlignMethod
|
48 |
+
from .color import ColorSystem
|
49 |
+
from .control import Control
|
50 |
+
from .emoji import EmojiVariant
|
51 |
+
from .highlighter import NullHighlighter, ReprHighlighter
|
52 |
+
from .markup import render as render_markup
|
53 |
+
from .measure import Measurement, measure_renderables
|
54 |
+
from .pager import Pager, SystemPager
|
55 |
+
from .pretty import Pretty, is_expandable
|
56 |
+
from .protocol import rich_cast
|
57 |
+
from .region import Region
|
58 |
+
from .scope import render_scope
|
59 |
+
from .screen import Screen
|
60 |
+
from .segment import Segment
|
61 |
+
from .style import Style, StyleType
|
62 |
+
from .styled import Styled
|
63 |
+
from .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme
|
64 |
+
from .text import Text, TextType
|
65 |
+
from .theme import Theme, ThemeStack
|
66 |
+
|
67 |
+
if TYPE_CHECKING:
|
68 |
+
from ._windows import WindowsConsoleFeatures
|
69 |
+
from .live import Live
|
70 |
+
from .status import Status
|
71 |
+
|
72 |
+
WINDOWS = platform.system() == "Windows"
|
73 |
+
|
74 |
+
HighlighterType = Callable[[Union[str, "Text"]], "Text"]
|
75 |
+
JustifyMethod = Literal["default", "left", "center", "right", "full"]
|
76 |
+
OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"]
|
77 |
+
|
78 |
+
|
79 |
+
class NoChange:
|
80 |
+
pass
|
81 |
+
|
82 |
+
|
83 |
+
NO_CHANGE = NoChange()
|
84 |
+
|
85 |
+
|
86 |
+
CONSOLE_HTML_FORMAT = """\
|
87 |
+
<!DOCTYPE html>
|
88 |
+
<head>
|
89 |
+
<meta charset="UTF-8">
|
90 |
+
<style>
|
91 |
+
{stylesheet}
|
92 |
+
body {{
|
93 |
+
color: {foreground};
|
94 |
+
background-color: {background};
|
95 |
+
}}
|
96 |
+
</style>
|
97 |
+
</head>
|
98 |
+
<html>
|
99 |
+
<body>
|
100 |
+
<code>
|
101 |
+
<pre style="font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
|
102 |
+
</code>
|
103 |
+
</body>
|
104 |
+
</html>
|
105 |
+
"""
|
106 |
+
|
107 |
+
_TERM_COLORS = {"256color": ColorSystem.EIGHT_BIT, "16color": ColorSystem.STANDARD}
|
108 |
+
|
109 |
+
|
110 |
+
class ConsoleDimensions(NamedTuple):
|
111 |
+
"""Size of the terminal."""
|
112 |
+
|
113 |
+
width: int
|
114 |
+
"""The width of the console in 'cells'."""
|
115 |
+
height: int
|
116 |
+
"""The height of the console in lines."""
|
117 |
+
|
118 |
+
|
119 |
+
@dataclass
|
120 |
+
class ConsoleOptions:
|
121 |
+
"""Options for __rich_console__ method."""
|
122 |
+
|
123 |
+
size: ConsoleDimensions
|
124 |
+
"""Size of console."""
|
125 |
+
legacy_windows: bool
|
126 |
+
"""legacy_windows: flag for legacy windows."""
|
127 |
+
min_width: int
|
128 |
+
"""Minimum width of renderable."""
|
129 |
+
max_width: int
|
130 |
+
"""Maximum width of renderable."""
|
131 |
+
is_terminal: bool
|
132 |
+
"""True if the target is a terminal, otherwise False."""
|
133 |
+
encoding: str
|
134 |
+
"""Encoding of terminal."""
|
135 |
+
max_height: int
|
136 |
+
"""Height of container (starts as terminal)"""
|
137 |
+
justify: Optional[JustifyMethod] = None
|
138 |
+
"""Justify value override for renderable."""
|
139 |
+
overflow: Optional[OverflowMethod] = None
|
140 |
+
"""Overflow value override for renderable."""
|
141 |
+
no_wrap: Optional[bool] = False
|
142 |
+
"""Disable wrapping for text."""
|
143 |
+
highlight: Optional[bool] = None
|
144 |
+
"""Highlight override for render_str."""
|
145 |
+
markup: Optional[bool] = None
|
146 |
+
"""Enable markup when rendering strings."""
|
147 |
+
height: Optional[int] = None
|
148 |
+
|
149 |
+
@property
|
150 |
+
def ascii_only(self) -> bool:
|
151 |
+
"""Check if renderables should use ascii only."""
|
152 |
+
return not self.encoding.startswith("utf")
|
153 |
+
|
154 |
+
def copy(self) -> "ConsoleOptions":
|
155 |
+
"""Return a copy of the options.
|
156 |
+
|
157 |
+
Returns:
|
158 |
+
ConsoleOptions: a copy of self.
|
159 |
+
"""
|
160 |
+
options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)
|
161 |
+
options.__dict__ = self.__dict__.copy()
|
162 |
+
return options
|
163 |
+
|
164 |
+
def update(
|
165 |
+
self,
|
166 |
+
*,
|
167 |
+
width: Union[int, NoChange] = NO_CHANGE,
|
168 |
+
min_width: Union[int, NoChange] = NO_CHANGE,
|
169 |
+
max_width: Union[int, NoChange] = NO_CHANGE,
|
170 |
+
justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE,
|
171 |
+
overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE,
|
172 |
+
no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE,
|
173 |
+
highlight: Union[Optional[bool], NoChange] = NO_CHANGE,
|
174 |
+
markup: Union[Optional[bool], NoChange] = NO_CHANGE,
|
175 |
+
height: Union[Optional[int], NoChange] = NO_CHANGE,
|
176 |
+
) -> "ConsoleOptions":
|
177 |
+
"""Update values, return a copy."""
|
178 |
+
options = self.copy()
|
179 |
+
if not isinstance(width, NoChange):
|
180 |
+
options.min_width = options.max_width = max(0, width)
|
181 |
+
if not isinstance(min_width, NoChange):
|
182 |
+
options.min_width = min_width
|
183 |
+
if not isinstance(max_width, NoChange):
|
184 |
+
options.max_width = max_width
|
185 |
+
if not isinstance(justify, NoChange):
|
186 |
+
options.justify = justify
|
187 |
+
if not isinstance(overflow, NoChange):
|
188 |
+
options.overflow = overflow
|
189 |
+
if not isinstance(no_wrap, NoChange):
|
190 |
+
options.no_wrap = no_wrap
|
191 |
+
if not isinstance(highlight, NoChange):
|
192 |
+
options.highlight = highlight
|
193 |
+
if not isinstance(markup, NoChange):
|
194 |
+
options.markup = markup
|
195 |
+
if not isinstance(height, NoChange):
|
196 |
+
if height is not None:
|
197 |
+
options.max_height = height
|
198 |
+
options.height = None if height is None else max(0, height)
|
199 |
+
return options
|
200 |
+
|
201 |
+
def update_width(self, width: int) -> "ConsoleOptions":
|
202 |
+
"""Update just the width, return a copy.
|
203 |
+
|
204 |
+
Args:
|
205 |
+
width (int): New width (sets both min_width and max_width)
|
206 |
+
|
207 |
+
Returns:
|
208 |
+
~ConsoleOptions: New console options instance.
|
209 |
+
"""
|
210 |
+
options = self.copy()
|
211 |
+
options.min_width = options.max_width = max(0, width)
|
212 |
+
return options
|
213 |
+
|
214 |
+
def update_height(self, height: int) -> "ConsoleOptions":
|
215 |
+
"""Update the height, and return a copy.
|
216 |
+
|
217 |
+
Args:
|
218 |
+
height (int): New height
|
219 |
+
|
220 |
+
Returns:
|
221 |
+
~ConsoleOptions: New Console options instance.
|
222 |
+
"""
|
223 |
+
options = self.copy()
|
224 |
+
options.max_height = options.height = height
|
225 |
+
return options
|
226 |
+
|
227 |
+
def update_dimensions(self, width: int, height: int) -> "ConsoleOptions":
|
228 |
+
"""Update the width and height, and return a copy.
|
229 |
+
|
230 |
+
Args:
|
231 |
+
width (int): New width (sets both min_width and max_width).
|
232 |
+
height (int): New height.
|
233 |
+
|
234 |
+
Returns:
|
235 |
+
~ConsoleOptions: New console options instance.
|
236 |
+
"""
|
237 |
+
options = self.copy()
|
238 |
+
options.min_width = options.max_width = max(0, width)
|
239 |
+
options.height = options.max_height = height
|
240 |
+
return options
|
241 |
+
|
242 |
+
|
243 |
+
@runtime_checkable
|
244 |
+
class RichCast(Protocol):
|
245 |
+
"""An object that may be 'cast' to a console renderable."""
|
246 |
+
|
247 |
+
def __rich__(self) -> Union["ConsoleRenderable", str]: # pragma: no cover
|
248 |
+
...
|
249 |
+
|
250 |
+
|
251 |
+
@runtime_checkable
|
252 |
+
class ConsoleRenderable(Protocol):
|
253 |
+
"""An object that supports the console protocol."""
|
254 |
+
|
255 |
+
def __rich_console__(
|
256 |
+
self, console: "Console", options: "ConsoleOptions"
|
257 |
+
) -> "RenderResult": # pragma: no cover
|
258 |
+
...
|
259 |
+
|
260 |
+
|
261 |
+
# A type that may be rendered by Console.
|
262 |
+
RenderableType = Union[ConsoleRenderable, RichCast, str]
|
263 |
+
|
264 |
+
|
265 |
+
# The result of calling a __rich_console__ method.
|
266 |
+
RenderResult = Iterable[Union[RenderableType, Segment]]
|
267 |
+
|
268 |
+
|
269 |
+
_null_highlighter = NullHighlighter()
|
270 |
+
|
271 |
+
|
272 |
+
class CaptureError(Exception):
|
273 |
+
"""An error in the Capture context manager."""
|
274 |
+
|
275 |
+
|
276 |
+
class NewLine:
|
277 |
+
"""A renderable to generate new line(s)"""
|
278 |
+
|
279 |
+
def __init__(self, count: int = 1) -> None:
|
280 |
+
self.count = count
|
281 |
+
|
282 |
+
def __rich_console__(
|
283 |
+
self, console: "Console", options: "ConsoleOptions"
|
284 |
+
) -> Iterable[Segment]:
|
285 |
+
yield Segment("\n" * self.count)
|
286 |
+
|
287 |
+
|
288 |
+
class ScreenUpdate:
|
289 |
+
"""Render a list of lines at a given offset."""
|
290 |
+
|
291 |
+
def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None:
|
292 |
+
self._lines = lines
|
293 |
+
self.x = x
|
294 |
+
self.y = y
|
295 |
+
|
296 |
+
def __rich_console__(
|
297 |
+
self, console: "Console", options: ConsoleOptions
|
298 |
+
) -> RenderResult:
|
299 |
+
x = self.x
|
300 |
+
move_to = Control.move_to
|
301 |
+
for offset, line in enumerate(self._lines, self.y):
|
302 |
+
yield move_to(x, offset)
|
303 |
+
yield from line
|
304 |
+
|
305 |
+
|
306 |
+
class Capture:
|
307 |
+
"""Context manager to capture the result of printing to the console.
|
308 |
+
See :meth:`~rich.console.Console.capture` for how to use.
|
309 |
+
|
310 |
+
Args:
|
311 |
+
console (Console): A console instance to capture output.
|
312 |
+
"""
|
313 |
+
|
314 |
+
def __init__(self, console: "Console") -> None:
|
315 |
+
self._console = console
|
316 |
+
self._result: Optional[str] = None
|
317 |
+
|
318 |
+
def __enter__(self) -> "Capture":
|
319 |
+
self._console.begin_capture()
|
320 |
+
return self
|
321 |
+
|
322 |
+
def __exit__(
|
323 |
+
self,
|
324 |
+
exc_type: Optional[Type[BaseException]],
|
325 |
+
exc_val: Optional[BaseException],
|
326 |
+
exc_tb: Optional[TracebackType],
|
327 |
+
) -> None:
|
328 |
+
self._result = self._console.end_capture()
|
329 |
+
|
330 |
+
def get(self) -> str:
|
331 |
+
"""Get the result of the capture."""
|
332 |
+
if self._result is None:
|
333 |
+
raise CaptureError(
|
334 |
+
"Capture result is not available until context manager exits."
|
335 |
+
)
|
336 |
+
return self._result
|
337 |
+
|
338 |
+
|
339 |
+
class ThemeContext:
|
340 |
+
"""A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage."""
|
341 |
+
|
342 |
+
def __init__(self, console: "Console", theme: Theme, inherit: bool = True) -> None:
|
343 |
+
self.console = console
|
344 |
+
self.theme = theme
|
345 |
+
self.inherit = inherit
|
346 |
+
|
347 |
+
def __enter__(self) -> "ThemeContext":
|
348 |
+
self.console.push_theme(self.theme)
|
349 |
+
return self
|
350 |
+
|
351 |
+
def __exit__(
|
352 |
+
self,
|
353 |
+
exc_type: Optional[Type[BaseException]],
|
354 |
+
exc_val: Optional[BaseException],
|
355 |
+
exc_tb: Optional[TracebackType],
|
356 |
+
) -> None:
|
357 |
+
self.console.pop_theme()
|
358 |
+
|
359 |
+
|
360 |
+
class PagerContext:
|
361 |
+
"""A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage."""
|
362 |
+
|
363 |
+
def __init__(
|
364 |
+
self,
|
365 |
+
console: "Console",
|
366 |
+
pager: Optional[Pager] = None,
|
367 |
+
styles: bool = False,
|
368 |
+
links: bool = False,
|
369 |
+
) -> None:
|
370 |
+
self._console = console
|
371 |
+
self.pager = SystemPager() if pager is None else pager
|
372 |
+
self.styles = styles
|
373 |
+
self.links = links
|
374 |
+
|
375 |
+
def __enter__(self) -> "PagerContext":
|
376 |
+
self._console._enter_buffer()
|
377 |
+
return self
|
378 |
+
|
379 |
+
def __exit__(
|
380 |
+
self,
|
381 |
+
exc_type: Optional[Type[BaseException]],
|
382 |
+
exc_val: Optional[BaseException],
|
383 |
+
exc_tb: Optional[TracebackType],
|
384 |
+
) -> None:
|
385 |
+
if exc_type is None:
|
386 |
+
with self._console._lock:
|
387 |
+
buffer: List[Segment] = self._console._buffer[:]
|
388 |
+
del self._console._buffer[:]
|
389 |
+
segments: Iterable[Segment] = buffer
|
390 |
+
if not self.styles:
|
391 |
+
segments = Segment.strip_styles(segments)
|
392 |
+
elif not self.links:
|
393 |
+
segments = Segment.strip_links(segments)
|
394 |
+
content = self._console._render_buffer(segments)
|
395 |
+
self.pager.show(content)
|
396 |
+
self._console._exit_buffer()
|
397 |
+
|
398 |
+
|
399 |
+
class ScreenContext:
|
400 |
+
"""A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage."""
|
401 |
+
|
402 |
+
def __init__(
|
403 |
+
self, console: "Console", hide_cursor: bool, style: StyleType = ""
|
404 |
+
) -> None:
|
405 |
+
self.console = console
|
406 |
+
self.hide_cursor = hide_cursor
|
407 |
+
self.screen = Screen(style=style)
|
408 |
+
self._changed = False
|
409 |
+
|
410 |
+
def update(
|
411 |
+
self, *renderables: RenderableType, style: Optional[StyleType] = None
|
412 |
+
) -> None:
|
413 |
+
"""Update the screen.
|
414 |
+
|
415 |
+
Args:
|
416 |
+
renderable (RenderableType, optional): Optional renderable to replace current renderable,
|
417 |
+
or None for no change. Defaults to None.
|
418 |
+
style: (Style, optional): Replacement style, or None for no change. Defaults to None.
|
419 |
+
"""
|
420 |
+
if renderables:
|
421 |
+
self.screen.renderable = (
|
422 |
+
Group(*renderables) if len(renderables) > 1 else renderables[0]
|
423 |
+
)
|
424 |
+
if style is not None:
|
425 |
+
self.screen.style = style
|
426 |
+
self.console.print(self.screen, end="")
|
427 |
+
|
428 |
+
def __enter__(self) -> "ScreenContext":
|
429 |
+
self._changed = self.console.set_alt_screen(True)
|
430 |
+
if self._changed and self.hide_cursor:
|
431 |
+
self.console.show_cursor(False)
|
432 |
+
return self
|
433 |
+
|
434 |
+
def __exit__(
|
435 |
+
self,
|
436 |
+
exc_type: Optional[Type[BaseException]],
|
437 |
+
exc_val: Optional[BaseException],
|
438 |
+
exc_tb: Optional[TracebackType],
|
439 |
+
) -> None:
|
440 |
+
if self._changed:
|
441 |
+
self.console.set_alt_screen(False)
|
442 |
+
if self.hide_cursor:
|
443 |
+
self.console.show_cursor(True)
|
444 |
+
|
445 |
+
|
446 |
+
class Group:
|
447 |
+
"""Takes a group of renderables and returns a renderable object that renders the group.
|
448 |
+
|
449 |
+
Args:
|
450 |
+
renderables (Iterable[RenderableType]): An iterable of renderable objects.
|
451 |
+
fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
|
452 |
+
"""
|
453 |
+
|
454 |
+
def __init__(self, *renderables: "RenderableType", fit: bool = True) -> None:
|
455 |
+
self._renderables = renderables
|
456 |
+
self.fit = fit
|
457 |
+
self._render: Optional[List[RenderableType]] = None
|
458 |
+
|
459 |
+
@property
|
460 |
+
def renderables(self) -> List["RenderableType"]:
|
461 |
+
if self._render is None:
|
462 |
+
self._render = list(self._renderables)
|
463 |
+
return self._render
|
464 |
+
|
465 |
+
def __rich_measure__(
|
466 |
+
self, console: "Console", options: "ConsoleOptions"
|
467 |
+
) -> "Measurement":
|
468 |
+
if self.fit:
|
469 |
+
return measure_renderables(console, options, self.renderables)
|
470 |
+
else:
|
471 |
+
return Measurement(options.max_width, options.max_width)
|
472 |
+
|
473 |
+
def __rich_console__(
|
474 |
+
self, console: "Console", options: "ConsoleOptions"
|
475 |
+
) -> RenderResult:
|
476 |
+
yield from self.renderables
|
477 |
+
|
478 |
+
|
479 |
+
def group(fit: bool = True) -> Callable[..., Callable[..., Group]]:
|
480 |
+
"""A decorator that turns an iterable of renderables in to a group.
|
481 |
+
|
482 |
+
Args:
|
483 |
+
fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.
|
484 |
+
"""
|
485 |
+
|
486 |
+
def decorator(
|
487 |
+
method: Callable[..., Iterable[RenderableType]]
|
488 |
+
) -> Callable[..., Group]:
|
489 |
+
"""Convert a method that returns an iterable of renderables in to a Group."""
|
490 |
+
|
491 |
+
@wraps(method)
|
492 |
+
def _replace(*args: Any, **kwargs: Any) -> Group:
|
493 |
+
renderables = method(*args, **kwargs)
|
494 |
+
return Group(*renderables, fit=fit)
|
495 |
+
|
496 |
+
return _replace
|
497 |
+
|
498 |
+
return decorator
|
499 |
+
|
500 |
+
|
501 |
+
def _is_jupyter() -> bool: # pragma: no cover
|
502 |
+
"""Check if we're running in a Jupyter notebook."""
|
503 |
+
try:
|
504 |
+
get_ipython # type: ignore
|
505 |
+
except NameError:
|
506 |
+
return False
|
507 |
+
ipython = get_ipython() # type: ignore
|
508 |
+
shell = ipython.__class__.__name__
|
509 |
+
if "google.colab" in str(ipython.__class__) or shell == "ZMQInteractiveShell":
|
510 |
+
return True # Jupyter notebook or qtconsole
|
511 |
+
elif shell == "TerminalInteractiveShell":
|
512 |
+
return False # Terminal running IPython
|
513 |
+
else:
|
514 |
+
return False # Other type (?)
|
515 |
+
|
516 |
+
|
517 |
+
COLOR_SYSTEMS = {
|
518 |
+
"standard": ColorSystem.STANDARD,
|
519 |
+
"256": ColorSystem.EIGHT_BIT,
|
520 |
+
"truecolor": ColorSystem.TRUECOLOR,
|
521 |
+
"windows": ColorSystem.WINDOWS,
|
522 |
+
}
|
523 |
+
|
524 |
+
|
525 |
+
_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}
|
526 |
+
|
527 |
+
|
528 |
+
@dataclass
|
529 |
+
class ConsoleThreadLocals(threading.local):
|
530 |
+
"""Thread local values for Console context."""
|
531 |
+
|
532 |
+
theme_stack: ThemeStack
|
533 |
+
buffer: List[Segment] = field(default_factory=list)
|
534 |
+
buffer_index: int = 0
|
535 |
+
|
536 |
+
|
537 |
+
class RenderHook(ABC):
|
538 |
+
"""Provides hooks in to the render process."""
|
539 |
+
|
540 |
+
@abstractmethod
|
541 |
+
def process_renderables(
|
542 |
+
self, renderables: List[ConsoleRenderable]
|
543 |
+
) -> List[ConsoleRenderable]:
|
544 |
+
"""Called with a list of objects to render.
|
545 |
+
|
546 |
+
This method can return a new list of renderables, or modify and return the same list.
|
547 |
+
|
548 |
+
Args:
|
549 |
+
renderables (List[ConsoleRenderable]): A number of renderable objects.
|
550 |
+
|
551 |
+
Returns:
|
552 |
+
List[ConsoleRenderable]: A replacement list of renderables.
|
553 |
+
"""
|
554 |
+
|
555 |
+
|
556 |
+
_windows_console_features: Optional["WindowsConsoleFeatures"] = None
|
557 |
+
|
558 |
+
|
559 |
+
def get_windows_console_features() -> "WindowsConsoleFeatures": # pragma: no cover
|
560 |
+
global _windows_console_features
|
561 |
+
if _windows_console_features is not None:
|
562 |
+
return _windows_console_features
|
563 |
+
from ._windows import get_windows_console_features
|
564 |
+
|
565 |
+
_windows_console_features = get_windows_console_features()
|
566 |
+
return _windows_console_features
|
567 |
+
|
568 |
+
|
569 |
+
def detect_legacy_windows() -> bool:
|
570 |
+
"""Detect legacy Windows."""
|
571 |
+
return WINDOWS and not get_windows_console_features().vt
|
572 |
+
|
573 |
+
|
574 |
+
if detect_legacy_windows(): # pragma: no cover
|
575 |
+
from pip._vendor.colorama import init
|
576 |
+
|
577 |
+
init(strip=False)
|
578 |
+
|
579 |
+
|
580 |
+
class Console:
|
581 |
+
"""A high level console interface.
|
582 |
+
|
583 |
+
Args:
|
584 |
+
color_system (str, optional): The color system supported by your terminal,
|
585 |
+
either ``"standard"``, ``"256"`` or ``"truecolor"``. Leave as ``"auto"`` to autodetect.
|
586 |
+
force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.
|
587 |
+
force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.
|
588 |
+
force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None.
|
589 |
+
soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False.
|
590 |
+
theme (Theme, optional): An optional style theme object, or ``None`` for default theme.
|
591 |
+
stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False.
|
592 |
+
file (IO, optional): A file object where the console should write to. Defaults to stdout.
|
593 |
+
quiet (bool, Optional): Boolean to suppress all output. Defaults to False.
|
594 |
+
width (int, optional): The width of the terminal. Leave as default to auto-detect width.
|
595 |
+
height (int, optional): The height of the terminal. Leave as default to auto-detect height.
|
596 |
+
style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.
|
597 |
+
no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None.
|
598 |
+
tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8.
|
599 |
+
record (bool, optional): Boolean to enable recording of terminal output,
|
600 |
+
required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.
|
601 |
+
markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.
|
602 |
+
emoji (bool, optional): Enable emoji code. Defaults to True.
|
603 |
+
emoji_variant (str, optional): Optional emoji variant, either "text" or "emoji". Defaults to None.
|
604 |
+
highlight (bool, optional): Enable automatic highlighting. Defaults to True.
|
605 |
+
log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.
|
606 |
+
log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.
|
607 |
+
log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%X] ".
|
608 |
+
highlighter (HighlighterType, optional): Default highlighter.
|
609 |
+
legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.
|
610 |
+
safe_box (bool, optional): Restrict box options that don't render on legacy Windows.
|
611 |
+
get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log),
|
612 |
+
or None for datetime.now.
|
613 |
+
get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic.
|
614 |
+
"""
|
615 |
+
|
616 |
+
_environ: Mapping[str, str] = os.environ
|
617 |
+
|
618 |
+
def __init__(
|
619 |
+
self,
|
620 |
+
*,
|
621 |
+
color_system: Optional[
|
622 |
+
Literal["auto", "standard", "256", "truecolor", "windows"]
|
623 |
+
] = "auto",
|
624 |
+
force_terminal: Optional[bool] = None,
|
625 |
+
force_jupyter: Optional[bool] = None,
|
626 |
+
force_interactive: Optional[bool] = None,
|
627 |
+
soft_wrap: bool = False,
|
628 |
+
theme: Optional[Theme] = None,
|
629 |
+
stderr: bool = False,
|
630 |
+
file: Optional[IO[str]] = None,
|
631 |
+
quiet: bool = False,
|
632 |
+
width: Optional[int] = None,
|
633 |
+
height: Optional[int] = None,
|
634 |
+
style: Optional[StyleType] = None,
|
635 |
+
no_color: Optional[bool] = None,
|
636 |
+
tab_size: int = 8,
|
637 |
+
record: bool = False,
|
638 |
+
markup: bool = True,
|
639 |
+
emoji: bool = True,
|
640 |
+
emoji_variant: Optional[EmojiVariant] = None,
|
641 |
+
highlight: bool = True,
|
642 |
+
log_time: bool = True,
|
643 |
+
log_path: bool = True,
|
644 |
+
log_time_format: Union[str, FormatTimeCallable] = "[%X]",
|
645 |
+
highlighter: Optional["HighlighterType"] = ReprHighlighter(),
|
646 |
+
legacy_windows: Optional[bool] = None,
|
647 |
+
safe_box: bool = True,
|
648 |
+
get_datetime: Optional[Callable[[], datetime]] = None,
|
649 |
+
get_time: Optional[Callable[[], float]] = None,
|
650 |
+
_environ: Optional[Mapping[str, str]] = None,
|
651 |
+
):
|
652 |
+
# Copy of os.environ allows us to replace it for testing
|
653 |
+
if _environ is not None:
|
654 |
+
self._environ = _environ
|
655 |
+
|
656 |
+
self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter
|
657 |
+
if self.is_jupyter:
|
658 |
+
width = width or 93
|
659 |
+
height = height or 100
|
660 |
+
|
661 |
+
self.soft_wrap = soft_wrap
|
662 |
+
self._width = width
|
663 |
+
self._height = height
|
664 |
+
self.tab_size = tab_size
|
665 |
+
self.record = record
|
666 |
+
self._markup = markup
|
667 |
+
self._emoji = emoji
|
668 |
+
self._emoji_variant: Optional[EmojiVariant] = emoji_variant
|
669 |
+
self._highlight = highlight
|
670 |
+
self.legacy_windows: bool = (
|
671 |
+
(detect_legacy_windows() and not self.is_jupyter)
|
672 |
+
if legacy_windows is None
|
673 |
+
else legacy_windows
|
674 |
+
)
|
675 |
+
if width is None:
|
676 |
+
columns = self._environ.get("COLUMNS")
|
677 |
+
if columns is not None and columns.isdigit():
|
678 |
+
width = int(columns) - self.legacy_windows
|
679 |
+
if height is None:
|
680 |
+
lines = self._environ.get("LINES")
|
681 |
+
if lines is not None and lines.isdigit():
|
682 |
+
height = int(lines)
|
683 |
+
|
684 |
+
self.soft_wrap = soft_wrap
|
685 |
+
self._width = width
|
686 |
+
self._height = height
|
687 |
+
|
688 |
+
self._color_system: Optional[ColorSystem]
|
689 |
+
self._force_terminal = force_terminal
|
690 |
+
self._file = file
|
691 |
+
self.quiet = quiet
|
692 |
+
self.stderr = stderr
|
693 |
+
|
694 |
+
if color_system is None:
|
695 |
+
self._color_system = None
|
696 |
+
elif color_system == "auto":
|
697 |
+
self._color_system = self._detect_color_system()
|
698 |
+
else:
|
699 |
+
self._color_system = COLOR_SYSTEMS[color_system]
|
700 |
+
|
701 |
+
self._lock = threading.RLock()
|
702 |
+
self._log_render = LogRender(
|
703 |
+
show_time=log_time,
|
704 |
+
show_path=log_path,
|
705 |
+
time_format=log_time_format,
|
706 |
+
)
|
707 |
+
self.highlighter: HighlighterType = highlighter or _null_highlighter
|
708 |
+
self.safe_box = safe_box
|
709 |
+
self.get_datetime = get_datetime or datetime.now
|
710 |
+
self.get_time = get_time or monotonic
|
711 |
+
self.style = style
|
712 |
+
self.no_color = (
|
713 |
+
no_color if no_color is not None else "NO_COLOR" in self._environ
|
714 |
+
)
|
715 |
+
self.is_interactive = (
|
716 |
+
(self.is_terminal and not self.is_dumb_terminal)
|
717 |
+
if force_interactive is None
|
718 |
+
else force_interactive
|
719 |
+
)
|
720 |
+
|
721 |
+
self._record_buffer_lock = threading.RLock()
|
722 |
+
self._thread_locals = ConsoleThreadLocals(
|
723 |
+
theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme)
|
724 |
+
)
|
725 |
+
self._record_buffer: List[Segment] = []
|
726 |
+
self._render_hooks: List[RenderHook] = []
|
727 |
+
self._live: Optional["Live"] = None
|
728 |
+
self._is_alt_screen = False
|
729 |
+
|
730 |
+
def __repr__(self) -> str:
|
731 |
+
return f"<console width={self.width} {str(self._color_system)}>"
|
732 |
+
|
733 |
+
@property
|
734 |
+
def file(self) -> IO[str]:
|
735 |
+
"""Get the file object to write to."""
|
736 |
+
file = self._file or (sys.stderr if self.stderr else sys.stdout)
|
737 |
+
file = getattr(file, "rich_proxied_file", file)
|
738 |
+
return file
|
739 |
+
|
740 |
+
@file.setter
|
741 |
+
def file(self, new_file: IO[str]) -> None:
|
742 |
+
"""Set a new file object."""
|
743 |
+
self._file = new_file
|
744 |
+
|
745 |
+
@property
|
746 |
+
def _buffer(self) -> List[Segment]:
|
747 |
+
"""Get a thread local buffer."""
|
748 |
+
return self._thread_locals.buffer
|
749 |
+
|
750 |
+
@property
|
751 |
+
def _buffer_index(self) -> int:
|
752 |
+
"""Get a thread local buffer."""
|
753 |
+
return self._thread_locals.buffer_index
|
754 |
+
|
755 |
+
@_buffer_index.setter
|
756 |
+
def _buffer_index(self, value: int) -> None:
|
757 |
+
self._thread_locals.buffer_index = value
|
758 |
+
|
759 |
+
@property
|
760 |
+
def _theme_stack(self) -> ThemeStack:
|
761 |
+
"""Get the thread local theme stack."""
|
762 |
+
return self._thread_locals.theme_stack
|
763 |
+
|
764 |
+
def _detect_color_system(self) -> Optional[ColorSystem]:
|
765 |
+
"""Detect color system from env vars."""
|
766 |
+
if self.is_jupyter:
|
767 |
+
return ColorSystem.TRUECOLOR
|
768 |
+
if not self.is_terminal or self.is_dumb_terminal:
|
769 |
+
return None
|
770 |
+
if WINDOWS: # pragma: no cover
|
771 |
+
if self.legacy_windows: # pragma: no cover
|
772 |
+
return ColorSystem.WINDOWS
|
773 |
+
windows_console_features = get_windows_console_features()
|
774 |
+
return (
|
775 |
+
ColorSystem.TRUECOLOR
|
776 |
+
if windows_console_features.truecolor
|
777 |
+
else ColorSystem.EIGHT_BIT
|
778 |
+
)
|
779 |
+
else:
|
780 |
+
color_term = self._environ.get("COLORTERM", "").strip().lower()
|
781 |
+
if color_term in ("truecolor", "24bit"):
|
782 |
+
return ColorSystem.TRUECOLOR
|
783 |
+
term = self._environ.get("TERM", "").strip().lower()
|
784 |
+
_term_name, _hyphen, colors = term.rpartition("-")
|
785 |
+
color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD)
|
786 |
+
return color_system
|
787 |
+
|
788 |
+
def _enter_buffer(self) -> None:
|
789 |
+
"""Enter in to a buffer context, and buffer all output."""
|
790 |
+
self._buffer_index += 1
|
791 |
+
|
792 |
+
def _exit_buffer(self) -> None:
|
793 |
+
"""Leave buffer context, and render content if required."""
|
794 |
+
self._buffer_index -= 1
|
795 |
+
self._check_buffer()
|
796 |
+
|
797 |
+
def set_live(self, live: "Live") -> None:
|
798 |
+
"""Set Live instance. Used by Live context manager.
|
799 |
+
|
800 |
+
Args:
|
801 |
+
live (Live): Live instance using this Console.
|
802 |
+
|
803 |
+
Raises:
|
804 |
+
errors.LiveError: If this Console has a Live context currently active.
|
805 |
+
"""
|
806 |
+
with self._lock:
|
807 |
+
if self._live is not None:
|
808 |
+
raise errors.LiveError("Only one live display may be active at once")
|
809 |
+
self._live = live
|
810 |
+
|
811 |
+
def clear_live(self) -> None:
|
812 |
+
"""Clear the Live instance."""
|
813 |
+
with self._lock:
|
814 |
+
self._live = None
|
815 |
+
|
816 |
+
def push_render_hook(self, hook: RenderHook) -> None:
|
817 |
+
"""Add a new render hook to the stack.
|
818 |
+
|
819 |
+
Args:
|
820 |
+
hook (RenderHook): Render hook instance.
|
821 |
+
"""
|
822 |
+
with self._lock:
|
823 |
+
self._render_hooks.append(hook)
|
824 |
+
|
825 |
+
def pop_render_hook(self) -> None:
|
826 |
+
"""Pop the last renderhook from the stack."""
|
827 |
+
with self._lock:
|
828 |
+
self._render_hooks.pop()
|
829 |
+
|
830 |
+
def __enter__(self) -> "Console":
|
831 |
+
"""Own context manager to enter buffer context."""
|
832 |
+
self._enter_buffer()
|
833 |
+
return self
|
834 |
+
|
835 |
+
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
836 |
+
"""Exit buffer context."""
|
837 |
+
self._exit_buffer()
|
838 |
+
|
839 |
+
def begin_capture(self) -> None:
|
840 |
+
"""Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output."""
|
841 |
+
self._enter_buffer()
|
842 |
+
|
843 |
+
def end_capture(self) -> str:
|
844 |
+
"""End capture mode and return captured string.
|
845 |
+
|
846 |
+
Returns:
|
847 |
+
str: Console output.
|
848 |
+
"""
|
849 |
+
render_result = self._render_buffer(self._buffer)
|
850 |
+
del self._buffer[:]
|
851 |
+
self._exit_buffer()
|
852 |
+
return render_result
|
853 |
+
|
854 |
+
def push_theme(self, theme: Theme, *, inherit: bool = True) -> None:
|
855 |
+
"""Push a new theme on to the top of the stack, replacing the styles from the previous theme.
|
856 |
+
Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather
|
857 |
+
than calling this method directly.
|
858 |
+
|
859 |
+
Args:
|
860 |
+
theme (Theme): A theme instance.
|
861 |
+
inherit (bool, optional): Inherit existing styles. Defaults to True.
|
862 |
+
"""
|
863 |
+
self._theme_stack.push_theme(theme, inherit=inherit)
|
864 |
+
|
865 |
+
def pop_theme(self) -> None:
|
866 |
+
"""Remove theme from top of stack, restoring previous theme."""
|
867 |
+
self._theme_stack.pop_theme()
|
868 |
+
|
869 |
+
def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext:
|
870 |
+
"""Use a different theme for the duration of the context manager.
|
871 |
+
|
872 |
+
Args:
|
873 |
+
theme (Theme): Theme instance to user.
|
874 |
+
inherit (bool, optional): Inherit existing console styles. Defaults to True.
|
875 |
+
|
876 |
+
Returns:
|
877 |
+
ThemeContext: [description]
|
878 |
+
"""
|
879 |
+
return ThemeContext(self, theme, inherit)
|
880 |
+
|
881 |
+
@property
|
882 |
+
def color_system(self) -> Optional[str]:
|
883 |
+
"""Get color system string.
|
884 |
+
|
885 |
+
Returns:
|
886 |
+
Optional[str]: "standard", "256" or "truecolor".
|
887 |
+
"""
|
888 |
+
|
889 |
+
if self._color_system is not None:
|
890 |
+
return _COLOR_SYSTEMS_NAMES[self._color_system]
|
891 |
+
else:
|
892 |
+
return None
|
893 |
+
|
894 |
+
@property
|
895 |
+
def encoding(self) -> str:
|
896 |
+
"""Get the encoding of the console file, e.g. ``"utf-8"``.
|
897 |
+
|
898 |
+
Returns:
|
899 |
+
str: A standard encoding string.
|
900 |
+
"""
|
901 |
+
return (getattr(self.file, "encoding", "utf-8") or "utf-8").lower()
|
902 |
+
|
903 |
+
@property
|
904 |
+
def is_terminal(self) -> bool:
|
905 |
+
"""Check if the console is writing to a terminal.
|
906 |
+
|
907 |
+
Returns:
|
908 |
+
bool: True if the console writing to a device capable of
|
909 |
+
understanding terminal codes, otherwise False.
|
910 |
+
"""
|
911 |
+
if self._force_terminal is not None:
|
912 |
+
return self._force_terminal
|
913 |
+
isatty: Optional[Callable[[], bool]] = getattr(self.file, "isatty", None)
|
914 |
+
try:
|
915 |
+
return False if isatty is None else isatty()
|
916 |
+
except ValueError:
|
917 |
+
# in some situation (at the end of a pytest run for example) isatty() can raise
|
918 |
+
# ValueError: I/O operation on closed file
|
919 |
+
# return False because we aren't in a terminal anymore
|
920 |
+
return False
|
921 |
+
|
922 |
+
@property
|
923 |
+
def is_dumb_terminal(self) -> bool:
|
924 |
+
"""Detect dumb terminal.
|
925 |
+
|
926 |
+
Returns:
|
927 |
+
bool: True if writing to a dumb terminal, otherwise False.
|
928 |
+
|
929 |
+
"""
|
930 |
+
_term = self._environ.get("TERM", "")
|
931 |
+
is_dumb = _term.lower() in ("dumb", "unknown")
|
932 |
+
return self.is_terminal and is_dumb
|
933 |
+
|
934 |
+
@property
|
935 |
+
def options(self) -> ConsoleOptions:
|
936 |
+
"""Get default console options."""
|
937 |
+
return ConsoleOptions(
|
938 |
+
max_height=self.size.height,
|
939 |
+
size=self.size,
|
940 |
+
legacy_windows=self.legacy_windows,
|
941 |
+
min_width=1,
|
942 |
+
max_width=self.width,
|
943 |
+
encoding=self.encoding,
|
944 |
+
is_terminal=self.is_terminal,
|
945 |
+
)
|
946 |
+
|
947 |
+
@property
|
948 |
+
def size(self) -> ConsoleDimensions:
|
949 |
+
"""Get the size of the console.
|
950 |
+
|
951 |
+
Returns:
|
952 |
+
ConsoleDimensions: A named tuple containing the dimensions.
|
953 |
+
"""
|
954 |
+
|
955 |
+
if self._width is not None and self._height is not None:
|
956 |
+
return ConsoleDimensions(self._width - self.legacy_windows, self._height)
|
957 |
+
|
958 |
+
if self.is_dumb_terminal:
|
959 |
+
return ConsoleDimensions(80, 25)
|
960 |
+
|
961 |
+
width: Optional[int] = None
|
962 |
+
height: Optional[int] = None
|
963 |
+
|
964 |
+
if WINDOWS: # pragma: no cover
|
965 |
+
try:
|
966 |
+
width, height = os.get_terminal_size()
|
967 |
+
except OSError: # Probably not a terminal
|
968 |
+
pass
|
969 |
+
else:
|
970 |
+
try:
|
971 |
+
width, height = os.get_terminal_size(sys.__stdin__.fileno())
|
972 |
+
except (AttributeError, ValueError, OSError):
|
973 |
+
try:
|
974 |
+
width, height = os.get_terminal_size(sys.__stdout__.fileno())
|
975 |
+
except (AttributeError, ValueError, OSError):
|
976 |
+
pass
|
977 |
+
|
978 |
+
columns = self._environ.get("COLUMNS")
|
979 |
+
if columns is not None and columns.isdigit():
|
980 |
+
width = int(columns)
|
981 |
+
lines = self._environ.get("LINES")
|
982 |
+
if lines is not None and lines.isdigit():
|
983 |
+
height = int(lines)
|
984 |
+
|
985 |
+
# get_terminal_size can report 0, 0 if run from pseudo-terminal
|
986 |
+
width = width or 80
|
987 |
+
height = height or 25
|
988 |
+
return ConsoleDimensions(
|
989 |
+
width - self.legacy_windows if self._width is None else self._width,
|
990 |
+
height if self._height is None else self._height,
|
991 |
+
)
|
992 |
+
|
993 |
+
@size.setter
|
994 |
+
def size(self, new_size: Tuple[int, int]) -> None:
|
995 |
+
"""Set a new size for the terminal.
|
996 |
+
|
997 |
+
Args:
|
998 |
+
new_size (Tuple[int, int]): New width and height.
|
999 |
+
"""
|
1000 |
+
width, height = new_size
|
1001 |
+
self._width = width
|
1002 |
+
self._height = height
|
1003 |
+
|
1004 |
+
@property
|
1005 |
+
def width(self) -> int:
|
1006 |
+
"""Get the width of the console.
|
1007 |
+
|
1008 |
+
Returns:
|
1009 |
+
int: The width (in characters) of the console.
|
1010 |
+
"""
|
1011 |
+
return self.size.width
|
1012 |
+
|
1013 |
+
@width.setter
|
1014 |
+
def width(self, width: int) -> None:
|
1015 |
+
"""Set width.
|
1016 |
+
|
1017 |
+
Args:
|
1018 |
+
width (int): New width.
|
1019 |
+
"""
|
1020 |
+
self._width = width
|
1021 |
+
|
1022 |
+
@property
|
1023 |
+
def height(self) -> int:
|
1024 |
+
"""Get the height of the console.
|
1025 |
+
|
1026 |
+
Returns:
|
1027 |
+
int: The height (in lines) of the console.
|
1028 |
+
"""
|
1029 |
+
return self.size.height
|
1030 |
+
|
1031 |
+
@height.setter
|
1032 |
+
def height(self, height: int) -> None:
|
1033 |
+
"""Set height.
|
1034 |
+
|
1035 |
+
Args:
|
1036 |
+
height (int): new height.
|
1037 |
+
"""
|
1038 |
+
self._height = height
|
1039 |
+
|
1040 |
+
def bell(self) -> None:
|
1041 |
+
"""Play a 'bell' sound (if supported by the terminal)."""
|
1042 |
+
self.control(Control.bell())
|
1043 |
+
|
1044 |
+
def capture(self) -> Capture:
|
1045 |
+
"""A context manager to *capture* the result of print() or log() in a string,
|
1046 |
+
rather than writing it to the console.
|
1047 |
+
|
1048 |
+
Example:
|
1049 |
+
>>> from rich.console import Console
|
1050 |
+
>>> console = Console()
|
1051 |
+
>>> with console.capture() as capture:
|
1052 |
+
... console.print("[bold magenta]Hello World[/]")
|
1053 |
+
>>> print(capture.get())
|
1054 |
+
|
1055 |
+
Returns:
|
1056 |
+
Capture: Context manager with disables writing to the terminal.
|
1057 |
+
"""
|
1058 |
+
capture = Capture(self)
|
1059 |
+
return capture
|
1060 |
+
|
1061 |
+
def pager(
|
1062 |
+
self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False
|
1063 |
+
) -> PagerContext:
|
1064 |
+
"""A context manager to display anything printed within a "pager". The pager application
|
1065 |
+
is defined by the system and will typically support at least pressing a key to scroll.
|
1066 |
+
|
1067 |
+
Args:
|
1068 |
+
pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None.
|
1069 |
+
styles (bool, optional): Show styles in pager. Defaults to False.
|
1070 |
+
links (bool, optional): Show links in pager. Defaults to False.
|
1071 |
+
|
1072 |
+
Example:
|
1073 |
+
>>> from rich.console import Console
|
1074 |
+
>>> from rich.__main__ import make_test_card
|
1075 |
+
>>> console = Console()
|
1076 |
+
>>> with console.pager():
|
1077 |
+
console.print(make_test_card())
|
1078 |
+
|
1079 |
+
Returns:
|
1080 |
+
PagerContext: A context manager.
|
1081 |
+
"""
|
1082 |
+
return PagerContext(self, pager=pager, styles=styles, links=links)
|
1083 |
+
|
1084 |
+
def line(self, count: int = 1) -> None:
|
1085 |
+
"""Write new line(s).
|
1086 |
+
|
1087 |
+
Args:
|
1088 |
+
count (int, optional): Number of new lines. Defaults to 1.
|
1089 |
+
"""
|
1090 |
+
|
1091 |
+
assert count >= 0, "count must be >= 0"
|
1092 |
+
self.print(NewLine(count))
|
1093 |
+
|
1094 |
+
def clear(self, home: bool = True) -> None:
|
1095 |
+
"""Clear the screen.
|
1096 |
+
|
1097 |
+
Args:
|
1098 |
+
home (bool, optional): Also move the cursor to 'home' position. Defaults to True.
|
1099 |
+
"""
|
1100 |
+
if home:
|
1101 |
+
self.control(Control.clear(), Control.home())
|
1102 |
+
else:
|
1103 |
+
self.control(Control.clear())
|
1104 |
+
|
1105 |
+
def status(
|
1106 |
+
self,
|
1107 |
+
status: RenderableType,
|
1108 |
+
*,
|
1109 |
+
spinner: str = "dots",
|
1110 |
+
spinner_style: str = "status.spinner",
|
1111 |
+
speed: float = 1.0,
|
1112 |
+
refresh_per_second: float = 12.5,
|
1113 |
+
) -> "Status":
|
1114 |
+
"""Display a status and spinner.
|
1115 |
+
|
1116 |
+
Args:
|
1117 |
+
status (RenderableType): A status renderable (str or Text typically).
|
1118 |
+
spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to "dots".
|
1119 |
+
spinner_style (StyleType, optional): Style of spinner. Defaults to "status.spinner".
|
1120 |
+
speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.
|
1121 |
+
refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.
|
1122 |
+
|
1123 |
+
Returns:
|
1124 |
+
Status: A Status object that may be used as a context manager.
|
1125 |
+
"""
|
1126 |
+
from .status import Status
|
1127 |
+
|
1128 |
+
status_renderable = Status(
|
1129 |
+
status,
|
1130 |
+
console=self,
|
1131 |
+
spinner=spinner,
|
1132 |
+
spinner_style=spinner_style,
|
1133 |
+
speed=speed,
|
1134 |
+
refresh_per_second=refresh_per_second,
|
1135 |
+
)
|
1136 |
+
return status_renderable
|
1137 |
+
|
1138 |
+
def show_cursor(self, show: bool = True) -> bool:
|
1139 |
+
"""Show or hide the cursor.
|
1140 |
+
|
1141 |
+
Args:
|
1142 |
+
show (bool, optional): Set visibility of the cursor.
|
1143 |
+
"""
|
1144 |
+
if self.is_terminal and not self.legacy_windows:
|
1145 |
+
self.control(Control.show_cursor(show))
|
1146 |
+
return True
|
1147 |
+
return False
|
1148 |
+
|
1149 |
+
def set_alt_screen(self, enable: bool = True) -> bool:
|
1150 |
+
"""Enables alternative screen mode.
|
1151 |
+
|
1152 |
+
Note, if you enable this mode, you should ensure that is disabled before
|
1153 |
+
the application exits. See :meth:`~rich.Console.screen` for a context manager
|
1154 |
+
that handles this for you.
|
1155 |
+
|
1156 |
+
Args:
|
1157 |
+
enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True.
|
1158 |
+
|
1159 |
+
Returns:
|
1160 |
+
bool: True if the control codes were written.
|
1161 |
+
|
1162 |
+
"""
|
1163 |
+
changed = False
|
1164 |
+
if self.is_terminal and not self.legacy_windows:
|
1165 |
+
self.control(Control.alt_screen(enable))
|
1166 |
+
changed = True
|
1167 |
+
self._is_alt_screen = enable
|
1168 |
+
return changed
|
1169 |
+
|
1170 |
+
@property
|
1171 |
+
def is_alt_screen(self) -> bool:
|
1172 |
+
"""Check if the alt screen was enabled.
|
1173 |
+
|
1174 |
+
Returns:
|
1175 |
+
bool: True if the alt screen was enabled, otherwise False.
|
1176 |
+
"""
|
1177 |
+
return self._is_alt_screen
|
1178 |
+
|
1179 |
+
def screen(
|
1180 |
+
self, hide_cursor: bool = True, style: Optional[StyleType] = None
|
1181 |
+
) -> "ScreenContext":
|
1182 |
+
"""Context manager to enable and disable 'alternative screen' mode.
|
1183 |
+
|
1184 |
+
Args:
|
1185 |
+
hide_cursor (bool, optional): Also hide the cursor. Defaults to False.
|
1186 |
+
style (Style, optional): Optional style for screen. Defaults to None.
|
1187 |
+
|
1188 |
+
Returns:
|
1189 |
+
~ScreenContext: Context which enables alternate screen on enter, and disables it on exit.
|
1190 |
+
"""
|
1191 |
+
return ScreenContext(self, hide_cursor=hide_cursor, style=style or "")
|
1192 |
+
|
1193 |
+
def measure(
|
1194 |
+
self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None
|
1195 |
+
) -> Measurement:
|
1196 |
+
"""Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains
|
1197 |
+
information regarding the number of characters required to print the renderable.
|
1198 |
+
|
1199 |
+
Args:
|
1200 |
+
renderable (RenderableType): Any renderable or string.
|
1201 |
+
options (Optional[ConsoleOptions], optional): Options to use when measuring, or None
|
1202 |
+
to use default options. Defaults to None.
|
1203 |
+
|
1204 |
+
Returns:
|
1205 |
+
Measurement: A measurement of the renderable.
|
1206 |
+
"""
|
1207 |
+
measurement = Measurement.get(self, options or self.options, renderable)
|
1208 |
+
return measurement
|
1209 |
+
|
1210 |
+
def render(
|
1211 |
+
self, renderable: RenderableType, options: Optional[ConsoleOptions] = None
|
1212 |
+
) -> Iterable[Segment]:
|
1213 |
+
"""Render an object in to an iterable of `Segment` instances.
|
1214 |
+
|
1215 |
+
This method contains the logic for rendering objects with the console protocol.
|
1216 |
+
You are unlikely to need to use it directly, unless you are extending the library.
|
1217 |
+
|
1218 |
+
Args:
|
1219 |
+
renderable (RenderableType): An object supporting the console protocol, or
|
1220 |
+
an object that may be converted to a string.
|
1221 |
+
options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.
|
1222 |
+
|
1223 |
+
Returns:
|
1224 |
+
Iterable[Segment]: An iterable of segments that may be rendered.
|
1225 |
+
"""
|
1226 |
+
|
1227 |
+
_options = options or self.options
|
1228 |
+
if _options.max_width < 1:
|
1229 |
+
# No space to render anything. This prevents potential recursion errors.
|
1230 |
+
return
|
1231 |
+
render_iterable: RenderResult
|
1232 |
+
|
1233 |
+
renderable = rich_cast(renderable)
|
1234 |
+
if hasattr(renderable, "__rich_console__") and not isclass(renderable):
|
1235 |
+
render_iterable = renderable.__rich_console__(self, _options) # type: ignore
|
1236 |
+
elif isinstance(renderable, str):
|
1237 |
+
text_renderable = self.render_str(
|
1238 |
+
renderable, highlight=_options.highlight, markup=_options.markup
|
1239 |
+
)
|
1240 |
+
render_iterable = text_renderable.__rich_console__(self, _options)
|
1241 |
+
else:
|
1242 |
+
raise errors.NotRenderableError(
|
1243 |
+
f"Unable to render {renderable!r}; "
|
1244 |
+
"A str, Segment or object with __rich_console__ method is required"
|
1245 |
+
)
|
1246 |
+
|
1247 |
+
try:
|
1248 |
+
iter_render = iter(render_iterable)
|
1249 |
+
except TypeError:
|
1250 |
+
raise errors.NotRenderableError(
|
1251 |
+
f"object {render_iterable!r} is not renderable"
|
1252 |
+
)
|
1253 |
+
_Segment = Segment
|
1254 |
+
for render_output in iter_render:
|
1255 |
+
if isinstance(render_output, _Segment):
|
1256 |
+
yield render_output
|
1257 |
+
else:
|
1258 |
+
yield from self.render(render_output, _options)
|
1259 |
+
|
1260 |
+
def render_lines(
|
1261 |
+
self,
|
1262 |
+
renderable: RenderableType,
|
1263 |
+
options: Optional[ConsoleOptions] = None,
|
1264 |
+
*,
|
1265 |
+
style: Optional[Style] = None,
|
1266 |
+
pad: bool = True,
|
1267 |
+
new_lines: bool = False,
|
1268 |
+
) -> List[List[Segment]]:
|
1269 |
+
"""Render objects in to a list of lines.
|
1270 |
+
|
1271 |
+
The output of render_lines is useful when further formatting of rendered console text
|
1272 |
+
is required, such as the Panel class which draws a border around any renderable object.
|
1273 |
+
|
1274 |
+
Args:
|
1275 |
+
renderable (RenderableType): Any object renderable in the console.
|
1276 |
+
options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.
|
1277 |
+
style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.
|
1278 |
+
pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.
|
1279 |
+
new_lines (bool, optional): Include "\n" characters at end of lines.
|
1280 |
+
|
1281 |
+
Returns:
|
1282 |
+
List[List[Segment]]: A list of lines, where a line is a list of Segment objects.
|
1283 |
+
"""
|
1284 |
+
with self._lock:
|
1285 |
+
render_options = options or self.options
|
1286 |
+
_rendered = self.render(renderable, render_options)
|
1287 |
+
if style:
|
1288 |
+
_rendered = Segment.apply_style(_rendered, style)
|
1289 |
+
lines = list(
|
1290 |
+
islice(
|
1291 |
+
Segment.split_and_crop_lines(
|
1292 |
+
_rendered,
|
1293 |
+
render_options.max_width,
|
1294 |
+
include_new_lines=new_lines,
|
1295 |
+
pad=pad,
|
1296 |
+
),
|
1297 |
+
None,
|
1298 |
+
render_options.height,
|
1299 |
+
)
|
1300 |
+
)
|
1301 |
+
if render_options.height is not None:
|
1302 |
+
extra_lines = render_options.height - len(lines)
|
1303 |
+
if extra_lines > 0:
|
1304 |
+
pad_line = [
|
1305 |
+
[Segment(" " * render_options.max_width, style), Segment("\n")]
|
1306 |
+
if new_lines
|
1307 |
+
else [Segment(" " * render_options.max_width, style)]
|
1308 |
+
]
|
1309 |
+
lines.extend(pad_line * extra_lines)
|
1310 |
+
|
1311 |
+
return lines
|
1312 |
+
|
1313 |
+
def render_str(
|
1314 |
+
self,
|
1315 |
+
text: str,
|
1316 |
+
*,
|
1317 |
+
style: Union[str, Style] = "",
|
1318 |
+
justify: Optional[JustifyMethod] = None,
|
1319 |
+
overflow: Optional[OverflowMethod] = None,
|
1320 |
+
emoji: Optional[bool] = None,
|
1321 |
+
markup: Optional[bool] = None,
|
1322 |
+
highlight: Optional[bool] = None,
|
1323 |
+
highlighter: Optional[HighlighterType] = None,
|
1324 |
+
) -> "Text":
|
1325 |
+
"""Convert a string to a Text instance. This is is called automatically if
|
1326 |
+
you print or log a string.
|
1327 |
+
|
1328 |
+
Args:
|
1329 |
+
text (str): Text to render.
|
1330 |
+
style (Union[str, Style], optional): Style to apply to rendered text.
|
1331 |
+
justify (str, optional): Justify method: "default", "left", "center", "full", or "right". Defaults to ``None``.
|
1332 |
+
overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to ``None``.
|
1333 |
+
emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.
|
1334 |
+
markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.
|
1335 |
+
highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default.
|
1336 |
+
highlighter (HighlighterType, optional): Optional highlighter to apply.
|
1337 |
+
Returns:
|
1338 |
+
ConsoleRenderable: Renderable object.
|
1339 |
+
|
1340 |
+
"""
|
1341 |
+
emoji_enabled = emoji or (emoji is None and self._emoji)
|
1342 |
+
markup_enabled = markup or (markup is None and self._markup)
|
1343 |
+
highlight_enabled = highlight or (highlight is None and self._highlight)
|
1344 |
+
|
1345 |
+
if markup_enabled:
|
1346 |
+
rich_text = render_markup(
|
1347 |
+
text,
|
1348 |
+
style=style,
|
1349 |
+
emoji=emoji_enabled,
|
1350 |
+
emoji_variant=self._emoji_variant,
|
1351 |
+
)
|
1352 |
+
rich_text.justify = justify
|
1353 |
+
rich_text.overflow = overflow
|
1354 |
+
else:
|
1355 |
+
rich_text = Text(
|
1356 |
+
_emoji_replace(text, default_variant=self._emoji_variant)
|
1357 |
+
if emoji_enabled
|
1358 |
+
else text,
|
1359 |
+
justify=justify,
|
1360 |
+
overflow=overflow,
|
1361 |
+
style=style,
|
1362 |
+
)
|
1363 |
+
|
1364 |
+
_highlighter = (highlighter or self.highlighter) if highlight_enabled else None
|
1365 |
+
if _highlighter is not None:
|
1366 |
+
highlight_text = _highlighter(str(rich_text))
|
1367 |
+
highlight_text.copy_styles(rich_text)
|
1368 |
+
return highlight_text
|
1369 |
+
|
1370 |
+
return rich_text
|
1371 |
+
|
1372 |
+
def get_style(
|
1373 |
+
self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None
|
1374 |
+
) -> Style:
|
1375 |
+
"""Get a Style instance by it's theme name or parse a definition.
|
1376 |
+
|
1377 |
+
Args:
|
1378 |
+
name (str): The name of a style or a style definition.
|
1379 |
+
|
1380 |
+
Returns:
|
1381 |
+
Style: A Style object.
|
1382 |
+
|
1383 |
+
Raises:
|
1384 |
+
MissingStyle: If no style could be parsed from name.
|
1385 |
+
|
1386 |
+
"""
|
1387 |
+
if isinstance(name, Style):
|
1388 |
+
return name
|
1389 |
+
|
1390 |
+
try:
|
1391 |
+
style = self._theme_stack.get(name)
|
1392 |
+
if style is None:
|
1393 |
+
style = Style.parse(name)
|
1394 |
+
return style.copy() if style.link else style
|
1395 |
+
except errors.StyleSyntaxError as error:
|
1396 |
+
if default is not None:
|
1397 |
+
return self.get_style(default)
|
1398 |
+
raise errors.MissingStyle(
|
1399 |
+
f"Failed to get style {name!r}; {error}"
|
1400 |
+
) from None
|
1401 |
+
|
1402 |
+
def _collect_renderables(
|
1403 |
+
self,
|
1404 |
+
objects: Iterable[Any],
|
1405 |
+
sep: str,
|
1406 |
+
end: str,
|
1407 |
+
*,
|
1408 |
+
justify: Optional[JustifyMethod] = None,
|
1409 |
+
emoji: Optional[bool] = None,
|
1410 |
+
markup: Optional[bool] = None,
|
1411 |
+
highlight: Optional[bool] = None,
|
1412 |
+
) -> List[ConsoleRenderable]:
|
1413 |
+
"""Combine a number of renderables and text into one renderable.
|
1414 |
+
|
1415 |
+
Args:
|
1416 |
+
objects (Iterable[Any]): Anything that Rich can render.
|
1417 |
+
sep (str): String to write between print data.
|
1418 |
+
end (str): String to write at end of print data.
|
1419 |
+
justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
|
1420 |
+
emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.
|
1421 |
+
markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.
|
1422 |
+
highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.
|
1423 |
+
|
1424 |
+
Returns:
|
1425 |
+
List[ConsoleRenderable]: A list of things to render.
|
1426 |
+
"""
|
1427 |
+
renderables: List[ConsoleRenderable] = []
|
1428 |
+
_append = renderables.append
|
1429 |
+
text: List[Text] = []
|
1430 |
+
append_text = text.append
|
1431 |
+
|
1432 |
+
append = _append
|
1433 |
+
if justify in ("left", "center", "right"):
|
1434 |
+
|
1435 |
+
def align_append(renderable: RenderableType) -> None:
|
1436 |
+
_append(Align(renderable, cast(AlignMethod, justify)))
|
1437 |
+
|
1438 |
+
append = align_append
|
1439 |
+
|
1440 |
+
_highlighter: HighlighterType = _null_highlighter
|
1441 |
+
if highlight or (highlight is None and self._highlight):
|
1442 |
+
_highlighter = self.highlighter
|
1443 |
+
|
1444 |
+
def check_text() -> None:
|
1445 |
+
if text:
|
1446 |
+
sep_text = Text(sep, justify=justify, end=end)
|
1447 |
+
append(sep_text.join(text))
|
1448 |
+
del text[:]
|
1449 |
+
|
1450 |
+
for renderable in objects:
|
1451 |
+
renderable = rich_cast(renderable)
|
1452 |
+
if isinstance(renderable, str):
|
1453 |
+
append_text(
|
1454 |
+
self.render_str(
|
1455 |
+
renderable, emoji=emoji, markup=markup, highlighter=_highlighter
|
1456 |
+
)
|
1457 |
+
)
|
1458 |
+
elif isinstance(renderable, Text):
|
1459 |
+
append_text(renderable)
|
1460 |
+
elif isinstance(renderable, ConsoleRenderable):
|
1461 |
+
check_text()
|
1462 |
+
append(renderable)
|
1463 |
+
elif is_expandable(renderable):
|
1464 |
+
check_text()
|
1465 |
+
append(Pretty(renderable, highlighter=_highlighter))
|
1466 |
+
else:
|
1467 |
+
append_text(_highlighter(str(renderable)))
|
1468 |
+
|
1469 |
+
check_text()
|
1470 |
+
|
1471 |
+
if self.style is not None:
|
1472 |
+
style = self.get_style(self.style)
|
1473 |
+
renderables = [Styled(renderable, style) for renderable in renderables]
|
1474 |
+
|
1475 |
+
return renderables
|
1476 |
+
|
1477 |
+
def rule(
|
1478 |
+
self,
|
1479 |
+
title: TextType = "",
|
1480 |
+
*,
|
1481 |
+
characters: str = "─",
|
1482 |
+
style: Union[str, Style] = "rule.line",
|
1483 |
+
align: AlignMethod = "center",
|
1484 |
+
) -> None:
|
1485 |
+
"""Draw a line with optional centered title.
|
1486 |
+
|
1487 |
+
Args:
|
1488 |
+
title (str, optional): Text to render over the rule. Defaults to "".
|
1489 |
+
characters (str, optional): Character(s) to form the line. Defaults to "─".
|
1490 |
+
style (str, optional): Style of line. Defaults to "rule.line".
|
1491 |
+
align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
|
1492 |
+
"""
|
1493 |
+
from .rule import Rule
|
1494 |
+
|
1495 |
+
rule = Rule(title=title, characters=characters, style=style, align=align)
|
1496 |
+
self.print(rule)
|
1497 |
+
|
1498 |
+
def control(self, *control: Control) -> None:
|
1499 |
+
"""Insert non-printing control codes.
|
1500 |
+
|
1501 |
+
Args:
|
1502 |
+
control_codes (str): Control codes, such as those that may move the cursor.
|
1503 |
+
"""
|
1504 |
+
if not self.is_dumb_terminal:
|
1505 |
+
with self:
|
1506 |
+
self._buffer.extend(_control.segment for _control in control)
|
1507 |
+
|
1508 |
+
def out(
|
1509 |
+
self,
|
1510 |
+
*objects: Any,
|
1511 |
+
sep: str = " ",
|
1512 |
+
end: str = "\n",
|
1513 |
+
style: Optional[Union[str, Style]] = None,
|
1514 |
+
highlight: Optional[bool] = None,
|
1515 |
+
) -> None:
|
1516 |
+
"""Output to the terminal. This is a low-level way of writing to the terminal which unlike
|
1517 |
+
:meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will
|
1518 |
+
optionally apply highlighting and a basic style.
|
1519 |
+
|
1520 |
+
Args:
|
1521 |
+
sep (str, optional): String to write between print data. Defaults to " ".
|
1522 |
+
end (str, optional): String to write at end of print data. Defaults to "\\\\n".
|
1523 |
+
style (Union[str, Style], optional): A style to apply to output. Defaults to None.
|
1524 |
+
highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use
|
1525 |
+
console default. Defaults to ``None``.
|
1526 |
+
"""
|
1527 |
+
raw_output: str = sep.join(str(_object) for _object in objects)
|
1528 |
+
self.print(
|
1529 |
+
raw_output,
|
1530 |
+
style=style,
|
1531 |
+
highlight=highlight,
|
1532 |
+
emoji=False,
|
1533 |
+
markup=False,
|
1534 |
+
no_wrap=True,
|
1535 |
+
overflow="ignore",
|
1536 |
+
crop=False,
|
1537 |
+
end=end,
|
1538 |
+
)
|
1539 |
+
|
1540 |
+
def print(
|
1541 |
+
self,
|
1542 |
+
*objects: Any,
|
1543 |
+
sep: str = " ",
|
1544 |
+
end: str = "\n",
|
1545 |
+
style: Optional[Union[str, Style]] = None,
|
1546 |
+
justify: Optional[JustifyMethod] = None,
|
1547 |
+
overflow: Optional[OverflowMethod] = None,
|
1548 |
+
no_wrap: Optional[bool] = None,
|
1549 |
+
emoji: Optional[bool] = None,
|
1550 |
+
markup: Optional[bool] = None,
|
1551 |
+
highlight: Optional[bool] = None,
|
1552 |
+
width: Optional[int] = None,
|
1553 |
+
height: Optional[int] = None,
|
1554 |
+
crop: bool = True,
|
1555 |
+
soft_wrap: Optional[bool] = None,
|
1556 |
+
new_line_start: bool = False,
|
1557 |
+
) -> None:
|
1558 |
+
"""Print to the console.
|
1559 |
+
|
1560 |
+
Args:
|
1561 |
+
objects (positional args): Objects to log to the terminal.
|
1562 |
+
sep (str, optional): String to write between print data. Defaults to " ".
|
1563 |
+
end (str, optional): String to write at end of print data. Defaults to "\\\\n".
|
1564 |
+
style (Union[str, Style], optional): A style to apply to output. Defaults to None.
|
1565 |
+
justify (str, optional): Justify method: "default", "left", "right", "center", or "full". Defaults to ``None``.
|
1566 |
+
overflow (str, optional): Overflow method: "ignore", "crop", "fold", or "ellipsis". Defaults to None.
|
1567 |
+
no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.
|
1568 |
+
emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.
|
1569 |
+
markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.
|
1570 |
+
highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.
|
1571 |
+
width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.
|
1572 |
+
crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.
|
1573 |
+
soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for
|
1574 |
+
Console default. Defaults to ``None``.
|
1575 |
+
new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.
|
1576 |
+
"""
|
1577 |
+
if not objects:
|
1578 |
+
objects = (NewLine(),)
|
1579 |
+
|
1580 |
+
if soft_wrap is None:
|
1581 |
+
soft_wrap = self.soft_wrap
|
1582 |
+
if soft_wrap:
|
1583 |
+
if no_wrap is None:
|
1584 |
+
no_wrap = True
|
1585 |
+
if overflow is None:
|
1586 |
+
overflow = "ignore"
|
1587 |
+
crop = False
|
1588 |
+
render_hooks = self._render_hooks[:]
|
1589 |
+
with self:
|
1590 |
+
renderables = self._collect_renderables(
|
1591 |
+
objects,
|
1592 |
+
sep,
|
1593 |
+
end,
|
1594 |
+
justify=justify,
|
1595 |
+
emoji=emoji,
|
1596 |
+
markup=markup,
|
1597 |
+
highlight=highlight,
|
1598 |
+
)
|
1599 |
+
for hook in render_hooks:
|
1600 |
+
renderables = hook.process_renderables(renderables)
|
1601 |
+
render_options = self.options.update(
|
1602 |
+
justify=justify,
|
1603 |
+
overflow=overflow,
|
1604 |
+
width=min(width, self.width) if width is not None else NO_CHANGE,
|
1605 |
+
height=height,
|
1606 |
+
no_wrap=no_wrap,
|
1607 |
+
markup=markup,
|
1608 |
+
highlight=highlight,
|
1609 |
+
)
|
1610 |
+
|
1611 |
+
new_segments: List[Segment] = []
|
1612 |
+
extend = new_segments.extend
|
1613 |
+
render = self.render
|
1614 |
+
if style is None:
|
1615 |
+
for renderable in renderables:
|
1616 |
+
extend(render(renderable, render_options))
|
1617 |
+
else:
|
1618 |
+
for renderable in renderables:
|
1619 |
+
extend(
|
1620 |
+
Segment.apply_style(
|
1621 |
+
render(renderable, render_options), self.get_style(style)
|
1622 |
+
)
|
1623 |
+
)
|
1624 |
+
if new_line_start:
|
1625 |
+
if (
|
1626 |
+
len("".join(segment.text for segment in new_segments).splitlines())
|
1627 |
+
> 1
|
1628 |
+
):
|
1629 |
+
new_segments.insert(0, Segment.line())
|
1630 |
+
if crop:
|
1631 |
+
buffer_extend = self._buffer.extend
|
1632 |
+
for line in Segment.split_and_crop_lines(
|
1633 |
+
new_segments, self.width, pad=False
|
1634 |
+
):
|
1635 |
+
buffer_extend(line)
|
1636 |
+
else:
|
1637 |
+
self._buffer.extend(new_segments)
|
1638 |
+
|
1639 |
+
def print_json(
|
1640 |
+
self,
|
1641 |
+
json: Optional[str] = None,
|
1642 |
+
*,
|
1643 |
+
data: Any = None,
|
1644 |
+
indent: Union[None, int, str] = 2,
|
1645 |
+
highlight: bool = True,
|
1646 |
+
skip_keys: bool = False,
|
1647 |
+
ensure_ascii: bool = True,
|
1648 |
+
check_circular: bool = True,
|
1649 |
+
allow_nan: bool = True,
|
1650 |
+
default: Optional[Callable[[Any], Any]] = None,
|
1651 |
+
sort_keys: bool = False,
|
1652 |
+
) -> None:
|
1653 |
+
"""Pretty prints JSON. Output will be valid JSON.
|
1654 |
+
|
1655 |
+
Args:
|
1656 |
+
json (Optional[str]): A string containing JSON.
|
1657 |
+
data (Any): If json is not supplied, then encode this data.
|
1658 |
+
indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2.
|
1659 |
+
highlight (bool, optional): Enable highlighting of output: Defaults to True.
|
1660 |
+
skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
|
1661 |
+
ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
|
1662 |
+
check_circular (bool, optional): Check for circular references. Defaults to True.
|
1663 |
+
allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
|
1664 |
+
default (Callable, optional): A callable that converts values that can not be encoded
|
1665 |
+
in to something that can be JSON encoded. Defaults to None.
|
1666 |
+
sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
|
1667 |
+
"""
|
1668 |
+
from pip._vendor.rich.json import JSON
|
1669 |
+
|
1670 |
+
if json is None:
|
1671 |
+
json_renderable = JSON.from_data(
|
1672 |
+
data,
|
1673 |
+
indent=indent,
|
1674 |
+
highlight=highlight,
|
1675 |
+
skip_keys=skip_keys,
|
1676 |
+
ensure_ascii=ensure_ascii,
|
1677 |
+
check_circular=check_circular,
|
1678 |
+
allow_nan=allow_nan,
|
1679 |
+
default=default,
|
1680 |
+
sort_keys=sort_keys,
|
1681 |
+
)
|
1682 |
+
else:
|
1683 |
+
if not isinstance(json, str):
|
1684 |
+
raise TypeError(
|
1685 |
+
f"json must be str. Did you mean print_json(data={json!r}) ?"
|
1686 |
+
)
|
1687 |
+
json_renderable = JSON(
|
1688 |
+
json,
|
1689 |
+
indent=indent,
|
1690 |
+
highlight=highlight,
|
1691 |
+
skip_keys=skip_keys,
|
1692 |
+
ensure_ascii=ensure_ascii,
|
1693 |
+
check_circular=check_circular,
|
1694 |
+
allow_nan=allow_nan,
|
1695 |
+
default=default,
|
1696 |
+
sort_keys=sort_keys,
|
1697 |
+
)
|
1698 |
+
self.print(json_renderable, soft_wrap=True)
|
1699 |
+
|
1700 |
+
def update_screen(
|
1701 |
+
self,
|
1702 |
+
renderable: RenderableType,
|
1703 |
+
*,
|
1704 |
+
region: Optional[Region] = None,
|
1705 |
+
options: Optional[ConsoleOptions] = None,
|
1706 |
+
) -> None:
|
1707 |
+
"""Update the screen at a given offset.
|
1708 |
+
|
1709 |
+
Args:
|
1710 |
+
renderable (RenderableType): A Rich renderable.
|
1711 |
+
region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None.
|
1712 |
+
x (int, optional): x offset. Defaults to 0.
|
1713 |
+
y (int, optional): y offset. Defaults to 0.
|
1714 |
+
|
1715 |
+
Raises:
|
1716 |
+
errors.NoAltScreen: If the Console isn't in alt screen mode.
|
1717 |
+
|
1718 |
+
"""
|
1719 |
+
if not self.is_alt_screen:
|
1720 |
+
raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
|
1721 |
+
render_options = options or self.options
|
1722 |
+
if region is None:
|
1723 |
+
x = y = 0
|
1724 |
+
render_options = render_options.update_dimensions(
|
1725 |
+
render_options.max_width, render_options.height or self.height
|
1726 |
+
)
|
1727 |
+
else:
|
1728 |
+
x, y, width, height = region
|
1729 |
+
render_options = render_options.update_dimensions(width, height)
|
1730 |
+
|
1731 |
+
lines = self.render_lines(renderable, options=render_options)
|
1732 |
+
self.update_screen_lines(lines, x, y)
|
1733 |
+
|
1734 |
+
def update_screen_lines(
|
1735 |
+
self, lines: List[List[Segment]], x: int = 0, y: int = 0
|
1736 |
+
) -> None:
|
1737 |
+
"""Update lines of the screen at a given offset.
|
1738 |
+
|
1739 |
+
Args:
|
1740 |
+
lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`).
|
1741 |
+
x (int, optional): x offset (column no). Defaults to 0.
|
1742 |
+
y (int, optional): y offset (column no). Defaults to 0.
|
1743 |
+
|
1744 |
+
Raises:
|
1745 |
+
errors.NoAltScreen: If the Console isn't in alt screen mode.
|
1746 |
+
"""
|
1747 |
+
if not self.is_alt_screen:
|
1748 |
+
raise errors.NoAltScreen("Alt screen must be enabled to call update_screen")
|
1749 |
+
screen_update = ScreenUpdate(lines, x, y)
|
1750 |
+
segments = self.render(screen_update)
|
1751 |
+
self._buffer.extend(segments)
|
1752 |
+
self._check_buffer()
|
1753 |
+
|
1754 |
+
def print_exception(
|
1755 |
+
self,
|
1756 |
+
*,
|
1757 |
+
width: Optional[int] = 100,
|
1758 |
+
extra_lines: int = 3,
|
1759 |
+
theme: Optional[str] = None,
|
1760 |
+
word_wrap: bool = False,
|
1761 |
+
show_locals: bool = False,
|
1762 |
+
suppress: Iterable[Union[str, ModuleType]] = (),
|
1763 |
+
max_frames: int = 100,
|
1764 |
+
) -> None:
|
1765 |
+
"""Prints a rich render of the last exception and traceback.
|
1766 |
+
|
1767 |
+
Args:
|
1768 |
+
width (Optional[int], optional): Number of characters used to render code. Defaults to 88.
|
1769 |
+
extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
|
1770 |
+
theme (str, optional): Override pygments theme used in traceback
|
1771 |
+
word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
|
1772 |
+
show_locals (bool, optional): Enable display of local variables. Defaults to False.
|
1773 |
+
suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
|
1774 |
+
max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
|
1775 |
+
"""
|
1776 |
+
from .traceback import Traceback
|
1777 |
+
|
1778 |
+
traceback = Traceback(
|
1779 |
+
width=width,
|
1780 |
+
extra_lines=extra_lines,
|
1781 |
+
theme=theme,
|
1782 |
+
word_wrap=word_wrap,
|
1783 |
+
show_locals=show_locals,
|
1784 |
+
suppress=suppress,
|
1785 |
+
max_frames=max_frames,
|
1786 |
+
)
|
1787 |
+
self.print(traceback)
|
1788 |
+
|
1789 |
+
@staticmethod
|
1790 |
+
def _caller_frame_info(
|
1791 |
+
offset: int,
|
1792 |
+
currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe,
|
1793 |
+
) -> Tuple[str, int, Dict[str, Any]]:
|
1794 |
+
"""Get caller frame information.
|
1795 |
+
|
1796 |
+
Args:
|
1797 |
+
offset (int): the caller offset within the current frame stack.
|
1798 |
+
currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to
|
1799 |
+
retrieve the current frame. Defaults to ``inspect.currentframe``.
|
1800 |
+
|
1801 |
+
Returns:
|
1802 |
+
Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and
|
1803 |
+
the dictionary of local variables associated with the caller frame.
|
1804 |
+
|
1805 |
+
Raises:
|
1806 |
+
RuntimeError: If the stack offset is invalid.
|
1807 |
+
"""
|
1808 |
+
# Ignore the frame of this local helper
|
1809 |
+
offset += 1
|
1810 |
+
|
1811 |
+
frame = currentframe()
|
1812 |
+
if frame is not None:
|
1813 |
+
# Use the faster currentframe where implemented
|
1814 |
+
while offset and frame:
|
1815 |
+
frame = frame.f_back
|
1816 |
+
offset -= 1
|
1817 |
+
assert frame is not None
|
1818 |
+
return frame.f_code.co_filename, frame.f_lineno, frame.f_locals
|
1819 |
+
else:
|
1820 |
+
# Fallback to the slower stack
|
1821 |
+
frame_info = inspect.stack()[offset]
|
1822 |
+
return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals
|
1823 |
+
|
1824 |
+
def log(
|
1825 |
+
self,
|
1826 |
+
*objects: Any,
|
1827 |
+
sep: str = " ",
|
1828 |
+
end: str = "\n",
|
1829 |
+
style: Optional[Union[str, Style]] = None,
|
1830 |
+
justify: Optional[JustifyMethod] = None,
|
1831 |
+
emoji: Optional[bool] = None,
|
1832 |
+
markup: Optional[bool] = None,
|
1833 |
+
highlight: Optional[bool] = None,
|
1834 |
+
log_locals: bool = False,
|
1835 |
+
_stack_offset: int = 1,
|
1836 |
+
) -> None:
|
1837 |
+
"""Log rich content to the terminal.
|
1838 |
+
|
1839 |
+
Args:
|
1840 |
+
objects (positional args): Objects to log to the terminal.
|
1841 |
+
sep (str, optional): String to write between print data. Defaults to " ".
|
1842 |
+
end (str, optional): String to write at end of print data. Defaults to "\\\\n".
|
1843 |
+
style (Union[str, Style], optional): A style to apply to output. Defaults to None.
|
1844 |
+
justify (str, optional): One of "left", "right", "center", or "full". Defaults to ``None``.
|
1845 |
+
overflow (str, optional): Overflow method: "crop", "fold", or "ellipsis". Defaults to None.
|
1846 |
+
emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.
|
1847 |
+
markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.
|
1848 |
+
highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.
|
1849 |
+
log_locals (bool, optional): Boolean to enable logging of locals where ``log()``
|
1850 |
+
was called. Defaults to False.
|
1851 |
+
_stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.
|
1852 |
+
"""
|
1853 |
+
if not objects:
|
1854 |
+
objects = (NewLine(),)
|
1855 |
+
|
1856 |
+
render_hooks = self._render_hooks[:]
|
1857 |
+
|
1858 |
+
with self:
|
1859 |
+
renderables = self._collect_renderables(
|
1860 |
+
objects,
|
1861 |
+
sep,
|
1862 |
+
end,
|
1863 |
+
justify=justify,
|
1864 |
+
emoji=emoji,
|
1865 |
+
markup=markup,
|
1866 |
+
highlight=highlight,
|
1867 |
+
)
|
1868 |
+
if style is not None:
|
1869 |
+
renderables = [Styled(renderable, style) for renderable in renderables]
|
1870 |
+
|
1871 |
+
filename, line_no, locals = self._caller_frame_info(_stack_offset)
|
1872 |
+
link_path = None if filename.startswith("<") else os.path.abspath(filename)
|
1873 |
+
path = filename.rpartition(os.sep)[-1]
|
1874 |
+
if log_locals:
|
1875 |
+
locals_map = {
|
1876 |
+
key: value
|
1877 |
+
for key, value in locals.items()
|
1878 |
+
if not key.startswith("__")
|
1879 |
+
}
|
1880 |
+
renderables.append(render_scope(locals_map, title="[i]locals"))
|
1881 |
+
|
1882 |
+
renderables = [
|
1883 |
+
self._log_render(
|
1884 |
+
self,
|
1885 |
+
renderables,
|
1886 |
+
log_time=self.get_datetime(),
|
1887 |
+
path=path,
|
1888 |
+
line_no=line_no,
|
1889 |
+
link_path=link_path,
|
1890 |
+
)
|
1891 |
+
]
|
1892 |
+
for hook in render_hooks:
|
1893 |
+
renderables = hook.process_renderables(renderables)
|
1894 |
+
new_segments: List[Segment] = []
|
1895 |
+
extend = new_segments.extend
|
1896 |
+
render = self.render
|
1897 |
+
render_options = self.options
|
1898 |
+
for renderable in renderables:
|
1899 |
+
extend(render(renderable, render_options))
|
1900 |
+
buffer_extend = self._buffer.extend
|
1901 |
+
for line in Segment.split_and_crop_lines(
|
1902 |
+
new_segments, self.width, pad=False
|
1903 |
+
):
|
1904 |
+
buffer_extend(line)
|
1905 |
+
|
1906 |
+
def _check_buffer(self) -> None:
|
1907 |
+
"""Check if the buffer may be rendered."""
|
1908 |
+
if self.quiet:
|
1909 |
+
del self._buffer[:]
|
1910 |
+
return
|
1911 |
+
with self._lock:
|
1912 |
+
if self._buffer_index == 0:
|
1913 |
+
if self.is_jupyter: # pragma: no cover
|
1914 |
+
from .jupyter import display
|
1915 |
+
|
1916 |
+
display(self._buffer, self._render_buffer(self._buffer[:]))
|
1917 |
+
del self._buffer[:]
|
1918 |
+
else:
|
1919 |
+
text = self._render_buffer(self._buffer[:])
|
1920 |
+
del self._buffer[:]
|
1921 |
+
if text:
|
1922 |
+
try:
|
1923 |
+
if WINDOWS: # pragma: no cover
|
1924 |
+
# https://bugs.python.org/issue37871
|
1925 |
+
write = self.file.write
|
1926 |
+
for line in text.splitlines(True):
|
1927 |
+
write(line)
|
1928 |
+
else:
|
1929 |
+
self.file.write(text)
|
1930 |
+
self.file.flush()
|
1931 |
+
except UnicodeEncodeError as error:
|
1932 |
+
error.reason = f"{error.reason}\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***"
|
1933 |
+
raise
|
1934 |
+
|
1935 |
+
def _render_buffer(self, buffer: Iterable[Segment]) -> str:
|
1936 |
+
"""Render buffered output, and clear buffer."""
|
1937 |
+
output: List[str] = []
|
1938 |
+
append = output.append
|
1939 |
+
color_system = self._color_system
|
1940 |
+
legacy_windows = self.legacy_windows
|
1941 |
+
if self.record:
|
1942 |
+
with self._record_buffer_lock:
|
1943 |
+
self._record_buffer.extend(buffer)
|
1944 |
+
not_terminal = not self.is_terminal
|
1945 |
+
if self.no_color and color_system:
|
1946 |
+
buffer = Segment.remove_color(buffer)
|
1947 |
+
for text, style, control in buffer:
|
1948 |
+
if style:
|
1949 |
+
append(
|
1950 |
+
style.render(
|
1951 |
+
text,
|
1952 |
+
color_system=color_system,
|
1953 |
+
legacy_windows=legacy_windows,
|
1954 |
+
)
|
1955 |
+
)
|
1956 |
+
elif not (not_terminal and control):
|
1957 |
+
append(text)
|
1958 |
+
|
1959 |
+
rendered = "".join(output)
|
1960 |
+
return rendered
|
1961 |
+
|
1962 |
+
def input(
|
1963 |
+
self,
|
1964 |
+
prompt: TextType = "",
|
1965 |
+
*,
|
1966 |
+
markup: bool = True,
|
1967 |
+
emoji: bool = True,
|
1968 |
+
password: bool = False,
|
1969 |
+
stream: Optional[TextIO] = None,
|
1970 |
+
) -> str:
|
1971 |
+
"""Displays a prompt and waits for input from the user. The prompt may contain color / style.
|
1972 |
+
|
1973 |
+
It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded.
|
1974 |
+
|
1975 |
+
Args:
|
1976 |
+
prompt (Union[str, Text]): Text to render in the prompt.
|
1977 |
+
markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.
|
1978 |
+
emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.
|
1979 |
+
password: (bool, optional): Hide typed text. Defaults to False.
|
1980 |
+
stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.
|
1981 |
+
|
1982 |
+
Returns:
|
1983 |
+
str: Text read from stdin.
|
1984 |
+
"""
|
1985 |
+
prompt_str = ""
|
1986 |
+
if prompt:
|
1987 |
+
with self.capture() as capture:
|
1988 |
+
self.print(prompt, markup=markup, emoji=emoji, end="")
|
1989 |
+
prompt_str = capture.get()
|
1990 |
+
if self.legacy_windows:
|
1991 |
+
# Legacy windows doesn't like ANSI codes in getpass or input (colorama bug)?
|
1992 |
+
self.file.write(prompt_str)
|
1993 |
+
prompt_str = ""
|
1994 |
+
if password:
|
1995 |
+
result = getpass(prompt_str, stream=stream)
|
1996 |
+
else:
|
1997 |
+
if stream:
|
1998 |
+
self.file.write(prompt_str)
|
1999 |
+
result = stream.readline()
|
2000 |
+
else:
|
2001 |
+
result = input(prompt_str)
|
2002 |
+
return result
|
2003 |
+
|
2004 |
+
def export_text(self, *, clear: bool = True, styles: bool = False) -> str:
|
2005 |
+
"""Generate text from console contents (requires record=True argument in constructor).
|
2006 |
+
|
2007 |
+
Args:
|
2008 |
+
clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
|
2009 |
+
styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.
|
2010 |
+
Defaults to ``False``.
|
2011 |
+
|
2012 |
+
Returns:
|
2013 |
+
str: String containing console contents.
|
2014 |
+
|
2015 |
+
"""
|
2016 |
+
assert (
|
2017 |
+
self.record
|
2018 |
+
), "To export console contents set record=True in the constructor or instance"
|
2019 |
+
|
2020 |
+
with self._record_buffer_lock:
|
2021 |
+
if styles:
|
2022 |
+
text = "".join(
|
2023 |
+
(style.render(text) if style else text)
|
2024 |
+
for text, style, _ in self._record_buffer
|
2025 |
+
)
|
2026 |
+
else:
|
2027 |
+
text = "".join(
|
2028 |
+
segment.text
|
2029 |
+
for segment in self._record_buffer
|
2030 |
+
if not segment.control
|
2031 |
+
)
|
2032 |
+
if clear:
|
2033 |
+
del self._record_buffer[:]
|
2034 |
+
return text
|
2035 |
+
|
2036 |
+
def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None:
|
2037 |
+
"""Generate text from console and save to a given location (requires record=True argument in constructor).
|
2038 |
+
|
2039 |
+
Args:
|
2040 |
+
path (str): Path to write text files.
|
2041 |
+
clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
|
2042 |
+
styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.
|
2043 |
+
Defaults to ``False``.
|
2044 |
+
|
2045 |
+
"""
|
2046 |
+
text = self.export_text(clear=clear, styles=styles)
|
2047 |
+
with open(path, "wt", encoding="utf-8") as write_file:
|
2048 |
+
write_file.write(text)
|
2049 |
+
|
2050 |
+
def export_html(
|
2051 |
+
self,
|
2052 |
+
*,
|
2053 |
+
theme: Optional[TerminalTheme] = None,
|
2054 |
+
clear: bool = True,
|
2055 |
+
code_format: Optional[str] = None,
|
2056 |
+
inline_styles: bool = False,
|
2057 |
+
) -> str:
|
2058 |
+
"""Generate HTML from console contents (requires record=True argument in constructor).
|
2059 |
+
|
2060 |
+
Args:
|
2061 |
+
theme (TerminalTheme, optional): TerminalTheme object containing console colors.
|
2062 |
+
clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
|
2063 |
+
code_format (str, optional): Format string to render HTML, should contain {foreground}
|
2064 |
+
{background} and {code}.
|
2065 |
+
inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
|
2066 |
+
larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
|
2067 |
+
Defaults to False.
|
2068 |
+
|
2069 |
+
Returns:
|
2070 |
+
str: String containing console contents as HTML.
|
2071 |
+
"""
|
2072 |
+
assert (
|
2073 |
+
self.record
|
2074 |
+
), "To export console contents set record=True in the constructor or instance"
|
2075 |
+
fragments: List[str] = []
|
2076 |
+
append = fragments.append
|
2077 |
+
_theme = theme or DEFAULT_TERMINAL_THEME
|
2078 |
+
stylesheet = ""
|
2079 |
+
|
2080 |
+
render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format
|
2081 |
+
|
2082 |
+
with self._record_buffer_lock:
|
2083 |
+
if inline_styles:
|
2084 |
+
for text, style, _ in Segment.filter_control(
|
2085 |
+
Segment.simplify(self._record_buffer)
|
2086 |
+
):
|
2087 |
+
text = escape(text)
|
2088 |
+
if style:
|
2089 |
+
rule = style.get_html_style(_theme)
|
2090 |
+
if style.link:
|
2091 |
+
text = f'<a href="{style.link}">{text}</a>'
|
2092 |
+
text = f'<span style="{rule}">{text}</span>' if rule else text
|
2093 |
+
append(text)
|
2094 |
+
else:
|
2095 |
+
styles: Dict[str, int] = {}
|
2096 |
+
for text, style, _ in Segment.filter_control(
|
2097 |
+
Segment.simplify(self._record_buffer)
|
2098 |
+
):
|
2099 |
+
text = escape(text)
|
2100 |
+
if style:
|
2101 |
+
rule = style.get_html_style(_theme)
|
2102 |
+
style_number = styles.setdefault(rule, len(styles) + 1)
|
2103 |
+
if style.link:
|
2104 |
+
text = f'<a class="r{style_number}" href="{style.link}">{text}</a>'
|
2105 |
+
else:
|
2106 |
+
text = f'<span class="r{style_number}">{text}</span>'
|
2107 |
+
append(text)
|
2108 |
+
stylesheet_rules: List[str] = []
|
2109 |
+
stylesheet_append = stylesheet_rules.append
|
2110 |
+
for style_rule, style_number in styles.items():
|
2111 |
+
if style_rule:
|
2112 |
+
stylesheet_append(f".r{style_number} {{{style_rule}}}")
|
2113 |
+
stylesheet = "\n".join(stylesheet_rules)
|
2114 |
+
|
2115 |
+
rendered_code = render_code_format.format(
|
2116 |
+
code="".join(fragments),
|
2117 |
+
stylesheet=stylesheet,
|
2118 |
+
foreground=_theme.foreground_color.hex,
|
2119 |
+
background=_theme.background_color.hex,
|
2120 |
+
)
|
2121 |
+
if clear:
|
2122 |
+
del self._record_buffer[:]
|
2123 |
+
return rendered_code
|
2124 |
+
|
2125 |
+
def save_html(
|
2126 |
+
self,
|
2127 |
+
path: str,
|
2128 |
+
*,
|
2129 |
+
theme: Optional[TerminalTheme] = None,
|
2130 |
+
clear: bool = True,
|
2131 |
+
code_format: str = CONSOLE_HTML_FORMAT,
|
2132 |
+
inline_styles: bool = False,
|
2133 |
+
) -> None:
|
2134 |
+
"""Generate HTML from console contents and write to a file (requires record=True argument in constructor).
|
2135 |
+
|
2136 |
+
Args:
|
2137 |
+
path (str): Path to write html file.
|
2138 |
+
theme (TerminalTheme, optional): TerminalTheme object containing console colors.
|
2139 |
+
clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.
|
2140 |
+
code_format (str, optional): Format string to render HTML, should contain {foreground}
|
2141 |
+
{background} and {code}.
|
2142 |
+
inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files
|
2143 |
+
larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.
|
2144 |
+
Defaults to False.
|
2145 |
+
|
2146 |
+
"""
|
2147 |
+
html = self.export_html(
|
2148 |
+
theme=theme,
|
2149 |
+
clear=clear,
|
2150 |
+
code_format=code_format,
|
2151 |
+
inline_styles=inline_styles,
|
2152 |
+
)
|
2153 |
+
with open(path, "wt", encoding="utf-8") as write_file:
|
2154 |
+
write_file.write(html)
|
2155 |
+
|
2156 |
+
|
2157 |
+
if __name__ == "__main__": # pragma: no cover
|
2158 |
+
console = Console()
|
2159 |
+
|
2160 |
+
console.log(
|
2161 |
+
"JSONRPC [i]request[/i]",
|
2162 |
+
5,
|
2163 |
+
1.3,
|
2164 |
+
True,
|
2165 |
+
False,
|
2166 |
+
None,
|
2167 |
+
{
|
2168 |
+
"jsonrpc": "2.0",
|
2169 |
+
"method": "subtract",
|
2170 |
+
"params": {"minuend": 42, "subtrahend": 23},
|
2171 |
+
"id": 3,
|
2172 |
+
},
|
2173 |
+
)
|
2174 |
+
|
2175 |
+
console.log("Hello, World!", "{'a': 1}", repr(console))
|
2176 |
+
|
2177 |
+
console.print(
|
2178 |
+
{
|
2179 |
+
"name": None,
|
2180 |
+
"empty": [],
|
2181 |
+
"quiz": {
|
2182 |
+
"sport": {
|
2183 |
+
"answered": True,
|
2184 |
+
"q1": {
|
2185 |
+
"question": "Which one is correct team name in NBA?",
|
2186 |
+
"options": [
|
2187 |
+
"New York Bulls",
|
2188 |
+
"Los Angeles Kings",
|
2189 |
+
"Golden State Warriors",
|
2190 |
+
"Huston Rocket",
|
2191 |
+
],
|
2192 |
+
"answer": "Huston Rocket",
|
2193 |
+
},
|
2194 |
+
},
|
2195 |
+
"maths": {
|
2196 |
+
"answered": False,
|
2197 |
+
"q1": {
|
2198 |
+
"question": "5 + 7 = ?",
|
2199 |
+
"options": [10, 11, 12, 13],
|
2200 |
+
"answer": 12,
|
2201 |
+
},
|
2202 |
+
"q2": {
|
2203 |
+
"question": "12 - 8 = ?",
|
2204 |
+
"options": [1, 2, 3, 4],
|
2205 |
+
"answer": 4,
|
2206 |
+
},
|
2207 |
+
},
|
2208 |
+
},
|
2209 |
+
}
|
2210 |
+
)
|
2211 |
+
console.log("foo")
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/containers.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from itertools import zip_longest
|
2 |
+
from typing import (
|
3 |
+
Iterator,
|
4 |
+
Iterable,
|
5 |
+
List,
|
6 |
+
Optional,
|
7 |
+
Union,
|
8 |
+
overload,
|
9 |
+
TypeVar,
|
10 |
+
TYPE_CHECKING,
|
11 |
+
)
|
12 |
+
|
13 |
+
if TYPE_CHECKING:
|
14 |
+
from .console import (
|
15 |
+
Console,
|
16 |
+
ConsoleOptions,
|
17 |
+
JustifyMethod,
|
18 |
+
OverflowMethod,
|
19 |
+
RenderResult,
|
20 |
+
RenderableType,
|
21 |
+
)
|
22 |
+
from .text import Text
|
23 |
+
|
24 |
+
from .cells import cell_len
|
25 |
+
from .measure import Measurement
|
26 |
+
|
27 |
+
T = TypeVar("T")
|
28 |
+
|
29 |
+
|
30 |
+
class Renderables:
|
31 |
+
"""A list subclass which renders its contents to the console."""
|
32 |
+
|
33 |
+
def __init__(
|
34 |
+
self, renderables: Optional[Iterable["RenderableType"]] = None
|
35 |
+
) -> None:
|
36 |
+
self._renderables: List["RenderableType"] = (
|
37 |
+
list(renderables) if renderables is not None else []
|
38 |
+
)
|
39 |
+
|
40 |
+
def __rich_console__(
|
41 |
+
self, console: "Console", options: "ConsoleOptions"
|
42 |
+
) -> "RenderResult":
|
43 |
+
"""Console render method to insert line-breaks."""
|
44 |
+
yield from self._renderables
|
45 |
+
|
46 |
+
def __rich_measure__(
|
47 |
+
self, console: "Console", options: "ConsoleOptions"
|
48 |
+
) -> "Measurement":
|
49 |
+
dimensions = [
|
50 |
+
Measurement.get(console, options, renderable)
|
51 |
+
for renderable in self._renderables
|
52 |
+
]
|
53 |
+
if not dimensions:
|
54 |
+
return Measurement(1, 1)
|
55 |
+
_min = max(dimension.minimum for dimension in dimensions)
|
56 |
+
_max = max(dimension.maximum for dimension in dimensions)
|
57 |
+
return Measurement(_min, _max)
|
58 |
+
|
59 |
+
def append(self, renderable: "RenderableType") -> None:
|
60 |
+
self._renderables.append(renderable)
|
61 |
+
|
62 |
+
def __iter__(self) -> Iterable["RenderableType"]:
|
63 |
+
return iter(self._renderables)
|
64 |
+
|
65 |
+
|
66 |
+
class Lines:
|
67 |
+
"""A list subclass which can render to the console."""
|
68 |
+
|
69 |
+
def __init__(self, lines: Iterable["Text"] = ()) -> None:
|
70 |
+
self._lines: List["Text"] = list(lines)
|
71 |
+
|
72 |
+
def __repr__(self) -> str:
|
73 |
+
return f"Lines({self._lines!r})"
|
74 |
+
|
75 |
+
def __iter__(self) -> Iterator["Text"]:
|
76 |
+
return iter(self._lines)
|
77 |
+
|
78 |
+
@overload
|
79 |
+
def __getitem__(self, index: int) -> "Text":
|
80 |
+
...
|
81 |
+
|
82 |
+
@overload
|
83 |
+
def __getitem__(self, index: slice) -> List["Text"]:
|
84 |
+
...
|
85 |
+
|
86 |
+
def __getitem__(self, index: Union[slice, int]) -> Union["Text", List["Text"]]:
|
87 |
+
return self._lines[index]
|
88 |
+
|
89 |
+
def __setitem__(self, index: int, value: "Text") -> "Lines":
|
90 |
+
self._lines[index] = value
|
91 |
+
return self
|
92 |
+
|
93 |
+
def __len__(self) -> int:
|
94 |
+
return self._lines.__len__()
|
95 |
+
|
96 |
+
def __rich_console__(
|
97 |
+
self, console: "Console", options: "ConsoleOptions"
|
98 |
+
) -> "RenderResult":
|
99 |
+
"""Console render method to insert line-breaks."""
|
100 |
+
yield from self._lines
|
101 |
+
|
102 |
+
def append(self, line: "Text") -> None:
|
103 |
+
self._lines.append(line)
|
104 |
+
|
105 |
+
def extend(self, lines: Iterable["Text"]) -> None:
|
106 |
+
self._lines.extend(lines)
|
107 |
+
|
108 |
+
def pop(self, index: int = -1) -> "Text":
|
109 |
+
return self._lines.pop(index)
|
110 |
+
|
111 |
+
def justify(
|
112 |
+
self,
|
113 |
+
console: "Console",
|
114 |
+
width: int,
|
115 |
+
justify: "JustifyMethod" = "left",
|
116 |
+
overflow: "OverflowMethod" = "fold",
|
117 |
+
) -> None:
|
118 |
+
"""Justify and overflow text to a given width.
|
119 |
+
|
120 |
+
Args:
|
121 |
+
console (Console): Console instance.
|
122 |
+
width (int): Number of characters per line.
|
123 |
+
justify (str, optional): Default justify method for text: "left", "center", "full" or "right". Defaults to "left".
|
124 |
+
overflow (str, optional): Default overflow for text: "crop", "fold", or "ellipsis". Defaults to "fold".
|
125 |
+
|
126 |
+
"""
|
127 |
+
from .text import Text
|
128 |
+
|
129 |
+
if justify == "left":
|
130 |
+
for line in self._lines:
|
131 |
+
line.truncate(width, overflow=overflow, pad=True)
|
132 |
+
elif justify == "center":
|
133 |
+
for line in self._lines:
|
134 |
+
line.rstrip()
|
135 |
+
line.truncate(width, overflow=overflow)
|
136 |
+
line.pad_left((width - cell_len(line.plain)) // 2)
|
137 |
+
line.pad_right(width - cell_len(line.plain))
|
138 |
+
elif justify == "right":
|
139 |
+
for line in self._lines:
|
140 |
+
line.rstrip()
|
141 |
+
line.truncate(width, overflow=overflow)
|
142 |
+
line.pad_left(width - cell_len(line.plain))
|
143 |
+
elif justify == "full":
|
144 |
+
for line_index, line in enumerate(self._lines):
|
145 |
+
if line_index == len(self._lines) - 1:
|
146 |
+
break
|
147 |
+
words = line.split(" ")
|
148 |
+
words_size = sum(cell_len(word.plain) for word in words)
|
149 |
+
num_spaces = len(words) - 1
|
150 |
+
spaces = [1 for _ in range(num_spaces)]
|
151 |
+
index = 0
|
152 |
+
if spaces:
|
153 |
+
while words_size + num_spaces < width:
|
154 |
+
spaces[len(spaces) - index - 1] += 1
|
155 |
+
num_spaces += 1
|
156 |
+
index = (index + 1) % len(spaces)
|
157 |
+
tokens: List[Text] = []
|
158 |
+
for index, (word, next_word) in enumerate(
|
159 |
+
zip_longest(words, words[1:])
|
160 |
+
):
|
161 |
+
tokens.append(word)
|
162 |
+
if index < len(spaces):
|
163 |
+
style = word.get_style_at_offset(console, -1)
|
164 |
+
next_style = next_word.get_style_at_offset(console, 0)
|
165 |
+
space_style = style if style == next_style else line.style
|
166 |
+
tokens.append(Text(" " * spaces[index], style=space_style))
|
167 |
+
self[line_index] = Text("").join(tokens)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/control.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Callable, Dict, Iterable, List, TYPE_CHECKING, Union
|
2 |
+
|
3 |
+
from .segment import ControlCode, ControlType, Segment
|
4 |
+
|
5 |
+
if TYPE_CHECKING:
|
6 |
+
from .console import Console, ConsoleOptions, RenderResult
|
7 |
+
|
8 |
+
STRIP_CONTROL_CODES = [
|
9 |
+
8, # Backspace
|
10 |
+
11, # Vertical tab
|
11 |
+
12, # Form feed
|
12 |
+
13, # Carriage return
|
13 |
+
]
|
14 |
+
_CONTROL_TRANSLATE = {_codepoint: None for _codepoint in STRIP_CONTROL_CODES}
|
15 |
+
|
16 |
+
|
17 |
+
CONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = {
|
18 |
+
ControlType.BELL: lambda: "\x07",
|
19 |
+
ControlType.CARRIAGE_RETURN: lambda: "\r",
|
20 |
+
ControlType.HOME: lambda: "\x1b[H",
|
21 |
+
ControlType.CLEAR: lambda: "\x1b[2J",
|
22 |
+
ControlType.ENABLE_ALT_SCREEN: lambda: "\x1b[?1049h",
|
23 |
+
ControlType.DISABLE_ALT_SCREEN: lambda: "\x1b[?1049l",
|
24 |
+
ControlType.SHOW_CURSOR: lambda: "\x1b[?25h",
|
25 |
+
ControlType.HIDE_CURSOR: lambda: "\x1b[?25l",
|
26 |
+
ControlType.CURSOR_UP: lambda param: f"\x1b[{param}A",
|
27 |
+
ControlType.CURSOR_DOWN: lambda param: f"\x1b[{param}B",
|
28 |
+
ControlType.CURSOR_FORWARD: lambda param: f"\x1b[{param}C",
|
29 |
+
ControlType.CURSOR_BACKWARD: lambda param: f"\x1b[{param}D",
|
30 |
+
ControlType.CURSOR_MOVE_TO_COLUMN: lambda param: f"\x1b[{param+1}G",
|
31 |
+
ControlType.ERASE_IN_LINE: lambda param: f"\x1b[{param}K",
|
32 |
+
ControlType.CURSOR_MOVE_TO: lambda x, y: f"\x1b[{y+1};{x+1}H",
|
33 |
+
}
|
34 |
+
|
35 |
+
|
36 |
+
class Control:
|
37 |
+
"""A renderable that inserts a control code (non printable but may move cursor).
|
38 |
+
|
39 |
+
Args:
|
40 |
+
*codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a
|
41 |
+
tuple of ControlType and an integer parameter
|
42 |
+
"""
|
43 |
+
|
44 |
+
__slots__ = ["segment"]
|
45 |
+
|
46 |
+
def __init__(self, *codes: Union[ControlType, ControlCode]) -> None:
|
47 |
+
control_codes: List[ControlCode] = [
|
48 |
+
(code,) if isinstance(code, ControlType) else code for code in codes
|
49 |
+
]
|
50 |
+
_format_map = CONTROL_CODES_FORMAT
|
51 |
+
rendered_codes = "".join(
|
52 |
+
_format_map[code](*parameters) for code, *parameters in control_codes
|
53 |
+
)
|
54 |
+
self.segment = Segment(rendered_codes, None, control_codes)
|
55 |
+
|
56 |
+
@classmethod
|
57 |
+
def bell(cls) -> "Control":
|
58 |
+
"""Ring the 'bell'."""
|
59 |
+
return cls(ControlType.BELL)
|
60 |
+
|
61 |
+
@classmethod
|
62 |
+
def home(cls) -> "Control":
|
63 |
+
"""Move cursor to 'home' position."""
|
64 |
+
return cls(ControlType.HOME)
|
65 |
+
|
66 |
+
@classmethod
|
67 |
+
def move(cls, x: int = 0, y: int = 0) -> "Control":
|
68 |
+
"""Move cursor relative to current position.
|
69 |
+
|
70 |
+
Args:
|
71 |
+
x (int): X offset.
|
72 |
+
y (int): Y offset.
|
73 |
+
|
74 |
+
Returns:
|
75 |
+
~Control: Control object.
|
76 |
+
|
77 |
+
"""
|
78 |
+
|
79 |
+
def get_codes() -> Iterable[ControlCode]:
|
80 |
+
control = ControlType
|
81 |
+
if x:
|
82 |
+
yield (
|
83 |
+
control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD,
|
84 |
+
abs(x),
|
85 |
+
)
|
86 |
+
if y:
|
87 |
+
yield (
|
88 |
+
control.CURSOR_DOWN if y > 0 else control.CURSOR_UP,
|
89 |
+
abs(y),
|
90 |
+
)
|
91 |
+
|
92 |
+
control = cls(*get_codes())
|
93 |
+
return control
|
94 |
+
|
95 |
+
@classmethod
|
96 |
+
def move_to_column(cls, x: int, y: int = 0) -> "Control":
|
97 |
+
"""Move to the given column, optionally add offset to row.
|
98 |
+
|
99 |
+
Returns:
|
100 |
+
x (int): absolute x (column)
|
101 |
+
y (int): optional y offset (row)
|
102 |
+
|
103 |
+
Returns:
|
104 |
+
~Control: Control object.
|
105 |
+
"""
|
106 |
+
|
107 |
+
return (
|
108 |
+
cls(
|
109 |
+
(ControlType.CURSOR_MOVE_TO_COLUMN, x),
|
110 |
+
(
|
111 |
+
ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP,
|
112 |
+
abs(y),
|
113 |
+
),
|
114 |
+
)
|
115 |
+
if y
|
116 |
+
else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x))
|
117 |
+
)
|
118 |
+
|
119 |
+
@classmethod
|
120 |
+
def move_to(cls, x: int, y: int) -> "Control":
|
121 |
+
"""Move cursor to absolute position.
|
122 |
+
|
123 |
+
Args:
|
124 |
+
x (int): x offset (column)
|
125 |
+
y (int): y offset (row)
|
126 |
+
|
127 |
+
Returns:
|
128 |
+
~Control: Control object.
|
129 |
+
"""
|
130 |
+
return cls((ControlType.CURSOR_MOVE_TO, x, y))
|
131 |
+
|
132 |
+
@classmethod
|
133 |
+
def clear(cls) -> "Control":
|
134 |
+
"""Clear the screen."""
|
135 |
+
return cls(ControlType.CLEAR)
|
136 |
+
|
137 |
+
@classmethod
|
138 |
+
def show_cursor(cls, show: bool) -> "Control":
|
139 |
+
"""Show or hide the cursor."""
|
140 |
+
return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR)
|
141 |
+
|
142 |
+
@classmethod
|
143 |
+
def alt_screen(cls, enable: bool) -> "Control":
|
144 |
+
"""Enable or disable alt screen."""
|
145 |
+
if enable:
|
146 |
+
return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME)
|
147 |
+
else:
|
148 |
+
return cls(ControlType.DISABLE_ALT_SCREEN)
|
149 |
+
|
150 |
+
def __str__(self) -> str:
|
151 |
+
return self.segment.text
|
152 |
+
|
153 |
+
def __rich_console__(
|
154 |
+
self, console: "Console", options: "ConsoleOptions"
|
155 |
+
) -> "RenderResult":
|
156 |
+
if self.segment.text:
|
157 |
+
yield self.segment
|
158 |
+
|
159 |
+
|
160 |
+
def strip_control_codes(
|
161 |
+
text: str, _translate_table: Dict[int, None] = _CONTROL_TRANSLATE
|
162 |
+
) -> str:
|
163 |
+
"""Remove control codes from text.
|
164 |
+
|
165 |
+
Args:
|
166 |
+
text (str): A string possibly contain control codes.
|
167 |
+
|
168 |
+
Returns:
|
169 |
+
str: String with control codes removed.
|
170 |
+
"""
|
171 |
+
return text.translate(_translate_table)
|
172 |
+
|
173 |
+
|
174 |
+
if __name__ == "__main__": # pragma: no cover
|
175 |
+
print(strip_control_codes("hello\rWorld"))
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/default_styles.py
ADDED
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict
|
2 |
+
|
3 |
+
from .style import Style
|
4 |
+
|
5 |
+
|
6 |
+
DEFAULT_STYLES: Dict[str, Style] = {
|
7 |
+
"none": Style.null(),
|
8 |
+
"reset": Style(
|
9 |
+
color="default",
|
10 |
+
bgcolor="default",
|
11 |
+
dim=False,
|
12 |
+
bold=False,
|
13 |
+
italic=False,
|
14 |
+
underline=False,
|
15 |
+
blink=False,
|
16 |
+
blink2=False,
|
17 |
+
reverse=False,
|
18 |
+
conceal=False,
|
19 |
+
strike=False,
|
20 |
+
),
|
21 |
+
"dim": Style(dim=True),
|
22 |
+
"bright": Style(dim=False),
|
23 |
+
"bold": Style(bold=True),
|
24 |
+
"strong": Style(bold=True),
|
25 |
+
"code": Style(reverse=True, bold=True),
|
26 |
+
"italic": Style(italic=True),
|
27 |
+
"emphasize": Style(italic=True),
|
28 |
+
"underline": Style(underline=True),
|
29 |
+
"blink": Style(blink=True),
|
30 |
+
"blink2": Style(blink2=True),
|
31 |
+
"reverse": Style(reverse=True),
|
32 |
+
"strike": Style(strike=True),
|
33 |
+
"black": Style(color="black"),
|
34 |
+
"red": Style(color="red"),
|
35 |
+
"green": Style(color="green"),
|
36 |
+
"yellow": Style(color="yellow"),
|
37 |
+
"magenta": Style(color="magenta"),
|
38 |
+
"cyan": Style(color="cyan"),
|
39 |
+
"white": Style(color="white"),
|
40 |
+
"inspect.attr": Style(color="yellow", italic=True),
|
41 |
+
"inspect.attr.dunder": Style(color="yellow", italic=True, dim=True),
|
42 |
+
"inspect.callable": Style(bold=True, color="red"),
|
43 |
+
"inspect.def": Style(italic=True, color="bright_cyan"),
|
44 |
+
"inspect.error": Style(bold=True, color="red"),
|
45 |
+
"inspect.equals": Style(),
|
46 |
+
"inspect.help": Style(color="cyan"),
|
47 |
+
"inspect.doc": Style(dim=True),
|
48 |
+
"inspect.value.border": Style(color="green"),
|
49 |
+
"live.ellipsis": Style(bold=True, color="red"),
|
50 |
+
"layout.tree.row": Style(dim=False, color="red"),
|
51 |
+
"layout.tree.column": Style(dim=False, color="blue"),
|
52 |
+
"logging.keyword": Style(bold=True, color="yellow"),
|
53 |
+
"logging.level.notset": Style(dim=True),
|
54 |
+
"logging.level.debug": Style(color="green"),
|
55 |
+
"logging.level.info": Style(color="blue"),
|
56 |
+
"logging.level.warning": Style(color="red"),
|
57 |
+
"logging.level.error": Style(color="red", bold=True),
|
58 |
+
"logging.level.critical": Style(color="red", bold=True, reverse=True),
|
59 |
+
"log.level": Style.null(),
|
60 |
+
"log.time": Style(color="cyan", dim=True),
|
61 |
+
"log.message": Style.null(),
|
62 |
+
"log.path": Style(dim=True),
|
63 |
+
"repr.ellipsis": Style(color="yellow"),
|
64 |
+
"repr.indent": Style(color="green", dim=True),
|
65 |
+
"repr.error": Style(color="red", bold=True),
|
66 |
+
"repr.str": Style(color="green", italic=False, bold=False),
|
67 |
+
"repr.brace": Style(bold=True),
|
68 |
+
"repr.comma": Style(bold=True),
|
69 |
+
"repr.ipv4": Style(bold=True, color="bright_green"),
|
70 |
+
"repr.ipv6": Style(bold=True, color="bright_green"),
|
71 |
+
"repr.eui48": Style(bold=True, color="bright_green"),
|
72 |
+
"repr.eui64": Style(bold=True, color="bright_green"),
|
73 |
+
"repr.tag_start": Style(bold=True),
|
74 |
+
"repr.tag_name": Style(color="bright_magenta", bold=True),
|
75 |
+
"repr.tag_contents": Style(color="default"),
|
76 |
+
"repr.tag_end": Style(bold=True),
|
77 |
+
"repr.attrib_name": Style(color="yellow", italic=False),
|
78 |
+
"repr.attrib_equal": Style(bold=True),
|
79 |
+
"repr.attrib_value": Style(color="magenta", italic=False),
|
80 |
+
"repr.number": Style(color="cyan", bold=True, italic=False),
|
81 |
+
"repr.bool_true": Style(color="bright_green", italic=True),
|
82 |
+
"repr.bool_false": Style(color="bright_red", italic=True),
|
83 |
+
"repr.none": Style(color="magenta", italic=True),
|
84 |
+
"repr.url": Style(underline=True, color="bright_blue", italic=False, bold=False),
|
85 |
+
"repr.uuid": Style(color="bright_yellow", bold=False),
|
86 |
+
"repr.call": Style(color="magenta", bold=True),
|
87 |
+
"repr.path": Style(color="magenta"),
|
88 |
+
"repr.filename": Style(color="bright_magenta"),
|
89 |
+
"rule.line": Style(color="bright_green"),
|
90 |
+
"rule.text": Style.null(),
|
91 |
+
"json.brace": Style(bold=True),
|
92 |
+
"json.bool_true": Style(color="bright_green", italic=True),
|
93 |
+
"json.bool_false": Style(color="bright_red", italic=True),
|
94 |
+
"json.null": Style(color="magenta", italic=True),
|
95 |
+
"json.number": Style(color="cyan", bold=True, italic=False),
|
96 |
+
"json.str": Style(color="green", italic=False, bold=False),
|
97 |
+
"json.key": Style(color="blue", bold=True),
|
98 |
+
"prompt": Style.null(),
|
99 |
+
"prompt.choices": Style(color="magenta", bold=True),
|
100 |
+
"prompt.default": Style(color="cyan", bold=True),
|
101 |
+
"prompt.invalid": Style(color="red"),
|
102 |
+
"prompt.invalid.choice": Style(color="red"),
|
103 |
+
"pretty": Style.null(),
|
104 |
+
"scope.border": Style(color="blue"),
|
105 |
+
"scope.key": Style(color="yellow", italic=True),
|
106 |
+
"scope.key.special": Style(color="yellow", italic=True, dim=True),
|
107 |
+
"scope.equals": Style(color="red"),
|
108 |
+
"table.header": Style(bold=True),
|
109 |
+
"table.footer": Style(bold=True),
|
110 |
+
"table.cell": Style.null(),
|
111 |
+
"table.title": Style(italic=True),
|
112 |
+
"table.caption": Style(italic=True, dim=True),
|
113 |
+
"traceback.error": Style(color="red", italic=True),
|
114 |
+
"traceback.border.syntax_error": Style(color="bright_red"),
|
115 |
+
"traceback.border": Style(color="red"),
|
116 |
+
"traceback.text": Style.null(),
|
117 |
+
"traceback.title": Style(color="red", bold=True),
|
118 |
+
"traceback.exc_type": Style(color="bright_red", bold=True),
|
119 |
+
"traceback.exc_value": Style.null(),
|
120 |
+
"traceback.offset": Style(color="bright_red", bold=True),
|
121 |
+
"bar.back": Style(color="grey23"),
|
122 |
+
"bar.complete": Style(color="rgb(249,38,114)"),
|
123 |
+
"bar.finished": Style(color="rgb(114,156,31)"),
|
124 |
+
"bar.pulse": Style(color="rgb(249,38,114)"),
|
125 |
+
"progress.description": Style.null(),
|
126 |
+
"progress.filesize": Style(color="green"),
|
127 |
+
"progress.filesize.total": Style(color="green"),
|
128 |
+
"progress.download": Style(color="green"),
|
129 |
+
"progress.elapsed": Style(color="yellow"),
|
130 |
+
"progress.percentage": Style(color="magenta"),
|
131 |
+
"progress.remaining": Style(color="cyan"),
|
132 |
+
"progress.data.speed": Style(color="red"),
|
133 |
+
"progress.spinner": Style(color="green"),
|
134 |
+
"status.spinner": Style(color="green"),
|
135 |
+
"tree": Style(),
|
136 |
+
"tree.line": Style(),
|
137 |
+
"markdown.paragraph": Style(),
|
138 |
+
"markdown.text": Style(),
|
139 |
+
"markdown.emph": Style(italic=True),
|
140 |
+
"markdown.strong": Style(bold=True),
|
141 |
+
"markdown.code": Style(bgcolor="black", color="bright_white"),
|
142 |
+
"markdown.code_block": Style(dim=True, color="cyan", bgcolor="black"),
|
143 |
+
"markdown.block_quote": Style(color="magenta"),
|
144 |
+
"markdown.list": Style(color="cyan"),
|
145 |
+
"markdown.item": Style(),
|
146 |
+
"markdown.item.bullet": Style(color="yellow", bold=True),
|
147 |
+
"markdown.item.number": Style(color="yellow", bold=True),
|
148 |
+
"markdown.hr": Style(color="yellow"),
|
149 |
+
"markdown.h1.border": Style(),
|
150 |
+
"markdown.h1": Style(bold=True),
|
151 |
+
"markdown.h2": Style(bold=True, underline=True),
|
152 |
+
"markdown.h3": Style(bold=True),
|
153 |
+
"markdown.h4": Style(bold=True, dim=True),
|
154 |
+
"markdown.h5": Style(underline=True),
|
155 |
+
"markdown.h6": Style(italic=True),
|
156 |
+
"markdown.h7": Style(italic=True, dim=True),
|
157 |
+
"markdown.link": Style(color="bright_blue"),
|
158 |
+
"markdown.link_url": Style(color="blue"),
|
159 |
+
}
|
160 |
+
|
161 |
+
|
162 |
+
if __name__ == "__main__": # pragma: no cover
|
163 |
+
import argparse
|
164 |
+
import io
|
165 |
+
|
166 |
+
from pip._vendor.rich.console import Console
|
167 |
+
from pip._vendor.rich.table import Table
|
168 |
+
from pip._vendor.rich.text import Text
|
169 |
+
|
170 |
+
parser = argparse.ArgumentParser()
|
171 |
+
parser.add_argument("--html", action="store_true", help="Export as HTML table")
|
172 |
+
args = parser.parse_args()
|
173 |
+
html: bool = args.html
|
174 |
+
console = Console(record=True, width=70, file=io.StringIO()) if html else Console()
|
175 |
+
|
176 |
+
table = Table("Name", "Styling")
|
177 |
+
|
178 |
+
for style_name, style in DEFAULT_STYLES.items():
|
179 |
+
table.add_row(Text(style_name, style=style), str(style))
|
180 |
+
|
181 |
+
console.print(table)
|
182 |
+
if html:
|
183 |
+
print(console.export_html(inline_styles=True))
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/errors.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class ConsoleError(Exception):
|
2 |
+
"""An error in console operation."""
|
3 |
+
|
4 |
+
|
5 |
+
class StyleError(Exception):
|
6 |
+
"""An error in styles."""
|
7 |
+
|
8 |
+
|
9 |
+
class StyleSyntaxError(ConsoleError):
|
10 |
+
"""Style was badly formatted."""
|
11 |
+
|
12 |
+
|
13 |
+
class MissingStyle(StyleError):
|
14 |
+
"""No such style."""
|
15 |
+
|
16 |
+
|
17 |
+
class StyleStackError(ConsoleError):
|
18 |
+
"""Style stack is invalid."""
|
19 |
+
|
20 |
+
|
21 |
+
class NotRenderableError(ConsoleError):
|
22 |
+
"""Object is not renderable."""
|
23 |
+
|
24 |
+
|
25 |
+
class MarkupError(ConsoleError):
|
26 |
+
"""Markup was badly formatted."""
|
27 |
+
|
28 |
+
|
29 |
+
class LiveError(ConsoleError):
|
30 |
+
"""Error related to Live display."""
|
31 |
+
|
32 |
+
|
33 |
+
class NoAltScreen(ConsoleError):
|
34 |
+
"""Alt screen mode was required."""
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/file_proxy.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
from typing import List, Any, IO, TYPE_CHECKING
|
3 |
+
|
4 |
+
from .ansi import AnsiDecoder
|
5 |
+
from .text import Text
|
6 |
+
|
7 |
+
if TYPE_CHECKING:
|
8 |
+
from .console import Console
|
9 |
+
|
10 |
+
|
11 |
+
class FileProxy(io.TextIOBase):
|
12 |
+
"""Wraps a file (e.g. sys.stdout) and redirects writes to a console."""
|
13 |
+
|
14 |
+
def __init__(self, console: "Console", file: IO[str]) -> None:
|
15 |
+
self.__console = console
|
16 |
+
self.__file = file
|
17 |
+
self.__buffer: List[str] = []
|
18 |
+
self.__ansi_decoder = AnsiDecoder()
|
19 |
+
|
20 |
+
@property
|
21 |
+
def rich_proxied_file(self) -> IO[str]:
|
22 |
+
"""Get proxied file."""
|
23 |
+
return self.__file
|
24 |
+
|
25 |
+
def __getattr__(self, name: str) -> Any:
|
26 |
+
return getattr(self.__file, name)
|
27 |
+
|
28 |
+
def write(self, text: str) -> int:
|
29 |
+
if not isinstance(text, str):
|
30 |
+
raise TypeError(f"write() argument must be str, not {type(text).__name__}")
|
31 |
+
buffer = self.__buffer
|
32 |
+
lines: List[str] = []
|
33 |
+
while text:
|
34 |
+
line, new_line, text = text.partition("\n")
|
35 |
+
if new_line:
|
36 |
+
lines.append("".join(buffer) + line)
|
37 |
+
del buffer[:]
|
38 |
+
else:
|
39 |
+
buffer.append(line)
|
40 |
+
break
|
41 |
+
if lines:
|
42 |
+
console = self.__console
|
43 |
+
with console:
|
44 |
+
output = Text("\n").join(
|
45 |
+
self.__ansi_decoder.decode_line(line) for line in lines
|
46 |
+
)
|
47 |
+
console.print(output)
|
48 |
+
return len(text)
|
49 |
+
|
50 |
+
def flush(self) -> None:
|
51 |
+
buffer = self.__buffer
|
52 |
+
if buffer:
|
53 |
+
self.__console.print("".join(buffer))
|
54 |
+
del buffer[:]
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/filesize.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding: utf-8
|
2 |
+
"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2
|
3 |
+
|
4 |
+
The functions declared in this module should cover the different
|
5 |
+
usecases needed to generate a string representation of a file size
|
6 |
+
using several different units. Since there are many standards regarding
|
7 |
+
file size units, three different functions have been implemented.
|
8 |
+
|
9 |
+
See Also:
|
10 |
+
* `Wikipedia: Binary prefix <https://en.wikipedia.org/wiki/Binary_prefix>`_
|
11 |
+
|
12 |
+
"""
|
13 |
+
|
14 |
+
__all__ = ["decimal"]
|
15 |
+
|
16 |
+
from typing import Iterable, List, Tuple, Optional
|
17 |
+
|
18 |
+
|
19 |
+
def _to_str(
|
20 |
+
size: int,
|
21 |
+
suffixes: Iterable[str],
|
22 |
+
base: int,
|
23 |
+
*,
|
24 |
+
precision: Optional[int] = 1,
|
25 |
+
separator: Optional[str] = " ",
|
26 |
+
) -> str:
|
27 |
+
if size == 1:
|
28 |
+
return "1 byte"
|
29 |
+
elif size < base:
|
30 |
+
return "{:,} bytes".format(size)
|
31 |
+
|
32 |
+
for i, suffix in enumerate(suffixes, 2): # noqa: B007
|
33 |
+
unit = base ** i
|
34 |
+
if size < unit:
|
35 |
+
break
|
36 |
+
return "{:,.{precision}f}{separator}{}".format(
|
37 |
+
(base * size / unit),
|
38 |
+
suffix,
|
39 |
+
precision=precision,
|
40 |
+
separator=separator,
|
41 |
+
)
|
42 |
+
|
43 |
+
|
44 |
+
def pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:
|
45 |
+
"""Pick a suffix and base for the given size."""
|
46 |
+
for i, suffix in enumerate(suffixes):
|
47 |
+
unit = base ** i
|
48 |
+
if size < unit * base:
|
49 |
+
break
|
50 |
+
return unit, suffix
|
51 |
+
|
52 |
+
|
53 |
+
def decimal(
|
54 |
+
size: int,
|
55 |
+
*,
|
56 |
+
precision: Optional[int] = 1,
|
57 |
+
separator: Optional[str] = " ",
|
58 |
+
) -> str:
|
59 |
+
"""Convert a filesize in to a string (powers of 1000, SI prefixes).
|
60 |
+
|
61 |
+
In this convention, ``1000 B = 1 kB``.
|
62 |
+
|
63 |
+
This is typically the format used to advertise the storage
|
64 |
+
capacity of USB flash drives and the like (*256 MB* meaning
|
65 |
+
actually a storage capacity of more than *256 000 000 B*),
|
66 |
+
or used by **Mac OS X** since v10.6 to report file sizes.
|
67 |
+
|
68 |
+
Arguments:
|
69 |
+
int (size): A file size.
|
70 |
+
int (precision): The number of decimal places to include (default = 1).
|
71 |
+
str (separator): The string to separate the value from the units (default = " ").
|
72 |
+
|
73 |
+
Returns:
|
74 |
+
`str`: A string containing a abbreviated file size and units.
|
75 |
+
|
76 |
+
Example:
|
77 |
+
>>> filesize.decimal(30000)
|
78 |
+
'30.0 kB'
|
79 |
+
>>> filesize.decimal(30000, precision=2, separator="")
|
80 |
+
'30.00kB'
|
81 |
+
|
82 |
+
"""
|
83 |
+
return _to_str(
|
84 |
+
size,
|
85 |
+
("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"),
|
86 |
+
1000,
|
87 |
+
precision=precision,
|
88 |
+
separator=separator,
|
89 |
+
)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/highlighter.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import ABC, abstractmethod
|
2 |
+
from typing import List, Union
|
3 |
+
|
4 |
+
from .text import Text
|
5 |
+
|
6 |
+
|
7 |
+
def _combine_regex(*regexes: str) -> str:
|
8 |
+
"""Combine a number of regexes in to a single regex.
|
9 |
+
|
10 |
+
Returns:
|
11 |
+
str: New regex with all regexes ORed together.
|
12 |
+
"""
|
13 |
+
return "|".join(regexes)
|
14 |
+
|
15 |
+
|
16 |
+
class Highlighter(ABC):
|
17 |
+
"""Abstract base class for highlighters."""
|
18 |
+
|
19 |
+
def __call__(self, text: Union[str, Text]) -> Text:
|
20 |
+
"""Highlight a str or Text instance.
|
21 |
+
|
22 |
+
Args:
|
23 |
+
text (Union[str, ~Text]): Text to highlight.
|
24 |
+
|
25 |
+
Raises:
|
26 |
+
TypeError: If not called with text or str.
|
27 |
+
|
28 |
+
Returns:
|
29 |
+
Text: A test instance with highlighting applied.
|
30 |
+
"""
|
31 |
+
if isinstance(text, str):
|
32 |
+
highlight_text = Text(text)
|
33 |
+
elif isinstance(text, Text):
|
34 |
+
highlight_text = text.copy()
|
35 |
+
else:
|
36 |
+
raise TypeError(f"str or Text instance required, not {text!r}")
|
37 |
+
self.highlight(highlight_text)
|
38 |
+
return highlight_text
|
39 |
+
|
40 |
+
@abstractmethod
|
41 |
+
def highlight(self, text: Text) -> None:
|
42 |
+
"""Apply highlighting in place to text.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
text (~Text): A text object highlight.
|
46 |
+
"""
|
47 |
+
|
48 |
+
|
49 |
+
class NullHighlighter(Highlighter):
|
50 |
+
"""A highlighter object that doesn't highlight.
|
51 |
+
|
52 |
+
May be used to disable highlighting entirely.
|
53 |
+
|
54 |
+
"""
|
55 |
+
|
56 |
+
def highlight(self, text: Text) -> None:
|
57 |
+
"""Nothing to do"""
|
58 |
+
|
59 |
+
|
60 |
+
class RegexHighlighter(Highlighter):
|
61 |
+
"""Applies highlighting from a list of regular expressions."""
|
62 |
+
|
63 |
+
highlights: List[str] = []
|
64 |
+
base_style: str = ""
|
65 |
+
|
66 |
+
def highlight(self, text: Text) -> None:
|
67 |
+
"""Highlight :class:`rich.text.Text` using regular expressions.
|
68 |
+
|
69 |
+
Args:
|
70 |
+
text (~Text): Text to highlighted.
|
71 |
+
|
72 |
+
"""
|
73 |
+
|
74 |
+
highlight_regex = text.highlight_regex
|
75 |
+
for re_highlight in self.highlights:
|
76 |
+
highlight_regex(re_highlight, style_prefix=self.base_style)
|
77 |
+
|
78 |
+
|
79 |
+
class ReprHighlighter(RegexHighlighter):
|
80 |
+
"""Highlights the text typically produced from ``__repr__`` methods."""
|
81 |
+
|
82 |
+
base_style = "repr."
|
83 |
+
highlights = [
|
84 |
+
r"(?P<tag_start>\<)(?P<tag_name>[\w\-\.\:]*)(?P<tag_contents>[\w\W]*?)(?P<tag_end>\>)",
|
85 |
+
r"(?P<attrib_name>[\w_]{1,50})=(?P<attrib_value>\"?[\w_]+\"?)?",
|
86 |
+
r"(?P<brace>[\{\[\(\)\]\}])",
|
87 |
+
_combine_regex(
|
88 |
+
r"(?P<ipv4>[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})",
|
89 |
+
r"(?P<ipv6>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})",
|
90 |
+
r"(?P<eui64>(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){3}[0-9A-Fa-f]{4})",
|
91 |
+
r"(?P<eui48>(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})",
|
92 |
+
r"(?P<call>[\w\.]*?)\(",
|
93 |
+
r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b",
|
94 |
+
r"(?P<ellipsis>\.\.\.)",
|
95 |
+
r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)",
|
96 |
+
r"(?P<path>\B(\/[\w\.\-\_\+]+)*\/)(?P<filename>[\w\.\-\_\+]*)?",
|
97 |
+
r"(?<![\\\w])(?P<str>b?\'\'\'.*?(?<!\\)\'\'\'|b?\'.*?(?<!\\)\'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")",
|
98 |
+
r"(?P<uuid>[a-fA-F0-9]{8}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{12})",
|
99 |
+
r"(?P<url>(file|https|http|ws|wss):\/\/[0-9a-zA-Z\$\-\_\+\!`\(\)\,\.\?\/\;\:\&\=\%\#]*)",
|
100 |
+
),
|
101 |
+
]
|
102 |
+
|
103 |
+
|
104 |
+
class JSONHighlighter(RegexHighlighter):
|
105 |
+
"""Highlights JSON"""
|
106 |
+
|
107 |
+
base_style = "json."
|
108 |
+
highlights = [
|
109 |
+
_combine_regex(
|
110 |
+
r"(?P<brace>[\{\[\(\)\]\}])",
|
111 |
+
r"\b(?P<bool_true>true)\b|\b(?P<bool_false>false)\b|\b(?P<null>null)\b",
|
112 |
+
r"(?P<number>(?<!\w)\-?[0-9]+\.?[0-9]*(e[\-\+]?\d+?)?\b|0x[0-9a-fA-F]*)",
|
113 |
+
r"(?<![\\\w])(?P<str>b?\".*?(?<!\\)\")",
|
114 |
+
),
|
115 |
+
r"(?<![\\\w])(?P<key>b?\".*?(?<!\\)\")\:",
|
116 |
+
]
|
117 |
+
|
118 |
+
|
119 |
+
if __name__ == "__main__": # pragma: no cover
|
120 |
+
from .console import Console
|
121 |
+
|
122 |
+
console = Console()
|
123 |
+
console.print("[bold green]hello world![/bold green]")
|
124 |
+
console.print("'[bold green]hello world![/bold green]'")
|
125 |
+
|
126 |
+
console.print(" /foo")
|
127 |
+
console.print("/foo/")
|
128 |
+
console.print("/foo/bar")
|
129 |
+
console.print("foo/bar/baz")
|
130 |
+
|
131 |
+
console.print("/foo/bar/baz?foo=bar+egg&egg=baz")
|
132 |
+
console.print("/foo/bar/baz/")
|
133 |
+
console.print("/foo/bar/baz/egg")
|
134 |
+
console.print("/foo/bar/baz/egg.py")
|
135 |
+
console.print("/foo/bar/baz/egg.py word")
|
136 |
+
console.print(" /foo/bar/baz/egg.py word")
|
137 |
+
console.print("foo /foo/bar/baz/egg.py word")
|
138 |
+
console.print("foo /foo/bar/ba._++z/egg+.py word")
|
139 |
+
console.print("https://example.org?foo=bar#header")
|
140 |
+
|
141 |
+
console.print(1234567.34)
|
142 |
+
console.print(1 / 2)
|
143 |
+
console.print(-1 / 123123123123)
|
144 |
+
|
145 |
+
console.print(
|
146 |
+
"127.0.1.1 bar 192.168.1.4 2001:0db8:85a3:0000:0000:8a2e:0370:7334 foo"
|
147 |
+
)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/json.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from json import loads, dumps
|
2 |
+
from typing import Any, Callable, Optional, Union
|
3 |
+
|
4 |
+
from .text import Text
|
5 |
+
from .highlighter import JSONHighlighter, NullHighlighter
|
6 |
+
|
7 |
+
|
8 |
+
class JSON:
|
9 |
+
"""A renderable which pretty prints JSON.
|
10 |
+
|
11 |
+
Args:
|
12 |
+
json (str): JSON encoded data.
|
13 |
+
indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
|
14 |
+
highlight (bool, optional): Enable highlighting. Defaults to True.
|
15 |
+
skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
|
16 |
+
ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
|
17 |
+
check_circular (bool, optional): Check for circular references. Defaults to True.
|
18 |
+
allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
|
19 |
+
default (Callable, optional): A callable that converts values that can not be encoded
|
20 |
+
in to something that can be JSON encoded. Defaults to None.
|
21 |
+
sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
|
22 |
+
"""
|
23 |
+
|
24 |
+
def __init__(
|
25 |
+
self,
|
26 |
+
json: str,
|
27 |
+
indent: Union[None, int, str] = 2,
|
28 |
+
highlight: bool = True,
|
29 |
+
skip_keys: bool = False,
|
30 |
+
ensure_ascii: bool = True,
|
31 |
+
check_circular: bool = True,
|
32 |
+
allow_nan: bool = True,
|
33 |
+
default: Optional[Callable[[Any], Any]] = None,
|
34 |
+
sort_keys: bool = False,
|
35 |
+
) -> None:
|
36 |
+
data = loads(json)
|
37 |
+
json = dumps(
|
38 |
+
data,
|
39 |
+
indent=indent,
|
40 |
+
skipkeys=skip_keys,
|
41 |
+
ensure_ascii=ensure_ascii,
|
42 |
+
check_circular=check_circular,
|
43 |
+
allow_nan=allow_nan,
|
44 |
+
default=default,
|
45 |
+
sort_keys=sort_keys,
|
46 |
+
)
|
47 |
+
highlighter = JSONHighlighter() if highlight else NullHighlighter()
|
48 |
+
self.text = highlighter(json)
|
49 |
+
self.text.no_wrap = True
|
50 |
+
self.text.overflow = None
|
51 |
+
|
52 |
+
@classmethod
|
53 |
+
def from_data(
|
54 |
+
cls,
|
55 |
+
data: Any,
|
56 |
+
indent: Union[None, int, str] = 2,
|
57 |
+
highlight: bool = True,
|
58 |
+
skip_keys: bool = False,
|
59 |
+
ensure_ascii: bool = True,
|
60 |
+
check_circular: bool = True,
|
61 |
+
allow_nan: bool = True,
|
62 |
+
default: Optional[Callable[[Any], Any]] = None,
|
63 |
+
sort_keys: bool = False,
|
64 |
+
) -> "JSON":
|
65 |
+
"""Encodes a JSON object from arbitrary data.
|
66 |
+
|
67 |
+
Args:
|
68 |
+
data (Any): An object that may be encoded in to JSON
|
69 |
+
indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
|
70 |
+
highlight (bool, optional): Enable highlighting. Defaults to True.
|
71 |
+
default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None.
|
72 |
+
skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
|
73 |
+
ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
|
74 |
+
check_circular (bool, optional): Check for circular references. Defaults to True.
|
75 |
+
allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
|
76 |
+
default (Callable, optional): A callable that converts values that can not be encoded
|
77 |
+
in to something that can be JSON encoded. Defaults to None.
|
78 |
+
sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
|
79 |
+
|
80 |
+
Returns:
|
81 |
+
JSON: New JSON object from the given data.
|
82 |
+
"""
|
83 |
+
json_instance: "JSON" = cls.__new__(cls)
|
84 |
+
json = dumps(
|
85 |
+
data,
|
86 |
+
indent=indent,
|
87 |
+
skipkeys=skip_keys,
|
88 |
+
ensure_ascii=ensure_ascii,
|
89 |
+
check_circular=check_circular,
|
90 |
+
allow_nan=allow_nan,
|
91 |
+
default=default,
|
92 |
+
sort_keys=sort_keys,
|
93 |
+
)
|
94 |
+
highlighter = JSONHighlighter() if highlight else NullHighlighter()
|
95 |
+
json_instance.text = highlighter(json)
|
96 |
+
json_instance.text.no_wrap = True
|
97 |
+
json_instance.text.overflow = None
|
98 |
+
return json_instance
|
99 |
+
|
100 |
+
def __rich__(self) -> Text:
|
101 |
+
return self.text
|
102 |
+
|
103 |
+
|
104 |
+
if __name__ == "__main__":
|
105 |
+
|
106 |
+
import argparse
|
107 |
+
import sys
|
108 |
+
|
109 |
+
parser = argparse.ArgumentParser(description="Pretty print json")
|
110 |
+
parser.add_argument(
|
111 |
+
"path",
|
112 |
+
metavar="PATH",
|
113 |
+
help="path to file, or - for stdin",
|
114 |
+
)
|
115 |
+
parser.add_argument(
|
116 |
+
"-i",
|
117 |
+
"--indent",
|
118 |
+
metavar="SPACES",
|
119 |
+
type=int,
|
120 |
+
help="Number of spaces in an indent",
|
121 |
+
default=2,
|
122 |
+
)
|
123 |
+
args = parser.parse_args()
|
124 |
+
|
125 |
+
from pip._vendor.rich.console import Console
|
126 |
+
|
127 |
+
console = Console()
|
128 |
+
error_console = Console(stderr=True)
|
129 |
+
|
130 |
+
try:
|
131 |
+
if args.path == "-":
|
132 |
+
json_data = sys.stdin.read()
|
133 |
+
else:
|
134 |
+
with open(args.path, "rt") as json_file:
|
135 |
+
json_data = json_file.read()
|
136 |
+
except Exception as error:
|
137 |
+
error_console.print(f"Unable to read {args.path!r}; {error}")
|
138 |
+
sys.exit(-1)
|
139 |
+
|
140 |
+
console.print(JSON(json_data, indent=args.indent), soft_wrap=True)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/jupyter.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Dict, Iterable, List
|
2 |
+
|
3 |
+
from . import get_console
|
4 |
+
from .segment import Segment
|
5 |
+
from .terminal_theme import DEFAULT_TERMINAL_THEME
|
6 |
+
|
7 |
+
JUPYTER_HTML_FORMAT = """\
|
8 |
+
<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace">{code}</pre>
|
9 |
+
"""
|
10 |
+
|
11 |
+
|
12 |
+
class JupyterRenderable:
|
13 |
+
"""A shim to write html to Jupyter notebook."""
|
14 |
+
|
15 |
+
def __init__(self, html: str, text: str) -> None:
|
16 |
+
self.html = html
|
17 |
+
self.text = text
|
18 |
+
|
19 |
+
def _repr_mimebundle_(
|
20 |
+
self, include: Iterable[str], exclude: Iterable[str], **kwargs: Any
|
21 |
+
) -> Dict[str, str]:
|
22 |
+
data = {"text/plain": self.text, "text/html": self.html}
|
23 |
+
if include:
|
24 |
+
data = {k: v for (k, v) in data.items() if k in include}
|
25 |
+
if exclude:
|
26 |
+
data = {k: v for (k, v) in data.items() if k not in exclude}
|
27 |
+
return data
|
28 |
+
|
29 |
+
|
30 |
+
class JupyterMixin:
|
31 |
+
"""Add to an Rich renderable to make it render in Jupyter notebook."""
|
32 |
+
|
33 |
+
__slots__ = ()
|
34 |
+
|
35 |
+
def _repr_mimebundle_(
|
36 |
+
self, include: Iterable[str], exclude: Iterable[str], **kwargs: Any
|
37 |
+
) -> Dict[str, str]:
|
38 |
+
console = get_console()
|
39 |
+
segments = list(console.render(self, console.options)) # type: ignore
|
40 |
+
html = _render_segments(segments)
|
41 |
+
text = console._render_buffer(segments)
|
42 |
+
data = {"text/plain": text, "text/html": html}
|
43 |
+
if include:
|
44 |
+
data = {k: v for (k, v) in data.items() if k in include}
|
45 |
+
if exclude:
|
46 |
+
data = {k: v for (k, v) in data.items() if k not in exclude}
|
47 |
+
return data
|
48 |
+
|
49 |
+
|
50 |
+
def _render_segments(segments: Iterable[Segment]) -> str:
|
51 |
+
def escape(text: str) -> str:
|
52 |
+
"""Escape html."""
|
53 |
+
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
54 |
+
|
55 |
+
fragments: List[str] = []
|
56 |
+
append_fragment = fragments.append
|
57 |
+
theme = DEFAULT_TERMINAL_THEME
|
58 |
+
for text, style, control in Segment.simplify(segments):
|
59 |
+
if control:
|
60 |
+
continue
|
61 |
+
text = escape(text)
|
62 |
+
if style:
|
63 |
+
rule = style.get_html_style(theme)
|
64 |
+
text = f'<span style="{rule}">{text}</span>' if rule else text
|
65 |
+
if style.link:
|
66 |
+
text = f'<a href="{style.link}">{text}</a>'
|
67 |
+
append_fragment(text)
|
68 |
+
|
69 |
+
code = "".join(fragments)
|
70 |
+
html = JUPYTER_HTML_FORMAT.format(code=code)
|
71 |
+
|
72 |
+
return html
|
73 |
+
|
74 |
+
|
75 |
+
def display(segments: Iterable[Segment], text: str) -> None:
|
76 |
+
"""Render segments to Jupyter."""
|
77 |
+
html = _render_segments(segments)
|
78 |
+
jupyter_renderable = JupyterRenderable(html, text)
|
79 |
+
try:
|
80 |
+
from IPython.display import display as ipython_display
|
81 |
+
|
82 |
+
ipython_display(jupyter_renderable)
|
83 |
+
except ModuleNotFoundError:
|
84 |
+
# Handle the case where the Console has force_jupyter=True,
|
85 |
+
# but IPython is not installed.
|
86 |
+
pass
|
87 |
+
|
88 |
+
|
89 |
+
def print(*args: Any, **kwargs: Any) -> None:
|
90 |
+
"""Proxy for Console print."""
|
91 |
+
console = get_console()
|
92 |
+
return console.print(*args, **kwargs)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/layout.py
ADDED
@@ -0,0 +1,444 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import ABC, abstractmethod
|
2 |
+
from itertools import islice
|
3 |
+
from operator import itemgetter
|
4 |
+
from threading import RLock
|
5 |
+
from typing import (
|
6 |
+
TYPE_CHECKING,
|
7 |
+
Dict,
|
8 |
+
Iterable,
|
9 |
+
List,
|
10 |
+
NamedTuple,
|
11 |
+
Optional,
|
12 |
+
Sequence,
|
13 |
+
Tuple,
|
14 |
+
Union,
|
15 |
+
)
|
16 |
+
|
17 |
+
from ._ratio import ratio_resolve
|
18 |
+
from .align import Align
|
19 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
20 |
+
from .highlighter import ReprHighlighter
|
21 |
+
from .panel import Panel
|
22 |
+
from .pretty import Pretty
|
23 |
+
from .repr import rich_repr, Result
|
24 |
+
from .region import Region
|
25 |
+
from .segment import Segment
|
26 |
+
from .style import StyleType
|
27 |
+
|
28 |
+
if TYPE_CHECKING:
|
29 |
+
from pip._vendor.rich.tree import Tree
|
30 |
+
|
31 |
+
|
32 |
+
class LayoutRender(NamedTuple):
|
33 |
+
"""An individual layout render."""
|
34 |
+
|
35 |
+
region: Region
|
36 |
+
render: List[List[Segment]]
|
37 |
+
|
38 |
+
|
39 |
+
RegionMap = Dict["Layout", Region]
|
40 |
+
RenderMap = Dict["Layout", LayoutRender]
|
41 |
+
|
42 |
+
|
43 |
+
class LayoutError(Exception):
|
44 |
+
"""Layout related error."""
|
45 |
+
|
46 |
+
|
47 |
+
class NoSplitter(LayoutError):
|
48 |
+
"""Requested splitter does not exist."""
|
49 |
+
|
50 |
+
|
51 |
+
class _Placeholder:
|
52 |
+
"""An internal renderable used as a Layout placeholder."""
|
53 |
+
|
54 |
+
highlighter = ReprHighlighter()
|
55 |
+
|
56 |
+
def __init__(self, layout: "Layout", style: StyleType = "") -> None:
|
57 |
+
self.layout = layout
|
58 |
+
self.style = style
|
59 |
+
|
60 |
+
def __rich_console__(
|
61 |
+
self, console: Console, options: ConsoleOptions
|
62 |
+
) -> RenderResult:
|
63 |
+
width = options.max_width
|
64 |
+
height = options.height or options.size.height
|
65 |
+
layout = self.layout
|
66 |
+
title = (
|
67 |
+
f"{layout.name!r} ({width} x {height})"
|
68 |
+
if layout.name
|
69 |
+
else f"({width} x {height})"
|
70 |
+
)
|
71 |
+
yield Panel(
|
72 |
+
Align.center(Pretty(layout), vertical="middle"),
|
73 |
+
style=self.style,
|
74 |
+
title=self.highlighter(title),
|
75 |
+
border_style="blue",
|
76 |
+
)
|
77 |
+
|
78 |
+
|
79 |
+
class Splitter(ABC):
|
80 |
+
"""Base class for a splitter."""
|
81 |
+
|
82 |
+
name: str = ""
|
83 |
+
|
84 |
+
@abstractmethod
|
85 |
+
def get_tree_icon(self) -> str:
|
86 |
+
"""Get the icon (emoji) used in layout.tree"""
|
87 |
+
|
88 |
+
@abstractmethod
|
89 |
+
def divide(
|
90 |
+
self, children: Sequence["Layout"], region: Region
|
91 |
+
) -> Iterable[Tuple["Layout", Region]]:
|
92 |
+
"""Divide a region amongst several child layouts.
|
93 |
+
|
94 |
+
Args:
|
95 |
+
children (Sequence(Layout)): A number of child layouts.
|
96 |
+
region (Region): A rectangular region to divide.
|
97 |
+
"""
|
98 |
+
|
99 |
+
|
100 |
+
class RowSplitter(Splitter):
|
101 |
+
"""Split a layout region in to rows."""
|
102 |
+
|
103 |
+
name = "row"
|
104 |
+
|
105 |
+
def get_tree_icon(self) -> str:
|
106 |
+
return "[layout.tree.row]⬌"
|
107 |
+
|
108 |
+
def divide(
|
109 |
+
self, children: Sequence["Layout"], region: Region
|
110 |
+
) -> Iterable[Tuple["Layout", Region]]:
|
111 |
+
x, y, width, height = region
|
112 |
+
render_widths = ratio_resolve(width, children)
|
113 |
+
offset = 0
|
114 |
+
_Region = Region
|
115 |
+
for child, child_width in zip(children, render_widths):
|
116 |
+
yield child, _Region(x + offset, y, child_width, height)
|
117 |
+
offset += child_width
|
118 |
+
|
119 |
+
|
120 |
+
class ColumnSplitter(Splitter):
|
121 |
+
"""Split a layout region in to columns."""
|
122 |
+
|
123 |
+
name = "column"
|
124 |
+
|
125 |
+
def get_tree_icon(self) -> str:
|
126 |
+
return "[layout.tree.column]⬍"
|
127 |
+
|
128 |
+
def divide(
|
129 |
+
self, children: Sequence["Layout"], region: Region
|
130 |
+
) -> Iterable[Tuple["Layout", Region]]:
|
131 |
+
x, y, width, height = region
|
132 |
+
render_heights = ratio_resolve(height, children)
|
133 |
+
offset = 0
|
134 |
+
_Region = Region
|
135 |
+
for child, child_height in zip(children, render_heights):
|
136 |
+
yield child, _Region(x, y + offset, width, child_height)
|
137 |
+
offset += child_height
|
138 |
+
|
139 |
+
|
140 |
+
@rich_repr
|
141 |
+
class Layout:
|
142 |
+
"""A renderable to divide a fixed height in to rows or columns.
|
143 |
+
|
144 |
+
Args:
|
145 |
+
renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None.
|
146 |
+
name (str, optional): Optional identifier for Layout. Defaults to None.
|
147 |
+
size (int, optional): Optional fixed size of layout. Defaults to None.
|
148 |
+
minimum_size (int, optional): Minimum size of layout. Defaults to 1.
|
149 |
+
ratio (int, optional): Optional ratio for flexible layout. Defaults to 1.
|
150 |
+
visible (bool, optional): Visibility of layout. Defaults to True.
|
151 |
+
"""
|
152 |
+
|
153 |
+
splitters = {"row": RowSplitter, "column": ColumnSplitter}
|
154 |
+
|
155 |
+
def __init__(
|
156 |
+
self,
|
157 |
+
renderable: Optional[RenderableType] = None,
|
158 |
+
*,
|
159 |
+
name: Optional[str] = None,
|
160 |
+
size: Optional[int] = None,
|
161 |
+
minimum_size: int = 1,
|
162 |
+
ratio: int = 1,
|
163 |
+
visible: bool = True,
|
164 |
+
height: Optional[int] = None,
|
165 |
+
) -> None:
|
166 |
+
self._renderable = renderable or _Placeholder(self)
|
167 |
+
self.size = size
|
168 |
+
self.minimum_size = minimum_size
|
169 |
+
self.ratio = ratio
|
170 |
+
self.name = name
|
171 |
+
self.visible = visible
|
172 |
+
self.height = height
|
173 |
+
self.splitter: Splitter = self.splitters["column"]()
|
174 |
+
self._children: List[Layout] = []
|
175 |
+
self._render_map: RenderMap = {}
|
176 |
+
self._lock = RLock()
|
177 |
+
|
178 |
+
def __rich_repr__(self) -> Result:
|
179 |
+
yield "name", self.name, None
|
180 |
+
yield "size", self.size, None
|
181 |
+
yield "minimum_size", self.minimum_size, 1
|
182 |
+
yield "ratio", self.ratio, 1
|
183 |
+
|
184 |
+
@property
|
185 |
+
def renderable(self) -> RenderableType:
|
186 |
+
"""Layout renderable."""
|
187 |
+
return self if self._children else self._renderable
|
188 |
+
|
189 |
+
@property
|
190 |
+
def children(self) -> List["Layout"]:
|
191 |
+
"""Gets (visible) layout children."""
|
192 |
+
return [child for child in self._children if child.visible]
|
193 |
+
|
194 |
+
@property
|
195 |
+
def map(self) -> RenderMap:
|
196 |
+
"""Get a map of the last render."""
|
197 |
+
return self._render_map
|
198 |
+
|
199 |
+
def get(self, name: str) -> Optional["Layout"]:
|
200 |
+
"""Get a named layout, or None if it doesn't exist.
|
201 |
+
|
202 |
+
Args:
|
203 |
+
name (str): Name of layout.
|
204 |
+
|
205 |
+
Returns:
|
206 |
+
Optional[Layout]: Layout instance or None if no layout was found.
|
207 |
+
"""
|
208 |
+
if self.name == name:
|
209 |
+
return self
|
210 |
+
else:
|
211 |
+
for child in self._children:
|
212 |
+
named_layout = child.get(name)
|
213 |
+
if named_layout is not None:
|
214 |
+
return named_layout
|
215 |
+
return None
|
216 |
+
|
217 |
+
def __getitem__(self, name: str) -> "Layout":
|
218 |
+
layout = self.get(name)
|
219 |
+
if layout is None:
|
220 |
+
raise KeyError(f"No layout with name {name!r}")
|
221 |
+
return layout
|
222 |
+
|
223 |
+
@property
|
224 |
+
def tree(self) -> "Tree":
|
225 |
+
"""Get a tree renderable to show layout structure."""
|
226 |
+
from pip._vendor.rich.styled import Styled
|
227 |
+
from pip._vendor.rich.table import Table
|
228 |
+
from pip._vendor.rich.tree import Tree
|
229 |
+
|
230 |
+
def summary(layout: "Layout") -> Table:
|
231 |
+
|
232 |
+
icon = layout.splitter.get_tree_icon()
|
233 |
+
|
234 |
+
table = Table.grid(padding=(0, 1, 0, 0))
|
235 |
+
|
236 |
+
text: RenderableType = (
|
237 |
+
Pretty(layout) if layout.visible else Styled(Pretty(layout), "dim")
|
238 |
+
)
|
239 |
+
table.add_row(icon, text)
|
240 |
+
_summary = table
|
241 |
+
return _summary
|
242 |
+
|
243 |
+
layout = self
|
244 |
+
tree = Tree(
|
245 |
+
summary(layout),
|
246 |
+
guide_style=f"layout.tree.{layout.splitter.name}",
|
247 |
+
highlight=True,
|
248 |
+
)
|
249 |
+
|
250 |
+
def recurse(tree: "Tree", layout: "Layout") -> None:
|
251 |
+
for child in layout._children:
|
252 |
+
recurse(
|
253 |
+
tree.add(
|
254 |
+
summary(child),
|
255 |
+
guide_style=f"layout.tree.{child.splitter.name}",
|
256 |
+
),
|
257 |
+
child,
|
258 |
+
)
|
259 |
+
|
260 |
+
recurse(tree, self)
|
261 |
+
return tree
|
262 |
+
|
263 |
+
def split(
|
264 |
+
self,
|
265 |
+
*layouts: Union["Layout", RenderableType],
|
266 |
+
splitter: Union[Splitter, str] = "column",
|
267 |
+
) -> None:
|
268 |
+
"""Split the layout in to multiple sub-layouts.
|
269 |
+
|
270 |
+
Args:
|
271 |
+
*layouts (Layout): Positional arguments should be (sub) Layout instances.
|
272 |
+
splitter (Union[Splitter, str]): Splitter instance or name of splitter.
|
273 |
+
"""
|
274 |
+
_layouts = [
|
275 |
+
layout if isinstance(layout, Layout) else Layout(layout)
|
276 |
+
for layout in layouts
|
277 |
+
]
|
278 |
+
try:
|
279 |
+
self.splitter = (
|
280 |
+
splitter
|
281 |
+
if isinstance(splitter, Splitter)
|
282 |
+
else self.splitters[splitter]()
|
283 |
+
)
|
284 |
+
except KeyError:
|
285 |
+
raise NoSplitter(f"No splitter called {splitter!r}")
|
286 |
+
self._children[:] = _layouts
|
287 |
+
|
288 |
+
def add_split(self, *layouts: Union["Layout", RenderableType]) -> None:
|
289 |
+
"""Add a new layout(s) to existing split.
|
290 |
+
|
291 |
+
Args:
|
292 |
+
*layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances.
|
293 |
+
|
294 |
+
"""
|
295 |
+
_layouts = (
|
296 |
+
layout if isinstance(layout, Layout) else Layout(layout)
|
297 |
+
for layout in layouts
|
298 |
+
)
|
299 |
+
self._children.extend(_layouts)
|
300 |
+
|
301 |
+
def split_row(self, *layouts: Union["Layout", RenderableType]) -> None:
|
302 |
+
"""Split the layout in tow a row (Layouts side by side).
|
303 |
+
|
304 |
+
Args:
|
305 |
+
*layouts (Layout): Positional arguments should be (sub) Layout instances.
|
306 |
+
"""
|
307 |
+
self.split(*layouts, splitter="row")
|
308 |
+
|
309 |
+
def split_column(self, *layouts: Union["Layout", RenderableType]) -> None:
|
310 |
+
"""Split the layout in to a column (layouts stacked on top of each other).
|
311 |
+
|
312 |
+
Args:
|
313 |
+
*layouts (Layout): Positional arguments should be (sub) Layout instances.
|
314 |
+
"""
|
315 |
+
self.split(*layouts, splitter="column")
|
316 |
+
|
317 |
+
def unsplit(self) -> None:
|
318 |
+
"""Reset splits to initial state."""
|
319 |
+
del self._children[:]
|
320 |
+
|
321 |
+
def update(self, renderable: RenderableType) -> None:
|
322 |
+
"""Update renderable.
|
323 |
+
|
324 |
+
Args:
|
325 |
+
renderable (RenderableType): New renderable object.
|
326 |
+
"""
|
327 |
+
with self._lock:
|
328 |
+
self._renderable = renderable
|
329 |
+
|
330 |
+
def refresh_screen(self, console: "Console", layout_name: str) -> None:
|
331 |
+
"""Refresh a sub-layout.
|
332 |
+
|
333 |
+
Args:
|
334 |
+
console (Console): Console instance where Layout is to be rendered.
|
335 |
+
layout_name (str): Name of layout.
|
336 |
+
"""
|
337 |
+
with self._lock:
|
338 |
+
layout = self[layout_name]
|
339 |
+
region, _lines = self._render_map[layout]
|
340 |
+
(x, y, width, height) = region
|
341 |
+
lines = console.render_lines(
|
342 |
+
layout, console.options.update_dimensions(width, height)
|
343 |
+
)
|
344 |
+
self._render_map[layout] = LayoutRender(region, lines)
|
345 |
+
console.update_screen_lines(lines, x, y)
|
346 |
+
|
347 |
+
def _make_region_map(self, width: int, height: int) -> RegionMap:
|
348 |
+
"""Create a dict that maps layout on to Region."""
|
349 |
+
stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))]
|
350 |
+
push = stack.append
|
351 |
+
pop = stack.pop
|
352 |
+
layout_regions: List[Tuple[Layout, Region]] = []
|
353 |
+
append_layout_region = layout_regions.append
|
354 |
+
while stack:
|
355 |
+
append_layout_region(pop())
|
356 |
+
layout, region = layout_regions[-1]
|
357 |
+
children = layout.children
|
358 |
+
if children:
|
359 |
+
for child_and_region in layout.splitter.divide(children, region):
|
360 |
+
push(child_and_region)
|
361 |
+
|
362 |
+
region_map = {
|
363 |
+
layout: region
|
364 |
+
for layout, region in sorted(layout_regions, key=itemgetter(1))
|
365 |
+
}
|
366 |
+
return region_map
|
367 |
+
|
368 |
+
def render(self, console: Console, options: ConsoleOptions) -> RenderMap:
|
369 |
+
"""Render the sub_layouts.
|
370 |
+
|
371 |
+
Args:
|
372 |
+
console (Console): Console instance.
|
373 |
+
options (ConsoleOptions): Console options.
|
374 |
+
|
375 |
+
Returns:
|
376 |
+
RenderMap: A dict that maps Layout on to a tuple of Region, lines
|
377 |
+
"""
|
378 |
+
render_width = options.max_width
|
379 |
+
render_height = options.height or console.height
|
380 |
+
region_map = self._make_region_map(render_width, render_height)
|
381 |
+
layout_regions = [
|
382 |
+
(layout, region)
|
383 |
+
for layout, region in region_map.items()
|
384 |
+
if not layout.children
|
385 |
+
]
|
386 |
+
render_map: Dict["Layout", "LayoutRender"] = {}
|
387 |
+
render_lines = console.render_lines
|
388 |
+
update_dimensions = options.update_dimensions
|
389 |
+
|
390 |
+
for layout, region in layout_regions:
|
391 |
+
lines = render_lines(
|
392 |
+
layout.renderable, update_dimensions(region.width, region.height)
|
393 |
+
)
|
394 |
+
render_map[layout] = LayoutRender(region, lines)
|
395 |
+
return render_map
|
396 |
+
|
397 |
+
def __rich_console__(
|
398 |
+
self, console: Console, options: ConsoleOptions
|
399 |
+
) -> RenderResult:
|
400 |
+
with self._lock:
|
401 |
+
width = options.max_width or console.width
|
402 |
+
height = options.height or console.height
|
403 |
+
render_map = self.render(console, options.update_dimensions(width, height))
|
404 |
+
self._render_map = render_map
|
405 |
+
layout_lines: List[List[Segment]] = [[] for _ in range(height)]
|
406 |
+
_islice = islice
|
407 |
+
for (region, lines) in render_map.values():
|
408 |
+
_x, y, _layout_width, layout_height = region
|
409 |
+
for row, line in zip(
|
410 |
+
_islice(layout_lines, y, y + layout_height), lines
|
411 |
+
):
|
412 |
+
row.extend(line)
|
413 |
+
|
414 |
+
new_line = Segment.line()
|
415 |
+
for layout_row in layout_lines:
|
416 |
+
yield from layout_row
|
417 |
+
yield new_line
|
418 |
+
|
419 |
+
|
420 |
+
if __name__ == "__main__":
|
421 |
+
from pip._vendor.rich.console import Console
|
422 |
+
|
423 |
+
console = Console()
|
424 |
+
layout = Layout()
|
425 |
+
|
426 |
+
layout.split_column(
|
427 |
+
Layout(name="header", size=3),
|
428 |
+
Layout(ratio=1, name="main"),
|
429 |
+
Layout(size=10, name="footer"),
|
430 |
+
)
|
431 |
+
|
432 |
+
layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))
|
433 |
+
|
434 |
+
layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))
|
435 |
+
|
436 |
+
layout["s2"].split_column(
|
437 |
+
Layout(name="top"), Layout(name="middle"), Layout(name="bottom")
|
438 |
+
)
|
439 |
+
|
440 |
+
layout["side"].split_column(Layout(layout.tree, name="left1"), Layout(name="left2"))
|
441 |
+
|
442 |
+
layout["content"].update("foo")
|
443 |
+
|
444 |
+
console.print(layout)
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/live_render.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
from typing import Optional, Tuple
|
3 |
+
|
4 |
+
if sys.version_info >= (3, 8):
|
5 |
+
from typing import Literal
|
6 |
+
else:
|
7 |
+
from pip._vendor.typing_extensions import Literal # pragma: no cover
|
8 |
+
|
9 |
+
|
10 |
+
from ._loop import loop_last
|
11 |
+
from .console import Console, ConsoleOptions, RenderableType, RenderResult
|
12 |
+
from .control import Control
|
13 |
+
from .segment import ControlType, Segment
|
14 |
+
from .style import StyleType
|
15 |
+
from .text import Text
|
16 |
+
|
17 |
+
VerticalOverflowMethod = Literal["crop", "ellipsis", "visible"]
|
18 |
+
|
19 |
+
|
20 |
+
class LiveRender:
|
21 |
+
"""Creates a renderable that may be updated.
|
22 |
+
|
23 |
+
Args:
|
24 |
+
renderable (RenderableType): Any renderable object.
|
25 |
+
style (StyleType, optional): An optional style to apply to the renderable. Defaults to "".
|
26 |
+
"""
|
27 |
+
|
28 |
+
def __init__(
|
29 |
+
self,
|
30 |
+
renderable: RenderableType,
|
31 |
+
style: StyleType = "",
|
32 |
+
vertical_overflow: VerticalOverflowMethod = "ellipsis",
|
33 |
+
) -> None:
|
34 |
+
self.renderable = renderable
|
35 |
+
self.style = style
|
36 |
+
self.vertical_overflow = vertical_overflow
|
37 |
+
self._shape: Optional[Tuple[int, int]] = None
|
38 |
+
|
39 |
+
def set_renderable(self, renderable: RenderableType) -> None:
|
40 |
+
"""Set a new renderable.
|
41 |
+
|
42 |
+
Args:
|
43 |
+
renderable (RenderableType): Any renderable object, including str.
|
44 |
+
"""
|
45 |
+
self.renderable = renderable
|
46 |
+
|
47 |
+
def position_cursor(self) -> Control:
|
48 |
+
"""Get control codes to move cursor to beginning of live render.
|
49 |
+
|
50 |
+
Returns:
|
51 |
+
Control: A control instance that may be printed.
|
52 |
+
"""
|
53 |
+
if self._shape is not None:
|
54 |
+
_, height = self._shape
|
55 |
+
return Control(
|
56 |
+
ControlType.CARRIAGE_RETURN,
|
57 |
+
(ControlType.ERASE_IN_LINE, 2),
|
58 |
+
*(
|
59 |
+
(
|
60 |
+
(ControlType.CURSOR_UP, 1),
|
61 |
+
(ControlType.ERASE_IN_LINE, 2),
|
62 |
+
)
|
63 |
+
* (height - 1)
|
64 |
+
)
|
65 |
+
)
|
66 |
+
return Control()
|
67 |
+
|
68 |
+
def restore_cursor(self) -> Control:
|
69 |
+
"""Get control codes to clear the render and restore the cursor to its previous position.
|
70 |
+
|
71 |
+
Returns:
|
72 |
+
Control: A Control instance that may be printed.
|
73 |
+
"""
|
74 |
+
if self._shape is not None:
|
75 |
+
_, height = self._shape
|
76 |
+
return Control(
|
77 |
+
ControlType.CARRIAGE_RETURN,
|
78 |
+
*((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height
|
79 |
+
)
|
80 |
+
return Control()
|
81 |
+
|
82 |
+
def __rich_console__(
|
83 |
+
self, console: Console, options: ConsoleOptions
|
84 |
+
) -> RenderResult:
|
85 |
+
|
86 |
+
renderable = self.renderable
|
87 |
+
style = console.get_style(self.style)
|
88 |
+
lines = console.render_lines(renderable, options, style=style, pad=False)
|
89 |
+
shape = Segment.get_shape(lines)
|
90 |
+
|
91 |
+
_, height = shape
|
92 |
+
if height > options.size.height:
|
93 |
+
if self.vertical_overflow == "crop":
|
94 |
+
lines = lines[: options.size.height]
|
95 |
+
shape = Segment.get_shape(lines)
|
96 |
+
elif self.vertical_overflow == "ellipsis":
|
97 |
+
lines = lines[: (options.size.height - 1)]
|
98 |
+
overflow_text = Text(
|
99 |
+
"...",
|
100 |
+
overflow="crop",
|
101 |
+
justify="center",
|
102 |
+
end="",
|
103 |
+
style="live.ellipsis",
|
104 |
+
)
|
105 |
+
lines.append(list(console.render(overflow_text)))
|
106 |
+
shape = Segment.get_shape(lines)
|
107 |
+
self._shape = shape
|
108 |
+
|
109 |
+
new_line = Segment.line()
|
110 |
+
for last, line in loop_last(lines):
|
111 |
+
yield from line
|
112 |
+
if not last:
|
113 |
+
yield new_line
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/logging.py
ADDED
@@ -0,0 +1,268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from datetime import datetime
|
3 |
+
from logging import Handler, LogRecord
|
4 |
+
from pathlib import Path
|
5 |
+
from typing import ClassVar, List, Optional, Type, Union
|
6 |
+
|
7 |
+
from . import get_console
|
8 |
+
from ._log_render import LogRender, FormatTimeCallable
|
9 |
+
from .console import Console, ConsoleRenderable
|
10 |
+
from .highlighter import Highlighter, ReprHighlighter
|
11 |
+
from .text import Text
|
12 |
+
from .traceback import Traceback
|
13 |
+
|
14 |
+
|
15 |
+
class RichHandler(Handler):
|
16 |
+
"""A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.
|
17 |
+
The level is color coded, and the message is syntax highlighted.
|
18 |
+
|
19 |
+
Note:
|
20 |
+
Be careful when enabling console markup in log messages if you have configured logging for libraries not
|
21 |
+
under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.
|
22 |
+
|
23 |
+
Args:
|
24 |
+
level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.
|
25 |
+
console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.
|
26 |
+
Default will use a global console instance writing to stdout.
|
27 |
+
show_time (bool, optional): Show a column for the time. Defaults to True.
|
28 |
+
omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.
|
29 |
+
show_level (bool, optional): Show a column for the level. Defaults to True.
|
30 |
+
show_path (bool, optional): Show the path to the original log call. Defaults to True.
|
31 |
+
enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.
|
32 |
+
highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.
|
33 |
+
markup (bool, optional): Enable console markup in log messages. Defaults to False.
|
34 |
+
rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False.
|
35 |
+
tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None.
|
36 |
+
tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None.
|
37 |
+
tracebacks_theme (str, optional): Override pygments theme used in traceback.
|
38 |
+
tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True.
|
39 |
+
tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False.
|
40 |
+
locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
|
41 |
+
Defaults to 10.
|
42 |
+
locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
|
43 |
+
log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to "[%x %X] ".
|
44 |
+
"""
|
45 |
+
|
46 |
+
KEYWORDS: ClassVar[Optional[List[str]]] = [
|
47 |
+
"GET",
|
48 |
+
"POST",
|
49 |
+
"HEAD",
|
50 |
+
"PUT",
|
51 |
+
"DELETE",
|
52 |
+
"OPTIONS",
|
53 |
+
"TRACE",
|
54 |
+
"PATCH",
|
55 |
+
]
|
56 |
+
HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter
|
57 |
+
|
58 |
+
def __init__(
|
59 |
+
self,
|
60 |
+
level: Union[int, str] = logging.NOTSET,
|
61 |
+
console: Optional[Console] = None,
|
62 |
+
*,
|
63 |
+
show_time: bool = True,
|
64 |
+
omit_repeated_times: bool = True,
|
65 |
+
show_level: bool = True,
|
66 |
+
show_path: bool = True,
|
67 |
+
enable_link_path: bool = True,
|
68 |
+
highlighter: Optional[Highlighter] = None,
|
69 |
+
markup: bool = False,
|
70 |
+
rich_tracebacks: bool = False,
|
71 |
+
tracebacks_width: Optional[int] = None,
|
72 |
+
tracebacks_extra_lines: int = 3,
|
73 |
+
tracebacks_theme: Optional[str] = None,
|
74 |
+
tracebacks_word_wrap: bool = True,
|
75 |
+
tracebacks_show_locals: bool = False,
|
76 |
+
locals_max_length: int = 10,
|
77 |
+
locals_max_string: int = 80,
|
78 |
+
log_time_format: Union[str, FormatTimeCallable] = "[%x %X]",
|
79 |
+
) -> None:
|
80 |
+
super().__init__(level=level)
|
81 |
+
self.console = console or get_console()
|
82 |
+
self.highlighter = highlighter or self.HIGHLIGHTER_CLASS()
|
83 |
+
self._log_render = LogRender(
|
84 |
+
show_time=show_time,
|
85 |
+
show_level=show_level,
|
86 |
+
show_path=show_path,
|
87 |
+
time_format=log_time_format,
|
88 |
+
omit_repeated_times=omit_repeated_times,
|
89 |
+
level_width=None,
|
90 |
+
)
|
91 |
+
self.enable_link_path = enable_link_path
|
92 |
+
self.markup = markup
|
93 |
+
self.rich_tracebacks = rich_tracebacks
|
94 |
+
self.tracebacks_width = tracebacks_width
|
95 |
+
self.tracebacks_extra_lines = tracebacks_extra_lines
|
96 |
+
self.tracebacks_theme = tracebacks_theme
|
97 |
+
self.tracebacks_word_wrap = tracebacks_word_wrap
|
98 |
+
self.tracebacks_show_locals = tracebacks_show_locals
|
99 |
+
self.locals_max_length = locals_max_length
|
100 |
+
self.locals_max_string = locals_max_string
|
101 |
+
|
102 |
+
def get_level_text(self, record: LogRecord) -> Text:
|
103 |
+
"""Get the level name from the record.
|
104 |
+
|
105 |
+
Args:
|
106 |
+
record (LogRecord): LogRecord instance.
|
107 |
+
|
108 |
+
Returns:
|
109 |
+
Text: A tuple of the style and level name.
|
110 |
+
"""
|
111 |
+
level_name = record.levelname
|
112 |
+
level_text = Text.styled(
|
113 |
+
level_name.ljust(8), f"logging.level.{level_name.lower()}"
|
114 |
+
)
|
115 |
+
return level_text
|
116 |
+
|
117 |
+
def emit(self, record: LogRecord) -> None:
|
118 |
+
"""Invoked by logging."""
|
119 |
+
message = self.format(record)
|
120 |
+
traceback = None
|
121 |
+
if (
|
122 |
+
self.rich_tracebacks
|
123 |
+
and record.exc_info
|
124 |
+
and record.exc_info != (None, None, None)
|
125 |
+
):
|
126 |
+
exc_type, exc_value, exc_traceback = record.exc_info
|
127 |
+
assert exc_type is not None
|
128 |
+
assert exc_value is not None
|
129 |
+
traceback = Traceback.from_exception(
|
130 |
+
exc_type,
|
131 |
+
exc_value,
|
132 |
+
exc_traceback,
|
133 |
+
width=self.tracebacks_width,
|
134 |
+
extra_lines=self.tracebacks_extra_lines,
|
135 |
+
theme=self.tracebacks_theme,
|
136 |
+
word_wrap=self.tracebacks_word_wrap,
|
137 |
+
show_locals=self.tracebacks_show_locals,
|
138 |
+
locals_max_length=self.locals_max_length,
|
139 |
+
locals_max_string=self.locals_max_string,
|
140 |
+
)
|
141 |
+
message = record.getMessage()
|
142 |
+
if self.formatter:
|
143 |
+
record.message = record.getMessage()
|
144 |
+
formatter = self.formatter
|
145 |
+
if hasattr(formatter, "usesTime") and formatter.usesTime():
|
146 |
+
record.asctime = formatter.formatTime(record, formatter.datefmt)
|
147 |
+
message = formatter.formatMessage(record)
|
148 |
+
|
149 |
+
message_renderable = self.render_message(record, message)
|
150 |
+
log_renderable = self.render(
|
151 |
+
record=record, traceback=traceback, message_renderable=message_renderable
|
152 |
+
)
|
153 |
+
try:
|
154 |
+
self.console.print(log_renderable)
|
155 |
+
except Exception:
|
156 |
+
self.handleError(record)
|
157 |
+
|
158 |
+
def render_message(self, record: LogRecord, message: str) -> "ConsoleRenderable":
|
159 |
+
"""Render message text in to Text.
|
160 |
+
|
161 |
+
record (LogRecord): logging Record.
|
162 |
+
message (str): String containing log message.
|
163 |
+
|
164 |
+
Returns:
|
165 |
+
ConsoleRenderable: Renderable to display log message.
|
166 |
+
"""
|
167 |
+
use_markup = getattr(record, "markup", self.markup)
|
168 |
+
message_text = Text.from_markup(message) if use_markup else Text(message)
|
169 |
+
|
170 |
+
highlighter = getattr(record, "highlighter", self.highlighter)
|
171 |
+
if highlighter:
|
172 |
+
message_text = highlighter(message_text)
|
173 |
+
|
174 |
+
if self.KEYWORDS:
|
175 |
+
message_text.highlight_words(self.KEYWORDS, "logging.keyword")
|
176 |
+
return message_text
|
177 |
+
|
178 |
+
def render(
|
179 |
+
self,
|
180 |
+
*,
|
181 |
+
record: LogRecord,
|
182 |
+
traceback: Optional[Traceback],
|
183 |
+
message_renderable: "ConsoleRenderable",
|
184 |
+
) -> "ConsoleRenderable":
|
185 |
+
"""Render log for display.
|
186 |
+
|
187 |
+
Args:
|
188 |
+
record (LogRecord): logging Record.
|
189 |
+
traceback (Optional[Traceback]): Traceback instance or None for no Traceback.
|
190 |
+
message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.
|
191 |
+
|
192 |
+
Returns:
|
193 |
+
ConsoleRenderable: Renderable to display log.
|
194 |
+
"""
|
195 |
+
path = Path(record.pathname).name
|
196 |
+
level = self.get_level_text(record)
|
197 |
+
time_format = None if self.formatter is None else self.formatter.datefmt
|
198 |
+
log_time = datetime.fromtimestamp(record.created)
|
199 |
+
|
200 |
+
log_renderable = self._log_render(
|
201 |
+
self.console,
|
202 |
+
[message_renderable] if not traceback else [message_renderable, traceback],
|
203 |
+
log_time=log_time,
|
204 |
+
time_format=time_format,
|
205 |
+
level=level,
|
206 |
+
path=path,
|
207 |
+
line_no=record.lineno,
|
208 |
+
link_path=record.pathname if self.enable_link_path else None,
|
209 |
+
)
|
210 |
+
return log_renderable
|
211 |
+
|
212 |
+
|
213 |
+
if __name__ == "__main__": # pragma: no cover
|
214 |
+
from time import sleep
|
215 |
+
|
216 |
+
FORMAT = "%(message)s"
|
217 |
+
# FORMAT = "%(asctime)-15s - %(levelname)s - %(message)s"
|
218 |
+
logging.basicConfig(
|
219 |
+
level="NOTSET",
|
220 |
+
format=FORMAT,
|
221 |
+
datefmt="[%X]",
|
222 |
+
handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)],
|
223 |
+
)
|
224 |
+
log = logging.getLogger("rich")
|
225 |
+
|
226 |
+
log.info("Server starting...")
|
227 |
+
log.info("Listening on http://127.0.0.1:8080")
|
228 |
+
sleep(1)
|
229 |
+
|
230 |
+
log.info("GET /index.html 200 1298")
|
231 |
+
log.info("GET /imgs/backgrounds/back1.jpg 200 54386")
|
232 |
+
log.info("GET /css/styles.css 200 54386")
|
233 |
+
log.warning("GET /favicon.ico 404 242")
|
234 |
+
sleep(1)
|
235 |
+
|
236 |
+
log.debug(
|
237 |
+
"JSONRPC request\n--> %r\n<-- %r",
|
238 |
+
{
|
239 |
+
"version": "1.1",
|
240 |
+
"method": "confirmFruitPurchase",
|
241 |
+
"params": [["apple", "orange", "mangoes", "pomelo"], 1.123],
|
242 |
+
"id": "194521489",
|
243 |
+
},
|
244 |
+
{"version": "1.1", "result": True, "error": None, "id": "194521489"},
|
245 |
+
)
|
246 |
+
log.debug(
|
247 |
+
"Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer"
|
248 |
+
)
|
249 |
+
log.error("Unable to find 'pomelo' in database!")
|
250 |
+
log.info("POST /jsonrpc/ 200 65532")
|
251 |
+
log.info("POST /admin/ 401 42234")
|
252 |
+
log.warning("password was rejected for admin site.")
|
253 |
+
|
254 |
+
def divide() -> None:
|
255 |
+
number = 1
|
256 |
+
divisor = 0
|
257 |
+
foos = ["foo"] * 100
|
258 |
+
log.debug("in divide")
|
259 |
+
try:
|
260 |
+
number / divisor
|
261 |
+
except:
|
262 |
+
log.exception("An error of some kind occurred!")
|
263 |
+
|
264 |
+
divide()
|
265 |
+
sleep(1)
|
266 |
+
log.critical("Out of memory!")
|
267 |
+
log.info("Server exited with code=-1")
|
268 |
+
log.info("[bold]EXITING...[/bold]", extra=dict(markup=True))
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/measure.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from operator import itemgetter
|
2 |
+
from typing import Callable, Iterable, NamedTuple, Optional, TYPE_CHECKING
|
3 |
+
|
4 |
+
from . import errors
|
5 |
+
from .protocol import is_renderable, rich_cast
|
6 |
+
|
7 |
+
if TYPE_CHECKING:
|
8 |
+
from .console import Console, ConsoleOptions, RenderableType
|
9 |
+
|
10 |
+
|
11 |
+
class Measurement(NamedTuple):
|
12 |
+
"""Stores the minimum and maximum widths (in characters) required to render an object."""
|
13 |
+
|
14 |
+
minimum: int
|
15 |
+
"""Minimum number of cells required to render."""
|
16 |
+
maximum: int
|
17 |
+
"""Maximum number of cells required to render."""
|
18 |
+
|
19 |
+
@property
|
20 |
+
def span(self) -> int:
|
21 |
+
"""Get difference between maximum and minimum."""
|
22 |
+
return self.maximum - self.minimum
|
23 |
+
|
24 |
+
def normalize(self) -> "Measurement":
|
25 |
+
"""Get measurement that ensures that minimum <= maximum and minimum >= 0
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
Measurement: A normalized measurement.
|
29 |
+
"""
|
30 |
+
minimum, maximum = self
|
31 |
+
minimum = min(max(0, minimum), maximum)
|
32 |
+
return Measurement(max(0, minimum), max(0, max(minimum, maximum)))
|
33 |
+
|
34 |
+
def with_maximum(self, width: int) -> "Measurement":
|
35 |
+
"""Get a RenderableWith where the widths are <= width.
|
36 |
+
|
37 |
+
Args:
|
38 |
+
width (int): Maximum desired width.
|
39 |
+
|
40 |
+
Returns:
|
41 |
+
Measurement: New Measurement object.
|
42 |
+
"""
|
43 |
+
minimum, maximum = self
|
44 |
+
return Measurement(min(minimum, width), min(maximum, width))
|
45 |
+
|
46 |
+
def with_minimum(self, width: int) -> "Measurement":
|
47 |
+
"""Get a RenderableWith where the widths are >= width.
|
48 |
+
|
49 |
+
Args:
|
50 |
+
width (int): Minimum desired width.
|
51 |
+
|
52 |
+
Returns:
|
53 |
+
Measurement: New Measurement object.
|
54 |
+
"""
|
55 |
+
minimum, maximum = self
|
56 |
+
width = max(0, width)
|
57 |
+
return Measurement(max(minimum, width), max(maximum, width))
|
58 |
+
|
59 |
+
def clamp(
|
60 |
+
self, min_width: Optional[int] = None, max_width: Optional[int] = None
|
61 |
+
) -> "Measurement":
|
62 |
+
"""Clamp a measurement within the specified range.
|
63 |
+
|
64 |
+
Args:
|
65 |
+
min_width (int): Minimum desired width, or ``None`` for no minimum. Defaults to None.
|
66 |
+
max_width (int): Maximum desired width, or ``None`` for no maximum. Defaults to None.
|
67 |
+
|
68 |
+
Returns:
|
69 |
+
Measurement: New Measurement object.
|
70 |
+
"""
|
71 |
+
measurement = self
|
72 |
+
if min_width is not None:
|
73 |
+
measurement = measurement.with_minimum(min_width)
|
74 |
+
if max_width is not None:
|
75 |
+
measurement = measurement.with_maximum(max_width)
|
76 |
+
return measurement
|
77 |
+
|
78 |
+
@classmethod
|
79 |
+
def get(
|
80 |
+
cls, console: "Console", options: "ConsoleOptions", renderable: "RenderableType"
|
81 |
+
) -> "Measurement":
|
82 |
+
"""Get a measurement for a renderable.
|
83 |
+
|
84 |
+
Args:
|
85 |
+
console (~rich.console.Console): Console instance.
|
86 |
+
options (~rich.console.ConsoleOptions): Console options.
|
87 |
+
renderable (RenderableType): An object that may be rendered with Rich.
|
88 |
+
|
89 |
+
Raises:
|
90 |
+
errors.NotRenderableError: If the object is not renderable.
|
91 |
+
|
92 |
+
Returns:
|
93 |
+
Measurement: Measurement object containing range of character widths required to render the object.
|
94 |
+
"""
|
95 |
+
_max_width = options.max_width
|
96 |
+
if _max_width < 1:
|
97 |
+
return Measurement(0, 0)
|
98 |
+
if isinstance(renderable, str):
|
99 |
+
renderable = console.render_str(renderable, markup=options.markup)
|
100 |
+
renderable = rich_cast(renderable)
|
101 |
+
if is_renderable(renderable):
|
102 |
+
get_console_width: Optional[
|
103 |
+
Callable[["Console", "ConsoleOptions"], "Measurement"]
|
104 |
+
] = getattr(renderable, "__rich_measure__", None)
|
105 |
+
if get_console_width is not None:
|
106 |
+
render_width = (
|
107 |
+
get_console_width(console, options)
|
108 |
+
.normalize()
|
109 |
+
.with_maximum(_max_width)
|
110 |
+
)
|
111 |
+
if render_width.maximum < 1:
|
112 |
+
return Measurement(0, 0)
|
113 |
+
return render_width.normalize()
|
114 |
+
else:
|
115 |
+
return Measurement(0, _max_width)
|
116 |
+
else:
|
117 |
+
raise errors.NotRenderableError(
|
118 |
+
f"Unable to get render width for {renderable!r}; "
|
119 |
+
"a str, Segment, or object with __rich_console__ method is required"
|
120 |
+
)
|
121 |
+
|
122 |
+
|
123 |
+
def measure_renderables(
|
124 |
+
console: "Console",
|
125 |
+
options: "ConsoleOptions",
|
126 |
+
renderables: Iterable["RenderableType"],
|
127 |
+
) -> "Measurement":
|
128 |
+
"""Get a measurement that would fit a number of renderables.
|
129 |
+
|
130 |
+
Args:
|
131 |
+
console (~rich.console.Console): Console instance.
|
132 |
+
options (~rich.console.ConsoleOptions): Console options.
|
133 |
+
renderables (Iterable[RenderableType]): One or more renderable objects.
|
134 |
+
|
135 |
+
Returns:
|
136 |
+
Measurement: Measurement object containing range of character widths required to
|
137 |
+
contain all given renderables.
|
138 |
+
"""
|
139 |
+
if not renderables:
|
140 |
+
return Measurement(0, 0)
|
141 |
+
get_measurement = Measurement.get
|
142 |
+
measurements = [
|
143 |
+
get_measurement(console, options, renderable) for renderable in renderables
|
144 |
+
]
|
145 |
+
measured_width = Measurement(
|
146 |
+
max(measurements, key=itemgetter(0)).minimum,
|
147 |
+
max(measurements, key=itemgetter(1)).maximum,
|
148 |
+
)
|
149 |
+
return measured_width
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/padding.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import cast, List, Optional, Tuple, TYPE_CHECKING, Union
|
2 |
+
|
3 |
+
if TYPE_CHECKING:
|
4 |
+
from .console import (
|
5 |
+
Console,
|
6 |
+
ConsoleOptions,
|
7 |
+
RenderableType,
|
8 |
+
RenderResult,
|
9 |
+
)
|
10 |
+
from .jupyter import JupyterMixin
|
11 |
+
from .measure import Measurement
|
12 |
+
from .style import Style
|
13 |
+
from .segment import Segment
|
14 |
+
|
15 |
+
|
16 |
+
PaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int]]
|
17 |
+
|
18 |
+
|
19 |
+
class Padding(JupyterMixin):
|
20 |
+
"""Draw space around content.
|
21 |
+
|
22 |
+
Example:
|
23 |
+
>>> print(Padding("Hello", (2, 4), style="on blue"))
|
24 |
+
|
25 |
+
Args:
|
26 |
+
renderable (RenderableType): String or other renderable.
|
27 |
+
pad (Union[int, Tuple[int]]): Padding for top, right, bottom, and left borders.
|
28 |
+
May be specified with 1, 2, or 4 integers (CSS style).
|
29 |
+
style (Union[str, Style], optional): Style for padding characters. Defaults to "none".
|
30 |
+
expand (bool, optional): Expand padding to fit available width. Defaults to True.
|
31 |
+
"""
|
32 |
+
|
33 |
+
def __init__(
|
34 |
+
self,
|
35 |
+
renderable: "RenderableType",
|
36 |
+
pad: "PaddingDimensions" = (0, 0, 0, 0),
|
37 |
+
*,
|
38 |
+
style: Union[str, Style] = "none",
|
39 |
+
expand: bool = True,
|
40 |
+
):
|
41 |
+
self.renderable = renderable
|
42 |
+
self.top, self.right, self.bottom, self.left = self.unpack(pad)
|
43 |
+
self.style = style
|
44 |
+
self.expand = expand
|
45 |
+
|
46 |
+
@classmethod
|
47 |
+
def indent(cls, renderable: "RenderableType", level: int) -> "Padding":
|
48 |
+
"""Make padding instance to render an indent.
|
49 |
+
|
50 |
+
Args:
|
51 |
+
renderable (RenderableType): String or other renderable.
|
52 |
+
level (int): Number of characters to indent.
|
53 |
+
|
54 |
+
Returns:
|
55 |
+
Padding: A Padding instance.
|
56 |
+
"""
|
57 |
+
|
58 |
+
return Padding(renderable, pad=(0, 0, 0, level), expand=False)
|
59 |
+
|
60 |
+
@staticmethod
|
61 |
+
def unpack(pad: "PaddingDimensions") -> Tuple[int, int, int, int]:
|
62 |
+
"""Unpack padding specified in CSS style."""
|
63 |
+
if isinstance(pad, int):
|
64 |
+
return (pad, pad, pad, pad)
|
65 |
+
if len(pad) == 1:
|
66 |
+
_pad = pad[0]
|
67 |
+
return (_pad, _pad, _pad, _pad)
|
68 |
+
if len(pad) == 2:
|
69 |
+
pad_top, pad_right = cast(Tuple[int, int], pad)
|
70 |
+
return (pad_top, pad_right, pad_top, pad_right)
|
71 |
+
if len(pad) == 4:
|
72 |
+
top, right, bottom, left = cast(Tuple[int, int, int, int], pad)
|
73 |
+
return (top, right, bottom, left)
|
74 |
+
raise ValueError(f"1, 2 or 4 integers required for padding; {len(pad)} given")
|
75 |
+
|
76 |
+
def __repr__(self) -> str:
|
77 |
+
return f"Padding({self.renderable!r}, ({self.top},{self.right},{self.bottom},{self.left}))"
|
78 |
+
|
79 |
+
def __rich_console__(
|
80 |
+
self, console: "Console", options: "ConsoleOptions"
|
81 |
+
) -> "RenderResult":
|
82 |
+
style = console.get_style(self.style)
|
83 |
+
if self.expand:
|
84 |
+
width = options.max_width
|
85 |
+
else:
|
86 |
+
width = min(
|
87 |
+
Measurement.get(console, options, self.renderable).maximum
|
88 |
+
+ self.left
|
89 |
+
+ self.right,
|
90 |
+
options.max_width,
|
91 |
+
)
|
92 |
+
render_options = options.update_width(width - self.left - self.right)
|
93 |
+
if render_options.height is not None:
|
94 |
+
render_options = render_options.update_height(
|
95 |
+
height=render_options.height - self.top - self.bottom
|
96 |
+
)
|
97 |
+
lines = console.render_lines(
|
98 |
+
self.renderable, render_options, style=style, pad=True
|
99 |
+
)
|
100 |
+
_Segment = Segment
|
101 |
+
|
102 |
+
left = _Segment(" " * self.left, style) if self.left else None
|
103 |
+
right = (
|
104 |
+
[_Segment(f'{" " * self.right}', style), _Segment.line()]
|
105 |
+
if self.right
|
106 |
+
else [_Segment.line()]
|
107 |
+
)
|
108 |
+
blank_line: Optional[List[Segment]] = None
|
109 |
+
if self.top:
|
110 |
+
blank_line = [_Segment(f'{" " * width}\n', style)]
|
111 |
+
yield from blank_line * self.top
|
112 |
+
if left:
|
113 |
+
for line in lines:
|
114 |
+
yield left
|
115 |
+
yield from line
|
116 |
+
yield from right
|
117 |
+
else:
|
118 |
+
for line in lines:
|
119 |
+
yield from line
|
120 |
+
yield from right
|
121 |
+
if self.bottom:
|
122 |
+
blank_line = blank_line or [_Segment(f'{" " * width}\n', style)]
|
123 |
+
yield from blank_line * self.bottom
|
124 |
+
|
125 |
+
def __rich_measure__(
|
126 |
+
self, console: "Console", options: "ConsoleOptions"
|
127 |
+
) -> "Measurement":
|
128 |
+
max_width = options.max_width
|
129 |
+
extra_width = self.left + self.right
|
130 |
+
if max_width - extra_width < 1:
|
131 |
+
return Measurement(max_width, max_width)
|
132 |
+
measure_min, measure_max = Measurement.get(console, options, self.renderable)
|
133 |
+
measurement = Measurement(measure_min + extra_width, measure_max + extra_width)
|
134 |
+
measurement = measurement.with_maximum(max_width)
|
135 |
+
return measurement
|
136 |
+
|
137 |
+
|
138 |
+
if __name__ == "__main__": # pragma: no cover
|
139 |
+
from pip._vendor.rich import print
|
140 |
+
|
141 |
+
print(Padding("Hello, World", (2, 4), style="on blue"))
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/pager.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from abc import ABC, abstractmethod
|
2 |
+
from typing import Any, Callable
|
3 |
+
|
4 |
+
|
5 |
+
class Pager(ABC):
|
6 |
+
"""Base class for a pager."""
|
7 |
+
|
8 |
+
@abstractmethod
|
9 |
+
def show(self, content: str) -> None:
|
10 |
+
"""Show content in pager.
|
11 |
+
|
12 |
+
Args:
|
13 |
+
content (str): Content to be displayed.
|
14 |
+
"""
|
15 |
+
|
16 |
+
|
17 |
+
class SystemPager(Pager):
|
18 |
+
"""Uses the pager installed on the system."""
|
19 |
+
|
20 |
+
def _pager(self, content: str) -> Any: # pragma: no cover
|
21 |
+
return __import__("pydoc").pager(content)
|
22 |
+
|
23 |
+
def show(self, content: str) -> None:
|
24 |
+
"""Use the same pager used by pydoc."""
|
25 |
+
self._pager(content)
|
26 |
+
|
27 |
+
|
28 |
+
if __name__ == "__main__": # pragma: no cover
|
29 |
+
from .__main__ import make_test_card
|
30 |
+
from .console import Console
|
31 |
+
|
32 |
+
console = Console()
|
33 |
+
with console.pager(styles=True):
|
34 |
+
console.print(make_test_card())
|
env-llmeval/lib/python3.10/site-packages/pip/_vendor/rich/palette.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from math import sqrt
|
2 |
+
from functools import lru_cache
|
3 |
+
from typing import Sequence, Tuple, TYPE_CHECKING
|
4 |
+
|
5 |
+
from .color_triplet import ColorTriplet
|
6 |
+
|
7 |
+
if TYPE_CHECKING:
|
8 |
+
from pip._vendor.rich.table import Table
|
9 |
+
|
10 |
+
|
11 |
+
class Palette:
|
12 |
+
"""A palette of available colors."""
|
13 |
+
|
14 |
+
def __init__(self, colors: Sequence[Tuple[int, int, int]]):
|
15 |
+
self._colors = colors
|
16 |
+
|
17 |
+
def __getitem__(self, number: int) -> ColorTriplet:
|
18 |
+
return ColorTriplet(*self._colors[number])
|
19 |
+
|
20 |
+
def __rich__(self) -> "Table":
|
21 |
+
from pip._vendor.rich.color import Color
|
22 |
+
from pip._vendor.rich.style import Style
|
23 |
+
from pip._vendor.rich.text import Text
|
24 |
+
from pip._vendor.rich.table import Table
|
25 |
+
|
26 |
+
table = Table(
|
27 |
+
"index",
|
28 |
+
"RGB",
|
29 |
+
"Color",
|
30 |
+
title="Palette",
|
31 |
+
caption=f"{len(self._colors)} colors",
|
32 |
+
highlight=True,
|
33 |
+
caption_justify="right",
|
34 |
+
)
|
35 |
+
for index, color in enumerate(self._colors):
|
36 |
+
table.add_row(
|
37 |
+
str(index),
|
38 |
+
repr(color),
|
39 |
+
Text(" " * 16, style=Style(bgcolor=Color.from_rgb(*color))),
|
40 |
+
)
|
41 |
+
return table
|
42 |
+
|
43 |
+
# This is somewhat inefficient and needs caching
|
44 |
+
@lru_cache(maxsize=1024)
|
45 |
+
def match(self, color: Tuple[int, int, int]) -> int:
|
46 |
+
"""Find a color from a palette that most closely matches a given color.
|
47 |
+
|
48 |
+
Args:
|
49 |
+
color (Tuple[int, int, int]): RGB components in range 0 > 255.
|
50 |
+
|
51 |
+
Returns:
|
52 |
+
int: Index of closes matching color.
|
53 |
+
"""
|
54 |
+
red1, green1, blue1 = color
|
55 |
+
_sqrt = sqrt
|
56 |
+
get_color = self._colors.__getitem__
|
57 |
+
|
58 |
+
def get_color_distance(index: int) -> float:
|
59 |
+
"""Get the distance to a color."""
|
60 |
+
red2, green2, blue2 = get_color(index)
|
61 |
+
red_mean = (red1 + red2) // 2
|
62 |
+
red = red1 - red2
|
63 |
+
green = green1 - green2
|
64 |
+
blue = blue1 - blue2
|
65 |
+
return _sqrt(
|
66 |
+
(((512 + red_mean) * red * red) >> 8)
|
67 |
+
+ 4 * green * green
|
68 |
+
+ (((767 - red_mean) * blue * blue) >> 8)
|
69 |
+
)
|
70 |
+
|
71 |
+
min_index = min(range(len(self._colors)), key=get_color_distance)
|
72 |
+
return min_index
|
73 |
+
|
74 |
+
|
75 |
+
if __name__ == "__main__": # pragma: no cover
|
76 |
+
import colorsys
|
77 |
+
from typing import Iterable
|
78 |
+
from pip._vendor.rich.color import Color
|
79 |
+
from pip._vendor.rich.console import Console, ConsoleOptions
|
80 |
+
from pip._vendor.rich.segment import Segment
|
81 |
+
from pip._vendor.rich.style import Style
|
82 |
+
|
83 |
+
class ColorBox:
|
84 |
+
def __rich_console__(
|
85 |
+
self, console: Console, options: ConsoleOptions
|
86 |
+
) -> Iterable[Segment]:
|
87 |
+
height = console.size.height - 3
|
88 |
+
for y in range(0, height):
|
89 |
+
for x in range(options.max_width):
|
90 |
+
h = x / options.max_width
|
91 |
+
l = y / (height + 1)
|
92 |
+
r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)
|
93 |
+
r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0)
|
94 |
+
bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)
|
95 |
+
color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)
|
96 |
+
yield Segment("▄", Style(color=color, bgcolor=bgcolor))
|
97 |
+
yield Segment.line()
|
98 |
+
|
99 |
+
console = Console()
|
100 |
+
console.print(ColorBox())
|