Skip to main content

drft/rules/
script.rs

1use std::path::Path;
2use std::process::Command;
3
4use crate::analyses::EnrichedGraph;
5use crate::config::{Config, RuleConfig};
6use crate::diagnostic::Diagnostic;
7
8/// Run all script rules defined in the config against the enriched graph.
9/// Script rules are rules with a `command` field in `[rules]`.
10/// Each script rule receives `{ graph, options }` as JSON on stdin —
11/// the enriched graph (nodes, edges, analyses) plus the rule's options —
12/// and emits diagnostics as newline-delimited JSON on stdout.
13///
14/// Expected output format per line:
15/// {"message": "...", "source": "...", "target": "...", "node": "...", "fix": "..."}
16///
17/// All fields except `message` are optional. The `rule` and `severity` fields
18/// are set by drft from the config — the script doesn't need to provide them.
19pub fn run_script_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.script_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: script rule \"{rule_name}\" failed: {e}");
28                // Surface failures as diagnostics so JSON consumers see them
29                diagnostics.push(Diagnostic {
30                    rule: rule_name.to_string(),
31                    severity: rule_config.severity,
32                    message: format!("script rule failed: {e}"),
33                    fix: Some(format!(
34                        "script 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
45fn 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    // Build the enriched graph + options JSON to pass on stdin
58    let graph_json = build_enriched_json(enriched, rule_config.options.as_ref());
59
60    // Parse command string (split on whitespace for simple commands)
61    let parts: Vec<&str> = command.split_whitespace().collect();
62    if parts.is_empty() {
63        anyhow::bail!("empty command");
64    }
65
66    // Resolve command path relative to config directory (where drft.toml lives)
67    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: script 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
137/// Build the JSON envelope sent to script rules: `{ graph, options }`.
138///
139/// The `graph` object contains the full enriched graph — nodes, edges,
140/// and all analysis results. `options` carries the rule's `[rules.<name>.options]`.
141fn 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        meta.insert("type".into(), serde_json::json!(node.node_type));
148        if let Some(h) = &node.hash {
149            meta.insert("hash".into(), serde_json::json!(h));
150        }
151        nodes.insert(path.clone(), serde_json::json!({ "metadata": meta }));
152    }
153
154    let edges: Vec<serde_json::Value> = graph
155        .edges
156        .iter()
157        .filter(|e| graph.nodes.contains_key(&e.target))
158        .map(|e| {
159            let mut edge = serde_json::json!({
160                "source": e.source,
161                "target": e.target,
162                "parser": e.parser,
163            });
164            if let Some(ref r) = e.link {
165                edge["link"] = serde_json::json!(r);
166            }
167            edge
168        })
169        .collect();
170
171    let analyses = serde_json::json!({
172        "betweenness": enriched.betweenness,
173        "bridges": enriched.bridges,
174        "change_propagation": enriched.change_propagation,
175        "connected_components": enriched.connected_components,
176        "degree": enriched.degree,
177        "depth": enriched.depth,
178        "graph_boundaries": enriched.graph_boundaries,
179        "graph_stats": enriched.graph_stats,
180        "impact_radius": enriched.impact_radius,
181        "pagerank": enriched.pagerank,
182        "scc": enriched.scc,
183        "transitive_reduction": enriched.transitive_reduction,
184    });
185
186    let output = serde_json::json!({
187        "graph": {
188            "directed": true,
189            "nodes": nodes,
190            "edges": edges,
191            "analyses": analyses,
192        },
193        "options": options.unwrap_or(&toml::Value::Table(Default::default())),
194    });
195
196    serde_json::to_string(&output).unwrap()
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use crate::analyses::enrich_graph;
203    use crate::graph::{Edge, Graph, Node, NodeType};
204    use std::collections::HashMap;
205    use std::fs;
206    use tempfile::TempDir;
207
208    fn make_enriched(dir: &Path) -> EnrichedGraph {
209        let mut g = Graph::new();
210        g.add_node(Node {
211            path: "index.md".into(),
212            node_type: NodeType::File,
213            hash: Some("b3:aaa".into()),
214            graph: None,
215            metadata: HashMap::new(),
216        });
217        g.add_node(Node {
218            path: "setup.md".into(),
219            node_type: NodeType::File,
220            hash: Some("b3:bbb".into()),
221            graph: None,
222            metadata: HashMap::new(),
223        });
224        g.add_edge(Edge {
225            source: "index.md".into(),
226            target: "setup.md".into(),
227            link: None,
228            parser: "markdown".into(),
229        });
230        let config = crate::config::Config {
231            include: vec!["*.md".into()],
232            exclude: vec![],
233            interface: None,
234            parsers: std::collections::HashMap::new(),
235            rules: std::collections::HashMap::new(),
236            config_dir: None,
237        };
238        enrich_graph(g, dir, &config, None)
239    }
240
241    #[test]
242    fn runs_custom_script() {
243        let dir = TempDir::new().unwrap();
244
245        // Write a simple script that emits one diagnostic
246        let script = dir.path().join("my-rule.sh");
247        fs::write(
248            &script,
249            "#!/bin/sh\necho '{\"message\": \"custom issue\", \"node\": \"index.md\", \"fix\": \"do something\"}'\n",
250        )
251        .unwrap();
252
253        #[cfg(unix)]
254        {
255            use std::os::unix::fs::PermissionsExt;
256            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
257        }
258
259        let config = RuleConfig {
260            command: Some(script.to_string_lossy().to_string()),
261            severity: crate::config::RuleSeverity::Warn,
262            ignore: Vec::new(),
263            options: None,
264            ignore_compiled: None,
265        };
266
267        let enriched = make_enriched(dir.path());
268        let diagnostics = run_one("my-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
269
270        assert_eq!(diagnostics.len(), 1);
271        assert_eq!(diagnostics[0].rule, "my-rule");
272        assert_eq!(diagnostics[0].message, "custom issue");
273        assert_eq!(diagnostics[0].node.as_deref(), Some("index.md"));
274        assert_eq!(diagnostics[0].fix.as_deref(), Some("do something"));
275    }
276
277    #[test]
278    fn handles_failing_script() {
279        let dir = TempDir::new().unwrap();
280        let script = dir.path().join("bad-rule.sh");
281        fs::write(&script, "#!/bin/sh\nexit 1\n").unwrap();
282
283        #[cfg(unix)]
284        {
285            use std::os::unix::fs::PermissionsExt;
286            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
287        }
288
289        let config = RuleConfig {
290            command: Some(script.to_string_lossy().to_string()),
291            severity: crate::config::RuleSeverity::Warn,
292            ignore: Vec::new(),
293            options: None,
294            ignore_compiled: None,
295        };
296
297        let enriched = make_enriched(dir.path());
298        let result = run_one("bad-rule", &config, &enriched, dir.path(), dir.path());
299        assert!(result.is_err());
300    }
301
302    #[test]
303    fn resolves_command_relative_to_config_dir() {
304        let dir = TempDir::new().unwrap();
305
306        // config_dir is the parent, root is a child subdirectory
307        let config_dir = dir.path();
308        let root = dir.path().join("docs");
309        fs::create_dir_all(&root).unwrap();
310
311        // Script lives relative to config_dir, not root
312        let scripts_dir = config_dir.join("scripts");
313        fs::create_dir_all(&scripts_dir).unwrap();
314        let script = scripts_dir.join("check.sh");
315        fs::write(
316            &script,
317            "#!/bin/sh\necho '{\"message\": \"found issue\", \"node\": \"index.md\"}'\n",
318        )
319        .unwrap();
320
321        #[cfg(unix)]
322        {
323            use std::os::unix::fs::PermissionsExt;
324            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
325        }
326
327        let config = RuleConfig {
328            command: Some("./scripts/check.sh".to_string()),
329            severity: crate::config::RuleSeverity::Warn,
330            ignore: Vec::new(),
331            options: None,
332            ignore_compiled: None,
333        };
334
335        let enriched = make_enriched(dir.path());
336        // config_dir != root — script should resolve relative to config_dir
337        let diagnostics = run_one("my-rule", &config, &enriched, &root, config_dir).unwrap();
338
339        assert_eq!(diagnostics.len(), 1);
340        assert_eq!(diagnostics[0].message, "found issue");
341    }
342
343    #[test]
344    fn passes_options_to_script() {
345        let dir = TempDir::new().unwrap();
346
347        // Script reads stdin, parses the JSON, and echoes back whether options were received
348        let script = dir.path().join("options-rule.sh");
349        fs::write(
350            &script,
351            r#"#!/bin/sh
352INPUT=$(cat)
353# Check if options.threshold exists in the JSON
354HAS_OPTIONS=$(echo "$INPUT" | grep -c '"threshold"')
355if [ "$HAS_OPTIONS" -gt 0 ]; then
356  echo '{"message": "got options"}'
357else
358  echo '{"message": "no options"}'
359fi
360"#,
361        )
362        .unwrap();
363
364        #[cfg(unix)]
365        {
366            use std::os::unix::fs::PermissionsExt;
367            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
368        }
369
370        let options: toml::Value = toml::from_str("threshold = 5").unwrap();
371        let config = RuleConfig {
372            command: Some(script.to_string_lossy().to_string()),
373            severity: crate::config::RuleSeverity::Warn,
374            ignore: Vec::new(),
375            options: Some(options),
376            ignore_compiled: None,
377        };
378
379        let enriched = make_enriched(dir.path());
380        let diagnostics =
381            run_one("options-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
382
383        assert_eq!(diagnostics.len(), 1);
384        assert_eq!(diagnostics[0].message, "got options");
385    }
386
387    #[test]
388    fn includes_analyses_in_graph_json() {
389        let dir = TempDir::new().unwrap();
390
391        // Script checks that analyses are present in the graph JSON
392        let script = dir.path().join("analyses-rule.sh");
393        fs::write(
394            &script,
395            r#"#!/bin/sh
396INPUT=$(cat)
397HAS_ANALYSES=$(echo "$INPUT" | grep -c '"analyses"')
398if [ "$HAS_ANALYSES" -gt 0 ]; then
399  echo '{"message": "has analyses"}'
400else
401  echo '{"message": "no analyses"}'
402fi
403"#,
404        )
405        .unwrap();
406
407        #[cfg(unix)]
408        {
409            use std::os::unix::fs::PermissionsExt;
410            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
411        }
412
413        let config = RuleConfig {
414            command: Some(script.to_string_lossy().to_string()),
415            severity: crate::config::RuleSeverity::Warn,
416            ignore: Vec::new(),
417            options: None,
418            ignore_compiled: None,
419        };
420
421        let enriched = make_enriched(dir.path());
422        let diagnostics =
423            run_one("analyses-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
424
425        assert_eq!(diagnostics.len(), 1);
426        assert_eq!(diagnostics[0].message, "has analyses");
427    }
428}