Skip to main content

source_mesh_core/export/
dot.rs

1use std::io::Write;
2
3use anyhow::Result;
4use graphviz_rust::dot_structures::Attribute;
5use graphviz_rust::dot_structures::Edge;
6use graphviz_rust::dot_structures::EdgeTy;
7use graphviz_rust::dot_structures::Graph;
8use graphviz_rust::dot_structures::Id;
9use graphviz_rust::dot_structures::Node;
10use graphviz_rust::dot_structures::NodeId;
11use graphviz_rust::dot_structures::Stmt as Statement;
12use graphviz_rust::dot_structures::Subgraph;
13use graphviz_rust::dot_structures::Vertex;
14use graphviz_rust::printer::DotPrinter as _;
15use graphviz_rust::printer::PrinterContext;
16
17use super::edge_style::CYCLE_EDGE_WIDTH;
18use super::edge_style::TEST_EDGE_COLOR;
19use super::edge_style::edge_label;
20use super::exporter::Exporter;
21use super::exporter::Options;
22use super::structure::Folder;
23use super::structure::IndexedGraph;
24use crate::cycle_presentation::group_color;
25use crate::model::DependencyKind;
26use crate::model::FolderGraph;
27
28pub struct Dot;
29
30impl Exporter for Dot {
31    fn write(&self, graph: &FolderGraph, output: &mut dyn Write) -> Result<()> {
32        self.write_with_options(graph, &Options::new(false, None), output)
33    }
34
35    fn write_grouped(&self, graph: &FolderGraph, output: &mut dyn Write) -> Result<()> {
36        self.write_with_options(graph, &Options::new(true, None), output)
37    }
38
39    fn write_with_options(&self, graph: &FolderGraph, options: &Options<'_>, output: &mut dyn Write) -> Result<()> {
40        let indexed_graph = IndexedGraph::with_cycles(graph, options.cycles())?;
41        let nodes = if options.group_folders() {
42            Folder::hierarchy(&indexed_graph)?.iter().map(folder_statement).collect()
43        } else {
44            indexed_graph.nodes().iter().map(|(label, &index)| node_statement(label, index)).collect()
45        };
46        write_graph(nodes, &indexed_graph, output)
47    }
48}
49
50#[must_use]
51fn node_identifier(index: usize) -> NodeId {
52    NodeId(Id::Plain(format!("n{index}")), None)
53}
54
55#[must_use]
56fn escaped_label(label: &str) -> Id {
57    // graphviz-rust prints Id::Escaped verbatim, including its quotes.
58    let label = label
59        .replace('\\', "\\\\")
60        .replace('"', "\\\"")
61        .replace('\n', "\\n")
62        .replace('\r', "\\r");
63    Id::Escaped(format!("\"{label}\""))
64}
65
66#[must_use]
67fn node_statement(label: &str, index: usize) -> Statement {
68    Statement::Node(Node::new(
69        node_identifier(index),
70        vec![
71            Attribute(Id::Plain("label".into()), escaped_label(label)),
72            Attribute(Id::Plain("shape".into()), Id::Plain("box".into())),
73        ],
74    ))
75}
76
77#[must_use]
78fn folder_statement(folder: &Folder<'_>) -> Statement {
79    if folder.children().is_empty() {
80        return node_statement(folder.display_label(), folder.index());
81    }
82    let mut statements = vec![Statement::Attribute(Attribute(
83        Id::Plain("label".into()), escaped_label(folder.display_label()),
84    ))];
85    if folder.dependency() {
86        statements.push(node_statement(folder.display_label(), folder.index()));
87    }
88    statements.extend(folder.children().iter().map(folder_statement));
89    Statement::Subgraph(Subgraph {
90        id: Id::Plain(format!("cluster_n{}", folder.index())),
91        stmts: statements,
92    })
93}
94
95fn write_graph(nodes: Vec<Statement>, graph: &IndexedGraph<'_>, output: &mut dyn Write) -> Result<()> {
96    let mut statements = vec![Statement::Attribute(Attribute(
97        Id::Plain("rankdir".into()), Id::Plain("LR".into()),
98    ))];
99    statements.extend(nodes);
100    statements.extend(graph.edges().iter().map(|edge| {
101        let mut attributes = vec![Attribute(
102            Id::Plain("label".into()), escaped_label(&edge_label(edge.kind(), edge.weight())),
103        )];
104        let color = edge.cycle_group().map(|group| group_color(group, graph.cycle_group_count()))
105            .or_else(|| (edge.kind() == DependencyKind::Test).then(|| TEST_EDGE_COLOR.to_owned()));
106        if let Some(color) = color {
107            attributes.push(Attribute(Id::Plain("color".into()), escaped_label(&color)));
108        }
109        if edge.kind() == DependencyKind::Test {
110            attributes.push(Attribute(Id::Plain("style".into()), Id::Plain("dashed".into())));
111        }
112        if let Some(group) = edge.cycle_group() {
113            attributes.push(Attribute(Id::Plain("penwidth".into()), Id::Plain(CYCLE_EDGE_WIDTH.into())));
114            attributes.push(Attribute(Id::Plain("cycle_group".into()), Id::Plain(group.number().to_string())));
115        }
116        Statement::Edge(Edge {
117            ty: EdgeTy::Pair(
118                Vertex::N(node_identifier(edge.source())),
119                Vertex::N(node_identifier(edge.target())),
120            ),
121            attributes,
122        })
123    }));
124    let dot_graph = Graph::DiGraph {
125        id: Id::Plain("folders".into()),
126        strict: graph.edges().iter().all(|edge| edge.kind() == DependencyKind::Production),
127        stmts: statements,
128    };
129    writeln!(output, "{}", dot_graph.print(&mut PrinterContext::default()))?;
130    Ok(())
131}