drft-cli 0.7.0

A structural integrity checker for linked file systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use std::path::Path;
use std::process::Command;

use crate::analyses::EnrichedGraph;
use crate::config::{Config, RuleConfig};
use crate::diagnostic::Diagnostic;

/// Run all custom rules defined in the config against the enriched graph.
/// Custom rules are rules with a `command` field in `[rules]`.
/// Each custom rule receives `{ graph, options }` as JSON on stdin —
/// the enriched graph (nodes, edges, analyses) plus the rule's options —
/// and emits diagnostics as newline-delimited JSON on stdout.
///
/// Expected output format per line:
/// {"message": "...", "source": "...", "target": "...", "node": "...", "fix": "..."}
///
/// All fields except `message` are optional. The `rule` and `severity` fields
/// are set by drft from the config — the command doesn't need to provide them.
pub fn run_custom_rules(enriched: &EnrichedGraph, root: &Path, config: &Config) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();
    let config_dir = config.config_dir.as_deref().unwrap_or(root);

    for (rule_name, rule_config) in config.custom_rules() {
        match run_one(rule_name, rule_config, enriched, root, config_dir) {
            Ok(mut results) => diagnostics.append(&mut results),
            Err(e) => {
                eprintln!("warn: custom rule \"{rule_name}\" failed: {e}");
                // Surface failures as diagnostics so JSON consumers see them
                diagnostics.push(Diagnostic {
                    rule: rule_name.to_string(),
                    severity: rule_config.severity,
                    message: format!("custom rule failed: {e}"),
                    fix: Some(format!(
                        "custom rule \"{rule_name}\" failed to execute — check the command path and script"
                    )),
                    ..Default::default()
                });
            }
        }
    }

    diagnostics
}

pub fn run_one(
    rule_name: &str,
    rule_config: &RuleConfig,
    enriched: &EnrichedGraph,
    root: &Path,
    config_dir: &Path,
) -> anyhow::Result<Vec<Diagnostic>> {
    let command = rule_config
        .command
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("rule \"{rule_name}\" has no command"))?;

    // Build the enriched graph + options JSON to pass on stdin
    let graph_json = build_enriched_json(enriched, rule_config.options.as_ref());

    // Parse command string (split on whitespace for simple commands)
    let parts: Vec<&str> = command.split_whitespace().collect();
    if parts.is_empty() {
        anyhow::bail!("empty command");
    }

    // Resolve command path relative to config directory (where drft.toml lives)
    let cmd = if parts[0].starts_with("./") || parts[0].starts_with("../") {
        config_dir.join(parts[0]).to_string_lossy().to_string()
    } else {
        parts[0].to_string()
    };

    let output = Command::new(&cmd)
        .args(&parts[1..])
        .current_dir(root)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            if let Some(ref mut stdin) = child.stdin {
                let _ = stdin.write_all(graph_json.as_bytes());
            }
            child.wait_with_output()
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("exited with {}: {}", output.status, stderr.trim());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut diagnostics = Vec::new();

    for line in stdout.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        match serde_json::from_str::<CustomDiagnostic>(line) {
            Ok(cd) => {
                diagnostics.push(Diagnostic {
                    rule: rule_name.to_string(),
                    severity: rule_config.severity,
                    message: cd.message,
                    source: cd.source,
                    target: cd.target,
                    node: cd.node,
                    fix: cd.fix,
                    ..Default::default()
                });
            }
            Err(e) => {
                eprintln!("warn: custom rule \"{rule_name}\": failed to parse output line: {e}");
            }
        }
    }

    Ok(diagnostics)
}

#[derive(serde::Deserialize)]
struct CustomDiagnostic {
    message: String,
    #[serde(default)]
    source: Option<String>,
    #[serde(default)]
    target: Option<String>,
    #[serde(default)]
    node: Option<String>,
    #[serde(default)]
    fix: Option<String>,
}

/// Build the JSON envelope sent to custom rules: `{ graph, options }`.
///
/// The `graph` object contains the full enriched graph — nodes, edges,
/// and all analysis results. `options` carries the rule's `[rules.<name>.options]`.
fn build_enriched_json(enriched: &EnrichedGraph, options: Option<&toml::Value>) -> String {
    let graph = &enriched.graph;

    let mut nodes = serde_json::Map::new();
    for (path, node) in &graph.nodes {
        let mut meta = serde_json::Map::new();
        if let Some(nt) = &node.node_type {
            meta.insert("type".into(), serde_json::json!(nt));
        }
        meta.insert("included".into(), serde_json::json!(node.included));
        if let Some(h) = &node.hash {
            meta.insert("hash".into(), serde_json::json!(h));
        }
        for (key, value) in &node.metadata {
            meta.insert(key.clone(), value.clone());
        }
        nodes.insert(path.clone(), serde_json::json!({ "metadata": meta }));
    }

    let edges: Vec<serde_json::Value> = graph
        .edges
        .iter()
        .map(|e| {
            let mut edge = serde_json::json!({
                "source": e.source,
                "target": e.target,
                "parser": e.parser,
            });
            if let Some(ref r) = e.link {
                edge["link"] = serde_json::json!(r);
            }
            edge
        })
        .collect();

    let analyses = serde_json::json!({
        "betweenness": enriched.betweenness,
        "bridges": enriched.bridges,
        "change_propagation": enriched.change_propagation,
        "connected_components": enriched.connected_components,
        "degree": enriched.degree,
        "depth": enriched.depth,
        "graph_stats": enriched.graph_stats,
        "impact_radius": enriched.impact_radius,
        "pagerank": enriched.pagerank,
        "scc": enriched.scc,
        "transitive_reduction": enriched.transitive_reduction,
    });

    let output = serde_json::json!({
        "graph": {
            "directed": true,
            "nodes": nodes,
            "edges": edges,
            "analyses": analyses,
        },
        "options": options.unwrap_or(&toml::Value::Table(Default::default())),
    });

    serde_json::to_string(&output).unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analyses::enrich_graph;
    use crate::graph::test_helpers::make_edge;
    use crate::graph::{Graph, Node, NodeType};
    use std::collections::HashMap;
    use std::fs;
    use tempfile::TempDir;

    fn make_enriched(dir: &Path) -> EnrichedGraph {
        let mut g = Graph::new();
        g.add_node(Node {
            path: "index.md".into(),
            node_type: Some(NodeType::File),
            included: true,
            hash: Some("b3:aaa".into()),
            metadata: HashMap::new(),
        });
        g.add_node(Node {
            path: "setup.md".into(),
            node_type: Some(NodeType::File),
            included: true,
            hash: Some("b3:bbb".into()),
            metadata: HashMap::new(),
        });
        g.add_edge(make_edge("index.md", "setup.md"));
        let config = crate::config::Config {
            include: vec!["*.md".into()],
            exclude: vec![],
            parsers: std::collections::HashMap::new(),
            rules: std::collections::HashMap::new(),
            config_dir: None,
        };
        enrich_graph(g, dir, &config, None)
    }

    #[test]
    fn runs_custom_script() {
        let dir = TempDir::new().unwrap();

        // Write a simple script that emits one diagnostic
        let script = dir.path().join("my-rule.sh");
        fs::write(
            &script,
            "#!/bin/sh\necho '{\"message\": \"custom issue\", \"node\": \"index.md\", \"fix\": \"do something\"}'\n",
        )
        .unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        }

        let config = RuleConfig {
            command: Some(script.to_string_lossy().to_string()),
            severity: crate::config::RuleSeverity::Warn,
            files: Vec::new(),
            ignore: Vec::new(),
            parsers: Vec::new(),
            options: None,
            files_compiled: None,
            ignore_compiled: None,
        };

        let enriched = make_enriched(dir.path());
        let diagnostics = run_one("my-rule", &config, &enriched, dir.path(), dir.path()).unwrap();

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].rule, "my-rule");
        assert_eq!(diagnostics[0].message, "custom issue");
        assert_eq!(diagnostics[0].node.as_deref(), Some("index.md"));
        assert_eq!(diagnostics[0].fix.as_deref(), Some("do something"));
    }

    #[test]
    fn handles_failing_script() {
        let dir = TempDir::new().unwrap();
        let script = dir.path().join("bad-rule.sh");
        fs::write(&script, "#!/bin/sh\nexit 1\n").unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        }

        let config = RuleConfig {
            command: Some(script.to_string_lossy().to_string()),
            severity: crate::config::RuleSeverity::Warn,
            files: Vec::new(),
            ignore: Vec::new(),
            parsers: Vec::new(),
            options: None,
            files_compiled: None,
            ignore_compiled: None,
        };

        let enriched = make_enriched(dir.path());
        let result = run_one("bad-rule", &config, &enriched, dir.path(), dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn resolves_command_relative_to_config_dir() {
        let dir = TempDir::new().unwrap();

        // config_dir is the parent, root is a child subdirectory
        let config_dir = dir.path();
        let root = dir.path().join("docs");
        fs::create_dir_all(&root).unwrap();

        // Script lives relative to config_dir, not root
        let scripts_dir = config_dir.join("scripts");
        fs::create_dir_all(&scripts_dir).unwrap();
        let script = scripts_dir.join("check.sh");
        fs::write(
            &script,
            "#!/bin/sh\necho '{\"message\": \"found issue\", \"node\": \"index.md\"}'\n",
        )
        .unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        }

        let config = RuleConfig {
            command: Some("./scripts/check.sh".to_string()),
            severity: crate::config::RuleSeverity::Warn,
            files: Vec::new(),
            ignore: Vec::new(),
            parsers: Vec::new(),
            options: None,
            files_compiled: None,
            ignore_compiled: None,
        };

        let enriched = make_enriched(dir.path());
        // config_dir != root — script should resolve relative to config_dir
        let diagnostics = run_one("my-rule", &config, &enriched, &root, config_dir).unwrap();

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].message, "found issue");
    }

    #[test]
    fn passes_options_to_script() {
        let dir = TempDir::new().unwrap();

        // Script reads stdin, parses the JSON, and echoes back whether options were received
        let script = dir.path().join("options-rule.sh");
        fs::write(
            &script,
            r#"#!/bin/sh
INPUT=$(cat)
# Check if options.threshold exists in the JSON
HAS_OPTIONS=$(echo "$INPUT" | grep -c '"threshold"')
if [ "$HAS_OPTIONS" -gt 0 ]; then
  echo '{"message": "got options"}'
else
  echo '{"message": "no options"}'
fi
"#,
        )
        .unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        }

        let options: toml::Value = toml::from_str("threshold = 5").unwrap();
        let config = RuleConfig {
            command: Some(script.to_string_lossy().to_string()),
            severity: crate::config::RuleSeverity::Warn,
            files: Vec::new(),
            ignore: Vec::new(),
            parsers: Vec::new(),
            options: Some(options),
            files_compiled: None,
            ignore_compiled: None,
        };

        let enriched = make_enriched(dir.path());
        let diagnostics =
            run_one("options-rule", &config, &enriched, dir.path(), dir.path()).unwrap();

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].message, "got options");
    }

    #[test]
    fn includes_analyses_in_graph_json() {
        let dir = TempDir::new().unwrap();

        // Script checks that analyses are present in the graph JSON
        let script = dir.path().join("analyses-rule.sh");
        fs::write(
            &script,
            r#"#!/bin/sh
INPUT=$(cat)
HAS_ANALYSES=$(echo "$INPUT" | grep -c '"analyses"')
if [ "$HAS_ANALYSES" -gt 0 ]; then
  echo '{"message": "has analyses"}'
else
  echo '{"message": "no analyses"}'
fi
"#,
        )
        .unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
        }

        let config = RuleConfig {
            command: Some(script.to_string_lossy().to_string()),
            severity: crate::config::RuleSeverity::Warn,
            files: Vec::new(),
            ignore: Vec::new(),
            parsers: Vec::new(),
            options: None,
            files_compiled: None,
            ignore_compiled: None,
        };

        let enriched = make_enriched(dir.path());
        let diagnostics =
            run_one("analyses-rule", &config, &enriched, dir.path(), dir.path()).unwrap();

        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].message, "has analyses");
    }
}