content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
"""\nTimer context manager, only used in debug.\n\n"""\n\nfrom time import time\n\nimport contextlib\nfrom typing import Generator\n\n\n@contextlib.contextmanager\ndef timer(subject: str = "time") -> Generator[None, None, None]:\n """print the elapsed time. (only used in debugging)"""\n start = time()\n yield\n elapsed = time() - start\n elapsed_ms = elapsed * 1000\n print(f"{subject} elapsed {elapsed_ms:.1f}ms")\n | .venv\Lib\site-packages\pip\_vendor\rich\_timer.py | _timer.py | Python | 417 | 0.85 | 0.052632 | 0 | python-kit | 930 | 2025-02-28T14:09:32.820617 | MIT | false | ae43057547af31fdad66b2df35d85a23 |
"""Light wrapper around the Win32 Console API - this module should only be imported on Windows\n\nThe API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions\n"""\n\nimport ctypes\nimport sys\nfrom typing import Any\n\nwindll: Any = None\nif sys.platform == "win32":\n windll = ctypes.LibraryLoader(ctypes.WinDLL)\nelse:\n raise ImportError(f"{__name__} can only be imported on Windows")\n\nimport time\nfrom ctypes import Structure, byref, wintypes\nfrom typing import IO, NamedTuple, Type, cast\n\nfrom pip._vendor.rich.color import ColorSystem\nfrom pip._vendor.rich.style import Style\n\nSTDOUT = -11\nENABLE_VIRTUAL_TERMINAL_PROCESSING = 4\n\nCOORD = wintypes._COORD\n\n\nclass LegacyWindowsError(Exception):\n pass\n\n\nclass WindowsCoordinates(NamedTuple):\n """Coordinates in the Windows Console API are (y, x), not (x, y).\n This class is intended to prevent that confusion.\n Rows and columns are indexed from 0.\n This class can be used in place of wintypes._COORD in arguments and argtypes.\n """\n\n row: int\n col: int\n\n @classmethod\n def from_param(cls, value: "WindowsCoordinates") -> COORD:\n """Converts a WindowsCoordinates into a wintypes _COORD structure.\n This classmethod is internally called by ctypes to perform the conversion.\n\n Args:\n value (WindowsCoordinates): The input coordinates to convert.\n\n Returns:\n wintypes._COORD: The converted coordinates struct.\n """\n return COORD(value.col, value.row)\n\n\nclass CONSOLE_SCREEN_BUFFER_INFO(Structure):\n _fields_ = [\n ("dwSize", COORD),\n ("dwCursorPosition", COORD),\n ("wAttributes", wintypes.WORD),\n ("srWindow", wintypes.SMALL_RECT),\n ("dwMaximumWindowSize", COORD),\n ]\n\n\nclass CONSOLE_CURSOR_INFO(ctypes.Structure):\n _fields_ = [("dwSize", wintypes.DWORD), ("bVisible", wintypes.BOOL)]\n\n\n_GetStdHandle = windll.kernel32.GetStdHandle\n_GetStdHandle.argtypes = [\n wintypes.DWORD,\n]\n_GetStdHandle.restype = wintypes.HANDLE\n\n\ndef GetStdHandle(handle: int = STDOUT) -> wintypes.HANDLE:\n """Retrieves a handle to the specified standard device (standard input, standard output, or standard error).\n\n Args:\n handle (int): Integer identifier for the handle. Defaults to -11 (stdout).\n\n Returns:\n wintypes.HANDLE: The handle\n """\n return cast(wintypes.HANDLE, _GetStdHandle(handle))\n\n\n_GetConsoleMode = windll.kernel32.GetConsoleMode\n_GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD]\n_GetConsoleMode.restype = wintypes.BOOL\n\n\ndef GetConsoleMode(std_handle: wintypes.HANDLE) -> int:\n """Retrieves the current input mode of a console's input buffer\n or the current output mode of a console screen buffer.\n\n Args:\n std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n\n Raises:\n LegacyWindowsError: If any error occurs while calling the Windows console API.\n\n Returns:\n int: Value representing the current console mode as documented at\n https://docs.microsoft.com/en-us/windows/console/getconsolemode#parameters\n """\n\n console_mode = wintypes.DWORD()\n success = bool(_GetConsoleMode(std_handle, console_mode))\n if not success:\n raise LegacyWindowsError("Unable to get legacy Windows Console Mode")\n return console_mode.value\n\n\n_FillConsoleOutputCharacterW = windll.kernel32.FillConsoleOutputCharacterW\n_FillConsoleOutputCharacterW.argtypes = [\n wintypes.HANDLE,\n ctypes.c_char,\n wintypes.DWORD,\n cast(Type[COORD], WindowsCoordinates),\n ctypes.POINTER(wintypes.DWORD),\n]\n_FillConsoleOutputCharacterW.restype = wintypes.BOOL\n\n\ndef FillConsoleOutputCharacter(\n std_handle: wintypes.HANDLE,\n char: str,\n length: int,\n start: WindowsCoordinates,\n) -> int:\n """Writes a character to the console screen buffer a specified number of times, beginning at the specified coordinates.\n\n Args:\n std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n char (str): The character to write. Must be a string of length 1.\n length (int): The number of times to write the character.\n start (WindowsCoordinates): The coordinates to start writing at.\n\n Returns:\n int: The number of characters written.\n """\n character = ctypes.c_char(char.encode())\n num_characters = wintypes.DWORD(length)\n num_written = wintypes.DWORD(0)\n _FillConsoleOutputCharacterW(\n std_handle,\n character,\n num_characters,\n start,\n byref(num_written),\n )\n return num_written.value\n\n\n_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute\n_FillConsoleOutputAttribute.argtypes = [\n wintypes.HANDLE,\n wintypes.WORD,\n wintypes.DWORD,\n cast(Type[COORD], WindowsCoordinates),\n ctypes.POINTER(wintypes.DWORD),\n]\n_FillConsoleOutputAttribute.restype = wintypes.BOOL\n\n\ndef FillConsoleOutputAttribute(\n std_handle: wintypes.HANDLE,\n attributes: int,\n length: int,\n start: WindowsCoordinates,\n) -> int:\n """Sets the character attributes for a specified number of character cells,\n beginning at the specified coordinates in a screen buffer.\n\n Args:\n std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n attributes (int): Integer value representing the foreground and background colours of the cells.\n length (int): The number of cells to set the output attribute of.\n start (WindowsCoordinates): The coordinates of the first cell whose attributes are to be set.\n\n Returns:\n int: The number of cells whose attributes were actually set.\n """\n num_cells = wintypes.DWORD(length)\n style_attrs = wintypes.WORD(attributes)\n num_written = wintypes.DWORD(0)\n _FillConsoleOutputAttribute(\n std_handle, style_attrs, num_cells, start, byref(num_written)\n )\n return num_written.value\n\n\n_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute\n_SetConsoleTextAttribute.argtypes = [\n wintypes.HANDLE,\n wintypes.WORD,\n]\n_SetConsoleTextAttribute.restype = wintypes.BOOL\n\n\ndef SetConsoleTextAttribute(\n std_handle: wintypes.HANDLE, attributes: wintypes.WORD\n) -> bool:\n """Set the colour attributes for all text written after this function is called.\n\n Args:\n std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n attributes (int): Integer value representing the foreground and background colours.\n\n\n Returns:\n bool: True if the attribute was set successfully, otherwise False.\n """\n return bool(_SetConsoleTextAttribute(std_handle, attributes))\n\n\n_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo\n_GetConsoleScreenBufferInfo.argtypes = [\n wintypes.HANDLE,\n ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO),\n]\n_GetConsoleScreenBufferInfo.restype = wintypes.BOOL\n\n\ndef GetConsoleScreenBufferInfo(\n std_handle: wintypes.HANDLE,\n) -> CONSOLE_SCREEN_BUFFER_INFO:\n """Retrieves information about the specified console screen buffer.\n\n Args:\n std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n\n Returns:\n CONSOLE_SCREEN_BUFFER_INFO: A CONSOLE_SCREEN_BUFFER_INFO ctype struct contain information about\n screen size, cursor position, colour attributes, and more."""\n console_screen_buffer_info = CONSOLE_SCREEN_BUFFER_INFO()\n _GetConsoleScreenBufferInfo(std_handle, byref(console_screen_buffer_info))\n return console_screen_buffer_info\n\n\n_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition\n_SetConsoleCursorPosition.argtypes = [\n wintypes.HANDLE,\n cast(Type[COORD], WindowsCoordinates),\n]\n_SetConsoleCursorPosition.restype = wintypes.BOOL\n\n\ndef SetConsoleCursorPosition(\n std_handle: wintypes.HANDLE, coords: WindowsCoordinates\n) -> bool:\n """Set the position of the cursor in the console screen\n\n Args:\n std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n coords (WindowsCoordinates): The coordinates to move the cursor to.\n\n Returns:\n bool: True if the function succeeds, otherwise False.\n """\n return bool(_SetConsoleCursorPosition(std_handle, coords))\n\n\n_GetConsoleCursorInfo = windll.kernel32.GetConsoleCursorInfo\n_GetConsoleCursorInfo.argtypes = [\n wintypes.HANDLE,\n ctypes.POINTER(CONSOLE_CURSOR_INFO),\n]\n_GetConsoleCursorInfo.restype = wintypes.BOOL\n\n\ndef GetConsoleCursorInfo(\n std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO\n) -> bool:\n """Get the cursor info - used to get cursor visibility and width\n\n Args:\n std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct that receives information\n about the console's cursor.\n\n Returns:\n bool: True if the function succeeds, otherwise False.\n """\n return bool(_GetConsoleCursorInfo(std_handle, byref(cursor_info)))\n\n\n_SetConsoleCursorInfo = windll.kernel32.SetConsoleCursorInfo\n_SetConsoleCursorInfo.argtypes = [\n wintypes.HANDLE,\n ctypes.POINTER(CONSOLE_CURSOR_INFO),\n]\n_SetConsoleCursorInfo.restype = wintypes.BOOL\n\n\ndef SetConsoleCursorInfo(\n std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO\n) -> bool:\n """Set the cursor info - used for adjusting cursor visibility and width\n\n Args:\n std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct containing the new cursor info.\n\n Returns:\n bool: True if the function succeeds, otherwise False.\n """\n return bool(_SetConsoleCursorInfo(std_handle, byref(cursor_info)))\n\n\n_SetConsoleTitle = windll.kernel32.SetConsoleTitleW\n_SetConsoleTitle.argtypes = [wintypes.LPCWSTR]\n_SetConsoleTitle.restype = wintypes.BOOL\n\n\ndef SetConsoleTitle(title: str) -> bool:\n """Sets the title of the current console window\n\n Args:\n title (str): The new title of the console window.\n\n Returns:\n bool: True if the function succeeds, otherwise False.\n """\n return bool(_SetConsoleTitle(title))\n\n\nclass LegacyWindowsTerm:\n """This class allows interaction with the legacy Windows Console API. It should only be used in the context\n of environments where virtual terminal processing is not available. However, if it is used in a Windows environment,\n the entire API should work.\n\n Args:\n file (IO[str]): The file which the Windows Console API HANDLE is retrieved from, defaults to sys.stdout.\n """\n\n BRIGHT_BIT = 8\n\n # Indices are ANSI color numbers, values are the corresponding Windows Console API color numbers\n ANSI_TO_WINDOWS = [\n 0, # black The Windows colours are defined in wincon.h as follows:\n 4, # red define FOREGROUND_BLUE 0x0001 -- 0000 0001\n 2, # green define FOREGROUND_GREEN 0x0002 -- 0000 0010\n 6, # yellow define FOREGROUND_RED 0x0004 -- 0000 0100\n 1, # blue define FOREGROUND_INTENSITY 0x0008 -- 0000 1000\n 5, # magenta define BACKGROUND_BLUE 0x0010 -- 0001 0000\n 3, # cyan define BACKGROUND_GREEN 0x0020 -- 0010 0000\n 7, # white define BACKGROUND_RED 0x0040 -- 0100 0000\n 8, # bright black (grey) define BACKGROUND_INTENSITY 0x0080 -- 1000 0000\n 12, # bright red\n 10, # bright green\n 14, # bright yellow\n 9, # bright blue\n 13, # bright magenta\n 11, # bright cyan\n 15, # bright white\n ]\n\n def __init__(self, file: "IO[str]") -> None:\n handle = GetStdHandle(STDOUT)\n self._handle = handle\n default_text = GetConsoleScreenBufferInfo(handle).wAttributes\n self._default_text = default_text\n\n self._default_fore = default_text & 7\n self._default_back = (default_text >> 4) & 7\n self._default_attrs = self._default_fore | (self._default_back << 4)\n\n self._file = file\n self.write = file.write\n self.flush = file.flush\n\n @property\n def cursor_position(self) -> WindowsCoordinates:\n """Returns the current position of the cursor (0-based)\n\n Returns:\n WindowsCoordinates: The current cursor position.\n """\n coord: COORD = GetConsoleScreenBufferInfo(self._handle).dwCursorPosition\n return WindowsCoordinates(row=coord.Y, col=coord.X)\n\n @property\n def screen_size(self) -> WindowsCoordinates:\n """Returns the current size of the console screen buffer, in character columns and rows\n\n Returns:\n WindowsCoordinates: The width and height of the screen as WindowsCoordinates.\n """\n screen_size: COORD = GetConsoleScreenBufferInfo(self._handle).dwSize\n return WindowsCoordinates(row=screen_size.Y, col=screen_size.X)\n\n def write_text(self, text: str) -> None:\n """Write text directly to the terminal without any modification of styles\n\n Args:\n text (str): The text to write to the console\n """\n self.write(text)\n self.flush()\n\n def write_styled(self, text: str, style: Style) -> None:\n """Write styled text to the terminal.\n\n Args:\n text (str): The text to write\n style (Style): The style of the text\n """\n color = style.color\n bgcolor = style.bgcolor\n if style.reverse:\n color, bgcolor = bgcolor, color\n\n if color:\n fore = color.downgrade(ColorSystem.WINDOWS).number\n fore = fore if fore is not None else 7 # Default to ANSI 7: White\n if style.bold:\n fore = fore | self.BRIGHT_BIT\n if style.dim:\n fore = fore & ~self.BRIGHT_BIT\n fore = self.ANSI_TO_WINDOWS[fore]\n else:\n fore = self._default_fore\n\n if bgcolor:\n back = bgcolor.downgrade(ColorSystem.WINDOWS).number\n back = back if back is not None else 0 # Default to ANSI 0: Black\n back = self.ANSI_TO_WINDOWS[back]\n else:\n back = self._default_back\n\n assert fore is not None\n assert back is not None\n\n SetConsoleTextAttribute(\n self._handle, attributes=ctypes.c_ushort(fore | (back << 4))\n )\n self.write_text(text)\n SetConsoleTextAttribute(self._handle, attributes=self._default_text)\n\n def move_cursor_to(self, new_position: WindowsCoordinates) -> None:\n """Set the position of the cursor\n\n Args:\n new_position (WindowsCoordinates): The WindowsCoordinates representing the new position of the cursor.\n """\n if new_position.col < 0 or new_position.row < 0:\n return\n SetConsoleCursorPosition(self._handle, coords=new_position)\n\n def erase_line(self) -> None:\n """Erase all content on the line the cursor is currently located at"""\n screen_size = self.screen_size\n cursor_position = self.cursor_position\n cells_to_erase = screen_size.col\n start_coordinates = WindowsCoordinates(row=cursor_position.row, col=0)\n FillConsoleOutputCharacter(\n self._handle, " ", length=cells_to_erase, start=start_coordinates\n )\n FillConsoleOutputAttribute(\n self._handle,\n self._default_attrs,\n length=cells_to_erase,\n start=start_coordinates,\n )\n\n def erase_end_of_line(self) -> None:\n """Erase all content from the cursor position to the end of that line"""\n cursor_position = self.cursor_position\n cells_to_erase = self.screen_size.col - cursor_position.col\n FillConsoleOutputCharacter(\n self._handle, " ", length=cells_to_erase, start=cursor_position\n )\n FillConsoleOutputAttribute(\n self._handle,\n self._default_attrs,\n length=cells_to_erase,\n start=cursor_position,\n )\n\n def erase_start_of_line(self) -> None:\n """Erase all content from the cursor position to the start of that line"""\n row, col = self.cursor_position\n start = WindowsCoordinates(row, 0)\n FillConsoleOutputCharacter(self._handle, " ", length=col, start=start)\n FillConsoleOutputAttribute(\n self._handle, self._default_attrs, length=col, start=start\n )\n\n def move_cursor_up(self) -> None:\n """Move the cursor up a single cell"""\n cursor_position = self.cursor_position\n SetConsoleCursorPosition(\n self._handle,\n coords=WindowsCoordinates(\n row=cursor_position.row - 1, col=cursor_position.col\n ),\n )\n\n def move_cursor_down(self) -> None:\n """Move the cursor down a single cell"""\n cursor_position = self.cursor_position\n SetConsoleCursorPosition(\n self._handle,\n coords=WindowsCoordinates(\n row=cursor_position.row + 1,\n col=cursor_position.col,\n ),\n )\n\n def move_cursor_forward(self) -> None:\n """Move the cursor forward a single cell. Wrap to the next line if required."""\n row, col = self.cursor_position\n if col == self.screen_size.col - 1:\n row += 1\n col = 0\n else:\n col += 1\n SetConsoleCursorPosition(\n self._handle, coords=WindowsCoordinates(row=row, col=col)\n )\n\n def move_cursor_to_column(self, column: int) -> None:\n """Move cursor to the column specified by the zero-based column index, staying on the same row\n\n Args:\n column (int): The zero-based column index to move the cursor to.\n """\n row, _ = self.cursor_position\n SetConsoleCursorPosition(self._handle, coords=WindowsCoordinates(row, column))\n\n def move_cursor_backward(self) -> None:\n """Move the cursor backward a single cell. Wrap to the previous line if required."""\n row, col = self.cursor_position\n if col == 0:\n row -= 1\n col = self.screen_size.col - 1\n else:\n col -= 1\n SetConsoleCursorPosition(\n self._handle, coords=WindowsCoordinates(row=row, col=col)\n )\n\n def hide_cursor(self) -> None:\n """Hide the cursor"""\n current_cursor_size = self._get_cursor_size()\n invisible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=0)\n SetConsoleCursorInfo(self._handle, cursor_info=invisible_cursor)\n\n def show_cursor(self) -> None:\n """Show the cursor"""\n current_cursor_size = self._get_cursor_size()\n visible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=1)\n SetConsoleCursorInfo(self._handle, cursor_info=visible_cursor)\n\n def set_title(self, title: str) -> None:\n """Set the title of the terminal window\n\n Args:\n title (str): The new title of the console window\n """\n assert len(title) < 255, "Console title must be less than 255 characters"\n SetConsoleTitle(title)\n\n def _get_cursor_size(self) -> int:\n """Get the percentage of the character cell that is filled by the cursor"""\n cursor_info = CONSOLE_CURSOR_INFO()\n GetConsoleCursorInfo(self._handle, cursor_info=cursor_info)\n return int(cursor_info.dwSize)\n\n\nif __name__ == "__main__":\n handle = GetStdHandle()\n\n from pip._vendor.rich.console import Console\n\n console = Console()\n\n term = LegacyWindowsTerm(sys.stdout)\n term.set_title("Win32 Console Examples")\n\n style = Style(color="black", bgcolor="red")\n\n heading = Style.parse("black on green")\n\n # Check colour output\n console.rule("Checking colour output")\n console.print("[on red]on red!")\n console.print("[blue]blue!")\n console.print("[yellow]yellow!")\n console.print("[bold yellow]bold yellow!")\n console.print("[bright_yellow]bright_yellow!")\n console.print("[dim bright_yellow]dim bright_yellow!")\n console.print("[italic cyan]italic cyan!")\n console.print("[bold white on blue]bold white on blue!")\n console.print("[reverse bold white on blue]reverse bold white on blue!")\n console.print("[bold black on cyan]bold black on cyan!")\n console.print("[black on green]black on green!")\n console.print("[blue on green]blue on green!")\n console.print("[white on black]white on black!")\n console.print("[black on white]black on white!")\n console.print("[#1BB152 on #DA812D]#1BB152 on #DA812D!")\n\n # Check cursor movement\n console.rule("Checking cursor movement")\n console.print()\n term.move_cursor_backward()\n term.move_cursor_backward()\n term.write_text("went back and wrapped to prev line")\n time.sleep(1)\n term.move_cursor_up()\n term.write_text("we go up")\n time.sleep(1)\n term.move_cursor_down()\n term.write_text("and down")\n time.sleep(1)\n term.move_cursor_up()\n term.move_cursor_backward()\n term.move_cursor_backward()\n term.write_text("we went up and back 2")\n time.sleep(1)\n term.move_cursor_down()\n term.move_cursor_backward()\n term.move_cursor_backward()\n term.write_text("we went down and back 2")\n time.sleep(1)\n\n # Check erasing of lines\n term.hide_cursor()\n console.print()\n console.rule("Checking line erasing")\n console.print("\n...Deleting to the start of the line...")\n term.write_text("The red arrow shows the cursor location, and direction of erase")\n time.sleep(1)\n term.move_cursor_to_column(16)\n term.write_styled("<", Style.parse("black on red"))\n term.move_cursor_backward()\n time.sleep(1)\n term.erase_start_of_line()\n time.sleep(1)\n\n console.print("\n\n...And to the end of the line...")\n term.write_text("The red arrow shows the cursor location, and direction of erase")\n time.sleep(1)\n\n term.move_cursor_to_column(16)\n term.write_styled(">", Style.parse("black on red"))\n time.sleep(1)\n term.erase_end_of_line()\n time.sleep(1)\n\n console.print("\n\n...Now the whole line will be erased...")\n term.write_styled("I'm going to disappear!", style=Style.parse("black on cyan"))\n time.sleep(1)\n term.erase_line()\n\n term.show_cursor()\n print("\n")\n | .venv\Lib\site-packages\pip\_vendor\rich\_win32_console.py | _win32_console.py | Python | 22,755 | 0.95 | 0.102874 | 0.007561 | react-lib | 481 | 2024-06-01T00:21:18.727917 | MIT | false | fdc916e90d2909c29ccce4e3595b8dce |
import sys\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass WindowsConsoleFeatures:\n """Windows features available."""\n\n vt: bool = False\n """The console supports VT codes."""\n truecolor: bool = False\n """The console supports truecolor."""\n\n\ntry:\n import ctypes\n from ctypes import LibraryLoader\n\n if sys.platform == "win32":\n windll = LibraryLoader(ctypes.WinDLL)\n else:\n windll = None\n raise ImportError("Not windows")\n\n from pip._vendor.rich._win32_console import (\n ENABLE_VIRTUAL_TERMINAL_PROCESSING,\n GetConsoleMode,\n GetStdHandle,\n LegacyWindowsError,\n )\n\nexcept (AttributeError, ImportError, ValueError):\n # Fallback if we can't load the Windows DLL\n def get_windows_console_features() -> WindowsConsoleFeatures:\n features = WindowsConsoleFeatures()\n return features\n\nelse:\n\n def get_windows_console_features() -> WindowsConsoleFeatures:\n """Get windows console features.\n\n Returns:\n WindowsConsoleFeatures: An instance of WindowsConsoleFeatures.\n """\n handle = GetStdHandle()\n try:\n console_mode = GetConsoleMode(handle)\n success = True\n except LegacyWindowsError:\n console_mode = 0\n success = False\n vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)\n truecolor = False\n if vt:\n win_version = sys.getwindowsversion()\n truecolor = win_version.major > 10 or (\n win_version.major == 10 and win_version.build >= 15063\n )\n features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor)\n return features\n\n\nif __name__ == "__main__":\n import platform\n\n features = get_windows_console_features()\n from pip._vendor.rich import print\n\n print(f'platform="{platform.system()}"')\n print(repr(features))\n | .venv\Lib\site-packages\pip\_vendor\rich\_windows.py | _windows.py | Python | 1,925 | 0.95 | 0.126761 | 0.017857 | node-utils | 946 | 2025-07-03T06:46:17.017532 | MIT | false | 524db6c0df2d9313e7a2cea3586ef2de |
from typing import Iterable, Sequence, Tuple, cast\n\nfrom pip._vendor.rich._win32_console import LegacyWindowsTerm, WindowsCoordinates\nfrom pip._vendor.rich.segment import ControlCode, ControlType, Segment\n\n\ndef legacy_windows_render(buffer: Iterable[Segment], term: LegacyWindowsTerm) -> None:\n """Makes appropriate Windows Console API calls based on the segments in the buffer.\n\n Args:\n buffer (Iterable[Segment]): Iterable of Segments to convert to Win32 API calls.\n term (LegacyWindowsTerm): Used to call the Windows Console API.\n """\n for text, style, control in buffer:\n if not control:\n if style:\n term.write_styled(text, style)\n else:\n term.write_text(text)\n else:\n control_codes: Sequence[ControlCode] = control\n for control_code in control_codes:\n control_type = control_code[0]\n if control_type == ControlType.CURSOR_MOVE_TO:\n _, x, y = cast(Tuple[ControlType, int, int], control_code)\n term.move_cursor_to(WindowsCoordinates(row=y - 1, col=x - 1))\n elif control_type == ControlType.CARRIAGE_RETURN:\n term.write_text("\r")\n elif control_type == ControlType.HOME:\n term.move_cursor_to(WindowsCoordinates(0, 0))\n elif control_type == ControlType.CURSOR_UP:\n term.move_cursor_up()\n elif control_type == ControlType.CURSOR_DOWN:\n term.move_cursor_down()\n elif control_type == ControlType.CURSOR_FORWARD:\n term.move_cursor_forward()\n elif control_type == ControlType.CURSOR_BACKWARD:\n term.move_cursor_backward()\n elif control_type == ControlType.CURSOR_MOVE_TO_COLUMN:\n _, column = cast(Tuple[ControlType, int], control_code)\n term.move_cursor_to_column(column - 1)\n elif control_type == ControlType.HIDE_CURSOR:\n term.hide_cursor()\n elif control_type == ControlType.SHOW_CURSOR:\n term.show_cursor()\n elif control_type == ControlType.ERASE_IN_LINE:\n _, mode = cast(Tuple[ControlType, int], control_code)\n if mode == 0:\n term.erase_end_of_line()\n elif mode == 1:\n term.erase_start_of_line()\n elif mode == 2:\n term.erase_line()\n elif control_type == ControlType.SET_WINDOW_TITLE:\n _, title = cast(Tuple[ControlType, str], control_code)\n term.set_title(title)\n | .venv\Lib\site-packages\pip\_vendor\rich\_windows_renderer.py | _windows_renderer.py | Python | 2,783 | 0.85 | 0.125 | 0 | python-kit | 647 | 2025-03-27T22:42:30.962881 | BSD-3-Clause | false | 0f359f6a95e64cad8beba9876575e6de |
from __future__ import annotations\n\nimport re\nfrom typing import Iterable\n\nfrom ._loop import loop_last\nfrom .cells import cell_len, chop_cells\n\nre_word = re.compile(r"\s*\S+\s*")\n\n\ndef words(text: str) -> Iterable[tuple[int, int, str]]:\n """Yields each word from the text as a tuple\n containing (start_index, end_index, word). A "word" in this context may\n include the actual word and any whitespace to the right.\n """\n position = 0\n word_match = re_word.match(text, position)\n while word_match is not None:\n start, end = word_match.span()\n word = word_match.group(0)\n yield start, end, word\n word_match = re_word.match(text, end)\n\n\ndef divide_line(text: str, width: int, fold: bool = True) -> list[int]:\n """Given a string of text, and a width (measured in cells), return a list\n of cell offsets which the string should be split at in order for it to fit\n within the given width.\n\n Args:\n text: The text to examine.\n width: The available cell width.\n fold: If True, words longer than `width` will be folded onto a new line.\n\n Returns:\n A list of indices to break the line at.\n """\n break_positions: list[int] = [] # offsets to insert the breaks at\n append = break_positions.append\n cell_offset = 0\n _cell_len = cell_len\n\n for start, _end, word in words(text):\n word_length = _cell_len(word.rstrip())\n remaining_space = width - cell_offset\n word_fits_remaining_space = remaining_space >= word_length\n\n if word_fits_remaining_space:\n # Simplest case - the word fits within the remaining width for this line.\n cell_offset += _cell_len(word)\n else:\n # Not enough space remaining for this word on the current line.\n if word_length > width:\n # The word doesn't fit on any line, so we can't simply\n # place it on the next line...\n if fold:\n # Fold the word across multiple lines.\n folded_word = chop_cells(word, width=width)\n for last, line in loop_last(folded_word):\n if start:\n append(start)\n if last:\n cell_offset = _cell_len(line)\n else:\n start += len(line)\n else:\n # Folding isn't allowed, so crop the word.\n if start:\n append(start)\n cell_offset = _cell_len(word)\n elif cell_offset and start:\n # The word doesn't fit within the remaining space on the current\n # line, but it *can* fit on to the next (empty) line.\n append(start)\n cell_offset = _cell_len(word)\n\n return break_positions\n\n\nif __name__ == "__main__": # pragma: no cover\n from .console import Console\n\n console = Console(width=10)\n console.print("12345 abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ 12345")\n print(chop_cells("abcdefghijklmnopqrstuvwxyz", 10))\n\n console = Console(width=20)\n console.rule()\n console.print("TextualはPythonの高速アプリケーション開発フレームワークです")\n\n console.rule()\n console.print("アプリケーションは1670万色を使用でき")\n | .venv\Lib\site-packages\pip\_vendor\rich\_wrap.py | _wrap.py | Python | 3,404 | 0.95 | 0.16129 | 0.105263 | awesome-app | 14 | 2024-05-13T08:47:48.503243 | MIT | false | 440510bfdf54e59b40ae3d34537ea429 |
"""Rich text and beautiful formatting in the terminal."""\n\nimport os\nfrom typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union\n\nfrom ._extension import load_ipython_extension # noqa: F401\n\n__all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"]\n\nif TYPE_CHECKING:\n from .console import Console\n\n# Global console used by alternative print\n_console: Optional["Console"] = None\n\ntry:\n _IMPORT_CWD = os.path.abspath(os.getcwd())\nexcept FileNotFoundError:\n # Can happen if the cwd has been deleted\n _IMPORT_CWD = ""\n\n\ndef get_console() -> "Console":\n """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,\n and hasn't been explicitly given one.\n\n Returns:\n Console: A console instance.\n """\n global _console\n if _console is None:\n from .console import Console\n\n _console = Console()\n\n return _console\n\n\ndef reconfigure(*args: Any, **kwargs: Any) -> None:\n """Reconfigures the global console by replacing it with another.\n\n Args:\n *args (Any): Positional arguments for the replacement :class:`~rich.console.Console`.\n **kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`.\n """\n from pip._vendor.rich.console import Console\n\n new_console = Console(*args, **kwargs)\n _console = get_console()\n _console.__dict__ = new_console.__dict__\n\n\ndef print(\n *objects: Any,\n sep: str = " ",\n end: str = "\n",\n file: Optional[IO[str]] = None,\n flush: bool = False,\n) -> None:\n r"""Print object(s) supplied via positional arguments.\n This function has an identical signature to the built-in print.\n For more advanced features, see the :class:`~rich.console.Console` class.\n\n Args:\n sep (str, optional): Separator between printed objects. Defaults to " ".\n end (str, optional): Character to write at end of output. Defaults to "\\n".\n file (IO[str], optional): File to write to, or None for stdout. Defaults to None.\n flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False.\n\n """\n from .console import Console\n\n write_console = get_console() if file is None else Console(file=file)\n return write_console.print(*objects, sep=sep, end=end)\n\n\ndef print_json(\n json: Optional[str] = None,\n *,\n data: Any = None,\n indent: Union[None, int, str] = 2,\n highlight: bool = True,\n skip_keys: bool = False,\n ensure_ascii: bool = False,\n check_circular: bool = True,\n allow_nan: bool = True,\n default: Optional[Callable[[Any], Any]] = None,\n sort_keys: bool = False,\n) -> None:\n """Pretty prints JSON. Output will be valid JSON.\n\n Args:\n json (str): A string containing JSON.\n data (Any): If json is not supplied, then encode this data.\n indent (int, optional): Number of spaces to indent. Defaults to 2.\n highlight (bool, optional): Enable highlighting of output: Defaults to True.\n skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n check_circular (bool, optional): Check for circular references. Defaults to True.\n allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n default (Callable, optional): A callable that converts values that can not be encoded\n in to something that can be JSON encoded. Defaults to None.\n sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n """\n\n get_console().print_json(\n json,\n data=data,\n indent=indent,\n highlight=highlight,\n skip_keys=skip_keys,\n ensure_ascii=ensure_ascii,\n check_circular=check_circular,\n allow_nan=allow_nan,\n default=default,\n sort_keys=sort_keys,\n )\n\n\ndef inspect(\n obj: Any,\n *,\n console: Optional["Console"] = None,\n title: Optional[str] = None,\n help: bool = False,\n methods: bool = False,\n docs: bool = True,\n private: bool = False,\n dunder: bool = False,\n sort: bool = True,\n all: bool = False,\n value: bool = True,\n) -> None:\n """Inspect any Python object.\n\n * inspect(<OBJECT>) to see summarized info.\n * inspect(<OBJECT>, methods=True) to see methods.\n * inspect(<OBJECT>, help=True) to see full (non-abbreviated) help.\n * inspect(<OBJECT>, private=True) to see private attributes (single underscore).\n * inspect(<OBJECT>, dunder=True) to see attributes beginning with double underscore.\n * inspect(<OBJECT>, all=True) to see all attributes.\n\n Args:\n obj (Any): An object to inspect.\n title (str, optional): Title to display over inspect result, or None use type. Defaults to None.\n help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.\n methods (bool, optional): Enable inspection of callables. Defaults to False.\n docs (bool, optional): Also render doc strings. Defaults to True.\n private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.\n dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.\n sort (bool, optional): Sort attributes alphabetically. Defaults to True.\n all (bool, optional): Show all attributes. Defaults to False.\n value (bool, optional): Pretty print value. Defaults to True.\n """\n _console = console or get_console()\n from pip._vendor.rich._inspect import Inspect\n\n # Special case for inspect(inspect)\n is_inspect = obj is inspect\n\n _inspect = Inspect(\n obj,\n title=title,\n help=is_inspect or help,\n methods=is_inspect or methods,\n docs=is_inspect or docs,\n private=private,\n dunder=dunder,\n sort=sort,\n all=all,\n value=value,\n )\n _console.print(_inspect)\n\n\nif __name__ == "__main__": # pragma: no cover\n print("Hello, **World**")\n | .venv\Lib\site-packages\pip\_vendor\rich\__init__.py | __init__.py | Python | 6,090 | 0.95 | 0.129944 | 0.096552 | python-kit | 306 | 2025-02-07T18:35:07.822338 | GPL-3.0 | false | f434655ddd93988a30786a6b71ddcd9c |
import colorsys\nimport io\nfrom time import process_time\n\nfrom pip._vendor.rich import box\nfrom pip._vendor.rich.color import Color\nfrom pip._vendor.rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult\nfrom pip._vendor.rich.markdown import Markdown\nfrom pip._vendor.rich.measure import Measurement\nfrom pip._vendor.rich.pretty import Pretty\nfrom pip._vendor.rich.segment import Segment\nfrom pip._vendor.rich.style import Style\nfrom pip._vendor.rich.syntax import Syntax\nfrom pip._vendor.rich.table import Table\nfrom pip._vendor.rich.text import Text\n\n\nclass ColorBox:\n def __rich_console__(\n self, console: Console, options: ConsoleOptions\n ) -> RenderResult:\n for y in range(0, 5):\n for x in range(options.max_width):\n h = x / options.max_width\n l = 0.1 + ((y / 5) * 0.7)\n r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)\n r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0)\n bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)\n color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)\n yield Segment("▄", Style(color=color, bgcolor=bgcolor))\n yield Segment.line()\n\n def __rich_measure__(\n self, console: "Console", options: ConsoleOptions\n ) -> Measurement:\n return Measurement(1, options.max_width)\n\n\ndef make_test_card() -> Table:\n """Get a renderable that demonstrates a number of features."""\n table = Table.grid(padding=1, pad_edge=True)\n table.title = "Rich features"\n table.add_column("Feature", no_wrap=True, justify="center", style="bold red")\n table.add_column("Demonstration")\n\n color_table = Table(\n box=None,\n expand=False,\n show_header=False,\n show_edge=False,\n pad_edge=False,\n )\n color_table.add_row(\n (\n "✓ [bold green]4-bit color[/]\n"\n "✓ [bold blue]8-bit color[/]\n"\n "✓ [bold magenta]Truecolor (16.7 million)[/]\n"\n "✓ [bold yellow]Dumb terminals[/]\n"\n "✓ [bold cyan]Automatic color conversion"\n ),\n ColorBox(),\n )\n\n table.add_row("Colors", color_table)\n\n table.add_row(\n "Styles",\n "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].",\n )\n\n lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus."\n lorem_table = Table.grid(padding=1, collapse_padding=True)\n lorem_table.pad_edge = False\n lorem_table.add_row(\n Text(lorem, justify="left", style="green"),\n Text(lorem, justify="center", style="yellow"),\n Text(lorem, justify="right", style="blue"),\n Text(lorem, justify="full", style="red"),\n )\n table.add_row(\n "Text",\n Group(\n Text.from_markup(\n """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n"""\n ),\n lorem_table,\n ),\n )\n\n def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table:\n table = Table(show_header=False, pad_edge=False, box=None, expand=True)\n table.add_column("1", ratio=1)\n table.add_column("2", ratio=1)\n table.add_row(renderable1, renderable2)\n return table\n\n table.add_row(\n "Asian\nlanguage\nsupport",\n ":flag_for_china: 该库支持中文,日文和韩文文本!\n:flag_for_japan: ライブラリは中国語、日本語、韓国語のテキストをサポートしています\n:flag_for_south_korea: 이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다",\n )\n\n markup_example = (\n "[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! "\n ":+1: :apple: :ant: :bear: :baguette_bread: :bus: "\n )\n table.add_row("Markup", markup_example)\n\n example_table = Table(\n show_edge=False,\n show_header=True,\n expand=False,\n row_styles=["none", "dim"],\n box=box.SIMPLE,\n )\n example_table.add_column("[green]Date", style="green", no_wrap=True)\n example_table.add_column("[blue]Title", style="blue")\n example_table.add_column(\n "[cyan]Production Budget",\n style="cyan",\n justify="right",\n no_wrap=True,\n )\n example_table.add_column(\n "[magenta]Box Office",\n style="magenta",\n justify="right",\n no_wrap=True,\n )\n example_table.add_row(\n "Dec 20, 2019",\n "Star Wars: The Rise of Skywalker",\n "$275,000,000",\n "$375,126,118",\n )\n example_table.add_row(\n "May 25, 2018",\n "[b]Solo[/]: A Star Wars Story",\n "$275,000,000",\n "$393,151,347",\n )\n example_table.add_row(\n "Dec 15, 2017",\n "Star Wars Ep. VIII: The Last Jedi",\n "$262,000,000",\n "[bold]$1,332,539,889[/bold]",\n )\n example_table.add_row(\n "May 19, 1999",\n "Star Wars Ep. [b]I[/b]: [i]The phantom Menace",\n "$115,000,000",\n "$1,027,044,677",\n )\n\n table.add_row("Tables", example_table)\n\n code = '''\\ndef iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n """Iterate and generate a tuple with a flag for last value."""\n iter_values = iter(values)\n try:\n previous_value = next(iter_values)\n except StopIteration:\n return\n for value in iter_values:\n yield False, previous_value\n previous_value = value\n yield True, previous_value'''\n\n pretty_data = {\n "foo": [\n 3.1427,\n (\n "Paul Atreides",\n "Vladimir Harkonnen",\n "Thufir Hawat",\n ),\n ],\n "atomic": (False, True, None),\n }\n table.add_row(\n "Syntax\nhighlighting\n&\npretty\nprinting",\n comparison(\n Syntax(code, "python3", line_numbers=True, indent_guides=True),\n Pretty(pretty_data, indent_guides=True),\n ),\n )\n\n markdown_example = """\\n# Markdown\n\nSupports much of the *markdown* __syntax__!\n\n- Headers\n- Basic formatting: **bold**, *italic*, `code`\n- Block quotes\n- Lists, and more...\n """\n table.add_row(\n "Markdown", comparison("[cyan]" + markdown_example, Markdown(markdown_example))\n )\n\n table.add_row(\n "+more!",\n """Progress bars, columns, styled logging handler, tracebacks, etc...""",\n )\n return table\n\n\nif __name__ == "__main__": # pragma: no cover\n console = Console(\n file=io.StringIO(),\n force_terminal=True,\n )\n test_card = make_test_card()\n\n # Print once to warm cache\n start = process_time()\n console.print(test_card)\n pre_cache_taken = round((process_time() - start) * 1000.0, 1)\n\n console.file = io.StringIO()\n\n start = process_time()\n console.print(test_card)\n taken = round((process_time() - start) * 1000.0, 1)\n\n c = Console(record=True)\n c.print(test_card)\n\n print(f"rendered in {pre_cache_taken}ms (cold cache)")\n print(f"rendered in {taken}ms (warm cache)")\n\n from pip._vendor.rich.panel import Panel\n\n console = Console()\n\n sponsor_message = Table.grid(padding=1)\n sponsor_message.add_column(style="green", justify="right")\n sponsor_message.add_column(no_wrap=True)\n\n sponsor_message.add_row(\n "Textualize",\n "[u blue link=https://github.com/textualize]https://github.com/textualize",\n )\n sponsor_message.add_row(\n "Twitter",\n "[u blue link=https://twitter.com/willmcgugan]https://twitter.com/willmcgugan",\n )\n\n intro_message = Text.from_markup(\n """\\nWe hope you enjoy using Rich!\n\nRich is maintained with [red]:heart:[/] by [link=https://www.textualize.io]Textualize.io[/]\n\n- Will McGugan"""\n )\n\n message = Table.grid(padding=2)\n message.add_column()\n message.add_column(no_wrap=True)\n message.add_row(intro_message, sponsor_message)\n\n console.print(\n Panel.fit(\n message,\n box=box.ROUNDED,\n padding=(1, 2),\n title="[b red]Thanks for trying out Rich!",\n border_style="bright_blue",\n ),\n justify="center",\n )\n | .venv\Lib\site-packages\pip\_vendor\rich\__main__.py | __main__.py | Python | 8,477 | 0.95 | 0.051282 | 0.008475 | awesome-app | 279 | 2025-01-18T18:30:50.661231 | GPL-3.0 | false | 02e4c99e83b2692660a46e7f2ea41e8f |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\abc.cpython-313.pyc | abc.cpython-313.pyc | Other | 1,692 | 0.85 | 0.318182 | 0.055556 | node-utils | 43 | 2023-11-16T13:40:47.947005 | BSD-3-Clause | false | 3afe5eac796841f376fe46e02a21dc33 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\align.cpython-313.pyc | align.cpython-313.pyc | Other | 12,576 | 0.95 | 0.030928 | 0.022099 | react-lib | 259 | 2024-07-07T08:46:07.970737 | MIT | false | ccf2b3a176c5eea9c73ab5ed86b4b801 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\ansi.cpython-313.pyc | ansi.cpython-313.pyc | Other | 9,264 | 0.8 | 0 | 0.015625 | node-utils | 306 | 2023-08-10T19:42:41.555134 | GPL-3.0 | false | b39be1a4e2b43631da137f0054a26a07 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\bar.cpython-313.pyc | bar.cpython-313.pyc | Other | 4,337 | 0.8 | 0.03125 | 0 | node-utils | 312 | 2024-07-15T02:32:49.268880 | GPL-3.0 | false | cf5f0e8659b3a2cdcf9ee3e2bd1af16a |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\box.cpython-313.pyc | box.cpython-313.pyc | Other | 11,826 | 0.8 | 0.019934 | 0 | node-utils | 809 | 2025-05-23T05:56:07.509628 | BSD-3-Clause | false | 9a47371693dcaaaf7d3df0cbd78c30d6 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\cells.cpython-313.pyc | cells.cpython-313.pyc | Other | 5,507 | 0.95 | 0 | 0 | react-lib | 708 | 2023-07-15T21:02:10.480196 | Apache-2.0 | false | 458ee722bb4164d163bccf9075149d49 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\color.cpython-313.pyc | color.cpython-313.pyc | Other | 26,534 | 0.8 | 0.033333 | 0.007722 | react-lib | 845 | 2024-05-28T19:54:24.841626 | Apache-2.0 | false | ed59574629dd92d96d4244c23ad08ba1 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\color_triplet.cpython-313.pyc | color_triplet.cpython-313.pyc | Other | 1,709 | 0.8 | 0 | 0 | node-utils | 694 | 2025-03-29T03:07:57.761674 | BSD-3-Clause | false | 45fee63da584fbbcdcaec5a7ebd65d91 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\columns.cpython-313.pyc | columns.cpython-313.pyc | Other | 8,720 | 0.8 | 0.018018 | 0 | python-kit | 701 | 2023-10-22T10:20:28.436382 | MIT | false | 56c6a7de8d4fefc83ee0c13688d158ad |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\constrain.cpython-313.pyc | constrain.cpython-313.pyc | Other | 2,315 | 0.8 | 0 | 0 | awesome-app | 942 | 2024-07-23T08:57:48.390424 | Apache-2.0 | false | a7c05f34fd025fdf84e2187fd14fcf79 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\containers.cpython-313.pyc | containers.cpython-313.pyc | Other | 9,258 | 0.95 | 0.016 | 0 | vue-tools | 903 | 2024-08-23T01:06:11.130826 | GPL-3.0 | false | 3fb6829b90a62f273a946c769c79ad8f |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\control.cpython-313.pyc | control.cpython-313.pyc | Other | 10,916 | 0.8 | 0.006711 | 0.007692 | awesome-app | 586 | 2023-12-12T01:59:25.157852 | Apache-2.0 | false | 895e89e1cf4c0434842f110b89ea1bdb |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\default_styles.cpython-313.pyc | default_styles.cpython-313.pyc | Other | 9,699 | 0.8 | 0 | 0 | node-utils | 70 | 2024-08-25T19:38:58.225044 | GPL-3.0 | false | a555b0f80f35bbc5f572325458d81799 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\diagnose.cpython-313.pyc | diagnose.cpython-313.pyc | Other | 1,514 | 0.8 | 0 | 0 | react-lib | 80 | 2023-11-06T08:39:39.452260 | BSD-3-Clause | false | 5f35d552f5b3d8098a890b6ba43d56dd |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\emoji.cpython-313.pyc | emoji.cpython-313.pyc | Other | 4,254 | 0.8 | 0 | 0 | node-utils | 418 | 2023-11-28T10:12:29.110882 | BSD-3-Clause | false | 9885039596c1b85f8bc3825945d3f67d |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\errors.cpython-313.pyc | errors.cpython-313.pyc | Other | 2,051 | 0.95 | 0 | 0 | react-lib | 515 | 2024-11-29T19:05:05.077886 | Apache-2.0 | false | 68e0c10260e2ce4d8521c625066dc2cf |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\filesize.cpython-313.pyc | filesize.cpython-313.pyc | Other | 2,961 | 0.95 | 0.035714 | 0.022727 | python-kit | 533 | 2023-10-15T18:10:58.165046 | BSD-3-Clause | false | 92ba4493560589dd244c5e49a86cb06f |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\file_proxy.cpython-313.pyc | file_proxy.cpython-313.pyc | Other | 3,711 | 0.8 | 0 | 0 | react-lib | 330 | 2023-09-20T06:40:43.464096 | GPL-3.0 | false | 4a829dd6fea096edf3218f0dc79c7ce0 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\highlighter.cpython-313.pyc | highlighter.cpython-313.pyc | Other | 9,981 | 0.95 | 0.037975 | 0.029412 | vue-tools | 730 | 2024-04-02T15:03:36.520931 | Apache-2.0 | false | d7903ad04839446f1d738252428ccc6a |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\json.cpython-313.pyc | json.cpython-313.pyc | Other | 5,922 | 0.8 | 0.041237 | 0 | vue-tools | 354 | 2024-05-22T19:46:54.689329 | BSD-3-Clause | false | aafd29e158842b9b70b02648c3a6b416 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\jupyter.cpython-313.pyc | jupyter.cpython-313.pyc | Other | 5,394 | 0.8 | 0.020833 | 0 | vue-tools | 750 | 2023-07-16T16:31:33.239369 | Apache-2.0 | false | 4cc37fcce2c58a9d3fae9600e05bd956 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\layout.cpython-313.pyc | layout.cpython-313.pyc | Other | 20,177 | 0.95 | 0.033019 | 0.020513 | awesome-app | 285 | 2025-03-23T16:33:04.870981 | GPL-3.0 | false | 7eceda39f9ef997e6c75ce5fa351284b |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\live.cpython-313.pyc | live.cpython-313.pyc | Other | 19,642 | 0.95 | 0.04918 | 0 | node-utils | 147 | 2023-08-01T18:56:09.079498 | MIT | false | a53856f23bcffc917fe7061872be36b4 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\live_render.cpython-313.pyc | live_render.cpython-313.pyc | Other | 4,873 | 0.8 | 0 | 0 | awesome-app | 645 | 2024-01-14T08:15:35.590277 | Apache-2.0 | false | 1a5de8a87b0dfaebc3143861ca090b86 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\logging.cpython-313.pyc | logging.cpython-313.pyc | Other | 14,023 | 0.8 | 0.089655 | 0.007463 | react-lib | 612 | 2024-08-28T00:47:58.865600 | BSD-3-Clause | false | 749663a3b54cfd877c9d6831683d4606 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\markup.cpython-313.pyc | markup.cpython-313.pyc | Other | 9,725 | 0.8 | 0 | 0.017857 | python-kit | 884 | 2024-03-13T01:57:52.286848 | GPL-3.0 | false | 3568ce167739a4e5320c04a63cccabb4 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\measure.cpython-313.pyc | measure.cpython-313.pyc | Other | 6,202 | 0.95 | 0.042105 | 0 | awesome-app | 760 | 2024-06-23T18:44:17.364362 | Apache-2.0 | false | 2d678aa09ef94c3a7f8a5bc90a18c2db |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\padding.cpython-313.pyc | padding.cpython-313.pyc | Other | 6,949 | 0.95 | 0.037975 | 0 | python-kit | 3 | 2024-09-03T03:01:18.457845 | GPL-3.0 | false | a06551547c0881e7723a7cd147070859 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\pager.cpython-313.pyc | pager.cpython-313.pyc | Other | 1,889 | 0.95 | 0.064516 | 0 | vue-tools | 524 | 2024-12-13T13:33:17.320626 | MIT | false | f6bf292cf71cc0303501c8e620a1d866 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\palette.cpython-313.pyc | palette.cpython-313.pyc | Other | 5,316 | 0.8 | 0 | 0 | vue-tools | 890 | 2024-11-03T13:52:24.958768 | MIT | false | 8191daa26ec6902e08cbc138bc05910e |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\panel.cpython-313.pyc | panel.cpython-313.pyc | Other | 12,740 | 0.8 | 0.01087 | 0 | vue-tools | 72 | 2023-12-13T17:25:14.012290 | BSD-3-Clause | false | e45ef8af105d785b82aff9491a84c29b |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\pretty.cpython-313.pyc | pretty.cpython-313.pyc | Other | 41,288 | 0.95 | 0.080275 | 0.009975 | awesome-app | 694 | 2024-08-02T07:36:01.063548 | GPL-3.0 | false | fa169420ab1a52e2513366a352bd841b |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\progress.cpython-313.pyc | progress.cpython-313.pyc | Other | 75,536 | 0.75 | 0.077895 | 0.005787 | node-utils | 298 | 2024-05-06T19:44:06.983790 | GPL-3.0 | false | a2cd2cea854d3bfc791657bf8bc6f2be |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\progress_bar.cpython-313.pyc | progress_bar.cpython-313.pyc | Other | 10,453 | 0.8 | 0.047945 | 0.007519 | vue-tools | 49 | 2023-09-01T19:17:15.689223 | Apache-2.0 | false | 021971cdd5ee551d78cb2935e4c3b675 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\prompt.cpython-313.pyc | prompt.cpython-313.pyc | Other | 15,812 | 0.95 | 0.031873 | 0 | awesome-app | 486 | 2023-08-19T11:12:48.216667 | BSD-3-Clause | false | a5f6b2857836c51805a670ad6bae36e0 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\protocol.cpython-313.pyc | protocol.cpython-313.pyc | Other | 1,872 | 0.8 | 0.068966 | 0 | awesome-app | 615 | 2023-08-23T00:19:10.565744 | BSD-3-Clause | false | 9b5cd7cf8f345b205ec0bfa52e82c14b |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\region.cpython-313.pyc | region.cpython-313.pyc | Other | 629 | 0.7 | 0 | 0 | react-lib | 468 | 2023-11-07T17:32:26.118873 | MIT | false | 0c515840f6c5518bbeebc28c668b209b |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\repr.cpython-313.pyc | repr.cpython-313.pyc | Other | 6,749 | 0.8 | 0 | 0.014085 | vue-tools | 743 | 2024-08-12T07:06:28.335735 | Apache-2.0 | false | 84b883e0b6f01d451f6facfc428c56d1 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\rule.cpython-313.pyc | rule.cpython-313.pyc | Other | 6,623 | 0.95 | 0.010989 | 0 | vue-tools | 305 | 2023-11-05T13:12:56.810992 | BSD-3-Clause | false | 6f8074ead967c515bcb9a8abe2af111e |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\scope.cpython-313.pyc | scope.cpython-313.pyc | Other | 3,798 | 0.8 | 0.018519 | 0 | react-lib | 209 | 2025-03-10T22:52:45.919516 | MIT | false | 53b9ff2ec5cc2993d4d2602287611238 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\screen.cpython-313.pyc | screen.cpython-313.pyc | Other | 2,554 | 0.8 | 0 | 0 | node-utils | 229 | 2024-10-27T15:23:15.803145 | MIT | false | c2846a6ed841a26e8c1afc94c1c31e86 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\segment.cpython-313.pyc | segment.cpython-313.pyc | Other | 28,280 | 0.95 | 0.034853 | 0.006192 | node-utils | 229 | 2025-05-13T07:31:40.680759 | MIT | false | 24281f9233725a1ad648696fed138a39 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\spinner.cpython-313.pyc | spinner.cpython-313.pyc | Other | 6,159 | 0.8 | 0.053191 | 0 | vue-tools | 630 | 2024-02-08T01:54:52.543589 | BSD-3-Clause | false | 5d9c1d85b00c587c03581b46ac257254 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\status.cpython-313.pyc | status.cpython-313.pyc | Other | 6,030 | 0.8 | 0.088889 | 0.0125 | awesome-app | 91 | 2023-10-27T14:44:52.684559 | MIT | false | bff7d8982b4a97fa748748a2d36ed36c |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\style.cpython-313.pyc | style.cpython-313.pyc | Other | 34,397 | 0.8 | 0.040936 | 0.010135 | python-kit | 992 | 2023-10-06T01:51:17.984844 | BSD-3-Clause | false | 015101106cbae0d5faa8e8328583c0aa |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\styled.cpython-313.pyc | styled.cpython-313.pyc | Other | 2,191 | 0.8 | 0 | 0 | react-lib | 814 | 2025-07-05T01:44:23.335198 | MIT | false | 6814f428b0b6d813aa7aaa5d20fe45b2 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\syntax.cpython-313.pyc | syntax.cpython-313.pyc | Other | 39,842 | 0.95 | 0.064732 | 0.007212 | awesome-app | 331 | 2025-03-11T16:35:33.780153 | GPL-3.0 | false | 137ede5cf3fb7ffafcac8fcaf63b8c5a |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\table.cpython-313.pyc | table.cpython-313.pyc | Other | 44,338 | 0.95 | 0.071287 | 0.008565 | react-lib | 854 | 2025-02-05T07:21:39.992294 | GPL-3.0 | false | 257c6cb1cc3b5867fbe216d267366bd9 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\terminal_theme.cpython-313.pyc | terminal_theme.cpython-313.pyc | Other | 3,410 | 0.8 | 0 | 0 | python-kit | 810 | 2025-03-23T18:18:19.877047 | Apache-2.0 | false | 3bcd4b08330a2453a3d9e221b6560ef4 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\text.cpython-313.pyc | text.cpython-313.pyc | Other | 60,289 | 0.75 | 0.02642 | 0.007519 | python-kit | 693 | 2024-06-26T08:54:34.127195 | MIT | false | e6ae54ef8335e96238dbe7c1cdde298d |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\theme.cpython-313.pyc | theme.cpython-313.pyc | Other | 6,326 | 0.8 | 0.056818 | 0.038961 | react-lib | 700 | 2025-07-01T17:44:34.241177 | Apache-2.0 | false | ccbb434dc24129b78062a0f0ba0eff95 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\themes.cpython-313.pyc | themes.cpython-313.pyc | Other | 318 | 0.7 | 0 | 0 | python-kit | 326 | 2023-09-14T12:01:26.958372 | Apache-2.0 | false | 1eba5ccc2eb48ed630d0e68c994abb9b |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\traceback.cpython-313.pyc | traceback.cpython-313.pyc | Other | 36,247 | 0.95 | 0.026316 | 0.002545 | python-kit | 226 | 2024-04-12T15:49:34.333996 | Apache-2.0 | false | 7ddd9f3b503fdfd4d6fbc06191b7a4f0 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\tree.cpython-313.pyc | tree.cpython-313.pyc | Other | 11,923 | 0.95 | 0.045455 | 0 | react-lib | 555 | 2025-04-17T18:49:01.361528 | Apache-2.0 | false | b4504d6ee20f6f8e90b8e42dcac539a2 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_cell_widths.cpython-313.pyc | _cell_widths.cpython-313.pyc | Other | 7,876 | 0.8 | 0.043478 | 0 | node-utils | 985 | 2023-11-07T21:03:40.593474 | BSD-3-Clause | false | 99f25757ad63a6462add294a0f3a8e9b |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_emoji_replace.cpython-313.pyc | _emoji_replace.cpython-313.pyc | Other | 1,748 | 0.8 | 0 | 0 | node-utils | 354 | 2023-11-26T05:08:28.873962 | GPL-3.0 | false | 99f42a5007fa54c084c032c24a4df02d |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_export_format.cpython-313.pyc | _export_format.cpython-313.pyc | Other | 2,353 | 0.8 | 0.028571 | 0 | python-kit | 142 | 2025-01-04T22:58:48.977189 | BSD-3-Clause | false | 226a43b4d18ffd86145d9f6d6bc34f18 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_extension.cpython-313.pyc | _extension.cpython-313.pyc | Other | 543 | 0.7 | 0 | 0 | vue-tools | 118 | 2023-10-13T11:46:32.655751 | MIT | false | 68d454898a92b782e4fd73434288596e |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_fileno.cpython-313.pyc | _fileno.cpython-313.pyc | Other | 845 | 0.7 | 0.2 | 0 | node-utils | 985 | 2024-08-03T11:16:22.227793 | GPL-3.0 | false | 17b7482041d15b948439f8d563f04a00 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_inspect.cpython-313.pyc | _inspect.cpython-313.pyc | Other | 12,299 | 0.95 | 0.118519 | 0 | vue-tools | 729 | 2024-03-14T13:34:19.601289 | MIT | false | d0680f22096d389e3c29e9abba947cdf |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_log_render.cpython-313.pyc | _log_render.cpython-313.pyc | Other | 4,329 | 0.8 | 0 | 0 | react-lib | 560 | 2025-06-24T16:11:33.099694 | MIT | false | 3ace75dc4a015ce200169a0ae602815f |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_loop.cpython-313.pyc | _loop.cpython-313.pyc | Other | 1,904 | 0.8 | 0.1875 | 0 | vue-tools | 209 | 2025-01-12T01:50:37.501113 | BSD-3-Clause | false | 43594300bb8d9a74cf9db7559b3c1810 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_null_file.cpython-313.pyc | _null_file.cpython-313.pyc | Other | 3,739 | 0.8 | 0 | 0.034483 | node-utils | 841 | 2023-07-13T23:18:35.661137 | MIT | false | 589544e359c6af9dd91071c7ac359dc3 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_palettes.cpython-313.pyc | _palettes.cpython-313.pyc | Other | 5,164 | 0.8 | 0 | 0 | react-lib | 60 | 2024-06-02T07:28:30.586355 | MIT | false | 5c28be77eaf5fbd8fca18cf16c4c2090 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_pick.cpython-313.pyc | _pick.cpython-313.pyc | Other | 723 | 0.85 | 0 | 0.083333 | react-lib | 270 | 2025-07-08T08:49:29.721062 | BSD-3-Clause | false | 5f10a39f8e02acfb4e3e8a2d9f4cafe0 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_ratio.cpython-313.pyc | _ratio.cpython-313.pyc | Other | 6,604 | 0.8 | 0.05 | 0 | react-lib | 311 | 2023-12-15T14:58:37.208752 | GPL-3.0 | false | 09540b3f31372938a42107d56ff75078 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_spinners.cpython-313.pyc | _spinners.cpython-313.pyc | Other | 13,183 | 0.8 | 0 | 0.013333 | vue-tools | 919 | 2024-07-02T16:59:42.145021 | GPL-3.0 | false | 4cdc67db2cce417ba86c3022f7010a87 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_stack.cpython-313.pyc | _stack.cpython-313.pyc | Other | 1,031 | 0.7 | 0 | 0 | awesome-app | 199 | 2024-02-07T09:05:39.856799 | MIT | false | 316051e9b7739b959a002a9cdad253c7 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_timer.cpython-313.pyc | _timer.cpython-313.pyc | Other | 872 | 0.8 | 0 | 0 | vue-tools | 810 | 2025-03-30T00:49:04.452862 | BSD-3-Clause | false | eb6af579c50d774d83d21b22af9a590b |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_win32_console.cpython-313.pyc | _win32_console.cpython-313.pyc | Other | 28,343 | 0.95 | 0.074468 | 0 | awesome-app | 204 | 2025-02-22T00:25:07.926046 | MIT | false | 10ebc274e13d2eda3d5a8f548c8445e9 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_windows.cpython-313.pyc | _windows.cpython-313.pyc | Other | 2,570 | 0.8 | 0 | 0 | node-utils | 720 | 2024-03-01T22:56:28.636283 | BSD-3-Clause | false | 87d1c6caa8127d92cab2029eadec9c76 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_windows_renderer.cpython-313.pyc | _windows_renderer.cpython-313.pyc | Other | 3,617 | 0.8 | 0 | 0 | react-lib | 198 | 2024-04-26T13:10:02.826486 | GPL-3.0 | false | d86dcd9ad2ea6364b16f37bd4c5f4633 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\_wrap.cpython-313.pyc | _wrap.cpython-313.pyc | Other | 3,329 | 0.8 | 0.019608 | 0.06383 | node-utils | 147 | 2025-01-30T17:25:51.588388 | BSD-3-Clause | false | 778535169c4fd2f4047ef4f992910699 |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 6,878 | 0.95 | 0.091667 | 0.072727 | react-lib | 573 | 2024-11-10T10:51:28.386105 | Apache-2.0 | false | ce9bc73bb46b9d9f7711dfaf239cfd0c |
\n\n | .venv\Lib\site-packages\pip\_vendor\rich\__pycache__\__main__.cpython-313.pyc | __main__.cpython-313.pyc | Other | 10,179 | 0.95 | 0.054545 | 0 | vue-tools | 961 | 2025-04-07T07:15:11.526203 | Apache-2.0 | false | e3997e3bbbbeefef5610e778fd983830 |
# Marker file for PEP 561\n | .venv\Lib\site-packages\pip\_vendor\tomli\py.typed | py.typed | Other | 26 | 0.6 | 1 | 1 | vue-tools | 292 | 2024-05-25T20:14:13.797266 | BSD-3-Clause | false | bd2fa011a5e69d2b68df68fbc59f8be6 |
# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\nimport string\nimport sys\nfrom types import MappingProxyType\nfrom typing import IO, Any, Final, NamedTuple\nimport warnings\n\nfrom ._re import (\n RE_DATETIME,\n RE_LOCALTIME,\n RE_NUMBER,\n match_to_datetime,\n match_to_localtime,\n match_to_number,\n)\nfrom ._types import Key, ParseFloat, Pos\n\n# Inline tables/arrays are implemented using recursion. Pathologically\n# nested documents cause pure Python to raise RecursionError (which is OK),\n# but mypyc binary wheels will crash unrecoverably (not OK). According to\n# mypyc docs this will be fixed in the future:\n# https://mypyc.readthedocs.io/en/latest/differences_from_python.html#stack-overflows\n# Before mypyc's fix is in, recursion needs to be limited by this library.\n# Choosing `sys.getrecursionlimit()` as maximum inline table/array nesting\n# level, as it allows more nesting than pure Python, but still seems a far\n# lower number than where mypyc binaries crash.\nMAX_INLINE_NESTING: Final = sys.getrecursionlimit()\n\nASCII_CTRL: Final = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))\n\n# Neither of these sets include quotation mark or backslash. They are\n# currently handled as separate cases in the parser functions.\nILLEGAL_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t")\nILLEGAL_MULTILINE_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t\n")\n\nILLEGAL_LITERAL_STR_CHARS: Final = ILLEGAL_BASIC_STR_CHARS\nILLEGAL_MULTILINE_LITERAL_STR_CHARS: Final = ILLEGAL_MULTILINE_BASIC_STR_CHARS\n\nILLEGAL_COMMENT_CHARS: Final = ILLEGAL_BASIC_STR_CHARS\n\nTOML_WS: Final = frozenset(" \t")\nTOML_WS_AND_NEWLINE: Final = TOML_WS | frozenset("\n")\nBARE_KEY_CHARS: Final = frozenset(string.ascii_letters + string.digits + "-_")\nKEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset("\"'")\nHEXDIGIT_CHARS: Final = frozenset(string.hexdigits)\n\nBASIC_STR_ESCAPE_REPLACEMENTS: Final = MappingProxyType(\n {\n "\\b": "\u0008", # backspace\n "\\t": "\u0009", # tab\n "\\n": "\u000A", # linefeed\n "\\f": "\u000C", # form feed\n "\\r": "\u000D", # carriage return\n '\\"': "\u0022", # quote\n "\\\\": "\u005C", # backslash\n }\n)\n\n\nclass DEPRECATED_DEFAULT:\n """Sentinel to be used as default arg during deprecation\n period of TOMLDecodeError's free-form arguments."""\n\n\nclass TOMLDecodeError(ValueError):\n """An error raised if a document is not valid TOML.\n\n Adds the following attributes to ValueError:\n msg: The unformatted error message\n doc: The TOML document being parsed\n pos: The index of doc where parsing failed\n lineno: The line corresponding to pos\n colno: The column corresponding to pos\n """\n\n def __init__(\n self,\n msg: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,\n doc: str | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,\n pos: Pos | type[DEPRECATED_DEFAULT] = DEPRECATED_DEFAULT,\n *args: Any,\n ):\n if (\n args\n or not isinstance(msg, str)\n or not isinstance(doc, str)\n or not isinstance(pos, int)\n ):\n warnings.warn(\n "Free-form arguments for TOMLDecodeError are deprecated. "\n "Please set 'msg' (str), 'doc' (str) and 'pos' (int) arguments only.",\n DeprecationWarning,\n stacklevel=2,\n )\n if pos is not DEPRECATED_DEFAULT:\n args = pos, *args\n if doc is not DEPRECATED_DEFAULT:\n args = doc, *args\n if msg is not DEPRECATED_DEFAULT:\n args = msg, *args\n ValueError.__init__(self, *args)\n return\n\n lineno = doc.count("\n", 0, pos) + 1\n if lineno == 1:\n colno = pos + 1\n else:\n colno = pos - doc.rindex("\n", 0, pos)\n\n if pos >= len(doc):\n coord_repr = "end of document"\n else:\n coord_repr = f"line {lineno}, column {colno}"\n errmsg = f"{msg} (at {coord_repr})"\n ValueError.__init__(self, errmsg)\n\n self.msg = msg\n self.doc = doc\n self.pos = pos\n self.lineno = lineno\n self.colno = colno\n\n\ndef load(__fp: IO[bytes], *, parse_float: ParseFloat = float) -> dict[str, Any]:\n """Parse TOML from a binary file object."""\n b = __fp.read()\n try:\n s = b.decode()\n except AttributeError:\n raise TypeError(\n "File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`"\n ) from None\n return loads(s, parse_float=parse_float)\n\n\ndef loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]: # noqa: C901\n """Parse TOML from a string."""\n\n # The spec allows converting "\r\n" to "\n", even in string\n # literals. Let's do so to simplify parsing.\n try:\n src = __s.replace("\r\n", "\n")\n except (AttributeError, TypeError):\n raise TypeError(\n f"Expected str object, not '{type(__s).__qualname__}'"\n ) from None\n pos = 0\n out = Output(NestedDict(), Flags())\n header: Key = ()\n parse_float = make_safe_parse_float(parse_float)\n\n # Parse one statement at a time\n # (typically means one line in TOML source)\n while True:\n # 1. Skip line leading whitespace\n pos = skip_chars(src, pos, TOML_WS)\n\n # 2. Parse rules. Expect one of the following:\n # - end of file\n # - end of line\n # - comment\n # - key/value pair\n # - append dict to list (and move to its namespace)\n # - create dict (and move to its namespace)\n # Skip trailing whitespace when applicable.\n try:\n char = src[pos]\n except IndexError:\n break\n if char == "\n":\n pos += 1\n continue\n if char in KEY_INITIAL_CHARS:\n pos = key_value_rule(src, pos, out, header, parse_float)\n pos = skip_chars(src, pos, TOML_WS)\n elif char == "[":\n try:\n second_char: str | None = src[pos + 1]\n except IndexError:\n second_char = None\n out.flags.finalize_pending()\n if second_char == "[":\n pos, header = create_list_rule(src, pos, out)\n else:\n pos, header = create_dict_rule(src, pos, out)\n pos = skip_chars(src, pos, TOML_WS)\n elif char != "#":\n raise TOMLDecodeError("Invalid statement", src, pos)\n\n # 3. Skip comment\n pos = skip_comment(src, pos)\n\n # 4. Expect end of line or end of file\n try:\n char = src[pos]\n except IndexError:\n break\n if char != "\n":\n raise TOMLDecodeError(\n "Expected newline or end of document after a statement", src, pos\n )\n pos += 1\n\n return out.data.dict\n\n\nclass Flags:\n """Flags that map to parsed keys/namespaces."""\n\n # Marks an immutable namespace (inline array or inline table).\n FROZEN: Final = 0\n # Marks a nest that has been explicitly created and can no longer\n # be opened using the "[table]" syntax.\n EXPLICIT_NEST: Final = 1\n\n def __init__(self) -> None:\n self._flags: dict[str, dict] = {}\n self._pending_flags: set[tuple[Key, int]] = set()\n\n def add_pending(self, key: Key, flag: int) -> None:\n self._pending_flags.add((key, flag))\n\n def finalize_pending(self) -> None:\n for key, flag in self._pending_flags:\n self.set(key, flag, recursive=False)\n self._pending_flags.clear()\n\n def unset_all(self, key: Key) -> None:\n cont = self._flags\n for k in key[:-1]:\n if k not in cont:\n return\n cont = cont[k]["nested"]\n cont.pop(key[-1], None)\n\n def set(self, key: Key, flag: int, *, recursive: bool) -> None: # noqa: A003\n cont = self._flags\n key_parent, key_stem = key[:-1], key[-1]\n for k in key_parent:\n if k not in cont:\n cont[k] = {"flags": set(), "recursive_flags": set(), "nested": {}}\n cont = cont[k]["nested"]\n if key_stem not in cont:\n cont[key_stem] = {"flags": set(), "recursive_flags": set(), "nested": {}}\n cont[key_stem]["recursive_flags" if recursive else "flags"].add(flag)\n\n def is_(self, key: Key, flag: int) -> bool:\n if not key:\n return False # document root has no flags\n cont = self._flags\n for k in key[:-1]:\n if k not in cont:\n return False\n inner_cont = cont[k]\n if flag in inner_cont["recursive_flags"]:\n return True\n cont = inner_cont["nested"]\n key_stem = key[-1]\n if key_stem in cont:\n inner_cont = cont[key_stem]\n return flag in inner_cont["flags"] or flag in inner_cont["recursive_flags"]\n return False\n\n\nclass NestedDict:\n def __init__(self) -> None:\n # The parsed content of the TOML document\n self.dict: dict[str, Any] = {}\n\n def get_or_create_nest(\n self,\n key: Key,\n *,\n access_lists: bool = True,\n ) -> dict:\n cont: Any = self.dict\n for k in key:\n if k not in cont:\n cont[k] = {}\n cont = cont[k]\n if access_lists and isinstance(cont, list):\n cont = cont[-1]\n if not isinstance(cont, dict):\n raise KeyError("There is no nest behind this key")\n return cont\n\n def append_nest_to_list(self, key: Key) -> None:\n cont = self.get_or_create_nest(key[:-1])\n last_key = key[-1]\n if last_key in cont:\n list_ = cont[last_key]\n if not isinstance(list_, list):\n raise KeyError("An object other than list found behind this key")\n list_.append({})\n else:\n cont[last_key] = [{}]\n\n\nclass Output(NamedTuple):\n data: NestedDict\n flags: Flags\n\n\ndef skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:\n try:\n while src[pos] in chars:\n pos += 1\n except IndexError:\n pass\n return pos\n\n\ndef skip_until(\n src: str,\n pos: Pos,\n expect: str,\n *,\n error_on: frozenset[str],\n error_on_eof: bool,\n) -> Pos:\n try:\n new_pos = src.index(expect, pos)\n except ValueError:\n new_pos = len(src)\n if error_on_eof:\n raise TOMLDecodeError(f"Expected {expect!r}", src, new_pos) from None\n\n if not error_on.isdisjoint(src[pos:new_pos]):\n while src[pos] not in error_on:\n pos += 1\n raise TOMLDecodeError(f"Found invalid character {src[pos]!r}", src, pos)\n return new_pos\n\n\ndef skip_comment(src: str, pos: Pos) -> Pos:\n try:\n char: str | None = src[pos]\n except IndexError:\n char = None\n if char == "#":\n return skip_until(\n src, pos + 1, "\n", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False\n )\n return pos\n\n\ndef skip_comments_and_array_ws(src: str, pos: Pos) -> Pos:\n while True:\n pos_before_skip = pos\n pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)\n pos = skip_comment(src, pos)\n if pos == pos_before_skip:\n return pos\n\n\ndef create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:\n pos += 1 # Skip "["\n pos = skip_chars(src, pos, TOML_WS)\n pos, key = parse_key(src, pos)\n\n if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):\n raise TOMLDecodeError(f"Cannot declare {key} twice", src, pos)\n out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)\n try:\n out.data.get_or_create_nest(key)\n except KeyError:\n raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None\n\n if not src.startswith("]", pos):\n raise TOMLDecodeError(\n "Expected ']' at the end of a table declaration", src, pos\n )\n return pos + 1, key\n\n\ndef create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:\n pos += 2 # Skip "[["\n pos = skip_chars(src, pos, TOML_WS)\n pos, key = parse_key(src, pos)\n\n if out.flags.is_(key, Flags.FROZEN):\n raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)\n # Free the namespace now that it points to another empty list item...\n out.flags.unset_all(key)\n # ...but this key precisely is still prohibited from table declaration\n out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)\n try:\n out.data.append_nest_to_list(key)\n except KeyError:\n raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None\n\n if not src.startswith("]]", pos):\n raise TOMLDecodeError(\n "Expected ']]' at the end of an array declaration", src, pos\n )\n return pos + 2, key\n\n\ndef key_value_rule(\n src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat\n) -> Pos:\n pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl=0)\n key_parent, key_stem = key[:-1], key[-1]\n abs_key_parent = header + key_parent\n\n relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))\n for cont_key in relative_path_cont_keys:\n # Check that dotted key syntax does not redefine an existing table\n if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):\n raise TOMLDecodeError(f"Cannot redefine namespace {cont_key}", src, pos)\n # Containers in the relative path can't be opened with the table syntax or\n # dotted key/value syntax in following table sections.\n out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)\n\n if out.flags.is_(abs_key_parent, Flags.FROZEN):\n raise TOMLDecodeError(\n f"Cannot mutate immutable namespace {abs_key_parent}", src, pos\n )\n\n try:\n nest = out.data.get_or_create_nest(abs_key_parent)\n except KeyError:\n raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None\n if key_stem in nest:\n raise TOMLDecodeError("Cannot overwrite a value", src, pos)\n # Mark inline table and array namespaces recursively immutable\n if isinstance(value, (dict, list)):\n out.flags.set(header + key, Flags.FROZEN, recursive=True)\n nest[key_stem] = value\n return pos\n\n\ndef parse_key_value_pair(\n src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int\n) -> tuple[Pos, Key, Any]:\n pos, key = parse_key(src, pos)\n try:\n char: str | None = src[pos]\n except IndexError:\n char = None\n if char != "=":\n raise TOMLDecodeError("Expected '=' after a key in a key/value pair", src, pos)\n pos += 1\n pos = skip_chars(src, pos, TOML_WS)\n pos, value = parse_value(src, pos, parse_float, nest_lvl)\n return pos, key, value\n\n\ndef parse_key(src: str, pos: Pos) -> tuple[Pos, Key]:\n pos, key_part = parse_key_part(src, pos)\n key: Key = (key_part,)\n pos = skip_chars(src, pos, TOML_WS)\n while True:\n try:\n char: str | None = src[pos]\n except IndexError:\n char = None\n if char != ".":\n return pos, key\n pos += 1\n pos = skip_chars(src, pos, TOML_WS)\n pos, key_part = parse_key_part(src, pos)\n key += (key_part,)\n pos = skip_chars(src, pos, TOML_WS)\n\n\ndef parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:\n try:\n char: str | None = src[pos]\n except IndexError:\n char = None\n if char in BARE_KEY_CHARS:\n start_pos = pos\n pos = skip_chars(src, pos, BARE_KEY_CHARS)\n return pos, src[start_pos:pos]\n if char == "'":\n return parse_literal_str(src, pos)\n if char == '"':\n return parse_one_line_basic_str(src, pos)\n raise TOMLDecodeError("Invalid initial character for a key part", src, pos)\n\n\ndef parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:\n pos += 1\n return parse_basic_str(src, pos, multiline=False)\n\n\ndef parse_array(\n src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int\n) -> tuple[Pos, list]:\n pos += 1\n array: list = []\n\n pos = skip_comments_and_array_ws(src, pos)\n if src.startswith("]", pos):\n return pos + 1, array\n while True:\n pos, val = parse_value(src, pos, parse_float, nest_lvl)\n array.append(val)\n pos = skip_comments_and_array_ws(src, pos)\n\n c = src[pos : pos + 1]\n if c == "]":\n return pos + 1, array\n if c != ",":\n raise TOMLDecodeError("Unclosed array", src, pos)\n pos += 1\n\n pos = skip_comments_and_array_ws(src, pos)\n if src.startswith("]", pos):\n return pos + 1, array\n\n\ndef parse_inline_table(\n src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int\n) -> tuple[Pos, dict]:\n pos += 1\n nested_dict = NestedDict()\n flags = Flags()\n\n pos = skip_chars(src, pos, TOML_WS)\n if src.startswith("}", pos):\n return pos + 1, nested_dict.dict\n while True:\n pos, key, value = parse_key_value_pair(src, pos, parse_float, nest_lvl)\n key_parent, key_stem = key[:-1], key[-1]\n if flags.is_(key, Flags.FROZEN):\n raise TOMLDecodeError(f"Cannot mutate immutable namespace {key}", src, pos)\n try:\n nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)\n except KeyError:\n raise TOMLDecodeError("Cannot overwrite a value", src, pos) from None\n if key_stem in nest:\n raise TOMLDecodeError(f"Duplicate inline table key {key_stem!r}", src, pos)\n nest[key_stem] = value\n pos = skip_chars(src, pos, TOML_WS)\n c = src[pos : pos + 1]\n if c == "}":\n return pos + 1, nested_dict.dict\n if c != ",":\n raise TOMLDecodeError("Unclosed inline table", src, pos)\n if isinstance(value, (dict, list)):\n flags.set(key, Flags.FROZEN, recursive=True)\n pos += 1\n pos = skip_chars(src, pos, TOML_WS)\n\n\ndef parse_basic_str_escape(\n src: str, pos: Pos, *, multiline: bool = False\n) -> tuple[Pos, str]:\n escape_id = src[pos : pos + 2]\n pos += 2\n if multiline and escape_id in {"\\ ", "\\\t", "\\\n"}:\n # Skip whitespace until next non-whitespace character or end of\n # the doc. Error if non-whitespace is found before newline.\n if escape_id != "\\\n":\n pos = skip_chars(src, pos, TOML_WS)\n try:\n char = src[pos]\n except IndexError:\n return pos, ""\n if char != "\n":\n raise TOMLDecodeError("Unescaped '\\' in a string", src, pos)\n pos += 1\n pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)\n return pos, ""\n if escape_id == "\\u":\n return parse_hex_char(src, pos, 4)\n if escape_id == "\\U":\n return parse_hex_char(src, pos, 8)\n try:\n return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]\n except KeyError:\n raise TOMLDecodeError("Unescaped '\\' in a string", src, pos) from None\n\n\ndef parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:\n return parse_basic_str_escape(src, pos, multiline=True)\n\n\ndef parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:\n hex_str = src[pos : pos + hex_len]\n if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):\n raise TOMLDecodeError("Invalid hex value", src, pos)\n pos += hex_len\n hex_int = int(hex_str, 16)\n if not is_unicode_scalar_value(hex_int):\n raise TOMLDecodeError(\n "Escaped character is not a Unicode scalar value", src, pos\n )\n return pos, chr(hex_int)\n\n\ndef parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]:\n pos += 1 # Skip starting apostrophe\n start_pos = pos\n pos = skip_until(\n src, pos, "'", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True\n )\n return pos + 1, src[start_pos:pos] # Skip ending apostrophe\n\n\ndef parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]:\n pos += 3\n if src.startswith("\n", pos):\n pos += 1\n\n if literal:\n delim = "'"\n end_pos = skip_until(\n src,\n pos,\n "'''",\n error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS,\n error_on_eof=True,\n )\n result = src[pos:end_pos]\n pos = end_pos + 3\n else:\n delim = '"'\n pos, result = parse_basic_str(src, pos, multiline=True)\n\n # Add at maximum two extra apostrophes/quotes if the end sequence\n # is 4 or 5 chars long instead of just 3.\n if not src.startswith(delim, pos):\n return pos, result\n pos += 1\n if not src.startswith(delim, pos):\n return pos, result + delim\n pos += 1\n return pos, result + (delim * 2)\n\n\ndef parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:\n if multiline:\n error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS\n parse_escapes = parse_basic_str_escape_multiline\n else:\n error_on = ILLEGAL_BASIC_STR_CHARS\n parse_escapes = parse_basic_str_escape\n result = ""\n start_pos = pos\n while True:\n try:\n char = src[pos]\n except IndexError:\n raise TOMLDecodeError("Unterminated string", src, pos) from None\n if char == '"':\n if not multiline:\n return pos + 1, result + src[start_pos:pos]\n if src.startswith('"""', pos):\n return pos + 3, result + src[start_pos:pos]\n pos += 1\n continue\n if char == "\\":\n result += src[start_pos:pos]\n pos, parsed_escape = parse_escapes(src, pos)\n result += parsed_escape\n start_pos = pos\n continue\n if char in error_on:\n raise TOMLDecodeError(f"Illegal character {char!r}", src, pos)\n pos += 1\n\n\ndef parse_value( # noqa: C901\n src: str, pos: Pos, parse_float: ParseFloat, nest_lvl: int\n) -> tuple[Pos, Any]:\n if nest_lvl > MAX_INLINE_NESTING:\n # Pure Python should have raised RecursionError already.\n # This ensures mypyc binaries eventually do the same.\n raise RecursionError( # pragma: no cover\n "TOML inline arrays/tables are nested more than the allowed"\n f" {MAX_INLINE_NESTING} levels"\n )\n\n try:\n char: str | None = src[pos]\n except IndexError:\n char = None\n\n # IMPORTANT: order conditions based on speed of checking and likelihood\n\n # Basic strings\n if char == '"':\n if src.startswith('"""', pos):\n return parse_multiline_str(src, pos, literal=False)\n return parse_one_line_basic_str(src, pos)\n\n # Literal strings\n if char == "'":\n if src.startswith("'''", pos):\n return parse_multiline_str(src, pos, literal=True)\n return parse_literal_str(src, pos)\n\n # Booleans\n if char == "t":\n if src.startswith("true", pos):\n return pos + 4, True\n if char == "f":\n if src.startswith("false", pos):\n return pos + 5, False\n\n # Arrays\n if char == "[":\n return parse_array(src, pos, parse_float, nest_lvl + 1)\n\n # Inline tables\n if char == "{":\n return parse_inline_table(src, pos, parse_float, nest_lvl + 1)\n\n # Dates and times\n datetime_match = RE_DATETIME.match(src, pos)\n if datetime_match:\n try:\n datetime_obj = match_to_datetime(datetime_match)\n except ValueError as e:\n raise TOMLDecodeError("Invalid date or datetime", src, pos) from e\n return datetime_match.end(), datetime_obj\n localtime_match = RE_LOCALTIME.match(src, pos)\n if localtime_match:\n return localtime_match.end(), match_to_localtime(localtime_match)\n\n # Integers and "normal" floats.\n # The regex will greedily match any type starting with a decimal\n # char, so needs to be located after handling of dates and times.\n number_match = RE_NUMBER.match(src, pos)\n if number_match:\n return number_match.end(), match_to_number(number_match, parse_float)\n\n # Special floats\n first_three = src[pos : pos + 3]\n if first_three in {"inf", "nan"}:\n return pos + 3, parse_float(first_three)\n first_four = src[pos : pos + 4]\n if first_four in {"-inf", "+inf", "-nan", "+nan"}:\n return pos + 4, parse_float(first_four)\n\n raise TOMLDecodeError("Invalid value", src, pos)\n\n\ndef is_unicode_scalar_value(codepoint: int) -> bool:\n return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111)\n\n\ndef make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:\n """A decorator to make `parse_float` safe.\n\n `parse_float` must not return dicts or lists, because these types\n would be mixed with parsed TOML tables and arrays, thus confusing\n the parser. The returned decorated callable raises `ValueError`\n instead of returning illegal types.\n """\n # The default `float` callable never returns illegal types. Optimize it.\n if parse_float is float:\n return float\n\n def safe_parse_float(float_str: str) -> Any:\n float_value = parse_float(float_str)\n if isinstance(float_value, (dict, list)):\n raise ValueError("parse_float must not return dicts or lists")\n return float_value\n\n return safe_parse_float\n | .venv\Lib\site-packages\pip\_vendor\tomli\_parser.py | _parser.py | Python | 25,591 | 0.95 | 0.215584 | 0.091743 | python-kit | 968 | 2024-10-16T21:25:08.036359 | BSD-3-Clause | false | 0059dbcdfc289cd1c1382e701af18f71 |
# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom __future__ import annotations\n\nfrom datetime import date, datetime, time, timedelta, timezone, tzinfo\nfrom functools import lru_cache\nimport re\nfrom typing import Any, Final\n\nfrom ._types import ParseFloat\n\n# E.g.\n# - 00:32:00.999999\n# - 00:32:00\n_TIME_RE_STR: Final = (\n r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?"\n)\n\nRE_NUMBER: Final = re.compile(\n r"""\n0\n(?:\n x[0-9A-Fa-f](?:_?[0-9A-Fa-f])* # hex\n |\n b[01](?:_?[01])* # bin\n |\n o[0-7](?:_?[0-7])* # oct\n)\n|\n[+-]?(?:0|[1-9](?:_?[0-9])*) # dec, integer part\n(?P<floatpart>\n (?:\.[0-9](?:_?[0-9])*)? # optional fractional part\n (?:[eE][+-]?[0-9](?:_?[0-9])*)? # optional exponent part\n)\n""",\n flags=re.VERBOSE,\n)\nRE_LOCALTIME: Final = re.compile(_TIME_RE_STR)\nRE_DATETIME: Final = re.compile(\n rf"""\n([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27\n(?:\n [Tt ]\n {_TIME_RE_STR}\n (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))? # optional time offset\n)?\n""",\n flags=re.VERBOSE,\n)\n\n\ndef match_to_datetime(match: re.Match) -> datetime | date:\n """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.\n\n Raises ValueError if the match does not correspond to a valid date\n or datetime.\n """\n (\n year_str,\n month_str,\n day_str,\n hour_str,\n minute_str,\n sec_str,\n micros_str,\n zulu_time,\n offset_sign_str,\n offset_hour_str,\n offset_minute_str,\n ) = match.groups()\n year, month, day = int(year_str), int(month_str), int(day_str)\n if hour_str is None:\n return date(year, month, day)\n hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)\n micros = int(micros_str.ljust(6, "0")) if micros_str else 0\n if offset_sign_str:\n tz: tzinfo | None = cached_tz(\n offset_hour_str, offset_minute_str, offset_sign_str\n )\n elif zulu_time:\n tz = timezone.utc\n else: # local date-time\n tz = None\n return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)\n\n\n# No need to limit cache size. This is only ever called on input\n# that matched RE_DATETIME, so there is an implicit bound of\n# 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.\n@lru_cache(maxsize=None)\ndef cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:\n sign = 1 if sign_str == "+" else -1\n return timezone(\n timedelta(\n hours=sign * int(hour_str),\n minutes=sign * int(minute_str),\n )\n )\n\n\ndef match_to_localtime(match: re.Match) -> time:\n hour_str, minute_str, sec_str, micros_str = match.groups()\n micros = int(micros_str.ljust(6, "0")) if micros_str else 0\n return time(int(hour_str), int(minute_str), int(sec_str), micros)\n\n\ndef match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:\n if match.group("floatpart"):\n return parse_float(match.group())\n return int(match.group(), 0)\n | .venv\Lib\site-packages\pip\_vendor\tomli\_re.py | _re.py | Python | 3,171 | 0.95 | 0.098214 | 0.091837 | node-utils | 85 | 2024-03-30T11:25:46.365633 | BSD-3-Clause | false | 748fa7ca854e7e15332754a176c72bcf |
# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom typing import Any, Callable, Tuple\n\n# Type annotations\nParseFloat = Callable[[str], Any]\nKey = Tuple[str, ...]\nPos = int\n | .venv\Lib\site-packages\pip\_vendor\tomli\_types.py | _types.py | Python | 254 | 0.95 | 0 | 0.5 | vue-tools | 274 | 2024-07-05T19:06:13.836869 | BSD-3-Clause | false | 19a32b713392e66bac544e73f025b2cb |
# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\n__all__ = ("loads", "load", "TOMLDecodeError")\n__version__ = "2.2.1" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT\n\nfrom ._parser import TOMLDecodeError, load, loads\n | .venv\Lib\site-packages\pip\_vendor\tomli\__init__.py | __init__.py | Python | 314 | 0.95 | 0 | 0.5 | node-utils | 796 | 2025-01-20T13:02:16.088357 | BSD-3-Clause | false | 9af8abca9b3933053470d01d61c28906 |
\n\n | .venv\Lib\site-packages\pip\_vendor\tomli\__pycache__\_parser.cpython-313.pyc | _parser.cpython-313.pyc | Other | 29,585 | 0.8 | 0.010791 | 0.011029 | vue-tools | 235 | 2025-04-20T12:57:42.371598 | GPL-3.0 | false | efb328b8c5c3d30e03379688bdfd2573 |
\n\n | .venv\Lib\site-packages\pip\_vendor\tomli\__pycache__\_re.cpython-313.pyc | _re.cpython-313.pyc | Other | 4,031 | 0.8 | 0.015625 | 0.064516 | vue-tools | 422 | 2025-03-14T16:46:49.630180 | MIT | false | d8e9e693568cf76f552af597ad8c84c2 |
\n\n | .venv\Lib\site-packages\pip\_vendor\tomli\__pycache__\_types.cpython-313.pyc | _types.cpython-313.pyc | Other | 370 | 0.7 | 0 | 0 | vue-tools | 528 | 2023-09-15T11:40:26.786566 | BSD-3-Clause | false | 08b17f95ef9e1e6f726bbbc85aa350ce |
\n\n | .venv\Lib\site-packages\pip\_vendor\tomli\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 342 | 0.7 | 0 | 0 | node-utils | 322 | 2025-02-07T19:36:06.040069 | MIT | false | e48d3b5d95c6a8cfd441271ce5bad638 |
# Marker file for PEP 561\n | .venv\Lib\site-packages\pip\_vendor\tomli_w\py.typed | py.typed | Other | 26 | 0.6 | 1 | 1 | python-kit | 541 | 2023-08-04T04:56:02.096923 | Apache-2.0 | false | bd2fa011a5e69d2b68df68fbc59f8be6 |
from __future__ import annotations\n\nfrom collections.abc import Mapping\nfrom datetime import date, datetime, time\nfrom types import MappingProxyType\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from collections.abc import Generator\n from decimal import Decimal\n from typing import IO, Any, Final\n\nASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))\nILLEGAL_BASIC_STR_CHARS = frozenset('"\\') | ASCII_CTRL - frozenset("\t")\nBARE_KEY_CHARS = frozenset(\n "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "-_"\n)\nARRAY_TYPES = (list, tuple)\nMAX_LINE_LENGTH = 100\n\nCOMPACT_ESCAPES = MappingProxyType(\n {\n "\u0008": "\\b", # backspace\n "\u000A": "\\n", # linefeed\n "\u000C": "\\f", # form feed\n "\u000D": "\\r", # carriage return\n "\u0022": '\\"', # quote\n "\u005C": "\\\\", # backslash\n }\n)\n\n\nclass Context:\n def __init__(self, allow_multiline: bool, indent: int):\n if indent < 0:\n raise ValueError("Indent width must be non-negative")\n self.allow_multiline: Final = allow_multiline\n # cache rendered inline tables (mapping from object id to rendered inline table)\n self.inline_table_cache: Final[dict[int, str]] = {}\n self.indent_str: Final = " " * indent\n\n\ndef dump(\n obj: Mapping[str, Any],\n fp: IO[bytes],\n /,\n *,\n multiline_strings: bool = False,\n indent: int = 4,\n) -> None:\n ctx = Context(multiline_strings, indent)\n for chunk in gen_table_chunks(obj, ctx, name=""):\n fp.write(chunk.encode())\n\n\ndef dumps(\n obj: Mapping[str, Any], /, *, multiline_strings: bool = False, indent: int = 4\n) -> str:\n ctx = Context(multiline_strings, indent)\n return "".join(gen_table_chunks(obj, ctx, name=""))\n\n\ndef gen_table_chunks(\n table: Mapping[str, Any],\n ctx: Context,\n *,\n name: str,\n inside_aot: bool = False,\n) -> Generator[str, None, None]:\n yielded = False\n literals = []\n tables: list[tuple[str, Any, bool]] = [] # => [(key, value, inside_aot)]\n for k, v in table.items():\n if isinstance(v, Mapping):\n tables.append((k, v, False))\n elif is_aot(v) and not all(is_suitable_inline_table(t, ctx) for t in v):\n tables.extend((k, t, True) for t in v)\n else:\n literals.append((k, v))\n\n if inside_aot or name and (literals or not tables):\n yielded = True\n yield f"[[{name}]]\n" if inside_aot else f"[{name}]\n"\n\n if literals:\n yielded = True\n for k, v in literals:\n yield f"{format_key_part(k)} = {format_literal(v, ctx)}\n"\n\n for k, v, in_aot in tables:\n if yielded:\n yield "\n"\n else:\n yielded = True\n key_part = format_key_part(k)\n display_name = f"{name}.{key_part}" if name else key_part\n yield from gen_table_chunks(v, ctx, name=display_name, inside_aot=in_aot)\n\n\ndef format_literal(obj: object, ctx: Context, *, nest_level: int = 0) -> str:\n if isinstance(obj, bool):\n return "true" if obj else "false"\n if isinstance(obj, (int, float, date, datetime)):\n return str(obj)\n if isinstance(obj, time):\n if obj.tzinfo:\n raise ValueError("TOML does not support offset times")\n return str(obj)\n if isinstance(obj, str):\n return format_string(obj, allow_multiline=ctx.allow_multiline)\n if isinstance(obj, ARRAY_TYPES):\n return format_inline_array(obj, ctx, nest_level)\n if isinstance(obj, Mapping):\n return format_inline_table(obj, ctx)\n\n # Lazy import to improve module import time\n from decimal import Decimal\n\n if isinstance(obj, Decimal):\n return format_decimal(obj)\n raise TypeError(\n f"Object of type '{type(obj).__qualname__}' is not TOML serializable"\n )\n\n\ndef format_decimal(obj: Decimal) -> str:\n if obj.is_nan():\n return "nan"\n if obj.is_infinite():\n return "-inf" if obj.is_signed() else "inf"\n dec_str = str(obj).lower()\n return dec_str if "." in dec_str or "e" in dec_str else dec_str + ".0"\n\n\ndef format_inline_table(obj: Mapping, ctx: Context) -> str:\n # check cache first\n obj_id = id(obj)\n if obj_id in ctx.inline_table_cache:\n return ctx.inline_table_cache[obj_id]\n\n if not obj:\n rendered = "{}"\n else:\n rendered = (\n "{ "\n + ", ".join(\n f"{format_key_part(k)} = {format_literal(v, ctx)}"\n for k, v in obj.items()\n )\n + " }"\n )\n ctx.inline_table_cache[obj_id] = rendered\n return rendered\n\n\ndef format_inline_array(obj: tuple | list, ctx: Context, nest_level: int) -> str:\n if not obj:\n return "[]"\n item_indent = ctx.indent_str * (1 + nest_level)\n closing_bracket_indent = ctx.indent_str * nest_level\n return (\n "[\n"\n + ",\n".join(\n item_indent + format_literal(item, ctx, nest_level=nest_level + 1)\n for item in obj\n )\n + f",\n{closing_bracket_indent}]"\n )\n\n\ndef format_key_part(part: str) -> str:\n try:\n only_bare_key_chars = BARE_KEY_CHARS.issuperset(part)\n except TypeError:\n raise TypeError(\n f"Invalid mapping key '{part}' of type '{type(part).__qualname__}'."\n " A string is required."\n ) from None\n\n if part and only_bare_key_chars:\n return part\n return format_string(part, allow_multiline=False)\n\n\ndef format_string(s: str, *, allow_multiline: bool) -> str:\n do_multiline = allow_multiline and "\n" in s\n if do_multiline:\n result = '"""\n'\n s = s.replace("\r\n", "\n")\n else:\n result = '"'\n\n pos = seq_start = 0\n while True:\n try:\n char = s[pos]\n except IndexError:\n result += s[seq_start:pos]\n if do_multiline:\n return result + '"""'\n return result + '"'\n if char in ILLEGAL_BASIC_STR_CHARS:\n result += s[seq_start:pos]\n if char in COMPACT_ESCAPES:\n if do_multiline and char == "\n":\n result += "\n"\n else:\n result += COMPACT_ESCAPES[char]\n else:\n result += "\\u" + hex(ord(char))[2:].rjust(4, "0")\n seq_start = pos + 1\n pos += 1\n\n\ndef is_aot(obj: Any) -> bool:\n """Decides if an object behaves as an array of tables (i.e. a nonempty list\n of dicts)."""\n return bool(\n isinstance(obj, ARRAY_TYPES)\n and obj\n and all(isinstance(v, Mapping) for v in obj)\n )\n\n\ndef is_suitable_inline_table(obj: Mapping, ctx: Context) -> bool:\n """Use heuristics to decide if the inline-style representation is a good\n choice for a given table."""\n rendered_inline = f"{ctx.indent_str}{format_inline_table(obj, ctx)},"\n return len(rendered_inline) <= MAX_LINE_LENGTH and "\n" not in rendered_inline\n | .venv\Lib\site-packages\pip\_vendor\tomli_w\_writer.py | _writer.py | Python | 6,961 | 0.95 | 0.257642 | 0.025907 | vue-tools | 53 | 2025-01-01T01:03:12.734179 | MIT | false | f207caa8db60d2d7d66c185afd0433cf |
__all__ = ("dumps", "dump")\n__version__ = "1.2.0" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT\n\nfrom pip._vendor.tomli_w._writer import dump, dumps\n | .venv\Lib\site-packages\pip\_vendor\tomli_w\__init__.py | __init__.py | Python | 169 | 0.95 | 0 | 0 | react-lib | 717 | 2023-12-24T19:29:06.882365 | MIT | false | 0e10a1013bb53b8241c50c3ca3b10a84 |
\n\n | .venv\Lib\site-packages\pip\_vendor\tomli_w\__pycache__\_writer.cpython-313.pyc | _writer.cpython-313.pyc | Other | 10,788 | 0.95 | 0.028037 | 0 | react-lib | 822 | 2024-05-17T09:03:20.060265 | Apache-2.0 | false | 0df75ab447f9ce280530ce583fd6d821 |
\n\n | .venv\Lib\site-packages\pip\_vendor\tomli_w\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 331 | 0.7 | 0 | 0 | vue-tools | 837 | 2024-05-15T19:26:25.499708 | Apache-2.0 | false | ae320203a9ccb75ffbf31cc93e2f9c4b |
import os\nimport platform\nimport socket\nimport ssl\nimport sys\nimport typing\n\nimport _ssl\n\nfrom ._ssl_constants import (\n _original_SSLContext,\n _original_super_SSLContext,\n _truststore_SSLContext_dunder_class,\n _truststore_SSLContext_super_class,\n)\n\nif platform.system() == "Windows":\n from ._windows import _configure_context, _verify_peercerts_impl\nelif platform.system() == "Darwin":\n from ._macos import _configure_context, _verify_peercerts_impl\nelse:\n from ._openssl import _configure_context, _verify_peercerts_impl\n\nif typing.TYPE_CHECKING:\n from pip._vendor.typing_extensions import Buffer\n\n# From typeshed/stdlib/ssl.pyi\n_StrOrBytesPath: typing.TypeAlias = str | bytes | os.PathLike[str] | os.PathLike[bytes]\n_PasswordType: typing.TypeAlias = str | bytes | typing.Callable[[], str | bytes]\n\n\ndef inject_into_ssl() -> None:\n """Injects the :class:`truststore.SSLContext` into the ``ssl``\n module by replacing :class:`ssl.SSLContext`.\n """\n setattr(ssl, "SSLContext", SSLContext)\n # urllib3 holds on to its own reference of ssl.SSLContext\n # so we need to replace that reference too.\n try:\n import pip._vendor.urllib3.util.ssl_ as urllib3_ssl\n\n setattr(urllib3_ssl, "SSLContext", SSLContext)\n except ImportError:\n pass\n\n # requests starting with 2.32.0 added a preloaded SSL context to improve concurrent performance;\n # this unfortunately leads to a RecursionError, which can be avoided by patching the preloaded SSL context with\n # the truststore patched instance\n # also see https://github.com/psf/requests/pull/6667\n try:\n from pip._vendor.requests import adapters as requests_adapters\n\n preloaded_context = getattr(requests_adapters, "_preloaded_ssl_context", None)\n if preloaded_context is not None:\n setattr(\n requests_adapters,\n "_preloaded_ssl_context",\n SSLContext(ssl.PROTOCOL_TLS_CLIENT),\n )\n except ImportError:\n pass\n\n\ndef extract_from_ssl() -> None:\n """Restores the :class:`ssl.SSLContext` class to its original state"""\n setattr(ssl, "SSLContext", _original_SSLContext)\n try:\n import pip._vendor.urllib3.util.ssl_ as urllib3_ssl\n\n urllib3_ssl.SSLContext = _original_SSLContext # type: ignore[assignment]\n except ImportError:\n pass\n\n\nclass SSLContext(_truststore_SSLContext_super_class): # type: ignore[misc]\n """SSLContext API that uses system certificates on all platforms"""\n\n @property # type: ignore[misc]\n def __class__(self) -> type:\n # Dirty hack to get around isinstance() checks\n # for ssl.SSLContext instances in aiohttp/trustme\n # when using non-CPython implementations.\n return _truststore_SSLContext_dunder_class or SSLContext\n\n def __init__(self, protocol: int = None) -> None: # type: ignore[assignment]\n self._ctx = _original_SSLContext(protocol)\n\n class TruststoreSSLObject(ssl.SSLObject):\n # This object exists because wrap_bio() doesn't\n # immediately do the handshake so we need to do\n # certificate verifications after SSLObject.do_handshake()\n\n def do_handshake(self) -> None:\n ret = super().do_handshake()\n _verify_peercerts(self, server_hostname=self.server_hostname)\n return ret\n\n self._ctx.sslobject_class = TruststoreSSLObject\n\n def wrap_socket(\n self,\n sock: socket.socket,\n server_side: bool = False,\n do_handshake_on_connect: bool = True,\n suppress_ragged_eofs: bool = True,\n server_hostname: str | None = None,\n session: ssl.SSLSession | None = None,\n ) -> ssl.SSLSocket:\n # Use a context manager here because the\n # inner SSLContext holds on to our state\n # but also does the actual handshake.\n with _configure_context(self._ctx):\n ssl_sock = self._ctx.wrap_socket(\n sock,\n server_side=server_side,\n server_hostname=server_hostname,\n do_handshake_on_connect=do_handshake_on_connect,\n suppress_ragged_eofs=suppress_ragged_eofs,\n session=session,\n )\n try:\n _verify_peercerts(ssl_sock, server_hostname=server_hostname)\n except Exception:\n ssl_sock.close()\n raise\n return ssl_sock\n\n def wrap_bio(\n self,\n incoming: ssl.MemoryBIO,\n outgoing: ssl.MemoryBIO,\n server_side: bool = False,\n server_hostname: str | None = None,\n session: ssl.SSLSession | None = None,\n ) -> ssl.SSLObject:\n with _configure_context(self._ctx):\n ssl_obj = self._ctx.wrap_bio(\n incoming,\n outgoing,\n server_hostname=server_hostname,\n server_side=server_side,\n session=session,\n )\n return ssl_obj\n\n def load_verify_locations(\n self,\n cafile: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None,\n capath: str | bytes | os.PathLike[str] | os.PathLike[bytes] | None = None,\n cadata: typing.Union[str, "Buffer", None] = None,\n ) -> None:\n return self._ctx.load_verify_locations(\n cafile=cafile, capath=capath, cadata=cadata\n )\n\n def load_cert_chain(\n self,\n certfile: _StrOrBytesPath,\n keyfile: _StrOrBytesPath | None = None,\n password: _PasswordType | None = None,\n ) -> None:\n return self._ctx.load_cert_chain(\n certfile=certfile, keyfile=keyfile, password=password\n )\n\n def load_default_certs(\n self, purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH\n ) -> None:\n return self._ctx.load_default_certs(purpose)\n\n def set_alpn_protocols(self, alpn_protocols: typing.Iterable[str]) -> None:\n return self._ctx.set_alpn_protocols(alpn_protocols)\n\n def set_npn_protocols(self, npn_protocols: typing.Iterable[str]) -> None:\n return self._ctx.set_npn_protocols(npn_protocols)\n\n def set_ciphers(self, __cipherlist: str) -> None:\n return self._ctx.set_ciphers(__cipherlist)\n\n def get_ciphers(self) -> typing.Any:\n return self._ctx.get_ciphers()\n\n def session_stats(self) -> dict[str, int]:\n return self._ctx.session_stats()\n\n def cert_store_stats(self) -> dict[str, int]:\n raise NotImplementedError()\n\n def set_default_verify_paths(self) -> None:\n self._ctx.set_default_verify_paths()\n\n @typing.overload\n def get_ca_certs(\n self, binary_form: typing.Literal[False] = ...\n ) -> list[typing.Any]: ...\n\n @typing.overload\n def get_ca_certs(self, binary_form: typing.Literal[True] = ...) -> list[bytes]: ...\n\n @typing.overload\n def get_ca_certs(self, binary_form: bool = ...) -> typing.Any: ...\n\n def get_ca_certs(self, binary_form: bool = False) -> list[typing.Any] | list[bytes]:\n raise NotImplementedError()\n\n @property\n def check_hostname(self) -> bool:\n return self._ctx.check_hostname\n\n @check_hostname.setter\n def check_hostname(self, value: bool) -> None:\n self._ctx.check_hostname = value\n\n @property\n def hostname_checks_common_name(self) -> bool:\n return self._ctx.hostname_checks_common_name\n\n @hostname_checks_common_name.setter\n def hostname_checks_common_name(self, value: bool) -> None:\n self._ctx.hostname_checks_common_name = value\n\n @property\n def keylog_filename(self) -> str:\n return self._ctx.keylog_filename\n\n @keylog_filename.setter\n def keylog_filename(self, value: str) -> None:\n self._ctx.keylog_filename = value\n\n @property\n def maximum_version(self) -> ssl.TLSVersion:\n return self._ctx.maximum_version\n\n @maximum_version.setter\n def maximum_version(self, value: ssl.TLSVersion) -> None:\n _original_super_SSLContext.maximum_version.__set__( # type: ignore[attr-defined]\n self._ctx, value\n )\n\n @property\n def minimum_version(self) -> ssl.TLSVersion:\n return self._ctx.minimum_version\n\n @minimum_version.setter\n def minimum_version(self, value: ssl.TLSVersion) -> None:\n _original_super_SSLContext.minimum_version.__set__( # type: ignore[attr-defined]\n self._ctx, value\n )\n\n @property\n def options(self) -> ssl.Options:\n return self._ctx.options\n\n @options.setter\n def options(self, value: ssl.Options) -> None:\n _original_super_SSLContext.options.__set__( # type: ignore[attr-defined]\n self._ctx, value\n )\n\n @property\n def post_handshake_auth(self) -> bool:\n return self._ctx.post_handshake_auth\n\n @post_handshake_auth.setter\n def post_handshake_auth(self, value: bool) -> None:\n self._ctx.post_handshake_auth = value\n\n @property\n def protocol(self) -> ssl._SSLMethod:\n return self._ctx.protocol\n\n @property\n def security_level(self) -> int:\n return self._ctx.security_level\n\n @property\n def verify_flags(self) -> ssl.VerifyFlags:\n return self._ctx.verify_flags\n\n @verify_flags.setter\n def verify_flags(self, value: ssl.VerifyFlags) -> None:\n _original_super_SSLContext.verify_flags.__set__( # type: ignore[attr-defined]\n self._ctx, value\n )\n\n @property\n def verify_mode(self) -> ssl.VerifyMode:\n return self._ctx.verify_mode\n\n @verify_mode.setter\n def verify_mode(self, value: ssl.VerifyMode) -> None:\n _original_super_SSLContext.verify_mode.__set__( # type: ignore[attr-defined]\n self._ctx, value\n )\n\n\n# Python 3.13+ makes get_unverified_chain() a public API that only returns DER\n# encoded certificates. We detect whether we need to call public_bytes() for 3.10->3.12\n# Pre-3.13 returned None instead of an empty list from get_unverified_chain()\nif sys.version_info >= (3, 13):\n\n def _get_unverified_chain_bytes(sslobj: ssl.SSLObject) -> list[bytes]:\n unverified_chain = sslobj.get_unverified_chain() or () # type: ignore[attr-defined]\n return [\n cert if isinstance(cert, bytes) else cert.public_bytes(_ssl.ENCODING_DER)\n for cert in unverified_chain\n ]\n\nelse:\n\n def _get_unverified_chain_bytes(sslobj: ssl.SSLObject) -> list[bytes]:\n unverified_chain = sslobj.get_unverified_chain() or () # type: ignore[attr-defined]\n return [cert.public_bytes(_ssl.ENCODING_DER) for cert in unverified_chain]\n\n\ndef _verify_peercerts(\n sock_or_sslobj: ssl.SSLSocket | ssl.SSLObject, server_hostname: str | None\n) -> None:\n """\n Verifies the peer certificates from an SSLSocket or SSLObject\n against the certificates in the OS trust store.\n """\n sslobj: ssl.SSLObject = sock_or_sslobj # type: ignore[assignment]\n try:\n while not hasattr(sslobj, "get_unverified_chain"):\n sslobj = sslobj._sslobj # type: ignore[attr-defined]\n except AttributeError:\n pass\n\n cert_bytes = _get_unverified_chain_bytes(sslobj)\n _verify_peercerts_impl(\n sock_or_sslobj.context, cert_bytes, server_hostname=server_hostname\n )\n | .venv\Lib\site-packages\pip\_vendor\truststore\_api.py | _api.py | Python | 11,246 | 0.95 | 0.195195 | 0.070632 | react-lib | 97 | 2024-04-28T03:25:45.071702 | GPL-3.0 | false | 70e48079417907b41f699a00126691a7 |
import contextlib\nimport ctypes\nimport platform\nimport ssl\nimport typing\nfrom ctypes import (\n CDLL,\n POINTER,\n c_bool,\n c_char_p,\n c_int32,\n c_long,\n c_uint32,\n c_ulong,\n c_void_p,\n)\nfrom ctypes.util import find_library\n\nfrom ._ssl_constants import _set_ssl_context_verify_mode\n\n_mac_version = platform.mac_ver()[0]\n_mac_version_info = tuple(map(int, _mac_version.split(".")))\nif _mac_version_info < (10, 8):\n raise ImportError(\n f"Only OS X 10.8 and newer are supported, not {_mac_version_info[0]}.{_mac_version_info[1]}"\n )\n\n_is_macos_version_10_14_or_later = _mac_version_info >= (10, 14)\n\n\ndef _load_cdll(name: str, macos10_16_path: str) -> CDLL:\n """Loads a CDLL by name, falling back to known path on 10.16+"""\n try:\n # Big Sur is technically 11 but we use 10.16 due to the Big Sur\n # beta being labeled as 10.16.\n path: str | None\n if _mac_version_info >= (10, 16):\n path = macos10_16_path\n else:\n path = find_library(name)\n if not path:\n raise OSError # Caught and reraised as 'ImportError'\n return CDLL(path, use_errno=True)\n except OSError:\n raise ImportError(f"The library {name} failed to load") from None\n\n\nSecurity = _load_cdll(\n "Security", "/System/Library/Frameworks/Security.framework/Security"\n)\nCoreFoundation = _load_cdll(\n "CoreFoundation",\n "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation",\n)\n\nBoolean = c_bool\nCFIndex = c_long\nCFStringEncoding = c_uint32\nCFData = c_void_p\nCFString = c_void_p\nCFArray = c_void_p\nCFMutableArray = c_void_p\nCFError = c_void_p\nCFType = c_void_p\nCFTypeID = c_ulong\nCFTypeRef = POINTER(CFType)\nCFAllocatorRef = c_void_p\n\nOSStatus = c_int32\n\nCFErrorRef = POINTER(CFError)\nCFDataRef = POINTER(CFData)\nCFStringRef = POINTER(CFString)\nCFArrayRef = POINTER(CFArray)\nCFMutableArrayRef = POINTER(CFMutableArray)\nCFArrayCallBacks = c_void_p\nCFOptionFlags = c_uint32\n\nSecCertificateRef = POINTER(c_void_p)\nSecPolicyRef = POINTER(c_void_p)\nSecTrustRef = POINTER(c_void_p)\nSecTrustResultType = c_uint32\nSecTrustOptionFlags = c_uint32\n\ntry:\n Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]\n Security.SecCertificateCreateWithData.restype = SecCertificateRef\n\n Security.SecCertificateCopyData.argtypes = [SecCertificateRef]\n Security.SecCertificateCopyData.restype = CFDataRef\n\n Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]\n Security.SecCopyErrorMessageString.restype = CFStringRef\n\n Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]\n Security.SecTrustSetAnchorCertificates.restype = OSStatus\n\n Security.SecTrustSetAnchorCertificatesOnly.argtypes = [SecTrustRef, Boolean]\n Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus\n\n Security.SecPolicyCreateRevocation.argtypes = [CFOptionFlags]\n Security.SecPolicyCreateRevocation.restype = SecPolicyRef\n\n Security.SecPolicyCreateSSL.argtypes = [Boolean, CFStringRef]\n Security.SecPolicyCreateSSL.restype = SecPolicyRef\n\n Security.SecTrustCreateWithCertificates.argtypes = [\n CFTypeRef,\n CFTypeRef,\n POINTER(SecTrustRef),\n ]\n Security.SecTrustCreateWithCertificates.restype = OSStatus\n\n Security.SecTrustGetTrustResult.argtypes = [\n SecTrustRef,\n POINTER(SecTrustResultType),\n ]\n Security.SecTrustGetTrustResult.restype = OSStatus\n\n Security.SecTrustEvaluate.argtypes = [\n SecTrustRef,\n POINTER(SecTrustResultType),\n ]\n Security.SecTrustEvaluate.restype = OSStatus\n\n Security.SecTrustRef = SecTrustRef # type: ignore[attr-defined]\n Security.SecTrustResultType = SecTrustResultType # type: ignore[attr-defined]\n Security.OSStatus = OSStatus # type: ignore[attr-defined]\n\n kSecRevocationUseAnyAvailableMethod = 3\n kSecRevocationRequirePositiveResponse = 8\n\n CoreFoundation.CFRelease.argtypes = [CFTypeRef]\n CoreFoundation.CFRelease.restype = None\n\n CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]\n CoreFoundation.CFGetTypeID.restype = CFTypeID\n\n CoreFoundation.CFStringCreateWithCString.argtypes = [\n CFAllocatorRef,\n c_char_p,\n CFStringEncoding,\n ]\n CoreFoundation.CFStringCreateWithCString.restype = CFStringRef\n\n CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]\n CoreFoundation.CFStringGetCStringPtr.restype = c_char_p\n\n CoreFoundation.CFStringGetCString.argtypes = [\n CFStringRef,\n c_char_p,\n CFIndex,\n CFStringEncoding,\n ]\n CoreFoundation.CFStringGetCString.restype = c_bool\n\n CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]\n CoreFoundation.CFDataCreate.restype = CFDataRef\n\n CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]\n CoreFoundation.CFDataGetLength.restype = CFIndex\n\n CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]\n CoreFoundation.CFDataGetBytePtr.restype = c_void_p\n\n CoreFoundation.CFArrayCreate.argtypes = [\n CFAllocatorRef,\n POINTER(CFTypeRef),\n CFIndex,\n CFArrayCallBacks,\n ]\n CoreFoundation.CFArrayCreate.restype = CFArrayRef\n\n CoreFoundation.CFArrayCreateMutable.argtypes = [\n CFAllocatorRef,\n CFIndex,\n CFArrayCallBacks,\n ]\n CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef\n\n CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]\n CoreFoundation.CFArrayAppendValue.restype = None\n\n CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]\n CoreFoundation.CFArrayGetCount.restype = CFIndex\n\n CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]\n CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p\n\n CoreFoundation.CFErrorGetCode.argtypes = [CFErrorRef]\n CoreFoundation.CFErrorGetCode.restype = CFIndex\n\n CoreFoundation.CFErrorCopyDescription.argtypes = [CFErrorRef]\n CoreFoundation.CFErrorCopyDescription.restype = CFStringRef\n\n CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll( # type: ignore[attr-defined]\n CoreFoundation, "kCFAllocatorDefault"\n )\n CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll( # type: ignore[attr-defined]\n CoreFoundation, "kCFTypeArrayCallBacks"\n )\n\n CoreFoundation.CFTypeRef = CFTypeRef # type: ignore[attr-defined]\n CoreFoundation.CFArrayRef = CFArrayRef # type: ignore[attr-defined]\n CoreFoundation.CFStringRef = CFStringRef # type: ignore[attr-defined]\n CoreFoundation.CFErrorRef = CFErrorRef # type: ignore[attr-defined]\n\nexcept AttributeError as e:\n raise ImportError(f"Error initializing ctypes: {e}") from None\n\n# SecTrustEvaluateWithError is macOS 10.14+\nif _is_macos_version_10_14_or_later:\n try:\n Security.SecTrustEvaluateWithError.argtypes = [\n SecTrustRef,\n POINTER(CFErrorRef),\n ]\n Security.SecTrustEvaluateWithError.restype = c_bool\n except AttributeError as e:\n raise ImportError(f"Error initializing ctypes: {e}") from None\n\n\ndef _handle_osstatus(result: OSStatus, _: typing.Any, args: typing.Any) -> typing.Any:\n """\n Raises an error if the OSStatus value is non-zero.\n """\n if int(result) == 0:\n return args\n\n # Returns a CFString which we need to transform\n # into a UTF-8 Python string.\n error_message_cfstring = None\n try:\n error_message_cfstring = Security.SecCopyErrorMessageString(result, None)\n\n # First step is convert the CFString into a C string pointer.\n # We try the fast no-copy way first.\n error_message_cfstring_c_void_p = ctypes.cast(\n error_message_cfstring, ctypes.POINTER(ctypes.c_void_p)\n )\n message = CoreFoundation.CFStringGetCStringPtr(\n error_message_cfstring_c_void_p, CFConst.kCFStringEncodingUTF8\n )\n\n # Quoting the Apple dev docs:\n #\n # "A pointer to a C string or NULL if the internal\n # storage of theString does not allow this to be\n # returned efficiently."\n #\n # So we need to get our hands dirty.\n if message is None:\n buffer = ctypes.create_string_buffer(1024)\n result = CoreFoundation.CFStringGetCString(\n error_message_cfstring_c_void_p,\n buffer,\n 1024,\n CFConst.kCFStringEncodingUTF8,\n )\n if not result:\n raise OSError("Error copying C string from CFStringRef")\n message = buffer.value\n\n finally:\n if error_message_cfstring is not None:\n CoreFoundation.CFRelease(error_message_cfstring)\n\n # If no message can be found for this status we come\n # up with a generic one that forwards the status code.\n if message is None or message == "":\n message = f"SecureTransport operation returned a non-zero OSStatus: {result}"\n\n raise ssl.SSLError(message)\n\n\nSecurity.SecTrustCreateWithCertificates.errcheck = _handle_osstatus # type: ignore[assignment]\nSecurity.SecTrustSetAnchorCertificates.errcheck = _handle_osstatus # type: ignore[assignment]\nSecurity.SecTrustSetAnchorCertificatesOnly.errcheck = _handle_osstatus # type: ignore[assignment]\nSecurity.SecTrustGetTrustResult.errcheck = _handle_osstatus # type: ignore[assignment]\nSecurity.SecTrustEvaluate.errcheck = _handle_osstatus # type: ignore[assignment]\n\n\nclass CFConst:\n """CoreFoundation constants"""\n\n kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)\n\n errSecIncompleteCertRevocationCheck = -67635\n errSecHostNameMismatch = -67602\n errSecCertificateExpired = -67818\n errSecNotTrusted = -67843\n\n\ndef _bytes_to_cf_data_ref(value: bytes) -> CFDataRef: # type: ignore[valid-type]\n return CoreFoundation.CFDataCreate( # type: ignore[no-any-return]\n CoreFoundation.kCFAllocatorDefault, value, len(value)\n )\n\n\ndef _bytes_to_cf_string(value: bytes) -> CFString:\n """\n Given a Python binary data, create a CFString.\n The string must be CFReleased by the caller.\n """\n c_str = ctypes.c_char_p(value)\n cf_str = CoreFoundation.CFStringCreateWithCString(\n CoreFoundation.kCFAllocatorDefault,\n c_str,\n CFConst.kCFStringEncodingUTF8,\n )\n return cf_str # type: ignore[no-any-return]\n\n\ndef _cf_string_ref_to_str(cf_string_ref: CFStringRef) -> str | None: # type: ignore[valid-type]\n """\n Creates a Unicode string from a CFString object. Used entirely for error\n reporting.\n Yes, it annoys me quite a lot that this function is this complex.\n """\n\n string = CoreFoundation.CFStringGetCStringPtr(\n cf_string_ref, CFConst.kCFStringEncodingUTF8\n )\n if string is None:\n buffer = ctypes.create_string_buffer(1024)\n result = CoreFoundation.CFStringGetCString(\n cf_string_ref, buffer, 1024, CFConst.kCFStringEncodingUTF8\n )\n if not result:\n raise OSError("Error copying C string from CFStringRef")\n string = buffer.value\n if string is not None:\n string = string.decode("utf-8")\n return string # type: ignore[no-any-return]\n\n\ndef _der_certs_to_cf_cert_array(certs: list[bytes]) -> CFMutableArrayRef: # type: ignore[valid-type]\n """Builds a CFArray of SecCertificateRefs from a list of DER-encoded certificates.\n Responsibility of the caller to call CoreFoundation.CFRelease on the CFArray.\n """\n cf_array = CoreFoundation.CFArrayCreateMutable(\n CoreFoundation.kCFAllocatorDefault,\n 0,\n ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n )\n if not cf_array:\n raise MemoryError("Unable to allocate memory!")\n\n for cert_data in certs:\n cf_data = None\n sec_cert_ref = None\n try:\n cf_data = _bytes_to_cf_data_ref(cert_data)\n sec_cert_ref = Security.SecCertificateCreateWithData(\n CoreFoundation.kCFAllocatorDefault, cf_data\n )\n CoreFoundation.CFArrayAppendValue(cf_array, sec_cert_ref)\n finally:\n if cf_data:\n CoreFoundation.CFRelease(cf_data)\n if sec_cert_ref:\n CoreFoundation.CFRelease(sec_cert_ref)\n\n return cf_array # type: ignore[no-any-return]\n\n\n@contextlib.contextmanager\ndef _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:\n check_hostname = ctx.check_hostname\n verify_mode = ctx.verify_mode\n ctx.check_hostname = False\n _set_ssl_context_verify_mode(ctx, ssl.CERT_NONE)\n try:\n yield\n finally:\n ctx.check_hostname = check_hostname\n _set_ssl_context_verify_mode(ctx, verify_mode)\n\n\ndef _verify_peercerts_impl(\n ssl_context: ssl.SSLContext,\n cert_chain: list[bytes],\n server_hostname: str | None = None,\n) -> None:\n certs = None\n policies = None\n trust = None\n try:\n # Only set a hostname on the policy if we're verifying the hostname\n # on the leaf certificate.\n if server_hostname is not None and ssl_context.check_hostname:\n cf_str_hostname = None\n try:\n cf_str_hostname = _bytes_to_cf_string(server_hostname.encode("ascii"))\n ssl_policy = Security.SecPolicyCreateSSL(True, cf_str_hostname)\n finally:\n if cf_str_hostname:\n CoreFoundation.CFRelease(cf_str_hostname)\n else:\n ssl_policy = Security.SecPolicyCreateSSL(True, None)\n\n policies = ssl_policy\n if ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_CHAIN:\n # Add explicit policy requiring positive revocation checks\n policies = CoreFoundation.CFArrayCreateMutable(\n CoreFoundation.kCFAllocatorDefault,\n 0,\n ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n )\n CoreFoundation.CFArrayAppendValue(policies, ssl_policy)\n CoreFoundation.CFRelease(ssl_policy)\n revocation_policy = Security.SecPolicyCreateRevocation(\n kSecRevocationUseAnyAvailableMethod\n | kSecRevocationRequirePositiveResponse\n )\n CoreFoundation.CFArrayAppendValue(policies, revocation_policy)\n CoreFoundation.CFRelease(revocation_policy)\n elif ssl_context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF:\n raise NotImplementedError("VERIFY_CRL_CHECK_LEAF not implemented for macOS")\n\n certs = None\n try:\n certs = _der_certs_to_cf_cert_array(cert_chain)\n\n # Now that we have certificates loaded and a SecPolicy\n # we can finally create a SecTrust object!\n trust = Security.SecTrustRef()\n Security.SecTrustCreateWithCertificates(\n certs, policies, ctypes.byref(trust)\n )\n\n finally:\n # The certs are now being held by SecTrust so we can\n # release our handles for the array.\n if certs:\n CoreFoundation.CFRelease(certs)\n\n # If there are additional trust anchors to load we need to transform\n # the list of DER-encoded certificates into a CFArray.\n ctx_ca_certs_der: list[bytes] | None = ssl_context.get_ca_certs(\n binary_form=True\n )\n if ctx_ca_certs_der:\n ctx_ca_certs = None\n try:\n ctx_ca_certs = _der_certs_to_cf_cert_array(ctx_ca_certs_der)\n Security.SecTrustSetAnchorCertificates(trust, ctx_ca_certs)\n finally:\n if ctx_ca_certs:\n CoreFoundation.CFRelease(ctx_ca_certs)\n\n # We always want system certificates.\n Security.SecTrustSetAnchorCertificatesOnly(trust, False)\n\n # macOS 10.13 and earlier don't support SecTrustEvaluateWithError()\n # so we use SecTrustEvaluate() which means we need to construct error\n # messages ourselves.\n if _is_macos_version_10_14_or_later:\n _verify_peercerts_impl_macos_10_14(ssl_context, trust)\n else:\n _verify_peercerts_impl_macos_10_13(ssl_context, trust)\n finally:\n if policies:\n CoreFoundation.CFRelease(policies)\n if trust:\n CoreFoundation.CFRelease(trust)\n\n\ndef _verify_peercerts_impl_macos_10_13(\n ssl_context: ssl.SSLContext, sec_trust_ref: typing.Any\n) -> None:\n """Verify using 'SecTrustEvaluate' API for macOS 10.13 and earlier.\n macOS 10.14 added the 'SecTrustEvaluateWithError' API.\n """\n sec_trust_result_type = Security.SecTrustResultType()\n Security.SecTrustEvaluate(sec_trust_ref, ctypes.byref(sec_trust_result_type))\n\n try:\n sec_trust_result_type_as_int = int(sec_trust_result_type.value)\n except (ValueError, TypeError):\n sec_trust_result_type_as_int = -1\n\n # Apple doesn't document these values in their own API docs.\n # See: https://github.com/xybp888/iOS-SDKs/blob/master/iPhoneOS13.0.sdk/System/Library/Frameworks/Security.framework/Headers/SecTrust.h#L84\n if (\n ssl_context.verify_mode == ssl.CERT_REQUIRED\n and sec_trust_result_type_as_int not in (1, 4)\n ):\n # Note that we're not able to ignore only hostname errors\n # for macOS 10.13 and earlier, so check_hostname=False will\n # still return an error.\n sec_trust_result_type_to_message = {\n 0: "Invalid trust result type",\n # 1: "Trust evaluation succeeded",\n 2: "User confirmation required",\n 3: "User specified that certificate is not trusted",\n # 4: "Trust result is unspecified",\n 5: "Recoverable trust failure occurred",\n 6: "Fatal trust failure occurred",\n 7: "Other error occurred, certificate may be revoked",\n }\n error_message = sec_trust_result_type_to_message.get(\n sec_trust_result_type_as_int,\n f"Unknown trust result: {sec_trust_result_type_as_int}",\n )\n\n err = ssl.SSLCertVerificationError(error_message)\n err.verify_message = error_message\n err.verify_code = sec_trust_result_type_as_int\n raise err\n\n\ndef _verify_peercerts_impl_macos_10_14(\n ssl_context: ssl.SSLContext, sec_trust_ref: typing.Any\n) -> None:\n """Verify using 'SecTrustEvaluateWithError' API for macOS 10.14+."""\n cf_error = CoreFoundation.CFErrorRef()\n sec_trust_eval_result = Security.SecTrustEvaluateWithError(\n sec_trust_ref, ctypes.byref(cf_error)\n )\n # sec_trust_eval_result is a bool (0 or 1)\n # where 1 means that the certs are trusted.\n if sec_trust_eval_result == 1:\n is_trusted = True\n elif sec_trust_eval_result == 0:\n is_trusted = False\n else:\n raise ssl.SSLError(\n f"Unknown result from Security.SecTrustEvaluateWithError: {sec_trust_eval_result!r}"\n )\n\n cf_error_code = 0\n if not is_trusted:\n cf_error_code = CoreFoundation.CFErrorGetCode(cf_error)\n\n # If the error is a known failure that we're\n # explicitly okay with from SSLContext configuration\n # we can set is_trusted accordingly.\n if ssl_context.verify_mode != ssl.CERT_REQUIRED and (\n cf_error_code == CFConst.errSecNotTrusted\n or cf_error_code == CFConst.errSecCertificateExpired\n ):\n is_trusted = True\n\n # If we're still not trusted then we start to\n # construct and raise the SSLCertVerificationError.\n if not is_trusted:\n cf_error_string_ref = None\n try:\n cf_error_string_ref = CoreFoundation.CFErrorCopyDescription(cf_error)\n\n # Can this ever return 'None' if there's a CFError?\n cf_error_message = (\n _cf_string_ref_to_str(cf_error_string_ref)\n or "Certificate verification failed"\n )\n\n # TODO: Not sure if we need the SecTrustResultType for anything?\n # We only care whether or not it's a success or failure for now.\n sec_trust_result_type = Security.SecTrustResultType()\n Security.SecTrustGetTrustResult(\n sec_trust_ref, ctypes.byref(sec_trust_result_type)\n )\n\n err = ssl.SSLCertVerificationError(cf_error_message)\n err.verify_message = cf_error_message\n err.verify_code = cf_error_code\n raise err\n finally:\n if cf_error_string_ref:\n CoreFoundation.CFRelease(cf_error_string_ref)\n | .venv\Lib\site-packages\pip\_vendor\truststore\_macos.py | _macos.py | Python | 20,503 | 0.95 | 0.122592 | 0.095833 | node-utils | 822 | 2024-04-22T04:44:00.766149 | MIT | false | fdd99d0aa0598e467aaf3fd55a09a6ae |
import contextlib\nimport os\nimport re\nimport ssl\nimport typing\n\n# candidates based on https://github.com/tiran/certifi-system-store by Christian Heimes\n_CA_FILE_CANDIDATES = [\n # Alpine, Arch, Fedora 34+, OpenWRT, RHEL 9+, BSD\n "/etc/ssl/cert.pem",\n # Fedora <= 34, RHEL <= 9, CentOS <= 9\n "/etc/pki/tls/cert.pem",\n # Debian, Ubuntu (requires ca-certificates)\n "/etc/ssl/certs/ca-certificates.crt",\n # SUSE\n "/etc/ssl/ca-bundle.pem",\n]\n\n_HASHED_CERT_FILENAME_RE = re.compile(r"^[0-9a-fA-F]{8}\.[0-9]$")\n\n\n@contextlib.contextmanager\ndef _configure_context(ctx: ssl.SSLContext) -> typing.Iterator[None]:\n # First, check whether the default locations from OpenSSL\n # seem like they will give us a usable set of CA certs.\n # ssl.get_default_verify_paths already takes care of:\n # - getting cafile from either the SSL_CERT_FILE env var\n # or the path configured when OpenSSL was compiled,\n # and verifying that that path exists\n # - getting capath from either the SSL_CERT_DIR env var\n # or the path configured when OpenSSL was compiled,\n # and verifying that that path exists\n # In addition we'll check whether capath appears to contain certs.\n defaults = ssl.get_default_verify_paths()\n if defaults.cafile or (defaults.capath and _capath_contains_certs(defaults.capath)):\n ctx.set_default_verify_paths()\n else:\n # cafile from OpenSSL doesn't exist\n # and capath from OpenSSL doesn't contain certs.\n # Let's search other common locations instead.\n for cafile in _CA_FILE_CANDIDATES:\n if os.path.isfile(cafile):\n ctx.load_verify_locations(cafile=cafile)\n break\n\n yield\n\n\ndef _capath_contains_certs(capath: str) -> bool:\n """Check whether capath exists and contains certs in the expected format."""\n if not os.path.isdir(capath):\n return False\n for name in os.listdir(capath):\n if _HASHED_CERT_FILENAME_RE.match(name):\n return True\n return False\n\n\ndef _verify_peercerts_impl(\n ssl_context: ssl.SSLContext,\n cert_chain: list[bytes],\n server_hostname: str | None = None,\n) -> None:\n # This is a no-op because we've enabled SSLContext's built-in\n # verification via verify_mode=CERT_REQUIRED, and don't need to repeat it.\n pass\n | .venv\Lib\site-packages\pip\_vendor\truststore\_openssl.py | _openssl.py | Python | 2,324 | 0.95 | 0.136364 | 0.350877 | awesome-app | 418 | 2024-05-06T11:28:08.841853 | BSD-3-Clause | false | 303ad55f035b88677390f0ec61192477 |
import ssl\nimport sys\nimport typing\n\n# Hold on to the original class so we can create it consistently\n# even if we inject our own SSLContext into the ssl module.\n_original_SSLContext = ssl.SSLContext\n_original_super_SSLContext = super(_original_SSLContext, _original_SSLContext)\n\n# CPython is known to be good, but non-CPython implementations\n# may implement SSLContext differently so to be safe we don't\n# subclass the SSLContext.\n\n# This is returned by truststore.SSLContext.__class__()\n_truststore_SSLContext_dunder_class: typing.Optional[type]\n\n# This value is the superclass of truststore.SSLContext.\n_truststore_SSLContext_super_class: type\n\nif sys.implementation.name == "cpython":\n _truststore_SSLContext_super_class = _original_SSLContext\n _truststore_SSLContext_dunder_class = None\nelse:\n _truststore_SSLContext_super_class = object\n _truststore_SSLContext_dunder_class = _original_SSLContext\n\n\ndef _set_ssl_context_verify_mode(\n ssl_context: ssl.SSLContext, verify_mode: ssl.VerifyMode\n) -> None:\n _original_super_SSLContext.verify_mode.__set__(ssl_context, verify_mode) # type: ignore[attr-defined]\n | .venv\Lib\site-packages\pip\_vendor\truststore\_ssl_constants.py | _ssl_constants.py | Python | 1,130 | 0.95 | 0.129032 | 0.291667 | python-kit | 88 | 2025-05-12T06:41:04.430219 | MIT | false | 6b6afd01f3f9a225fe7a4366b3e04570 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.