Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/rich/_unicode_data/__init__.py: 67%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

45 statements  

1from __future__ import annotations 

2 

3import bisect 

4import os 

5from functools import cache 

6from importlib import import_module 

7from typing import TYPE_CHECKING, cast 

8 

9from rich._unicode_data._versions import VERSIONS 

10 

11if TYPE_CHECKING: 

12 from rich.cells import CellTable 

13 

14VERSION_ORDER = sorted( 

15 [ 

16 tuple( 

17 map(int, version.split(".")), 

18 ) 

19 for version in VERSIONS 

20 ] 

21) 

22VERSION_SET = frozenset(VERSIONS) 

23 

24 

25def _parse_version(version: str) -> tuple[int, int, int]: 

26 """Parse a version string into a tuple of 3 integers. 

27 

28 Args: 

29 version: A version string. 

30 

31 Raises: 

32 ValueError: If the version string is invalid. 

33 

34 Returns: 

35 A tuple of 3 integers. 

36 """ 

37 version_integers: tuple[int, ...] 

38 try: 

39 version_integers = tuple( 

40 map(int, version.split(".")), 

41 ) 

42 except ValueError: 

43 raise ValueError( 

44 f"unicode version string {version!r} is badly formatted" 

45 ) from None 

46 while len(version_integers) < 3: 

47 version_integers = version_integers + (0,) 

48 triple = cast("tuple[int, int, int]", version_integers[:3]) 

49 return triple 

50 

51 

52@cache 

53def load(unicode_version: str = "auto") -> CellTable: 

54 """Load a cell table for the given unicode version. 

55 

56 Args: 

57 unicode_version: Unicode version, or `None` to auto-detect. 

58 

59 """ 

60 if unicode_version == "auto": 

61 unicode_version = os.environ.get("UNICODE_VERSION", "latest") 

62 try: 

63 _parse_version(unicode_version) 

64 except ValueError: 

65 # The environment variable is invalid 

66 # Fallback to using the latest version seems reasonable 

67 unicode_version = "latest" 

68 

69 if unicode_version == "latest": 

70 version = VERSIONS[-1] 

71 else: 

72 try: 

73 version_numbers = _parse_version(unicode_version) 

74 except ValueError: 

75 version_numbers = _parse_version(VERSIONS[-1]) 

76 major, minor, patch = version_numbers 

77 version = f"{major}.{minor}.{patch}" 

78 if version not in VERSION_SET: 

79 insert_position = bisect.bisect_left(VERSION_ORDER, version_numbers) 

80 version = VERSIONS[max(0, insert_position - 1)] 

81 

82 version_path_component = version.replace(".", "-") 

83 module_name = f".unicode{version_path_component}" 

84 module = import_module(module_name, "rich._unicode_data") 

85 if TYPE_CHECKING: 

86 assert isinstance(module.cell_table, CellTable) 

87 return module.cell_table