返回 CodeWhale
check-bare-git.py
根目录 / scripts / check-bare-git.py
1 #!/usr/bin/env python3
2 """Refuse a bare `Command::new("git")` in product code.
3
4 Repository config can make even a read such as `git status` run a program the
5 workspace chose (core.fsmonitor, clean and smudge filters, hooks), and a bare
6 command hands that program the parent's whole environment. Every product git
7 spawn therefore starts from `codewhale_dependencies::Git` (`command`,
8 `review_base`, `review_command`, `status_command`, `workspace_command`), which
9 scrubs the environment and disables those helpers. Crates below that owner
10 receive their command from the caller (see `codewhale_lane::set_git_command`).
11
12 Test code is exempt, and it is found structurally, never by file name: a file
13 under a `tests` or `benches` directory, a file only reachable through
14 `#[cfg(test)] mod x;` or an `include!` inside a `#[cfg(test)]` item, and the
15 `#[cfg(test)]` items themselves (a `mod`, `fn`, `impl`, `use` or other item,
16 skipped to its closing brace or semicolon). An attribute on a field,
17 expression or statement hides nothing. A `Command` imported under another name
18 is matched too. The few product files below only ask git for a repository's top
19 level, remote URL or HEAD, which starts no repository-chosen program; each entry
20 names its reason and its exact count.
21 """
22
23 from __future__ import annotations
24
25 import re
26 import sys
27 from pathlib import Path
28
29 ROOT = Path(__file__).resolve().parents[1]
30 CRATES = ROOT / "crates"
31
32 ALLOWED = {
33 "crates/cli/src/lib.rs": (1, "rev-parse --show-toplevel before the dependency owner is reachable"),
34 "crates/memory/src/workspace.rs": (1, "rev-parse --verify HEAD in the standalone memory binary"),
35 "crates/runtime/src/native_memory.rs": (2, "config --get and rev-parse below the dependency owner"),
36 }
37
38 TOKEN_RE = re.compile(
39 r"""
40 (?P<line>//[^\n]*)
41 | (?P<block>/\*)
42 | (?P<raw>(?<![A-Za-z0-9_])b?r(?P<hashes>\#*)")
43 | (?P<string>(?<![A-Za-z0-9_])b?"(?:\\.|[^"\\])*")
44 | (?P<char>b?'(?:\\(?:x[0-9a-fA-F]{2}|u\{[0-9a-fA-F_]+\}|.)|[^\\'\n])')
45 """,
46 re.VERBOSE | re.DOTALL,
47 )
48 CFG_TEST_RE = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]")
49 INNER_CFG_TEST_RE = re.compile(r"#\s*!\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]")
50 ATTRIBUTE_RE = re.compile(r"\s*#\s*\[")
51 ITEM_RE = re.compile(
52 r"""
53 (?:pub(?:\s*\([^)]*\))?\s+)?
54 (?:(?:unsafe|async|const|default|extern(?:\s+"?\s*"?)?)\s+)*
55 (?:mod|fn|impl|struct|enum|trait|type|use|static|const|union|macro_rules\s*!|extern\s+crate)\b
56 """,
57 re.VERBOSE,
58 )
59 MOD_DECL_RE = re.compile(r"(?<![A-Za-z0-9_])mod\s+([A-Za-z_]\w*)\s*;")
60 VISIBILITY_RE = re.compile(r"(?<![A-Za-z0-9_])pub(?:\s*\([^)]*\))?\s*$")
61 PATH_ATTR_RE = re.compile(r'#\s*\[\s*path\s*=\s*"([^"]+)"\s*\]')
62 INCLUDE_RE = re.compile(r'(?<![A-Za-z0-9_])include\s*!\s*\(\s*"([^"]+)"\s*\)')
63 ALIAS_RE = re.compile(r"(?<![A-Za-z0-9_])Command\s+as\s+([A-Za-z_]\w*)")
64 GIT_LITERAL_RE = re.compile(r'"git(?:\.exe)?"')
65 BRACKETS = {"(": ")", "[": "]"}
66
67
68 def blank(text: str) -> str:
69 return re.sub(r"[^\n]", " ", text)
70
71
72 def lex(text: str) -> tuple[str, str]:
73 """Return `(plain, shape)`: same length and line layout as `text`.
74
75 `plain` blanks comments; `shape` also blanks string and character
76 literals, so braces and attributes inside them never count.
77 """
78 plain: list[str] = []
79 shape: list[str] = []
80 cursor = 0
81 position = 0
82 while True:
83 match = TOKEN_RE.search(text, position)
84 if match is None:
85 break
86 start = match.start()
87 if match.lastgroup == "block" or match.group("block"):
88 depth = 1
89 end = start + 2
90 while depth and end < len(text):
91 if text.startswith("/*", end):
92 depth += 1
93 end += 2
94 elif text.startswith("*/", end):
95 depth -= 1
96 end += 2
97 else:
98 end += 1
99 kind = "comment"
100 elif match.group("raw"):
101 closing = '"' + match.group("hashes")
102 found = text.find(closing, match.end())
103 end = len(text) if found < 0 else found + len(closing)
104 kind = "literal"
105 elif match.group("line"):
106 end = match.end()
107 kind = "comment"
108 else:
109 end = match.end()
110 kind = "literal"
111 plain.append(text[cursor:start])
112 shape.append(text[cursor:start])
113 chunk = text[start:end]
114 plain.append(blank(chunk) if kind == "comment" else chunk)
115 shape.append(blank(chunk))
116 cursor = end
117 position = end
118 plain.append(text[cursor:])
119 shape.append(text[cursor:])
120 return "".join(plain), "".join(shape)
121
122
123 def match_close(shape: str, start: int, opener: str, closer: str) -> int:
124 depth = 0
125 for index in range(start, len(shape)):
126 character = shape[index]
127 if character == opener:
128 depth += 1
129 elif character == closer:
130 depth -= 1
131 if depth == 0:
132 return index
133 return len(shape) - 1
134
135
136 def item_end(shape: str, start: int) -> int:
137 depth = 0
138 index = start
139 while index < len(shape):
140 character = shape[index]
141 if character in BRACKETS:
142 depth += 1
143 elif character in ")]":
144 depth = max(0, depth - 1)
145 elif depth == 0 and character == ";":
146 return index
147 elif depth == 0 and character == "{":
148 return match_close(shape, index, "{", "}")
149 index += 1
150 return len(shape) - 1
151
152
153 def test_spans(shape: str) -> list[tuple[int, int]]:
154 if INNER_CFG_TEST_RE.search(shape):
155 return [(0, len(shape))]
156 spans: list[tuple[int, int]] = []
157 for match in CFG_TEST_RE.finditer(shape):
158 position = match.end()
159 while True:
160 attribute = ATTRIBUTE_RE.match(shape, position)
161 if attribute is None:
162 break
163 position = match_close(shape, attribute.end() - 1, "[", "]") + 1
164 while position < len(shape) and shape[position].isspace():
165 position += 1
166 if shape.startswith("{", position):
167 spans.append((match.start(), match_close(shape, position, "{", "}") + 1))
168 elif ITEM_RE.match(shape, position):
169 spans.append((match.start(), item_end(shape, position) + 1))
170 return spans
171
172
173 def inside(spans: list[tuple[int, int]], offset: int) -> bool:
174 return any(start <= offset < end for start, end in spans)
175
176
177 def module_dir(path: Path) -> Path:
178 if path.name in ("lib.rs", "main.rs", "mod.rs"):
179 return path.parent
180 return path.parent / path.stem
181
182
183 def attributes_before(plain: str, start: int) -> str:
184 end = start
185 head = plain[max(0, start - 64) : start]
186 visibility = VISIBILITY_RE.search(head)
187 if visibility:
188 end = start - len(head) + visibility.start()
189 attributes: list[str] = []
190 while True:
191 while end > 0 and plain[end - 1].isspace():
192 end -= 1
193 if end == 0 or plain[end - 1] != "]":
194 break
195 depth = 0
196 index = end - 1
197 while index >= 0:
198 if plain[index] == "]":
199 depth += 1
200 elif plain[index] == "[":
201 depth -= 1
202 if depth == 0:
203 break
204 index -= 1
205 if index <= 0 or plain[index - 1] != "#":
206 break
207 attributes.append(plain[index - 1 : end])
208 end = index - 1
209 return " ".join(attributes)
210
211
212 def declared_files(path: Path, plain: str, spans: list[tuple[int, int]], only_test: bool) -> set[Path]:
213 found: set[Path] = set()
214 for match in MOD_DECL_RE.finditer(plain):
215 attributes = attributes_before(plain, match.start())
216 marked = bool(CFG_TEST_RE.search(attributes)) or inside(spans, match.start())
217 if only_test and not marked:
218 continue
219 explicit = PATH_ATTR_RE.search(attributes)
220 if explicit:
221 found.add(path.parent / explicit.group(1))
222 continue
223 base = module_dir(path)
224 name = match.group(1)
225 for candidate in (base / f"{name}.rs", base / name / "mod.rs"):
226 found.add(candidate)
227 for match in INCLUDE_RE.finditer(plain):
228 if only_test and not inside(spans, match.start()):
229 continue
230 found.add(path.parent / match.group(1))
231 return found
232
233
234 class Source:
235 def __init__(self, path: Path) -> None:
236 self.path = path
237 try:
238 text = path.read_text(encoding="utf-8")
239 except (OSError, UnicodeDecodeError):
240 text = ""
241 self.plain, self.shape = lex(text)
242 self.spans = test_spans(self.shape)
243
244
245 def test_only_files(files: list[Path], raws: dict[Path, str]) -> set[Path]:
246 known = set(files)
247 queue: list[Path] = []
248 marked: set[Path] = set()
249 for path in files:
250 raw = raws[path]
251 if not (
252 INNER_CFG_TEST_RE.search(raw)
253 or (CFG_TEST_RE.search(raw) and (MOD_DECL_RE.search(raw) or INCLUDE_RE.search(raw)))
254 ):
255 continue
256 source = Source(path)
257 if not source.spans:
258 continue
259 if source.spans == [(0, len(source.shape))]:
260 marked.add(path)
261 queue.append(path)
262 continue
263 for declared in declared_files(path, source.plain, source.spans, True):
264 if declared in known and declared not in marked:
265 marked.add(declared)
266 queue.append(declared)
267 while queue:
268 path = queue.pop()
269 raw = raws[path]
270 if not (MOD_DECL_RE.search(raw) or INCLUDE_RE.search(raw)):
271 continue
272 source = Source(path)
273 for declared in declared_files(path, source.plain, source.spans, False):
274 if declared in known and declared not in marked:
275 marked.add(declared)
276 queue.append(declared)
277 return marked
278
279
280 def in_test_directory(path: Path, root: Path) -> bool:
281 return any(part in ("tests", "benches") for part in path.relative_to(root).parts[:-1])
282
283
284 def spawn_pattern(shape: str) -> re.Pattern[str]:
285 names = ["Command", *ALIAS_RE.findall(shape)]
286 alternatives = "|".join(re.escape(name) for name in dict.fromkeys(names))
287 return re.compile(
288 rf'(?<![A-Za-z0-9_])(?:{alternatives})\s*::\s*new\s*\(\s*"git(?:\.exe)?"\s*\)'
289 )
290
291
292 def source_hits(source: Source) -> list[int]:
293 pattern = spawn_pattern(source.shape)
294 lines: list[int] = []
295 for match in pattern.finditer(source.plain):
296 if source.shape[match.start()] == " ":
297 continue
298 if inside(source.spans, match.start()):
299 continue
300 lines.append(source.plain.count("\n", 0, match.start()) + 1)
301 return lines
302
303
304 def file_hits(path: Path) -> list[int]:
305 try:
306 raw = path.read_text(encoding="utf-8")
307 except (OSError, UnicodeDecodeError):
308 return []
309 if not GIT_LITERAL_RE.search(raw):
310 return []
311 return source_hits(Source(path))
312
313
314 def find_violations(
315 root: Path = CRATES, base: Path = ROOT, allowlist: dict = ALLOWED
316 ) -> list[str]:
317 files = [
318 path
319 for path in sorted(root.rglob("*.rs"))
320 if "target" not in path.relative_to(root).parts
321 ]
322 candidates = [path for path in files if not in_test_directory(path, root)]
323 raws = {
324 path: path.read_text(encoding="utf-8", errors="replace") for path in candidates
325 }
326 suspects = [path for path in candidates if GIT_LITERAL_RE.search(raws[path])]
327 if not suspects:
328 return []
329 skipped = test_only_files(candidates, raws)
330 violations: list[str] = []
331 for path in suspects:
332 if path in skipped:
333 continue
334 hits = file_hits(path)
335 if not hits:
336 continue
337 rel = path.relative_to(base).as_posix()
338 allowed = allowlist.get(rel)
339 if allowed is not None and len(hits) == allowed[0]:
340 continue
341 for number in hits:
342 violations.append(f"{rel}:{number}")
343 return violations
344
345
346 def main() -> int:
347 violations = find_violations()
348 if violations:
349 print(
350 'bare Command::new("git") in product code (start from '
351 "codewhale_dependencies::Git instead):",
352 file=sys.stderr,
353 )
354 for violation in violations:
355 print(f" {violation}", file=sys.stderr)
356 return 1
357 print('bare git check OK: no bare Command::new("git") outside the allowlist.')
358 return 0
359
360
361 if __name__ == "__main__":
362 sys.exit(main())
363
363 lines PYTHON