drft/rules/
directed_cycle.rs1use crate::diagnostic::Diagnostic;
2use crate::rules::{Rule, RuleContext};
3
4pub struct DirectedCycleRule;
5
6impl Rule for DirectedCycleRule {
7 fn name(&self) -> &str {
8 "directed-cycle"
9 }
10
11 fn evaluate(&self, ctx: &RuleContext) -> Vec<Diagnostic> {
12 let result = &ctx.graph.scc;
13
14 result
15 .sccs
16 .iter()
17 .map(|scc| {
18 let mut path = scc.members.clone();
19 if let Some(first) = path.first().cloned() {
20 path.push(first);
21 }
22
23 let fix = format!(
24 "circular dependency \u{2014} review whether one of these links can be removed or the content restructured: {}",
25 scc.members.join(" \u{2192} ")
26 );
27
28 Diagnostic {
29 rule: "directed-cycle".into(),
30 message: "cycle detected".into(),
31 path: Some(path),
32 fix: Some(fix),
33 ..Default::default()
34 }
35 })
36 .collect()
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43 use crate::graph::Graph;
44 use crate::graph::test_helpers::{make_edge, make_enriched, make_node};
45 use crate::rules::RuleContext;
46
47 #[test]
48 fn detects_simple_cycle() {
49 let mut graph = Graph::new();
50 graph.add_node(make_node("a.md"));
51 graph.add_node(make_node("b.md"));
52 graph.add_node(make_node("c.md"));
53 graph.add_edge(make_edge("a.md", "b.md"));
54 graph.add_edge(make_edge("b.md", "c.md"));
55 graph.add_edge(make_edge("c.md", "a.md"));
56
57 let enriched = make_enriched(graph);
58 let ctx = RuleContext {
59 graph: &enriched,
60 options: None,
61 };
62 let diagnostics = DirectedCycleRule.evaluate(&ctx);
63 assert_eq!(diagnostics.len(), 1);
64 assert_eq!(diagnostics[0].rule, "directed-cycle");
65
66 let path = diagnostics[0].path.as_ref().unwrap();
67 assert_eq!(path.first(), path.last());
68 assert!(path.contains(&"a.md".to_string()));
69 assert!(path.contains(&"b.md".to_string()));
70 assert!(path.contains(&"c.md".to_string()));
71 }
72
73 #[test]
74 fn no_cycle_in_dag() {
75 let mut graph = Graph::new();
76 graph.add_node(make_node("a.md"));
77 graph.add_node(make_node("b.md"));
78 graph.add_node(make_node("c.md"));
79 graph.add_edge(make_edge("a.md", "b.md"));
80 graph.add_edge(make_edge("b.md", "c.md"));
81
82 let enriched = make_enriched(graph);
83 let ctx = RuleContext {
84 graph: &enriched,
85 options: None,
86 };
87 let diagnostics = DirectedCycleRule.evaluate(&ctx);
88 assert!(diagnostics.is_empty());
89 }
90
91 #[test]
92 fn ignores_broken_link_edges() {
93 let mut graph = Graph::new();
94 graph.add_node(make_node("a.md"));
95 graph.add_edge(make_edge("a.md", "missing.md"));
96
97 let enriched = make_enriched(graph);
98 let ctx = RuleContext {
99 graph: &enriched,
100 options: None,
101 };
102 let diagnostics = DirectedCycleRule.evaluate(&ctx);
103 assert!(diagnostics.is_empty());
104 }
105}