Debian Codegraph @

Tools/clinic/libclinic/utils.py

raw
1 import collections
2 import dataclasses as dc
3 import enum
4 import hashlib
5 import os
6 import re
7 import string
8 from typing import Literal, Final
9
10
11 def read_file(filename: str) -> str | None:
12 """Return the content of the file, or None if it does not exist."""
13 try:
14 with open(filename, encoding="utf-8") as fp:
15 return fp.read()
16 except FileNotFoundError:
17 return None
18
19
20 def write_file(filename: str, new_contents: str) -> None:
21 """Write new content to file, iff the content changed."""
22 if read_file(filename) == new_contents:
23 # no change: avoid modifying the file modification time
24 return
25 # Atomic write using a temporary file and os.replace()
26 filename_new = f"{filename}.new"
27 with open(filename_new, "w", encoding="utf-8") as fp:
28 fp.write(new_contents)
29 try:
30 os.replace(filename_new, filename)
31 except:
32 os.unlink(filename_new)
33 raise
34
35
36 @dc.dataclass(slots=True, frozen=True)
37 class FileChange:
38 filename: str
39 # None if the file does not exist yet.
40 old_contents: str | None
41 new_contents: str
42
43
44 @dc.dataclass(slots=True)
45 class FileWriter:
46 """Write the generated files.
47
48 In the dry run mode no file is written, the changes are only recorded.
49 """
50
51 dry_run: bool = False
52 changes: list[FileChange] = dc.field(default_factory=list)
53
54 def makedirs(self, dirname: str) -> None:
55 if not self.dry_run:
56 os.makedirs(dirname)
57 elif os.path.exists(dirname):
58 # Create nothing, but fail as os.makedirs() does, so that
59 # the caller can report an existing non-directory.
60 raise FileExistsError(dirname)
61
62 def write(self, filename: str, new_contents: str) -> None:
63 if not self.dry_run:
64 write_file(filename, new_contents)
65 return
66 old_contents = read_file(filename)
67 if old_contents != new_contents:
68 self.changes.append(
69 FileChange(filename, old_contents, new_contents))
70
71
72 def compute_checksum(input_: str, length: int | None = None) -> str:
73 checksum = hashlib.sha1(input_.encode("utf-8")).hexdigest()
74 if length:
75 checksum = checksum[:length]
76 return checksum
77
78
79 def create_regex(
80 before: str, after: str, word: bool = True, whole_line: bool = True
81 ) -> re.Pattern[str]:
82 """Create a regex object for matching marker lines."""
83 group_re = r"\w+" if word else ".+"
84 before = re.escape(before)
85 after = re.escape(after)
86 pattern = rf"{before}({group_re}){after}"
87 if whole_line:
88 pattern = rf"^{pattern}$"
89 return re.compile(pattern)
90
91
92 class FormatCounterFormatter(string.Formatter):
93 """
94 This counts how many instances of each formatter
95 "replacement string" appear in the format string.
96
97 e.g. after evaluating "string {a}, {b}, {c}, {a}"
98 the counts dict would now look like
99 {'a': 2, 'b': 1, 'c': 1}
100 """
101
102 def __init__(self) -> None:
103 self.counts = collections.Counter[str]()
104
105 def get_value(
106 self, key: str, args: object, kwargs: object # type: ignore[override]
107 ) -> Literal[""]:
108 self.counts[key] += 1
109 return ""
110
111
112 VersionTuple = tuple[int, int]
113
114
115 class Sentinels(enum.Enum):
116 unspecified = "unspecified"
117 unknown = "unknown"
118
119 def __repr__(self) -> str:
120 return f"<{self.value.capitalize()}>"
121
122
123 unspecified: Final = Sentinels.unspecified
124 unknown: Final = Sentinels.unknown
125
126
127 # This one needs to be a distinct class, unlike the other two
128 class Null:
129 def __repr__(self) -> str:
130 return '<Null>'
131
132
133 NULL = Null()