|
1 | 1 | #!/usr/bin/env python3 |
2 | | -from __future__ import annotations |
3 | | - |
4 | 2 | import json |
5 | 3 | import os |
6 | 4 | import sys |
7 | | -from typing import Any, Dict, List, Sequence |
8 | 5 |
|
| 6 | +from typing import Any, Dict, List, Sequence |
9 | 7 |
|
10 | 8 | NEW_PREFIX = "/github/workspace" |
11 | 9 |
|
12 | 10 |
|
13 | 11 | def _collect_paths(entries: Sequence[Dict[str, Any]]) -> List[str]: |
14 | | - """Return every absolute file/dir path found in *entries*.""" |
15 | | - raw_paths = ( |
16 | | - value |
17 | | - for entry in entries |
18 | | - for value in (entry.get("directory"), entry.get("file")) |
19 | | - if isinstance(value, str) # guard against None / non-string |
20 | | - ) |
21 | | - return [os.path.realpath(path) for path in raw_paths] |
| 12 | + return [ |
| 13 | + os.path.realpath(v) |
| 14 | + for e in entries |
| 15 | + for v in (e.get("directory"), e.get("file")) |
| 16 | + if isinstance(v, str) |
| 17 | + ] |
22 | 18 |
|
23 | 19 |
|
24 | | -def patch_compile_commands(path: str) -> None: # noqa: D401 |
| 20 | +def patch_compile_commands(path: str) -> None: |
25 | 21 | with open(path, "r", encoding="utf-8") as f: |
26 | 22 | data: List[Dict[str, Any]] = json.load(f) |
27 | 23 |
|
28 | | - paths: List[str] = _collect_paths(data) |
29 | | - if not paths: # nothing to patch |
30 | | - print("[WARN] compile_commands.json contained no absolute paths") |
31 | | - return |
32 | | - |
33 | | - old_prefix = os.path.commonpath(paths) |
| 24 | + old_prefix = os.path.commonpath(_collect_paths(data)) |
34 | 25 | print(f"[INFO] Patching compile_commands.json: '{old_prefix}' → '{NEW_PREFIX}'") |
35 | | - |
36 | 26 | for entry in data: |
37 | 27 | for key in ("file", "directory", "command"): |
38 | 28 | val = entry.get(key) |
39 | | - if ( |
40 | | - isinstance(val, str) |
41 | | - and os.path.isabs(val) |
42 | | - and val.startswith(old_prefix) |
43 | | - ): |
44 | | - entry[key] = val.replace(old_prefix, NEW_PREFIX, 1) |
| 29 | + if isinstance(val, str) and old_prefix in val: |
| 30 | + entry[key] = val.replace(old_prefix, NEW_PREFIX) |
45 | 31 |
|
46 | 32 | with open(path, "w", encoding="utf-8") as f: |
47 | 33 | json.dump(data, f, indent=2) |
48 | 34 |
|
49 | 35 |
|
50 | 36 | if __name__ == "__main__": |
51 | 37 | if len(sys.argv) != 2: |
52 | | - print("Usage: patch_compile_commands.py <path-to-compile_commands.json>") |
53 | | - sys.exit(1) |
54 | | - |
| 38 | + sys.exit("usage: patch_compile_commands.py <compile_commands.json>") |
55 | 39 | patch_compile_commands(sys.argv[1]) |
0 commit comments