Skip to main content

drft/rules/
custom.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 custom rules defined in the config against the enriched graph.
9/// Custom rules are rules with a `command` field in `[rules]`.
10/// Each custom 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 command doesn't need to provide them.
19pub 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                // 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!("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    // 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: 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
137/// Build the JSON envelope sent to custom 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            is_graph: false,
216            metadata: HashMap::new(),
217        });
218        g.add_node(Node {
219            path: "setup.md".into(),
220            node_type: NodeType::File,
221            hash: Some("b3:bbb".into()),
222            graph: None,
223            is_graph: false,
224            metadata: HashMap::new(),
225        });
226        g.add_edge(Edge {
227            source: "index.md".into(),
228            target: "setup.md".into(),
229            link: None,
230            parser: "markdown".into(),
231        });
232        let config = crate::config::Config {
233            include: vec!["*.md".into()],
234            exclude: vec![],
235            interface: None,
236            parsers: std::collections::HashMap::new(),
237            rules: std::collections::HashMap::new(),
238            config_dir: None,
239        };
240        enrich_graph(g, dir, &config, None)
241    }
242
243    #[test]
244    fn runs_custom_script() {
245        let dir = TempDir::new().unwrap();
246
247        // Write a simple script that emits one diagnostic
248        let script = dir.path().join("my-rule.sh");
249        fs::write(
250            &script,
251            "#!/bin/sh\necho '{\"message\": \"custom issue\", \"node\": \"index.md\", \"fix\": \"do something\"}'\n",
252        )
253        .unwrap();
254
255        #[cfg(unix)]
256        {
257            use std::os::unix::fs::PermissionsExt;
258            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
259        }
260
261        let config = RuleConfig {
262            command: Some(script.to_string_lossy().to_string()),
263            severity: crate::config::RuleSeverity::Warn,
264            files: Vec::new(),
265            ignore: Vec::new(),
266            parsers: Vec::new(),
267            options: None,
268            files_compiled: None,
269            ignore_compiled: None,
270        };
271
272        let enriched = make_enriched(dir.path());
273        let diagnostics = run_one("my-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
274
275        assert_eq!(diagnostics.len(), 1);
276        assert_eq!(diagnostics[0].rule, "my-rule");
277        assert_eq!(diagnostics[0].message, "custom issue");
278        assert_eq!(diagnostics[0].node.as_deref(), Some("index.md"));
279        assert_eq!(diagnostics[0].fix.as_deref(), Some("do something"));
280    }
281
282    #[test]
283    fn handles_failing_script() {
284        let dir = TempDir::new().unwrap();
285        let script = dir.path().join("bad-rule.sh");
286        fs::write(&script, "#!/bin/sh\nexit 1\n").unwrap();
287
288        #[cfg(unix)]
289        {
290            use std::os::unix::fs::PermissionsExt;
291            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
292        }
293
294        let config = RuleConfig {
295            command: Some(script.to_string_lossy().to_string()),
296            severity: crate::config::RuleSeverity::Warn,
297            files: Vec::new(),
298            ignore: Vec::new(),
299            parsers: Vec::new(),
300            options: None,
301            files_compiled: None,
302            ignore_compiled: None,
303        };
304
305        let enriched = make_enriched(dir.path());
306        let result = run_one("bad-rule", &config, &enriched, dir.path(), dir.path());
307        assert!(result.is_err());
308    }
309
310    #[test]
311    fn resolves_command_relative_to_config_dir() {
312        let dir = TempDir::new().unwrap();
313
314        // config_dir is the parent, root is a child subdirectory
315        let config_dir = dir.path();
316        let root = dir.path().join("docs");
317        fs::create_dir_all(&root).unwrap();
318
319        // Script lives relative to config_dir, not root
320        let scripts_dir = config_dir.join("scripts");
321        fs::create_dir_all(&scripts_dir).unwrap();
322        let script = scripts_dir.join("check.sh");
323        fs::write(
324            &script,
325            "#!/bin/sh\necho '{\"message\": \"found issue\", \"node\": \"index.md\"}'\n",
326        )
327        .unwrap();
328
329        #[cfg(unix)]
330        {
331            use std::os::unix::fs::PermissionsExt;
332            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
333        }
334
335        let config = RuleConfig {
336            command: Some("./scripts/check.sh".to_string()),
337            severity: crate::config::RuleSeverity::Warn,
338            files: Vec::new(),
339            ignore: Vec::new(),
340            parsers: Vec::new(),
341            options: None,
342            files_compiled: None,
343            ignore_compiled: None,
344        };
345
346        let enriched = make_enriched(dir.path());
347        // config_dir != root — script should resolve relative to config_dir
348        let diagnostics = run_one("my-rule", &config, &enriched, &root, config_dir).unwrap();
349
350        assert_eq!(diagnostics.len(), 1);
351        assert_eq!(diagnostics[0].message, "found issue");
352    }
353
354    #[test]
355    fn passes_options_to_script() {
356        let dir = TempDir::new().unwrap();
357
358        // Script reads stdin, parses the JSON, and echoes back whether options were received
359        let script = dir.path().join("options-rule.sh");
360        fs::write(
361            &script,
362            r#"#!/bin/sh
363INPUT=$(cat)
364# Check if options.threshold exists in the JSON
365HAS_OPTIONS=$(echo "$INPUT" | grep -c '"threshold"')
366if [ "$HAS_OPTIONS" -gt 0 ]; then
367  echo '{"message": "got options"}'
368else
369  echo '{"message": "no options"}'
370fi
371"#,
372        )
373        .unwrap();
374
375        #[cfg(unix)]
376        {
377            use std::os::unix::fs::PermissionsExt;
378            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
379        }
380
381        let options: toml::Value = toml::from_str("threshold = 5").unwrap();
382        let config = RuleConfig {
383            command: Some(script.to_string_lossy().to_string()),
384            severity: crate::config::RuleSeverity::Warn,
385            files: Vec::new(),
386            ignore: Vec::new(),
387            parsers: Vec::new(),
388            options: Some(options),
389            files_compiled: None,
390            ignore_compiled: None,
391        };
392
393        let enriched = make_enriched(dir.path());
394        let diagnostics =
395            run_one("options-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
396
397        assert_eq!(diagnostics.len(), 1);
398        assert_eq!(diagnostics[0].message, "got options");
399    }
400
401    #[test]
402    fn includes_analyses_in_graph_json() {
403        let dir = TempDir::new().unwrap();
404
405        // Script checks that analyses are present in the graph JSON
406        let script = dir.path().join("analyses-rule.sh");
407        fs::write(
408            &script,
409            r#"#!/bin/sh
410INPUT=$(cat)
411HAS_ANALYSES=$(echo "$INPUT" | grep -c '"analyses"')
412if [ "$HAS_ANALYSES" -gt 0 ]; then
413  echo '{"message": "has analyses"}'
414else
415  echo '{"message": "no analyses"}'
416fi
417"#,
418        )
419        .unwrap();
420
421        #[cfg(unix)]
422        {
423            use std::os::unix::fs::PermissionsExt;
424            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
425        }
426
427        let config = RuleConfig {
428            command: Some(script.to_string_lossy().to_string()),
429            severity: crate::config::RuleSeverity::Warn,
430            files: Vec::new(),
431            ignore: Vec::new(),
432            parsers: Vec::new(),
433            options: None,
434            files_compiled: None,
435            ignore_compiled: None,
436        };
437
438        let enriched = make_enriched(dir.path());
439        let diagnostics =
440            run_one("analyses-rule", &config, &enriched, dir.path(), dir.path()).unwrap();
441
442        assert_eq!(diagnostics.len(), 1);
443        assert_eq!(diagnostics[0].message, "has analyses");
444    }
445}