1use std::path::Path;
2use std::process::Command;
3
4use crate::analyses::EnrichedGraph;
5use crate::config::{Config, RuleConfig};
6use crate::diagnostic::Diagnostic;
7
8pub fn run_custom_rules(enriched: &EnrichedGraph, root: &Path, config: &Config) -> Vec<Diagnostic> {
20 let mut diagnostics = Vec::new();
21 let config_dir = config.config_dir.as_deref().unwrap_or(root);
22
23 for (rule_name, rule_config) in config.custom_rules() {
24 match run_one(rule_name, rule_config, enriched, root, config_dir) {
25 Ok(mut results) => diagnostics.append(&mut results),
26 Err(e) => {
27 eprintln!("warn: custom rule \"{rule_name}\" failed: {e}");
28 diagnostics.push(Diagnostic {
30 rule: rule_name.to_string(),
31 severity: rule_config.severity,
32 message: format!("custom rule failed: {e}"),
33 fix: Some(format!(
34 "custom rule \"{rule_name}\" failed to execute — check the command path and script"
35 )),
36 ..Default::default()
37 });
38 }
39 }
40 }
41
42 diagnostics
43}
44
45pub fn run_one(
46 rule_name: &str,
47 rule_config: &RuleConfig,
48 enriched: &EnrichedGraph,
49 root: &Path,
50 config_dir: &Path,
51) -> anyhow::Result<Vec<Diagnostic>> {
52 let command = rule_config
53 .command
54 .as_deref()
55 .ok_or_else(|| anyhow::anyhow!("rule \"{rule_name}\" has no command"))?;
56
57 let graph_json = build_enriched_json(enriched, rule_config.options.as_ref());
59
60 let parts: Vec<&str> = command.split_whitespace().collect();
62 if parts.is_empty() {
63 anyhow::bail!("empty command");
64 }
65
66 let cmd = if parts[0].starts_with("./") || parts[0].starts_with("../") {
68 config_dir.join(parts[0]).to_string_lossy().to_string()
69 } else {
70 parts[0].to_string()
71 };
72
73 let output = Command::new(&cmd)
74 .args(&parts[1..])
75 .current_dir(root)
76 .stdin(std::process::Stdio::piped())
77 .stdout(std::process::Stdio::piped())
78 .stderr(std::process::Stdio::piped())
79 .spawn()
80 .and_then(|mut child| {
81 use std::io::Write;
82 if let Some(ref mut stdin) = child.stdin {
83 let _ = stdin.write_all(graph_json.as_bytes());
84 }
85 child.wait_with_output()
86 })?;
87
88 if !output.status.success() {
89 let stderr = String::from_utf8_lossy(&output.stderr);
90 anyhow::bail!("exited with {}: {}", output.status, stderr.trim());
91 }
92
93 let stdout = String::from_utf8_lossy(&output.stdout);
94 let mut diagnostics = Vec::new();
95
96 for line in stdout.lines() {
97 let line = line.trim();
98 if line.is_empty() {
99 continue;
100 }
101
102 match serde_json::from_str::<CustomDiagnostic>(line) {
103 Ok(cd) => {
104 diagnostics.push(Diagnostic {
105 rule: rule_name.to_string(),
106 severity: rule_config.severity,
107 message: cd.message,
108 source: cd.source,
109 target: cd.target,
110 node: cd.node,
111 fix: cd.fix,
112 ..Default::default()
113 });
114 }
115 Err(e) => {
116 eprintln!("warn: custom rule \"{rule_name}\": failed to parse output line: {e}");
117 }
118 }
119 }
120
121 Ok(diagnostics)
122}
123
124#[derive(serde::Deserialize)]
125struct CustomDiagnostic {
126 message: String,
127 #[serde(default)]
128 source: Option<String>,
129 #[serde(default)]
130 target: Option<String>,
131 #[serde(default)]
132 node: Option<String>,
133 #[serde(default)]
134 fix: Option<String>,
135}
136
137fn build_enriched_json(enriched: &EnrichedGraph, options: Option<&toml::Value>) -> String {
142 let graph = &enriched.graph;
143
144 let mut nodes = serde_json::Map::new();
145 for (path, node) in &graph.nodes {
146 let mut meta = serde_json::Map::new();
147 if let Some(nt) = &node.node_type {
148 meta.insert("type".into(), serde_json::json!(nt));
149 }
150 meta.insert("included".into(), serde_json::json!(node.included));
151 if let Some(h) = &node.hash {
152 meta.insert("hash".into(), serde_json::json!(h));
153 }
154 for (key, value) in &node.metadata {
155 meta.insert(key.clone(), value.clone());
156 }
157 nodes.insert(path.clone(), serde_json::json!({ "metadata": meta }));
158 }
159
160 let edges: Vec<serde_json::Value> = graph
161 .edges
162 .iter()
163 .map(|e| {
164 let mut edge = serde_json::json!({
165 "source": e.source,
166 "target": e.target,
167 "parser": e.parser,
168 });
169 if let Some(ref r) = e.link {
170 edge["link"] = serde_json::json!(r);
171 }
172 edge
173 })
174 .collect();
175
176 let analyses = serde_json::json!({
177 "betweenness": enriched.betweenness,
178 "bridges": enriched.bridges,
179 "change_propagation": enriched.change_propagation,
180 "connected_components": enriched.connected_components,
181 "degree": enriched.degree,
182 "depth": enriched.depth,
183 "graph_stats": enriched.graph_stats,
184 "impact_radius": enriched.impact_radius,
185 "pagerank": enriched.pagerank,
186 "scc": enriched.scc,
187 "transitive_reduction": enriched.transitive_reduction,
188 });
189
190 let output = serde_json::json!({
191 "graph": {
192 "directed": true,
193 "nodes": nodes,
194 "edges": edges,
195 "analyses": analyses,
196 },
197 "options": options.unwrap_or(&toml::Value::Table(Default::default())),
198 });
199
200 serde_json::to_string(&output).unwrap()
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206 use crate::analyses::enrich_graph;
207 use crate::graph::test_helpers::make_edge;
208 use crate::graph::{Graph, Node, NodeType};
209 use std::collections::HashMap;
210 use std::fs;
211 use tempfile::TempDir;
212
213 fn make_enriched(dir: &Path) -> EnrichedGraph {
214 let mut g = Graph::new();
215 g.add_node(Node {
216 path: "index.md".into(),
217 node_type: Some(NodeType::File),
218 included: true,
219 hash: Some("b3:aaa".into()),
220 metadata: HashMap::new(),
221 });
222 g.add_node(Node {
223 path: "setup.md".into(),
224 node_type: Some(NodeType::File),
225 included: true,
226 hash: Some("b3:bbb".into()),
227 metadata: HashMap::new(),
228 });
229 g.add_edge(make_edge("index.md", "setup.md"));
230 let config = crate::config::Config {
231 include: vec!["*.md".into()],
232 exclude: vec![],
233 parsers: std::collections::HashMap::new(),
234 rules: std::collections::HashMap::new(),
235 config_dir: None,
236 };
237 enrich_graph(g, dir, &config, None)
238 }
239
240 #[test]
241 fn runs_custom_script() {
242 let dir = TempDir::new().unwrap();
243
244 let script = dir.path().join("my-rule.sh");
246 fs::write(
247 &script,
248 "#!/bin/sh\necho '{\"message\": \"custom issue\", \"node\": \"index.md\", \"fix\": \"do something\"}'\n",
249 )
250 .unwrap();
251
252 #[cfg(unix)]
253 {
254 use std::os::unix::fs::PermissionsExt;
255 fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
256 }
257
258 let config = RuleConfig {
259 command: Some(script.to_string_lossy().to_string()),
260 severity: crate::config::RuleSeverity::Warn,
261 files: Vec::new(),
262 ignore: Vec::new(),
263 parsers: Vec::new(),
264 options: None,
265 files_compiled: None,
266 ignore_compiled: None,
267 };
268
269 let enriched = make_enriched(dir.path());
270 let diagnostics = run_one("my-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
271
272 assert_eq!(diagnostics.len(), 1);
273 assert_eq!(diagnostics[0].rule, "my-rule");
274 assert_eq!(diagnostics[0].message, "custom issue");
275 assert_eq!(diagnostics[0].node.as_deref(), Some("index.md"));
276 assert_eq!(diagnostics[0].fix.as_deref(), Some("do something"));
277 }
278
279 #[test]
280 fn handles_failing_script() {
281 let dir = TempDir::new().unwrap();
282 let script = dir.path().join("bad-rule.sh");
283 fs::write(&script, "#!/bin/sh\nexit 1\n").unwrap();
284
285 #[cfg(unix)]
286 {
287 use std::os::unix::fs::PermissionsExt;
288 fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
289 }
290
291 let config = RuleConfig {
292 command: Some(script.to_string_lossy().to_string()),
293 severity: crate::config::RuleSeverity::Warn,
294 files: Vec::new(),
295 ignore: Vec::new(),
296 parsers: Vec::new(),
297 options: None,
298 files_compiled: None,
299 ignore_compiled: None,
300 };
301
302 let enriched = make_enriched(dir.path());
303 let result = run_one("bad-rule", &config, &enriched, dir.path(), dir.path());
304 assert!(result.is_err());
305 }
306
307 #[test]
308 fn resolves_command_relative_to_config_dir() {
309 let dir = TempDir::new().unwrap();
310
311 let config_dir = dir.path();
313 let root = dir.path().join("docs");
314 fs::create_dir_all(&root).unwrap();
315
316 let scripts_dir = config_dir.join("scripts");
318 fs::create_dir_all(&scripts_dir).unwrap();
319 let script = scripts_dir.join("check.sh");
320 fs::write(
321 &script,
322 "#!/bin/sh\necho '{\"message\": \"found issue\", \"node\": \"index.md\"}'\n",
323 )
324 .unwrap();
325
326 #[cfg(unix)]
327 {
328 use std::os::unix::fs::PermissionsExt;
329 fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
330 }
331
332 let config = RuleConfig {
333 command: Some("./scripts/check.sh".to_string()),
334 severity: crate::config::RuleSeverity::Warn,
335 files: Vec::new(),
336 ignore: Vec::new(),
337 parsers: Vec::new(),
338 options: None,
339 files_compiled: None,
340 ignore_compiled: None,
341 };
342
343 let enriched = make_enriched(dir.path());
344 let diagnostics = run_one("my-rule", &config, &enriched, &root, config_dir).unwrap();
346
347 assert_eq!(diagnostics.len(), 1);
348 assert_eq!(diagnostics[0].message, "found issue");
349 }
350
351 #[test]
352 fn passes_options_to_script() {
353 let dir = TempDir::new().unwrap();
354
355 let script = dir.path().join("options-rule.sh");
357 fs::write(
358 &script,
359 r#"#!/bin/sh
360INPUT=$(cat)
361# Check if options.threshold exists in the JSON
362HAS_OPTIONS=$(echo "$INPUT" | grep -c '"threshold"')
363if [ "$HAS_OPTIONS" -gt 0 ]; then
364 echo '{"message": "got options"}'
365else
366 echo '{"message": "no options"}'
367fi
368"#,
369 )
370 .unwrap();
371
372 #[cfg(unix)]
373 {
374 use std::os::unix::fs::PermissionsExt;
375 fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
376 }
377
378 let options: toml::Value = toml::from_str("threshold = 5").unwrap();
379 let config = RuleConfig {
380 command: Some(script.to_string_lossy().to_string()),
381 severity: crate::config::RuleSeverity::Warn,
382 files: Vec::new(),
383 ignore: Vec::new(),
384 parsers: Vec::new(),
385 options: Some(options),
386 files_compiled: None,
387 ignore_compiled: None,
388 };
389
390 let enriched = make_enriched(dir.path());
391 let diagnostics =
392 run_one("options-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
393
394 assert_eq!(diagnostics.len(), 1);
395 assert_eq!(diagnostics[0].message, "got options");
396 }
397
398 #[test]
399 fn includes_analyses_in_graph_json() {
400 let dir = TempDir::new().unwrap();
401
402 let script = dir.path().join("analyses-rule.sh");
404 fs::write(
405 &script,
406 r#"#!/bin/sh
407INPUT=$(cat)
408HAS_ANALYSES=$(echo "$INPUT" | grep -c '"analyses"')
409if [ "$HAS_ANALYSES" -gt 0 ]; then
410 echo '{"message": "has analyses"}'
411else
412 echo '{"message": "no analyses"}'
413fi
414"#,
415 )
416 .unwrap();
417
418 #[cfg(unix)]
419 {
420 use std::os::unix::fs::PermissionsExt;
421 fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
422 }
423
424 let config = RuleConfig {
425 command: Some(script.to_string_lossy().to_string()),
426 severity: crate::config::RuleSeverity::Warn,
427 files: Vec::new(),
428 ignore: Vec::new(),
429 parsers: Vec::new(),
430 options: None,
431 files_compiled: None,
432 ignore_compiled: None,
433 };
434
435 let enriched = make_enriched(dir.path());
436 let diagnostics =
437 run_one("analyses-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
438
439 assert_eq!(diagnostics.len(), 1);
440 assert_eq!(diagnostics[0].message, "has analyses");
441 }
442}