Debian Codegraph @

util/run-clippy.py

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: MIT
3 # spell-checker:ignore pcoreutils
4 """Run cargo clippy with appropriate flags and emit GitHub Actions annotations."""
5
6 from __future__ import annotations
7
8 import argparse
9 import json
10 import os
11 import re
12 import subprocess
13 import sys
14
15
16 def run_cmd(
17 cmd: list[str],
18 *,
19 check: bool = False,
20 ) -> subprocess.CompletedProcess[str]:
21 """Run a command with UTF-8 encoding (avoids cp1252 issues on Windows)."""
22 env = {**os.environ, "PYTHONUTF8": "1"}
23 return subprocess.run(
24 cmd,
25 capture_output=True,
26 text=True,
27 encoding="utf-8",
28 errors="replace",
29 check=check,
30 env=env,
31 )
32
33
34 def get_utility_list(features: str) -> list[str]:
35 """Get list of utilities from cargo metadata."""
36 if features == "all":
37 cmd = ["cargo", "metadata", "--all-features", "--format-version", "1"]
38 else:
39 cmd = ["cargo", "metadata", "--features", features, "--format-version", "1"]
40 result = run_cmd(cmd, check=True)
41 metadata = json.loads(result.stdout)
42 # Find the coreutils root node and collect uu_ dependencies
43 utilities = []
44 for node in metadata["resolve"]["nodes"]:
45 if re.search(r"coreutils[ @#]\d+\.\d+\.\d+", node["id"]):
46 for dep in node["deps"]:
47 # The pkg field contains the crate name (uu_<util>),
48 # while name is the renamed dependency alias
49 pkg = dep["pkg"]
50 match = re.search(r"uu_(\w+)[@#]", pkg)
51 if match:
52 utilities.append(match.group(1))
53 break
54 return sorted(utilities)
55
56
57 def build_clippy_command(
58 features: str,
59 *,
60 workspace: bool,
61 target: str | None,
62 ) -> list[str]:
63 """Build the cargo clippy command line."""
64 cmd = ["cargo", "clippy"]
65
66 extra = []
67 if features == "all":
68 extra.append("--all-features")
69 else:
70 extra.extend(["--features", features])
71
72 if workspace:
73 extra.append("--workspace")
74
75 if target:
76 extra.extend(["--no-default-features", "--target", target])
77 # For cross-compilation targets, just check -pcoreutils
78 # (show-utils.sh over-resolves due to default features)
79 extra.append("-pcoreutils")
80 else:
81 extra.extend(["--all-targets", "--tests", "--benches", "-pcoreutils"])
82 utilities = get_utility_list(features)
83 extra.extend(f"-puu_{u}" for u in utilities)
84
85 cmd.extend(extra)
86 cmd.extend(["--", "-D", "warnings"])
87 return cmd
88
89
90 # Pattern to match clippy/rustc errors for GHA annotations
91 ERROR_PATTERN = re.compile(
92 r"^error:\s+(.*)\n\s+-->\s+(.*):(\d+):(\d+)",
93 re.MULTILINE,
94 )
95
96
97 def emit_annotations(output: str, fault_type: str) -> None:
98 """Emit GitHub Actions annotations from cargo clippy errors."""
99 fault_prefix = fault_type.upper()
100 for m in ERROR_PATTERN.finditer(output):
101 message, file, line, col = m.groups()
102 print(
103 f"::{fault_type} file={file},line={line},col={col}"
104 f"::{fault_prefix}: `cargo clippy`: {message} (file:'{file}', line:{line})",
105 )
106
107
108 def main() -> int:
109 """Run cargo clippy and emit GHA annotations on failure."""
110 parser = argparse.ArgumentParser(description="Run cargo clippy for CI")
111 parser.add_argument("--features", required=True, help="Feature set to use")
112 parser.add_argument(
113 "--workspace",
114 action="store_true",
115 help="Include --workspace flag",
116 )
117 parser.add_argument("--target", default=None, help="Cross-compilation target")
118 parser.add_argument(
119 "--fault-type",
120 default="warning",
121 choices=["warning", "error"],
122 help="GHA annotation type",
123 )
124 parser.add_argument(
125 "--fail-on-fault",
126 action="store_true",
127 help="Exit with error code on clippy failures",
128 )
129 args = parser.parse_args()
130
131 cmd = build_clippy_command(
132 args.features,
133 workspace=args.workspace,
134 target=args.target,
135 )
136 print(f"Running: {' '.join(cmd)}", file=sys.stderr)
137
138 result = run_cmd(cmd)
139 output = result.stdout + result.stderr
140
141 # Always print the full output
142 print(output)
143
144 if result.returncode != 0:
145 emit_annotations(output, args.fault_type)
146 if args.fail_on_fault:
147 return 1
148
149 return 0
150
151
152 if __name__ == "__main__":
153 sys.exit(main())