1use std::collections::{HashMap, HashSet, VecDeque};
35use std::fmt::Write;
36
37use crate::graph::node::Language;
38use crate::graph::unified::concurrent::GraphSnapshot;
39use crate::graph::unified::edge::EdgeKind;
40#[cfg(test)]
41use crate::graph::unified::edge::ResolvedVia;
42use crate::graph::unified::node::NodeId;
43use crate::graph::unified::node::kind::NodeKind;
44use crate::graph::unified::storage::arena::NodeEntry;
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub enum Direction {
53 #[default]
55 LeftToRight,
56 TopToBottom,
58}
59
60impl Direction {
61 #[must_use]
63 pub const fn as_str(self) -> &'static str {
64 match self {
65 Self::LeftToRight => "LR",
66 Self::TopToBottom => "TB",
67 }
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub enum EdgeFilter {
74 Calls,
76 Imports,
78 Exports,
80 References,
82 Inherits,
84 Implements,
86 FfiCall,
88 HttpRequest,
90 DbQuery,
92}
93
94impl EdgeFilter {
95 #[must_use]
97 pub fn matches(&self, kind: &EdgeKind) -> bool {
98 matches!(
99 (self, kind),
100 (EdgeFilter::Calls, EdgeKind::Calls { .. })
101 | (EdgeFilter::Imports, EdgeKind::Imports { .. })
102 | (EdgeFilter::Exports, EdgeKind::Exports { .. })
103 | (EdgeFilter::References, EdgeKind::References)
104 | (EdgeFilter::Inherits, EdgeKind::Inherits)
105 | (EdgeFilter::Implements, EdgeKind::Implements)
106 | (EdgeFilter::FfiCall, EdgeKind::FfiCall { .. })
107 | (EdgeFilter::HttpRequest, EdgeKind::HttpRequest { .. })
108 | (EdgeFilter::DbQuery, EdgeKind::DbQuery { .. })
109 )
110 }
111}
112
113#[must_use]
119pub fn language_color(lang: Language) -> &'static str {
120 match lang {
121 Language::Rust => "#dea584",
122 Language::JavaScript => "#f7df1e",
123 Language::TypeScript => "#3178c6",
124 Language::Python => "#3572A5",
125 Language::Go => "#00ADD8",
126 Language::Java => "#b07219",
127 Language::Ruby => "#701516",
128 Language::Php => "#4F5D95",
129 Language::Cpp => "#f34b7d",
130 Language::C => "#555555",
131 Language::Swift => "#F05138",
132 Language::Kotlin => "#A97BFF",
133 Language::Scala => "#c22d40",
134 Language::Sql | Language::Plsql => "#e38c00",
135 Language::Shell => "#89e051",
136 Language::Lua => "#000080",
137 Language::Perl => "#0298c3",
138 Language::Dart => "#00B4AB",
139 Language::Groovy => "#4298b8",
140 Language::Http => "#005C9C",
141 Language::Css => "#563d7c",
142 Language::Elixir => "#6e4a7e",
143 Language::R => "#198CE7",
144 Language::Haskell => "#5e5086",
145 Language::Html => "#e34c26",
146 Language::Svelte => "#ff3e00",
147 Language::Vue => "#41b883",
148 Language::Zig => "#ec915c",
149 Language::Terraform => "#5c4ee5",
150 Language::Puppet => "#302B6D",
151 Language::Pulumi => "#6d2df5",
152 Language::Apex => "#1797c0",
153 Language::Abap => "#E8274B",
154 Language::ServiceNow => "#62d84e",
155 Language::CSharp => "#178600",
156 Language::Json => "#292929",
157 }
158}
159
160#[must_use]
162pub const fn default_language_color() -> &'static str {
163 "#cccccc"
164}
165
166#[must_use]
168pub fn node_shape(kind: &NodeKind) -> &'static str {
169 match kind {
170 NodeKind::Class | NodeKind::Struct => "component",
171 NodeKind::Interface | NodeKind::Trait => "ellipse",
172 NodeKind::Module => "folder",
173 NodeKind::Variable | NodeKind::Constant => "note",
174 NodeKind::Enum | NodeKind::EnumVariant => "hexagon",
175 NodeKind::Type => "diamond",
176 NodeKind::Macro => "parallelogram",
177 _ => "box",
178 }
179}
180
181#[must_use]
183pub fn edge_style(kind: &EdgeKind) -> (&'static str, &'static str) {
184 match kind {
185 EdgeKind::Calls { .. } => ("solid", "#333333"),
186 EdgeKind::Imports { .. } => ("dashed", "#0066cc"),
187 EdgeKind::Exports { .. } => ("dashed", "#00cc66"),
188 EdgeKind::References => ("dotted", "#666666"),
189 EdgeKind::Inherits => ("solid", "#990099"),
190 EdgeKind::Implements => ("dashed", "#990099"),
191 EdgeKind::FfiCall { .. } => ("bold", "#ff6600"),
192 EdgeKind::HttpRequest { .. } => ("bold", "#cc0000"),
193 EdgeKind::DbQuery { .. } => ("bold", "#009900"),
194 _ => ("solid", "#666666"),
195 }
196}
197
198#[must_use]
200pub fn edge_label(
201 kind: &EdgeKind,
202 strings: &crate::graph::unified::storage::interner::StringInterner,
203) -> String {
204 match kind {
205 EdgeKind::Calls {
206 argument_count,
207 is_async,
208 ..
209 } => {
210 if *is_async {
211 format!("async call({argument_count})")
212 } else {
213 format!("call({argument_count})")
214 }
215 }
216 EdgeKind::Imports { alias, is_wildcard } => {
217 if *is_wildcard {
218 "import *".to_string()
219 } else if let Some(alias_id) = alias {
220 let alias_str = strings
221 .resolve(*alias_id)
222 .map_or_else(|| "?".to_string(), |s| s.to_string());
223 format!("import as {alias_str}")
224 } else {
225 "import".to_string()
226 }
227 }
228 EdgeKind::Exports {
229 kind: export_kind,
230 alias,
231 } => {
232 let kind_str = match export_kind {
233 crate::graph::unified::edge::ExportKind::Direct => "export",
234 crate::graph::unified::edge::ExportKind::Reexport => "re-export",
235 crate::graph::unified::edge::ExportKind::Default => "default export",
236 crate::graph::unified::edge::ExportKind::Namespace => "export *",
237 };
238 if let Some(alias_id) = alias {
239 let alias_str = strings
240 .resolve(*alias_id)
241 .map_or_else(|| "?".to_string(), |s| s.to_string());
242 format!("{kind_str} as {alias_str}")
243 } else {
244 kind_str.to_string()
245 }
246 }
247 EdgeKind::References => "ref".to_string(),
248 EdgeKind::Inherits => "extends".to_string(),
249 EdgeKind::Implements => "implements".to_string(),
250 EdgeKind::FfiCall { convention } => format!("ffi:{convention:?}"),
251 EdgeKind::HttpRequest { method, .. } => method.as_str().to_string(),
252 EdgeKind::DbQuery { query_type, .. } => format!("{query_type:?}"),
253 _ => String::new(),
254 }
255}
256
257#[must_use]
259pub fn escape_dot(s: &str) -> String {
260 s.replace('\\', "\\\\")
261 .replace('"', "\\\"")
262 .replace('\n', "\\n")
263}
264
265#[must_use]
267pub fn escape_d2(s: &str) -> String {
268 s.replace('\\', "\\\\")
269 .replace('"', "\\\"")
270 .replace('\n', " ")
271}
272
273#[derive(Debug, Clone)]
279pub struct DotConfig {
280 pub filter_languages: HashSet<Language>,
282 pub filter_edges: HashSet<EdgeFilter>,
284 pub filter_files: HashSet<String>,
286 pub filter_node_ids: Option<HashSet<NodeId>>,
290 pub highlight_cross_language: bool,
292 pub max_depth: Option<usize>,
294 pub root_nodes: HashSet<NodeId>,
296 pub direction: Direction,
298 pub show_details: bool,
300 pub show_edge_labels: bool,
302}
303
304impl Default for DotConfig {
305 fn default() -> Self {
306 Self {
307 filter_languages: HashSet::new(),
308 filter_edges: HashSet::new(),
309 filter_files: HashSet::new(),
310 filter_node_ids: None,
311 highlight_cross_language: false,
312 max_depth: None,
313 root_nodes: HashSet::new(),
314 direction: Direction::LeftToRight,
315 show_details: true,
316 show_edge_labels: true,
317 }
318 }
319}
320
321impl DotConfig {
322 #[must_use]
324 pub fn with_cross_language_highlight(mut self, enabled: bool) -> Self {
325 self.highlight_cross_language = enabled;
326 self
327 }
328
329 #[must_use]
331 pub fn with_details(mut self, enabled: bool) -> Self {
332 self.show_details = enabled;
333 self
334 }
335
336 #[must_use]
338 pub fn with_edge_labels(mut self, enabled: bool) -> Self {
339 self.show_edge_labels = enabled;
340 self
341 }
342
343 #[must_use]
345 pub fn with_direction(mut self, direction: Direction) -> Self {
346 self.direction = direction;
347 self
348 }
349
350 #[must_use]
352 pub fn filter_language(mut self, lang: Language) -> Self {
353 self.filter_languages.insert(lang);
354 self
355 }
356
357 #[must_use]
359 pub fn filter_edge(mut self, edge: EdgeFilter) -> Self {
360 self.filter_edges.insert(edge);
361 self
362 }
363
364 #[must_use]
366 pub fn with_max_depth(mut self, depth: usize) -> Self {
367 self.max_depth = Some(depth);
368 self
369 }
370
371 #[must_use]
374 pub fn with_filter_node_ids(mut self, ids: Option<HashSet<NodeId>>) -> Self {
375 self.filter_node_ids = ids;
376 self
377 }
378}
379
380pub struct UnifiedDotExporter<'a> {
382 graph: &'a GraphSnapshot,
383 config: DotConfig,
384}
385
386impl<'a> UnifiedDotExporter<'a> {
387 #[must_use]
389 pub fn new(graph: &'a GraphSnapshot) -> Self {
390 Self {
391 graph,
392 config: DotConfig::default(),
393 }
394 }
395
396 #[must_use]
398 pub fn with_config(graph: &'a GraphSnapshot, config: DotConfig) -> Self {
399 Self { graph, config }
400 }
401
402 #[must_use]
404 pub fn export(&self) -> String {
405 let mut dot = String::from("digraph CodeGraph {\n");
406
407 let rankdir = self.config.direction.as_str();
409 writeln!(dot, " rankdir={rankdir};").expect("write to String never fails");
410 dot.push_str(" node [shape=box, style=filled];\n");
411 dot.push_str(" overlap=false;\n");
412 dot.push_str(" splines=true;\n\n");
413
414 let visible_nodes = self.filter_nodes();
416
417 for node_id in &visible_nodes {
419 if let Some(entry) = self.graph.get_node(*node_id) {
420 self.export_node(&mut dot, *node_id, entry);
421 }
422 }
423
424 dot.push('\n');
425
426 for (from, to, kind) in self.graph.iter_edges() {
428 if !visible_nodes.contains(&from) || !visible_nodes.contains(&to) {
429 continue;
430 }
431
432 if !self.edge_allowed(&kind) {
433 continue;
434 }
435
436 self.export_edge(&mut dot, from, to, &kind);
437 }
438
439 dot.push_str("}\n");
440 dot
441 }
442
443 fn filter_nodes(&self) -> HashSet<NodeId> {
445 if let Some(ref filter_ids) = self.config.filter_node_ids {
447 return filter_ids.clone();
448 }
449
450 if self.config.root_nodes.is_empty() && self.config.max_depth.is_none() {
452 return self
453 .graph
454 .iter_nodes()
455 .filter(|(id, entry)| self.should_include_node(*id, entry))
456 .map(|(id, _)| id)
457 .collect();
458 }
459
460 let adjacency = self.build_adjacency();
462 let depth_limit = self.config.max_depth.unwrap_or(usize::MAX);
463 let mut visible = HashSet::new();
464
465 let starting_nodes: Vec<NodeId> = if self.config.root_nodes.is_empty() {
466 self.graph
470 .iter_nodes()
471 .filter(|(_, entry)| !entry.is_unified_loser())
472 .map(|(id, _)| id)
473 .collect()
474 } else {
475 self.config.root_nodes.iter().copied().collect()
476 };
477
478 for node_id in starting_nodes {
479 if visible.contains(&node_id) {
480 continue;
481 }
482 self.collect_nodes(&mut visible, &adjacency, node_id, depth_limit);
483 }
484
485 visible
486 }
487
488 fn should_include_node(&self, _node_id: NodeId, entry: &NodeEntry) -> bool {
490 if entry.is_unified_loser() {
493 return false;
494 }
495 if !self.config.filter_languages.is_empty() {
497 if let Some(lang) = self.graph.files().language_for_file(entry.file) {
498 if !self.config.filter_languages.contains(&lang) {
499 return false;
500 }
501 } else {
502 return false;
503 }
504 }
505
506 if !self.config.filter_files.is_empty() {
508 if let Some(path) = self.graph.files().resolve(entry.file) {
509 let path_str = path.to_string_lossy();
510 if !self
511 .config
512 .filter_files
513 .iter()
514 .any(|f| path_str.contains(f))
515 {
516 return false;
517 }
518 } else {
519 return false;
520 }
521 }
522
523 true
524 }
525
526 fn edge_allowed(&self, kind: &EdgeKind) -> bool {
528 if self.config.filter_edges.is_empty() {
529 return true;
530 }
531 self.config.filter_edges.iter().any(|f| f.matches(kind))
532 }
533
534 fn build_adjacency(&self) -> HashMap<NodeId, Vec<NodeId>> {
536 let mut adjacency: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
537 for (from, to, _) in self.graph.iter_edges() {
538 adjacency.entry(from).or_default().push(to);
539 adjacency.entry(to).or_default().push(from);
540 }
541 adjacency
542 }
543
544 fn collect_nodes(
546 &self,
547 visible: &mut HashSet<NodeId>,
548 adjacency: &HashMap<NodeId, Vec<NodeId>>,
549 start: NodeId,
550 depth_limit: usize,
551 ) {
552 let mut queue = VecDeque::new();
553 queue.push_back((start, 0usize));
554
555 while let Some((node_id, depth)) = queue.pop_front() {
556 if depth > depth_limit {
557 continue;
558 }
559
560 let Some(entry) = self.graph.get_node(node_id) else {
561 continue;
562 };
563
564 if !self.should_include_node(node_id, entry) {
565 continue;
566 }
567
568 if !visible.insert(node_id) {
569 continue;
570 }
571
572 if depth == depth_limit {
573 continue;
574 }
575
576 if let Some(neighbors) = adjacency.get(&node_id) {
577 for neighbor in neighbors {
578 queue.push_back((*neighbor, depth + 1));
579 }
580 }
581 }
582 }
583
584 fn export_node(&self, dot: &mut String, node_id: NodeId, entry: &NodeEntry) {
586 let lang = self.graph.files().language_for_file(entry.file);
587 let color = lang.map_or(default_language_color(), language_color);
588 let shape = node_shape(&entry.kind);
589
590 let name = self
592 .graph
593 .strings()
594 .resolve(entry.name)
595 .unwrap_or_else(|| std::sync::Arc::from("?"));
596 let qualified_name = entry
597 .qualified_name
598 .and_then(|id| self.graph.strings().resolve(id))
599 .unwrap_or_else(|| std::sync::Arc::clone(&name));
600
601 let label = if self.config.show_details {
603 let file = self
604 .graph
605 .files()
606 .resolve(entry.file)
607 .map_or_else(|| "?".to_string(), |p| p.to_string_lossy().into_owned());
608 format!("{}\\n{}:{}", qualified_name, file, entry.start_line)
609 } else {
610 qualified_name.to_string()
611 };
612
613 let label = escape_dot(&label);
614 let node_key = format!("n{}", node_id.index());
615
616 writeln!(
617 dot,
618 " \"{node_key}\" [label=\"{label}\", fillcolor=\"{color}\", shape=\"{shape}\"];",
619 )
620 .expect("write to String never fails");
621 }
622
623 fn export_edge(&self, dot: &mut String, from: NodeId, to: NodeId, kind: &EdgeKind) {
625 let (style, base_color) = edge_style(kind);
626 let color = if self.config.highlight_cross_language
627 && let (Some(from_entry), Some(to_entry)) =
628 (self.graph.get_node(from), self.graph.get_node(to))
629 {
630 let from_lang = self.graph.files().language_for_file(from_entry.file);
631 let to_lang = self.graph.files().language_for_file(to_entry.file);
632 if from_lang == to_lang {
633 base_color
634 } else {
635 "red"
636 }
637 } else {
638 base_color
639 };
640
641 let label = if self.config.show_edge_labels {
642 edge_label(kind, self.graph.strings())
643 } else {
644 String::new()
645 };
646
647 let from_key = format!("n{}", from.index());
648 let to_key = format!("n{}", to.index());
649
650 if label.is_empty() {
651 writeln!(
652 dot,
653 " \"{from_key}\" -> \"{to_key}\" [style=\"{style}\", color=\"{color}\"];"
654 )
655 .expect("write to String never fails");
656 } else {
657 writeln!(
658 dot,
659 " \"{from_key}\" -> \"{to_key}\" [style=\"{style}\", color=\"{color}\", label=\"{}\"];",
660 escape_dot(&label)
661 )
662 .expect("write to String never fails");
663 }
664 }
665}
666
667#[derive(Debug, Clone)]
673pub struct D2Config {
674 pub filter_languages: HashSet<Language>,
676 pub filter_edges: HashSet<EdgeFilter>,
678 pub filter_node_ids: Option<HashSet<NodeId>>,
681 pub highlight_cross_language: bool,
683 pub show_details: bool,
685 pub show_edge_labels: bool,
687 pub direction: Direction,
689}
690
691impl Default for D2Config {
692 fn default() -> Self {
693 Self {
694 filter_languages: HashSet::new(),
695 filter_edges: HashSet::new(),
696 filter_node_ids: None,
697 highlight_cross_language: false,
698 show_details: true,
699 show_edge_labels: true,
700 direction: Direction::LeftToRight,
701 }
702 }
703}
704
705impl D2Config {
706 #[must_use]
708 pub fn with_cross_language_highlight(mut self, enabled: bool) -> Self {
709 self.highlight_cross_language = enabled;
710 self
711 }
712
713 #[must_use]
715 pub fn with_details(mut self, enabled: bool) -> Self {
716 self.show_details = enabled;
717 self
718 }
719
720 #[must_use]
722 pub fn with_edge_labels(mut self, enabled: bool) -> Self {
723 self.show_edge_labels = enabled;
724 self
725 }
726
727 #[must_use]
729 pub fn with_filter_node_ids(mut self, ids: Option<HashSet<NodeId>>) -> Self {
730 self.filter_node_ids = ids;
731 self
732 }
733}
734
735pub struct UnifiedD2Exporter<'a> {
737 graph: &'a GraphSnapshot,
738 config: D2Config,
739}
740
741impl<'a> UnifiedD2Exporter<'a> {
742 #[must_use]
744 pub fn new(graph: &'a GraphSnapshot) -> Self {
745 Self {
746 graph,
747 config: D2Config::default(),
748 }
749 }
750
751 #[must_use]
753 pub fn with_config(graph: &'a GraphSnapshot, config: D2Config) -> Self {
754 Self { graph, config }
755 }
756
757 #[must_use]
759 pub fn export(&self) -> String {
760 let mut d2 = String::new();
761
762 writeln!(d2, "direction: {}", self.config.direction.as_str())
764 .expect("write to String never fails");
765 d2.push('\n');
766
767 let visible_nodes: HashSet<NodeId> =
769 if let Some(ref filter_ids) = self.config.filter_node_ids {
770 filter_ids.clone()
771 } else {
772 self.graph
773 .iter_nodes()
774 .filter(|(id, entry)| self.should_include_node(*id, entry))
775 .map(|(id, _)| id)
776 .collect()
777 };
778
779 for node_id in &visible_nodes {
781 if let Some(entry) = self.graph.get_node(*node_id) {
782 self.export_node(&mut d2, *node_id, entry);
783 }
784 }
785
786 d2.push('\n');
787
788 for (from, to, kind) in self.graph.iter_edges() {
790 if !visible_nodes.contains(&from) || !visible_nodes.contains(&to) {
791 continue;
792 }
793
794 if !self.edge_allowed(&kind) {
795 continue;
796 }
797
798 self.export_edge(&mut d2, from, to, &kind);
799 }
800
801 d2
802 }
803
804 fn should_include_node(&self, _node_id: NodeId, entry: &NodeEntry) -> bool {
806 if entry.is_unified_loser() {
809 return false;
810 }
811 if !self.config.filter_languages.is_empty() {
812 if let Some(lang) = self.graph.files().language_for_file(entry.file) {
813 if !self.config.filter_languages.contains(&lang) {
814 return false;
815 }
816 } else {
817 return false;
818 }
819 }
820 true
821 }
822
823 fn edge_allowed(&self, kind: &EdgeKind) -> bool {
825 if self.config.filter_edges.is_empty() {
826 return true;
827 }
828 self.config.filter_edges.iter().any(|f| f.matches(kind))
829 }
830
831 fn export_node(&self, d2: &mut String, node_id: NodeId, entry: &NodeEntry) {
833 let lang = self.graph.files().language_for_file(entry.file);
834 let color = lang.map_or(default_language_color(), language_color);
835 let shape = match entry.kind {
836 NodeKind::Class | NodeKind::Struct => "class",
837 NodeKind::Interface | NodeKind::Trait => "oval",
838 NodeKind::Module => "package",
839 _ => "rectangle",
840 };
841
842 let name = self
843 .graph
844 .strings()
845 .resolve(entry.name)
846 .unwrap_or_else(|| std::sync::Arc::from("?"));
847 let qualified_name = entry
848 .qualified_name
849 .and_then(|id| self.graph.strings().resolve(id))
850 .unwrap_or_else(|| std::sync::Arc::clone(&name));
851
852 let label = if self.config.show_details {
853 let file = self
854 .graph
855 .files()
856 .resolve(entry.file)
857 .map_or_else(|| "?".to_string(), |p| p.to_string_lossy().into_owned());
858 format!("{} ({file}:{})", qualified_name.as_ref(), entry.start_line)
859 } else {
860 qualified_name.to_string()
861 };
862
863 let node_key = format!("n{}", node_id.index());
864 let label = escape_d2(&label);
865
866 writeln!(d2, "{node_key}: \"{label}\" {{").expect("write to String never fails");
867 writeln!(d2, " shape: {shape}").expect("write to String never fails");
868 writeln!(d2, " style.fill: \"{color}\"").expect("write to String never fails");
869 writeln!(d2, "}}").expect("write to String never fails");
870 }
871
872 fn export_edge(&self, d2: &mut String, from: NodeId, to: NodeId, kind: &EdgeKind) {
874 let (style, base_color) = edge_style(kind);
875 let color = if self.config.highlight_cross_language
876 && let (Some(from_entry), Some(to_entry)) =
877 (self.graph.get_node(from), self.graph.get_node(to))
878 {
879 let from_lang = self.graph.files().language_for_file(from_entry.file);
880 let to_lang = self.graph.files().language_for_file(to_entry.file);
881 if from_lang == to_lang {
882 base_color
883 } else {
884 "#ff0000"
885 }
886 } else {
887 base_color
888 };
889
890 let from_key = format!("n{}", from.index());
891 let to_key = format!("n{}", to.index());
892
893 let arrow = match kind {
894 EdgeKind::Inherits | EdgeKind::Implements => "<->",
895 _ => "->",
896 };
897
898 if self.config.show_edge_labels {
899 let label = edge_label(kind, self.graph.strings());
900 if label.is_empty() {
901 writeln!(d2, "{from_key} {arrow} {to_key}: {{")
902 .expect("write to String never fails");
903 } else {
904 writeln!(d2, "{from_key} {arrow} {to_key}: \"{label}\" {{")
905 .expect("write to String never fails");
906 }
907 } else {
908 writeln!(d2, "{from_key} {arrow} {to_key}: {{").expect("write to String never fails");
909 }
910
911 let d2_style = match style {
912 "dashed" => "stroke-dash: 3",
913 "dotted" => "stroke-dash: 1",
914 "bold" => "stroke-width: 3",
915 _ => "",
916 };
917
918 if !d2_style.is_empty() {
919 writeln!(d2, " style.{d2_style}").expect("write to String never fails");
920 }
921 writeln!(d2, " style.stroke: \"{color}\"").expect("write to String never fails");
922 writeln!(d2, "}}").expect("write to String never fails");
923 }
924}
925
926#[derive(Debug, Clone)]
932pub struct MermaidConfig {
933 pub filter_languages: HashSet<Language>,
935 pub filter_edges: HashSet<EdgeFilter>,
937 pub highlight_cross_language: bool,
939 pub show_edge_labels: bool,
941 pub direction: Direction,
943 pub filter_node_ids: Option<HashSet<NodeId>>,
946}
947
948impl Default for MermaidConfig {
949 fn default() -> Self {
950 Self {
951 filter_languages: HashSet::new(),
952 filter_edges: HashSet::new(),
953 highlight_cross_language: false,
954 show_edge_labels: true,
955 direction: Direction::LeftToRight,
956 filter_node_ids: None,
957 }
958 }
959}
960
961impl MermaidConfig {
962 #[must_use]
964 pub fn with_cross_language_highlight(mut self, enabled: bool) -> Self {
965 self.highlight_cross_language = enabled;
966 self
967 }
968
969 #[must_use]
971 pub fn with_edge_labels(mut self, enabled: bool) -> Self {
972 self.show_edge_labels = enabled;
973 self
974 }
975
976 #[must_use]
978 pub fn with_filter_node_ids(mut self, ids: Option<HashSet<NodeId>>) -> Self {
979 self.filter_node_ids = ids;
980 self
981 }
982}
983
984pub struct UnifiedMermaidExporter<'a> {
986 graph: &'a GraphSnapshot,
987 config: MermaidConfig,
988}
989
990impl<'a> UnifiedMermaidExporter<'a> {
991 #[must_use]
993 pub fn new(graph: &'a GraphSnapshot) -> Self {
994 Self {
995 graph,
996 config: MermaidConfig::default(),
997 }
998 }
999
1000 #[must_use]
1002 pub fn with_config(graph: &'a GraphSnapshot, config: MermaidConfig) -> Self {
1003 Self { graph, config }
1004 }
1005
1006 #[must_use]
1008 pub fn export(&self) -> String {
1009 let mut mermaid = String::new();
1010
1011 writeln!(mermaid, "graph {}", self.config.direction.as_str())
1013 .expect("write to String never fails");
1014
1015 let visible_nodes: HashSet<NodeId> =
1017 if let Some(ref filter_ids) = self.config.filter_node_ids {
1018 filter_ids.clone()
1019 } else {
1020 self.graph
1021 .iter_nodes()
1022 .filter(|(id, entry)| self.should_include_node(*id, entry))
1023 .map(|(id, _)| id)
1024 .collect()
1025 };
1026
1027 for node_id in &visible_nodes {
1029 if let Some(entry) = self.graph.get_node(*node_id) {
1030 self.export_node(&mut mermaid, *node_id, entry);
1031 }
1032 }
1033
1034 for (from, to, kind) in self.graph.iter_edges() {
1036 if !visible_nodes.contains(&from) || !visible_nodes.contains(&to) {
1037 continue;
1038 }
1039
1040 if !self.edge_allowed(&kind) {
1041 continue;
1042 }
1043
1044 self.export_edge(&mut mermaid, from, to, &kind);
1045 }
1046
1047 mermaid
1048 }
1049
1050 fn should_include_node(&self, _node_id: NodeId, entry: &NodeEntry) -> bool {
1052 if entry.is_unified_loser() {
1055 return false;
1056 }
1057 if !self.config.filter_languages.is_empty() {
1058 if let Some(lang) = self.graph.files().language_for_file(entry.file) {
1059 if !self.config.filter_languages.contains(&lang) {
1060 return false;
1061 }
1062 } else {
1063 return false;
1064 }
1065 }
1066 true
1067 }
1068
1069 fn edge_allowed(&self, kind: &EdgeKind) -> bool {
1071 if self.config.filter_edges.is_empty() {
1072 return true;
1073 }
1074 self.config.filter_edges.iter().any(|f| f.matches(kind))
1075 }
1076
1077 fn export_node(&self, mermaid: &mut String, node_id: NodeId, entry: &NodeEntry) {
1079 let name = self
1080 .graph
1081 .strings()
1082 .resolve(entry.name)
1083 .unwrap_or_else(|| std::sync::Arc::from("?"));
1084 let qualified_name = entry
1085 .qualified_name
1086 .and_then(|id| self.graph.strings().resolve(id))
1087 .unwrap_or_else(|| std::sync::Arc::clone(&name));
1088
1089 let node_key = format!("n{}", node_id.index());
1090 let label = Self::escape_mermaid(&qualified_name);
1091
1092 let (open, close) = match entry.kind {
1094 NodeKind::Class | NodeKind::Struct => ("[[", "]]"),
1095 NodeKind::Interface | NodeKind::Trait => ("([", "])"),
1096 NodeKind::Module => ("{{", "}}"),
1097 _ => ("[", "]"),
1098 };
1099
1100 writeln!(mermaid, " {node_key}{open}\"{label}\"{close}")
1101 .expect("write to String never fails");
1102 }
1103
1104 fn export_edge(&self, mermaid: &mut String, from: NodeId, to: NodeId, kind: &EdgeKind) {
1106 let from_key = format!("n{}", from.index());
1107 let to_key = format!("n{}", to.index());
1108
1109 let arrow = match kind {
1110 EdgeKind::Imports { .. } | EdgeKind::Exports { .. } => "-.->",
1111 EdgeKind::Calls { is_async: true, .. } => "==>",
1112 _ => "-->",
1113 };
1114
1115 if self.config.show_edge_labels {
1116 let label = edge_label(kind, self.graph.strings());
1117 if label.is_empty() {
1118 writeln!(mermaid, " {from_key} {arrow} {to_key}")
1119 .expect("write to String never fails");
1120 } else {
1121 let label = Self::escape_mermaid(&label);
1122 writeln!(mermaid, " {from_key} {arrow}|\"{label}\"| {to_key}")
1123 .expect("write to String never fails");
1124 }
1125 } else {
1126 writeln!(mermaid, " {from_key} {arrow} {to_key}")
1127 .expect("write to String never fails");
1128 }
1129 }
1130
1131 fn escape_mermaid(s: &str) -> String {
1133 s.replace('"', "#quot;")
1134 .replace('<', "<")
1135 .replace('>', ">")
1136 }
1137}
1138
1139#[derive(Debug, Clone, Default)]
1145pub struct JsonConfig {
1146 pub include_details: bool,
1148 pub include_edge_metadata: bool,
1150}
1151
1152impl JsonConfig {
1153 #[must_use]
1155 pub fn with_details(mut self, enabled: bool) -> Self {
1156 self.include_details = enabled;
1157 self
1158 }
1159
1160 #[must_use]
1162 pub fn with_edge_metadata(mut self, enabled: bool) -> Self {
1163 self.include_edge_metadata = enabled;
1164 self
1165 }
1166}
1167
1168pub struct UnifiedJsonExporter<'a> {
1170 graph: &'a GraphSnapshot,
1171 config: JsonConfig,
1172}
1173
1174impl<'a> UnifiedJsonExporter<'a> {
1175 #[must_use]
1177 pub fn new(graph: &'a GraphSnapshot) -> Self {
1178 Self {
1179 graph,
1180 config: JsonConfig::default(),
1181 }
1182 }
1183
1184 #[must_use]
1186 pub fn with_config(graph: &'a GraphSnapshot, config: JsonConfig) -> Self {
1187 Self { graph, config }
1188 }
1189
1190 #[must_use]
1192 pub fn export(&self) -> serde_json::Value {
1193 let nodes = self.export_nodes();
1194 let edges = self.export_edges();
1195
1196 serde_json::json!({
1197 "nodes": nodes,
1198 "edges": edges,
1199 "metadata": {
1200 "node_count": nodes.len(),
1201 "edge_count": edges.len(),
1202 }
1203 })
1204 }
1205
1206 fn export_nodes(&self) -> Vec<serde_json::Value> {
1207 self.graph
1210 .iter_nodes()
1211 .filter(|(_, entry)| !entry.is_unified_loser())
1212 .map(|(node_id, entry)| self.export_node(node_id, entry))
1213 .collect()
1214 }
1215
1216 fn export_node(&self, node_id: NodeId, entry: &NodeEntry) -> serde_json::Value {
1217 let name = self
1218 .graph
1219 .strings()
1220 .resolve(entry.name)
1221 .map_or_else(|| "?".to_string(), |s| s.to_string());
1222 let qualified_name = entry
1223 .qualified_name
1224 .and_then(|id| self.graph.strings().resolve(id))
1225 .map_or_else(|| name.clone(), |s| s.to_string());
1226 let file = self
1227 .graph
1228 .files()
1229 .resolve(entry.file)
1230 .map_or_else(|| "?".to_string(), |p| p.to_string_lossy().into_owned());
1231 let lang = self
1232 .graph
1233 .files()
1234 .language_for_file(entry.file)
1235 .map_or_else(|| "Unknown".to_string(), |l| format!("{l:?}"));
1236
1237 let mut node = serde_json::json!({
1238 "id": format!("n{}", node_id.index()),
1239 "name": name,
1240 "qualified_name": qualified_name,
1241 "kind": format!("{:?}", entry.kind),
1242 "file": file,
1243 "language": lang,
1244 "line": entry.start_line,
1245 });
1246
1247 if self.config.include_details {
1248 self.append_node_details(entry, &mut node);
1249 }
1250
1251 node
1252 }
1253
1254 fn append_node_details(&self, entry: &NodeEntry, node: &mut serde_json::Value) {
1255 if let Some(sig_id) = entry.signature
1256 && let Some(sig) = self.graph.strings().resolve(sig_id)
1257 {
1258 node["signature"] = serde_json::Value::String(sig.to_string());
1259 }
1260 if let Some(doc_id) = entry.doc
1261 && let Some(doc) = self.graph.strings().resolve(doc_id)
1262 {
1263 node["doc"] = serde_json::Value::String(doc.to_string());
1264 }
1265 if let Some(vis_id) = entry.visibility
1266 && let Some(vis) = self.graph.strings().resolve(vis_id)
1267 {
1268 node["visibility"] = serde_json::Value::String(vis.to_string());
1269 }
1270 node["is_async"] = serde_json::Value::Bool(entry.is_async);
1271 node["is_static"] = serde_json::Value::Bool(entry.is_static);
1272 }
1273
1274 fn export_edges(&self) -> Vec<serde_json::Value> {
1275 self.graph
1276 .iter_edges()
1277 .map(|(from, to, kind)| self.export_edge(from, to, &kind))
1278 .collect()
1279 }
1280
1281 fn export_edge(&self, from: NodeId, to: NodeId, kind: &EdgeKind) -> serde_json::Value {
1282 let from_key = format!("n{}", from.index());
1283 let to_key = format!("n{}", to.index());
1284
1285 let mut edge = serde_json::json!({
1286 "from": from_key,
1287 "to": to_key,
1288 "kind": Self::edge_kind_name(kind),
1289 });
1290
1291 if self.config.include_edge_metadata {
1292 self.append_edge_metadata(kind, &mut edge);
1293 }
1294
1295 edge
1296 }
1297
1298 fn append_edge_metadata(&self, kind: &EdgeKind, edge: &mut serde_json::Value) {
1299 match kind {
1300 EdgeKind::Calls {
1301 argument_count,
1302 is_async,
1303 ..
1304 } => {
1305 edge["argument_count"] = serde_json::Value::Number((*argument_count).into());
1306 edge["is_async"] = serde_json::Value::Bool(*is_async);
1307 }
1308 EdgeKind::Imports { alias, is_wildcard } => {
1309 edge["is_wildcard"] = serde_json::Value::Bool(*is_wildcard);
1310 if let Some(alias_id) = alias
1311 && let Some(alias_str) = self.graph.strings().resolve(*alias_id)
1312 {
1313 edge["alias"] = serde_json::Value::String(alias_str.to_string());
1314 }
1315 }
1316 EdgeKind::Exports {
1317 kind: export_kind,
1318 alias,
1319 } => {
1320 edge["export_kind"] = serde_json::Value::String(format!("{export_kind:?}"));
1321 if let Some(alias_id) = alias
1322 && let Some(alias_str) = self.graph.strings().resolve(*alias_id)
1323 {
1324 edge["alias"] = serde_json::Value::String(alias_str.to_string());
1325 }
1326 }
1327 EdgeKind::HttpRequest { method, url } => {
1328 edge["method"] = serde_json::Value::String(method.as_str().to_string());
1329 if let Some(url_id) = url
1330 && let Some(url_str) = self.graph.strings().resolve(*url_id)
1331 {
1332 edge["url"] = serde_json::Value::String(url_str.to_string());
1333 }
1334 }
1335 _ => {}
1336 }
1337 }
1338
1339 fn edge_kind_name(kind: &EdgeKind) -> &'static str {
1341 match kind {
1342 EdgeKind::Defines => "defines",
1343 EdgeKind::Contains => "contains",
1344 EdgeKind::Calls { .. } => "calls",
1345 EdgeKind::References => "references",
1346 EdgeKind::Imports { .. } => "imports",
1347 EdgeKind::Exports { .. } => "exports",
1348 EdgeKind::TypeOf { .. } => "type_of",
1349 EdgeKind::Inherits => "inherits",
1350 EdgeKind::Implements => "implements",
1351 EdgeKind::FfiCall { .. } => "ffi_call",
1352 EdgeKind::HttpRequest { .. } => "http_request",
1353 EdgeKind::GrpcCall { .. } => "grpc_call",
1354 EdgeKind::WebAssemblyCall => "wasm_call",
1355 EdgeKind::DbQuery { .. } => "db_query",
1356 EdgeKind::TableRead { .. } => "table_read",
1357 EdgeKind::TableWrite { .. } => "table_write",
1358 EdgeKind::TriggeredBy { .. } => "triggered_by",
1359 EdgeKind::MessageQueue { .. } => "message_queue",
1360 EdgeKind::WebSocket { .. } => "websocket",
1361 EdgeKind::GraphQLOperation { .. } => "graphql_operation",
1362 EdgeKind::ProcessExec { .. } => "process_exec",
1363 EdgeKind::FileIpc { .. } => "file_ipc",
1364 EdgeKind::ProtocolCall { .. } => "protocol_call",
1365 EdgeKind::LifetimeConstraint { .. } => "lifetime_constraint",
1367 EdgeKind::TraitMethodBinding { .. } => "trait_method_binding",
1368 EdgeKind::MacroExpansion { .. } => "macro_expansion",
1369 EdgeKind::GenericBound => "generic_bound",
1371 EdgeKind::AnnotatedWith => "annotated_with",
1372 EdgeKind::AnnotationParam => "annotation_param",
1373 EdgeKind::LambdaCaptures => "lambda_captures",
1374 EdgeKind::ModuleExports => "module_exports",
1375 EdgeKind::ModuleRequires => "module_requires",
1376 EdgeKind::ModuleOpens => "module_opens",
1377 EdgeKind::ModuleProvides => "module_provides",
1378 EdgeKind::TypeArgument => "type_argument",
1379 EdgeKind::ExtensionReceiver => "extension_receiver",
1380 EdgeKind::CompanionOf => "companion_of",
1381 EdgeKind::SealedPermit => "sealed_permit",
1382 EdgeKind::Wraps { .. } => "wraps",
1384 }
1385 }
1386}
1387
1388#[cfg(test)]
1389mod tests {
1390 use super::*;
1391
1392 #[test]
1395 fn test_direction_as_str() {
1396 assert_eq!(Direction::LeftToRight.as_str(), "LR");
1397 assert_eq!(Direction::TopToBottom.as_str(), "TB");
1398 }
1399
1400 #[test]
1401 fn test_direction_default() {
1402 assert_eq!(Direction::default(), Direction::LeftToRight);
1403 }
1404
1405 #[test]
1408 fn test_edge_filter_matches_calls() {
1409 assert!(EdgeFilter::Calls.matches(&EdgeKind::Calls {
1410 argument_count: 0,
1411 is_async: false,
1412 resolved_via: ResolvedVia::Direct,
1413 }));
1414 assert!(EdgeFilter::Calls.matches(&EdgeKind::Calls {
1415 argument_count: 5,
1416 is_async: true,
1417 resolved_via: ResolvedVia::Direct,
1418 }));
1419 assert!(!EdgeFilter::Calls.matches(&EdgeKind::References));
1420 }
1421
1422 #[test]
1423 fn test_edge_filter_matches_imports() {
1424 assert!(EdgeFilter::Imports.matches(&EdgeKind::Imports {
1425 alias: None,
1426 is_wildcard: false
1427 }));
1428 assert!(EdgeFilter::Imports.matches(&EdgeKind::Imports {
1429 alias: None,
1430 is_wildcard: true
1431 }));
1432 assert!(!EdgeFilter::Imports.matches(&EdgeKind::Exports {
1433 kind: crate::graph::unified::edge::ExportKind::Direct,
1434 alias: None
1435 }));
1436 }
1437
1438 #[test]
1439 fn test_edge_filter_matches_exports() {
1440 assert!(EdgeFilter::Exports.matches(&EdgeKind::Exports {
1441 kind: crate::graph::unified::edge::ExportKind::Direct,
1442 alias: None
1443 }));
1444 assert!(!EdgeFilter::Exports.matches(&EdgeKind::Imports {
1445 alias: None,
1446 is_wildcard: false
1447 }));
1448 }
1449
1450 #[test]
1451 fn test_edge_filter_matches_references() {
1452 assert!(EdgeFilter::References.matches(&EdgeKind::References));
1453 assert!(!EdgeFilter::References.matches(&EdgeKind::Calls {
1454 argument_count: 0,
1455 is_async: false,
1456 resolved_via: ResolvedVia::Direct,
1457 }));
1458 }
1459
1460 #[test]
1461 fn test_edge_filter_matches_inheritance() {
1462 assert!(EdgeFilter::Inherits.matches(&EdgeKind::Inherits));
1463 assert!(EdgeFilter::Implements.matches(&EdgeKind::Implements));
1464 assert!(!EdgeFilter::Inherits.matches(&EdgeKind::Implements));
1465 assert!(!EdgeFilter::Implements.matches(&EdgeKind::Inherits));
1466 }
1467
1468 #[test]
1469 fn test_edge_filter_matches_cross_language() {
1470 assert!(EdgeFilter::FfiCall.matches(&EdgeKind::FfiCall {
1471 convention: crate::graph::unified::edge::FfiConvention::C
1472 }));
1473 assert!(EdgeFilter::HttpRequest.matches(&EdgeKind::HttpRequest {
1474 method: crate::graph::unified::edge::HttpMethod::Get,
1475 url: None
1476 }));
1477 assert!(EdgeFilter::DbQuery.matches(&EdgeKind::DbQuery {
1478 query_type: crate::graph::unified::edge::DbQueryType::Select,
1479 table: None
1480 }));
1481 }
1482
1483 #[test]
1486 fn test_language_color_common_languages() {
1487 assert_eq!(language_color(Language::Rust), "#dea584");
1488 assert_eq!(language_color(Language::JavaScript), "#f7df1e");
1489 assert_eq!(language_color(Language::TypeScript), "#3178c6");
1490 assert_eq!(language_color(Language::Python), "#3572A5");
1491 assert_eq!(language_color(Language::Go), "#00ADD8");
1492 assert_eq!(language_color(Language::Java), "#b07219");
1493 }
1494
1495 #[test]
1496 fn test_language_color_all_languages() {
1497 let languages = [
1499 Language::Rust,
1500 Language::JavaScript,
1501 Language::TypeScript,
1502 Language::Python,
1503 Language::Go,
1504 Language::Java,
1505 Language::Ruby,
1506 Language::Php,
1507 Language::Cpp,
1508 Language::C,
1509 Language::Swift,
1510 Language::Kotlin,
1511 Language::Scala,
1512 Language::Sql,
1513 Language::Plsql,
1514 Language::Shell,
1515 Language::Lua,
1516 Language::Perl,
1517 Language::Dart,
1518 Language::Groovy,
1519 Language::Http,
1520 Language::Css,
1521 Language::Elixir,
1522 Language::R,
1523 Language::Haskell,
1524 Language::Html,
1525 Language::Svelte,
1526 Language::Vue,
1527 Language::Zig,
1528 Language::Terraform,
1529 Language::Puppet,
1530 Language::Apex,
1531 Language::Abap,
1532 Language::ServiceNow,
1533 Language::CSharp,
1534 ];
1535 for lang in languages {
1536 let color = language_color(lang);
1537 assert!(color.starts_with('#'), "Color for {lang:?} should be hex");
1538 }
1539 }
1540
1541 #[test]
1542 fn test_default_language_color() {
1543 assert_eq!(default_language_color(), "#cccccc");
1544 }
1545
1546 #[test]
1549 fn test_node_shape_class_types() {
1550 assert_eq!(node_shape(&NodeKind::Class), "component");
1551 assert_eq!(node_shape(&NodeKind::Struct), "component");
1552 }
1553
1554 #[test]
1555 fn test_node_shape_interface_types() {
1556 assert_eq!(node_shape(&NodeKind::Interface), "ellipse");
1557 assert_eq!(node_shape(&NodeKind::Trait), "ellipse");
1558 }
1559
1560 #[test]
1561 fn test_node_shape_module() {
1562 assert_eq!(node_shape(&NodeKind::Module), "folder");
1563 }
1564
1565 #[test]
1566 fn test_node_shape_variables() {
1567 assert_eq!(node_shape(&NodeKind::Variable), "note");
1568 assert_eq!(node_shape(&NodeKind::Constant), "note");
1569 }
1570
1571 #[test]
1572 fn test_node_shape_enums() {
1573 assert_eq!(node_shape(&NodeKind::Enum), "hexagon");
1574 assert_eq!(node_shape(&NodeKind::EnumVariant), "hexagon");
1575 }
1576
1577 #[test]
1578 fn test_node_shape_special() {
1579 assert_eq!(node_shape(&NodeKind::Type), "diamond");
1580 assert_eq!(node_shape(&NodeKind::Macro), "parallelogram");
1581 }
1582
1583 #[test]
1584 fn test_node_shape_default() {
1585 assert_eq!(node_shape(&NodeKind::Function), "box");
1586 assert_eq!(node_shape(&NodeKind::Method), "box");
1587 }
1588
1589 #[test]
1592 fn test_edge_style_calls() {
1593 let (style, color) = edge_style(&EdgeKind::Calls {
1594 argument_count: 0,
1595 is_async: false,
1596 resolved_via: ResolvedVia::Direct,
1597 });
1598 assert_eq!(style, "solid");
1599 assert_eq!(color, "#333333");
1600 }
1601
1602 #[test]
1603 fn test_edge_style_imports_exports() {
1604 let (style, color) = edge_style(&EdgeKind::Imports {
1605 alias: None,
1606 is_wildcard: false,
1607 });
1608 assert_eq!(style, "dashed");
1609 assert_eq!(color, "#0066cc");
1610
1611 let (style, color) = edge_style(&EdgeKind::Exports {
1612 kind: crate::graph::unified::edge::ExportKind::Direct,
1613 alias: None,
1614 });
1615 assert_eq!(style, "dashed");
1616 assert_eq!(color, "#00cc66");
1617 }
1618
1619 #[test]
1620 fn test_edge_style_references() {
1621 let (style, color) = edge_style(&EdgeKind::References);
1622 assert_eq!(style, "dotted");
1623 assert_eq!(color, "#666666");
1624 }
1625
1626 #[test]
1627 fn test_edge_style_inheritance() {
1628 let (style, color) = edge_style(&EdgeKind::Inherits);
1629 assert_eq!(style, "solid");
1630 assert_eq!(color, "#990099");
1631
1632 let (style, color) = edge_style(&EdgeKind::Implements);
1633 assert_eq!(style, "dashed");
1634 assert_eq!(color, "#990099");
1635 }
1636
1637 #[test]
1638 fn test_edge_style_cross_language() {
1639 let (style, color) = edge_style(&EdgeKind::FfiCall {
1640 convention: crate::graph::unified::edge::FfiConvention::C,
1641 });
1642 assert_eq!(style, "bold");
1643 assert_eq!(color, "#ff6600");
1644
1645 let (style, color) = edge_style(&EdgeKind::HttpRequest {
1646 method: crate::graph::unified::edge::HttpMethod::Get,
1647 url: None,
1648 });
1649 assert_eq!(style, "bold");
1650 assert_eq!(color, "#cc0000");
1651
1652 let (style, color) = edge_style(&EdgeKind::DbQuery {
1653 query_type: crate::graph::unified::edge::DbQueryType::Select,
1654 table: None,
1655 });
1656 assert_eq!(style, "bold");
1657 assert_eq!(color, "#009900");
1658 }
1659
1660 #[test]
1663 fn test_escape_dot_basic() {
1664 assert_eq!(escape_dot("hello"), "hello");
1665 assert_eq!(escape_dot("hello world"), "hello world");
1666 }
1667
1668 #[test]
1669 fn test_escape_dot_quotes() {
1670 assert_eq!(escape_dot("say \"hi\""), "say \\\"hi\\\"");
1671 assert_eq!(escape_dot("\"quoted\""), "\\\"quoted\\\"");
1672 }
1673
1674 #[test]
1675 fn test_escape_dot_newlines() {
1676 assert_eq!(escape_dot("line1\nline2"), "line1\\nline2");
1677 assert_eq!(escape_dot("a\nb\nc"), "a\\nb\\nc");
1678 }
1679
1680 #[test]
1681 fn test_escape_dot_backslashes() {
1682 assert_eq!(escape_dot("path\\to\\file"), "path\\\\to\\\\file");
1683 }
1684
1685 #[test]
1686 fn test_escape_d2_basic() {
1687 assert_eq!(escape_d2("hello"), "hello");
1688 assert_eq!(escape_d2("hello world"), "hello world");
1689 }
1690
1691 #[test]
1692 fn test_escape_d2_quotes_and_newlines() {
1693 assert_eq!(escape_d2("say \"hi\""), "say \\\"hi\\\"");
1695 assert_eq!(escape_d2("line1\nline2"), "line1 line2");
1696 assert_eq!(escape_d2("path\\to\\file"), "path\\\\to\\\\file");
1697 }
1698
1699 #[test]
1702 fn test_dot_config_default() {
1703 let config = DotConfig::default();
1704 assert_eq!(config.direction, Direction::LeftToRight);
1705 assert!(!config.highlight_cross_language);
1706 assert!(config.show_details); assert!(config.show_edge_labels); assert!(config.filter_node_ids.is_none());
1709 assert!(config.filter_languages.is_empty());
1710 assert!(config.filter_edges.is_empty());
1711 assert!(config.filter_files.is_empty());
1712 }
1713
1714 #[test]
1715 fn test_dot_config_builder() {
1716 let config = DotConfig::default()
1717 .with_direction(Direction::TopToBottom)
1718 .with_cross_language_highlight(true)
1719 .with_details(true);
1720 assert_eq!(config.direction, Direction::TopToBottom);
1721 assert!(config.highlight_cross_language);
1722 assert!(config.show_details);
1723
1724 let mut ids = HashSet::new();
1726 ids.insert(NodeId::new(0, 0));
1727 let config_with_filter = DotConfig::default().with_filter_node_ids(Some(ids.clone()));
1728 assert!(config_with_filter.filter_node_ids.is_some());
1729 assert_eq!(config_with_filter.filter_node_ids.as_ref().unwrap(), &ids);
1730
1731 let config_cleared = config_with_filter.with_filter_node_ids(None);
1732 assert!(config_cleared.filter_node_ids.is_none());
1733 }
1734
1735 #[test]
1736 fn test_d2_config_default() {
1737 let config = D2Config::default();
1738 assert_eq!(config.direction, Direction::LeftToRight);
1739 assert!(!config.highlight_cross_language);
1740 assert!(config.show_details); assert!(config.show_edge_labels); assert!(config.filter_node_ids.is_none());
1743 assert!(config.filter_languages.is_empty());
1744 assert!(config.filter_edges.is_empty());
1745 }
1746
1747 #[test]
1748 fn test_d2_config_builder() {
1749 let config = D2Config::default()
1750 .with_cross_language_highlight(true)
1751 .with_details(true)
1752 .with_edge_labels(true);
1753 assert!(config.highlight_cross_language);
1754 assert!(config.show_details);
1755 assert!(config.show_edge_labels);
1756
1757 let mut ids = HashSet::new();
1759 ids.insert(NodeId::new(0, 0));
1760 let config_with_filter = D2Config::default().with_filter_node_ids(Some(ids.clone()));
1761 assert!(config_with_filter.filter_node_ids.is_some());
1762 assert_eq!(config_with_filter.filter_node_ids.as_ref().unwrap(), &ids);
1763
1764 let config_cleared = config_with_filter.with_filter_node_ids(None);
1765 assert!(config_cleared.filter_node_ids.is_none());
1766 }
1767
1768 #[test]
1769 fn test_mermaid_config_default() {
1770 let config = MermaidConfig::default();
1771 assert_eq!(config.direction, Direction::LeftToRight);
1772 assert!(!config.highlight_cross_language);
1773 assert!(config.show_edge_labels); assert!(config.filter_node_ids.is_none());
1775 assert!(config.filter_languages.is_empty());
1776 assert!(config.filter_edges.is_empty());
1777 }
1778
1779 #[test]
1780 fn test_mermaid_config_builder() {
1781 let config = MermaidConfig::default()
1782 .with_cross_language_highlight(true)
1783 .with_edge_labels(false);
1784 assert!(config.highlight_cross_language);
1785 assert!(!config.show_edge_labels);
1786
1787 let mut ids = HashSet::new();
1789 ids.insert(NodeId::new(0, 0));
1790 let config_with_filter = MermaidConfig::default().with_filter_node_ids(Some(ids.clone()));
1791 assert!(config_with_filter.filter_node_ids.is_some());
1792 assert_eq!(config_with_filter.filter_node_ids.as_ref().unwrap(), &ids);
1793
1794 let config_cleared = config_with_filter.with_filter_node_ids(None);
1795 assert!(config_cleared.filter_node_ids.is_none());
1796 }
1797
1798 #[test]
1799 fn test_json_config_builder() {
1800 let config = JsonConfig::default()
1801 .with_details(true)
1802 .with_edge_metadata(true);
1803 assert!(config.include_details);
1804 assert!(config.include_edge_metadata);
1805 }
1806
1807 use crate::graph::unified::concurrent::CodeGraph;
1812 use crate::graph::unified::edge::BidirectionalEdgeStore;
1813 use crate::graph::unified::storage::NodeEntry;
1814 use crate::graph::unified::storage::arena::NodeArena;
1815 use crate::graph::unified::storage::indices::AuxiliaryIndices;
1816 use crate::graph::unified::storage::interner::StringInterner;
1817 use crate::graph::unified::storage::registry::FileRegistry;
1818 use std::path::Path;
1819
1820 fn create_test_graph_for_export() -> CodeGraph {
1822 let mut nodes = NodeArena::new();
1823 let mut strings = StringInterner::new();
1824 let mut files = FileRegistry::new();
1825 let edges = BidirectionalEdgeStore::new();
1826 let indices = AuxiliaryIndices::new();
1827
1828 let file_id = files
1830 .register_with_language(Path::new("src/main.rs"), Some(Language::Rust))
1831 .unwrap();
1832
1833 let name_main = strings.intern("main").unwrap();
1835 let name_helper = strings.intern("helper").unwrap();
1836 let qname_main = strings.intern("app::main").unwrap();
1837 let qname_helper = strings.intern("app::helper").unwrap();
1838 let sig = strings.intern("fn main()").unwrap();
1839
1840 let main_entry = NodeEntry {
1842 kind: NodeKind::Function,
1843 name: name_main,
1844 file: file_id,
1845 start_byte: 0,
1846 end_byte: 100,
1847 start_line: 1,
1848 start_column: 0,
1849 end_line: 10,
1850 end_column: 1,
1851 signature: Some(sig),
1852 doc: None,
1853 qualified_name: Some(qname_main),
1854 visibility: None,
1855 is_async: false,
1856 is_static: false,
1857 is_unsafe: false,
1858 body_hash: None,
1859 };
1860 let main_id = nodes.alloc(main_entry).unwrap();
1861
1862 let helper_entry = NodeEntry {
1863 kind: NodeKind::Function,
1864 name: name_helper,
1865 file: file_id,
1866 start_byte: 100,
1867 end_byte: 200,
1868 start_line: 11,
1869 start_column: 0,
1870 end_line: 20,
1871 end_column: 1,
1872 signature: None,
1873 doc: None,
1874 qualified_name: Some(qname_helper),
1875 visibility: None,
1876 is_async: true,
1877 is_static: false,
1878 is_unsafe: false,
1879 body_hash: None,
1880 };
1881 let helper_id = nodes.alloc(helper_entry).unwrap();
1882
1883 edges.add_edge(
1885 main_id,
1886 helper_id,
1887 EdgeKind::Calls {
1888 argument_count: 2,
1889 is_async: false,
1890 resolved_via: ResolvedVia::Direct,
1891 },
1892 file_id,
1893 );
1894
1895 CodeGraph::from_components(
1896 nodes,
1897 edges,
1898 strings,
1899 files,
1900 indices,
1901 crate::graph::unified::NodeMetadataStore::new(),
1902 )
1903 }
1904
1905 #[test]
1908 fn test_unified_dot_exporter_basic() {
1909 let graph = create_test_graph_for_export();
1910 let snapshot = graph.snapshot();
1911 let exporter = UnifiedDotExporter::new(&snapshot);
1912 let output = exporter.export();
1913
1914 assert!(output.starts_with("digraph CodeGraph {"));
1916 assert!(output.ends_with("}\n"));
1917 assert!(output.contains("rankdir=LR"));
1918 }
1919
1920 #[test]
1921 fn test_unified_dot_exporter_with_config() {
1922 let graph = create_test_graph_for_export();
1923 let snapshot = graph.snapshot();
1924 let config = DotConfig::default()
1925 .with_direction(Direction::TopToBottom)
1926 .with_cross_language_highlight(true)
1927 .with_details(true);
1928 let exporter = UnifiedDotExporter::with_config(&snapshot, config);
1929 let output = exporter.export();
1930
1931 assert!(output.contains("rankdir=TB"));
1932 }
1933
1934 #[test]
1935 fn test_unified_dot_exporter_contains_nodes() {
1936 let graph = create_test_graph_for_export();
1937 let snapshot = graph.snapshot();
1938 let exporter = UnifiedDotExporter::new(&snapshot);
1939 let output = exporter.export();
1940
1941 assert!(output.contains("n0"), "Should contain first node");
1943 assert!(output.contains("n1"), "Should contain second node");
1944 assert!(
1946 output.contains("main") || output.contains("app::main"),
1947 "Should contain main function name"
1948 );
1949 }
1950
1951 #[test]
1952 fn test_unified_dot_exporter_contains_edges() {
1953 let graph = create_test_graph_for_export();
1954 let snapshot = graph.snapshot();
1955 let exporter = UnifiedDotExporter::new(&snapshot);
1956 let output = exporter.export();
1957
1958 assert!(output.contains("->"), "Should contain edge arrow");
1960 }
1961
1962 #[test]
1963 fn test_unified_dot_exporter_empty_graph() {
1964 let graph = CodeGraph::new();
1965 let snapshot = graph.snapshot();
1966 let exporter = UnifiedDotExporter::new(&snapshot);
1967 let output = exporter.export();
1968
1969 assert!(output.starts_with("digraph CodeGraph {"));
1970 assert!(output.ends_with("}\n"));
1971 assert!(!output.contains("n0"));
1973 }
1974
1975 #[test]
1978 fn test_unified_d2_exporter_basic() {
1979 let graph = create_test_graph_for_export();
1980 let snapshot = graph.snapshot();
1981 let exporter = UnifiedD2Exporter::new(&snapshot);
1982 let output = exporter.export();
1983
1984 assert!(output.contains("direction: LR"));
1986 }
1987
1988 #[test]
1989 fn test_unified_d2_exporter_with_config() {
1990 let graph = create_test_graph_for_export();
1991 let snapshot = graph.snapshot();
1992 let config = D2Config::default().with_cross_language_highlight(true);
1993 let exporter = UnifiedD2Exporter::with_config(&snapshot, config);
1994 let output = exporter.export();
1995
1996 assert!(output.contains("direction:"));
1997 }
1998
1999 #[test]
2000 fn test_unified_d2_exporter_contains_nodes() {
2001 let graph = create_test_graph_for_export();
2002 let snapshot = graph.snapshot();
2003 let exporter = UnifiedD2Exporter::new(&snapshot);
2004 let output = exporter.export();
2005
2006 assert!(
2008 output.contains("n0:"),
2009 "Should contain first node definition"
2010 );
2011 assert!(
2012 output.contains("n1:"),
2013 "Should contain second node definition"
2014 );
2015 }
2016
2017 #[test]
2018 fn test_unified_d2_exporter_contains_edges() {
2019 let graph = create_test_graph_for_export();
2020 let snapshot = graph.snapshot();
2021 let exporter = UnifiedD2Exporter::new(&snapshot);
2022 let output = exporter.export();
2023
2024 assert!(
2026 output.contains("->") || output.contains("<->"),
2027 "Should contain edge"
2028 );
2029 }
2030
2031 #[test]
2034 fn test_unified_mermaid_exporter_basic() {
2035 let graph = create_test_graph_for_export();
2036 let snapshot = graph.snapshot();
2037 let exporter = UnifiedMermaidExporter::new(&snapshot);
2038 let output = exporter.export();
2039
2040 assert!(output.starts_with("graph LR"));
2042 }
2043
2044 #[test]
2045 fn test_unified_mermaid_exporter_with_config() {
2046 let graph = create_test_graph_for_export();
2047 let snapshot = graph.snapshot();
2048 let config = MermaidConfig::default()
2049 .with_cross_language_highlight(true)
2050 .with_edge_labels(false);
2051 let exporter = UnifiedMermaidExporter::with_config(&snapshot, config);
2052 let output = exporter.export();
2053
2054 assert!(output.starts_with("graph LR"));
2055 }
2056
2057 #[test]
2058 fn test_unified_mermaid_exporter_contains_nodes() {
2059 let graph = create_test_graph_for_export();
2060 let snapshot = graph.snapshot();
2061 let exporter = UnifiedMermaidExporter::new(&snapshot);
2062 let output = exporter.export();
2063
2064 assert!(output.contains("n0"), "Should contain first node");
2066 assert!(output.contains("n1"), "Should contain second node");
2067 }
2068
2069 #[test]
2070 fn test_unified_mermaid_exporter_contains_edges() {
2071 let graph = create_test_graph_for_export();
2072 let snapshot = graph.snapshot();
2073 let exporter = UnifiedMermaidExporter::new(&snapshot);
2074 let output = exporter.export();
2075
2076 assert!(
2078 output.contains("-->") || output.contains("==>") || output.contains("-.->"),
2079 "Should contain edge"
2080 );
2081 }
2082
2083 #[test]
2086 fn test_unified_json_exporter_basic() {
2087 let graph = create_test_graph_for_export();
2088 let snapshot = graph.snapshot();
2089 let exporter = UnifiedJsonExporter::new(&snapshot);
2090 let output = exporter.export();
2091
2092 assert!(output.is_object());
2094 assert!(output.get("nodes").is_some());
2095 assert!(output.get("edges").is_some());
2096 assert!(output.get("metadata").is_some());
2097 }
2098
2099 #[test]
2100 fn test_unified_json_exporter_node_count() {
2101 let graph = create_test_graph_for_export();
2102 let snapshot = graph.snapshot();
2103 let exporter = UnifiedJsonExporter::new(&snapshot);
2104 let output = exporter.export();
2105
2106 let nodes = output.get("nodes").unwrap().as_array().unwrap();
2107 assert_eq!(nodes.len(), 2, "Should have 2 nodes");
2108 }
2109
2110 #[test]
2111 fn test_unified_json_exporter_edge_count() {
2112 let graph = create_test_graph_for_export();
2113 let snapshot = graph.snapshot();
2114 let exporter = UnifiedJsonExporter::new(&snapshot);
2115 let output = exporter.export();
2116
2117 let edges = output.get("edges").unwrap().as_array().unwrap();
2118 assert_eq!(edges.len(), 1, "Should have 1 edge");
2119 }
2120
2121 #[test]
2122 fn test_unified_json_exporter_metadata() {
2123 let graph = create_test_graph_for_export();
2124 let snapshot = graph.snapshot();
2125 let exporter = UnifiedJsonExporter::new(&snapshot);
2126 let output = exporter.export();
2127
2128 let metadata = output.get("metadata").unwrap();
2129 assert_eq!(
2130 metadata.get("node_count").unwrap().as_u64().unwrap(),
2131 2,
2132 "Metadata should report 2 nodes"
2133 );
2134 assert_eq!(
2135 metadata.get("edge_count").unwrap().as_u64().unwrap(),
2136 1,
2137 "Metadata should report 1 edge"
2138 );
2139 }
2140
2141 #[test]
2142 fn test_unified_json_exporter_with_details() {
2143 let graph = create_test_graph_for_export();
2144 let snapshot = graph.snapshot();
2145 let config = JsonConfig::default().with_details(true);
2146 let exporter = UnifiedJsonExporter::with_config(&snapshot, config);
2147 let output = exporter.export();
2148
2149 let nodes = output.get("nodes").unwrap().as_array().unwrap();
2150 let main_node = &nodes[0];
2152 assert!(
2153 main_node.get("signature").is_some(),
2154 "Node should have signature when details enabled"
2155 );
2156 }
2157
2158 #[test]
2159 fn test_unified_json_exporter_with_edge_metadata() {
2160 let graph = create_test_graph_for_export();
2161 let snapshot = graph.snapshot();
2162 let config = JsonConfig::default().with_edge_metadata(true);
2163 let exporter = UnifiedJsonExporter::with_config(&snapshot, config);
2164 let output = exporter.export();
2165
2166 let edges = output.get("edges").unwrap().as_array().unwrap();
2167 let edge = &edges[0];
2168 assert!(
2170 edge.get("argument_count").is_some(),
2171 "Edge should have argument_count metadata"
2172 );
2173 }
2174
2175 #[test]
2176 fn test_unified_json_exporter_empty_graph() {
2177 let graph = CodeGraph::new();
2178 let snapshot = graph.snapshot();
2179 let exporter = UnifiedJsonExporter::new(&snapshot);
2180 let output = exporter.export();
2181
2182 let nodes = output.get("nodes").unwrap().as_array().unwrap();
2183 let edges = output.get("edges").unwrap().as_array().unwrap();
2184 assert!(nodes.is_empty(), "Empty graph should have no nodes");
2185 assert!(edges.is_empty(), "Empty graph should have no edges");
2186 }
2187
2188 #[test]
2191 fn test_edge_label_calls() {
2192 let strings = StringInterner::new();
2193 let label = edge_label(
2194 &EdgeKind::Calls {
2195 argument_count: 3,
2196 is_async: false,
2197 resolved_via: ResolvedVia::Direct,
2198 },
2199 &strings,
2200 );
2201 assert_eq!(label, "call(3)");
2202 }
2203
2204 #[test]
2205 fn test_edge_label_async_calls() {
2206 let strings = StringInterner::new();
2207 let label = edge_label(
2208 &EdgeKind::Calls {
2209 argument_count: 2,
2210 is_async: true,
2211 resolved_via: ResolvedVia::Direct,
2212 },
2213 &strings,
2214 );
2215 assert_eq!(label, "async call(2)");
2216 }
2217
2218 #[test]
2219 fn test_edge_label_imports_simple() {
2220 let strings = StringInterner::new();
2221 let label = edge_label(
2222 &EdgeKind::Imports {
2223 alias: None,
2224 is_wildcard: false,
2225 },
2226 &strings,
2227 );
2228 assert_eq!(label, "import");
2229 }
2230
2231 #[test]
2232 fn test_edge_label_imports_wildcard() {
2233 let strings = StringInterner::new();
2234 let label = edge_label(
2235 &EdgeKind::Imports {
2236 alias: None,
2237 is_wildcard: true,
2238 },
2239 &strings,
2240 );
2241 assert_eq!(label, "import *");
2242 }
2243
2244 #[test]
2245 fn test_edge_label_references() {
2246 let strings = StringInterner::new();
2247 let label = edge_label(&EdgeKind::References, &strings);
2248 assert_eq!(label, "ref");
2249 }
2250
2251 #[test]
2252 fn test_edge_label_inherits() {
2253 let strings = StringInterner::new();
2254 let label = edge_label(&EdgeKind::Inherits, &strings);
2255 assert_eq!(label, "extends");
2256 }
2257
2258 #[test]
2259 fn test_edge_label_implements() {
2260 let strings = StringInterner::new();
2261 let label = edge_label(&EdgeKind::Implements, &strings);
2262 assert_eq!(label, "implements");
2263 }
2264
2265 #[test]
2268 fn test_mermaid_filter_node_ids_restricts_output() {
2269 let graph = create_test_graph_for_export();
2270 let snapshot = graph.snapshot();
2271
2272 let all_nodes: Vec<NodeId> = snapshot.iter_nodes().map(|(id, _)| id).collect();
2274 assert!(
2275 all_nodes.len() >= 2,
2276 "test graph must have at least 2 nodes"
2277 );
2278
2279 let kept_id = all_nodes[0];
2281 let expected_key = format!("n{}", kept_id.index());
2282 let excluded_key = format!("n{}", all_nodes[1].index());
2284
2285 let mut filter = HashSet::new();
2286 filter.insert(kept_id);
2287
2288 let config = MermaidConfig::default().with_filter_node_ids(Some(filter));
2289 let exporter = UnifiedMermaidExporter::with_config(&snapshot, config);
2290 let output = exporter.export();
2291
2292 let node_defs: Vec<&str> = output
2294 .lines()
2295 .filter(|l| l.trim_start().starts_with('n') && l.contains('['))
2296 .collect();
2297
2298 assert_eq!(
2299 node_defs.len(),
2300 1,
2301 "filtered export should have exactly 1 node, got: {node_defs:?}"
2302 );
2303
2304 assert!(
2306 node_defs[0].trim_start().starts_with(&expected_key),
2307 "expected node key '{expected_key}' but got: {}",
2308 node_defs[0]
2309 );
2310
2311 let excluded_present = output
2313 .lines()
2314 .any(|l| l.trim_start().starts_with(&excluded_key));
2315 assert!(
2316 !excluded_present,
2317 "excluded node key '{excluded_key}' must not appear in filtered output"
2318 );
2319
2320 let edge_lines: Vec<&str> = output
2322 .lines()
2323 .filter(|l| l.contains("-->") || l.contains("---"))
2324 .collect();
2325 assert!(
2326 edge_lines.is_empty(),
2327 "no edges should appear when only one node is visible, got: {edge_lines:?}"
2328 );
2329 }
2330
2331 #[test]
2334 fn test_d2_filter_node_ids_restricts_output() {
2335 let graph = create_test_graph_for_export();
2336 let snapshot = graph.snapshot();
2337
2338 let all_nodes: Vec<NodeId> = snapshot.iter_nodes().map(|(id, _)| id).collect();
2340 assert!(
2341 all_nodes.len() >= 2,
2342 "test graph must have at least 2 nodes"
2343 );
2344
2345 let kept_id = all_nodes[0];
2347 let expected_key = format!("n{}:", kept_id.index());
2348 let excluded_key = format!("n{}:", all_nodes[1].index());
2350
2351 let mut filter = HashSet::new();
2352 filter.insert(kept_id);
2353
2354 let config = D2Config::default().with_filter_node_ids(Some(filter));
2355 let exporter = UnifiedD2Exporter::with_config(&snapshot, config);
2356 let output = exporter.export();
2357
2358 let node_defs: Vec<&str> = output
2360 .lines()
2361 .filter(|l| {
2362 let trimmed = l.trim_start();
2363 (trimmed.starts_with('n') && trimmed.contains(": {"))
2364 || (trimmed.starts_with('n') && trimmed.contains(": \""))
2365 })
2366 .collect();
2367
2368 assert_eq!(
2369 node_defs.len(),
2370 1,
2371 "filtered export should have exactly 1 node, got: {node_defs:?}"
2372 );
2373
2374 assert!(
2376 node_defs[0].trim_start().starts_with(&expected_key),
2377 "expected node key '{expected_key}' but got: {}",
2378 node_defs[0]
2379 );
2380
2381 let excluded_present = output
2383 .lines()
2384 .any(|l| l.trim_start().starts_with(&excluded_key));
2385 assert!(
2386 !excluded_present,
2387 "excluded node key '{excluded_key}' must not appear in filtered output"
2388 );
2389
2390 let edge_lines: Vec<&str> = output
2392 .lines()
2393 .filter(|l| l.contains("->") || l.contains("<->"))
2394 .collect();
2395 assert!(
2396 edge_lines.is_empty(),
2397 "no edges should appear when only one node is visible, got: {edge_lines:?}"
2398 );
2399 }
2400
2401 #[test]
2404 fn test_dot_filter_node_ids_restricts_output() {
2405 let graph = create_test_graph_for_export();
2406 let snapshot = graph.snapshot();
2407
2408 let all_nodes: Vec<NodeId> = snapshot.iter_nodes().map(|(id, _)| id).collect();
2410 assert!(
2411 all_nodes.len() >= 2,
2412 "test graph must have at least 2 nodes"
2413 );
2414
2415 let kept_id = all_nodes[0];
2417 let expected_key = format!("\"n{}\"", kept_id.index());
2418 let excluded_key = format!("\"n{}\"", all_nodes[1].index());
2420
2421 let mut filter = HashSet::new();
2422 filter.insert(kept_id);
2423
2424 let config = DotConfig::default().with_filter_node_ids(Some(filter));
2425 let exporter = UnifiedDotExporter::with_config(&snapshot, config);
2426 let output = exporter.export();
2427
2428 let node_defs: Vec<&str> = output
2430 .lines()
2431 .filter(|l| {
2432 let trimmed = l.trim_start();
2433 trimmed.starts_with('"') && trimmed.contains("[label=")
2434 })
2435 .collect();
2436
2437 assert_eq!(
2438 node_defs.len(),
2439 1,
2440 "filtered export should have exactly 1 node, got: {node_defs:?}"
2441 );
2442
2443 assert!(
2445 node_defs[0].trim_start().starts_with(&expected_key),
2446 "expected node key '{expected_key}' but got: {}",
2447 node_defs[0]
2448 );
2449
2450 let excluded_present = output
2452 .lines()
2453 .any(|l| l.trim_start().starts_with(&excluded_key) && l.contains("[label="));
2454 assert!(
2455 !excluded_present,
2456 "excluded node key '{excluded_key}' must not appear in filtered output"
2457 );
2458
2459 let edge_lines: Vec<&str> = output.lines().filter(|l| l.contains("->")).collect();
2461 assert!(
2462 edge_lines.is_empty(),
2463 "no edges should appear when only one node is visible, got: {edge_lines:?}"
2464 );
2465 }
2466
2467 #[test]
2470 fn test_dot_config_filter_language() {
2471 let config = DotConfig::default().filter_language(Language::Rust);
2472 assert!(config.filter_languages.contains(&Language::Rust));
2473 }
2474
2475 #[test]
2476 fn test_dot_config_filter_edge() {
2477 let config = DotConfig::default().filter_edge(EdgeFilter::Calls);
2478 assert!(config.filter_edges.contains(&EdgeFilter::Calls));
2479 }
2480
2481 #[test]
2482 fn test_dot_config_with_max_depth() {
2483 let config = DotConfig::default().with_max_depth(5);
2484 assert_eq!(config.max_depth, Some(5));
2485 }
2486}