source-mesh-core 1.2.0

Rust dependency graph analysis, diagrams, and cycle reports
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
443
444
445
446
447
448
449
450
451
452
use std::collections::BTreeMap;
use std::io::Write;
use std::num::NonZeroUsize;
use std::slice;

use anyhow::Context as _;
use anyhow::Result;
use anyhow::ensure;
use askama::Template;
use colorous::Color;

use crate::color::RgbColor;
use crate::cycle_presentation::group_color;
use crate::export::rendering::edge_style::CYCLE_EDGE_WIDTH;
use crate::export::rendering::edge_style::COLOR_EDGE_TEST;
use crate::export::rendering::edge_style::edge_label;
use crate::export::rendering::edge_style::kind_name;
use crate::export::rendering::exporter::Exporter;
use crate::export::rendering::exporter::Options;
use crate::export::rendering::structure::Folder;
use crate::export::rendering::structure::FolderEvent;
use crate::export::rendering::structure::Hierarchy;
use crate::export::rendering::structure::IndexedGraph;
use crate::model::DependencyKind;
use crate::model::FolderGraph;

pub(in crate::export) const NAMESPACE_GRAPHML: &str = "http://graphml.graphdrawing.org/xmlns";
pub(in crate::export) const NAMESPACE_YWORKS: &str = "http://www.yworks.com/xml/graphml";
const COLOR_GRAPHICS_DEFAULT: RgbColor = RgbColor::new(Color { r: 0x47, g: 0x69, b: 0x9B });
const LAYOUT_OVERFLOW: &str = "GraphML layout exceeds the supported coordinate range";

pub struct GraphMl;

struct Position {
    horizontal: usize,
    vertical: usize,
}

struct NodeVisual<'label> {
    index: usize,
    label: &'label str,
    display_label: &'label str,
    position: Position,
    width: usize,
    height: usize,
}

impl<'label> NodeVisual<'label> {
    fn new(index: usize, label: &'label str, position: Position) -> Result<Self> {
        let longest_line = label.lines().map(|line| line.chars().count()).max().unwrap_or(0);
        let (width, height) = text_dimensions(longest_line, label.lines().count())?;
        Ok(Self { index, label, display_label: label, position, width, height })
    }

    fn child_position(&self) -> Result<Position> {
        Ok(Position {
            horizontal: self.position.horizontal.checked_add(20).context(LAYOUT_OVERFLOW)?,
            vertical: self.position.vertical.checked_add(self.height).context(LAYOUT_OVERFLOW)?,
        })
    }

    fn include_child(&mut self, child: &Self) -> Result<()> {
        self.width = self.width.max(child.width.checked_add(40).context(LAYOUT_OVERFLOW)?);
        let child_bottom = self.height.checked_add(child.height);
        self.height = child_bottom.and_then(|height| height.checked_add(20)).context(LAYOUT_OVERFLOW)?;
        Ok(())
    }

    fn next_root_vertical_position(&self) -> Result<usize> {
        let root_bottom = self.position.vertical.checked_add(self.height);
        root_bottom.and_then(|position| position.checked_add(40)).context(LAYOUT_OVERFLOW)
    }
}

fn text_dimensions(longest_line: usize, line_count: usize) -> Result<(usize, usize)> {
    let padded_width = longest_line.checked_mul(8).and_then(|width| width.checked_add(40));
    let width = padded_width.context("GraphML label width exceeds the supported size")?;
    let padded_height = line_count.max(1).checked_mul(20).and_then(|height| height.checked_add(20));
    let height = padded_height.context("GraphML label height exceeds the supported size")?;
    Ok((width, height))
}

struct LayoutFrame<'hierarchy, 'label> {
    visual: NodeVisual<'label>,
    children: slice::Iter<'hierarchy, usize>,
}

impl<'hierarchy, 'label> LayoutFrame<'hierarchy, 'label> {
    fn new(folder: &'hierarchy Folder<'label>, position: Position) -> Result<Self> {
        let mut visual = NodeVisual::new(folder.index(), folder.display_label(), position)?;
        visual.label = folder.label();
        Ok(Self { visual, children: folder.children().iter() })
    }
}

struct Layout<'label> {
    visuals: BTreeMap<usize, NodeVisual<'label>>,
}

impl<'label> Layout<'label> {
    fn grouped(hierarchy: &Hierarchy<'label>) -> Result<Self> {
        let mut visuals = BTreeMap::new();
        let mut vertical_position = 0;
        for root in hierarchy.roots() {
            let mut work = vec![LayoutFrame::new(root, Position { horizontal: 0, vertical: vertical_position })?];
            while let Some(mut frame) = work.pop() {
                if let Some(&child) = frame.children.next() {
                    let position = frame.visual.child_position()?;
                    work.push(frame);
                    work.push(LayoutFrame::new(hierarchy.folder(child), position)?);
                } else {
                    if let Some(parent) = work.last_mut() {
                        parent.visual.include_child(&frame.visual)?;
                    } else {
                        vertical_position = frame.visual.next_root_vertical_position()?;
                    }
                    visuals.insert(frame.visual.index, frame.visual);
                }
            }
        }
        Ok(Self { visuals })
    }

    fn flat(graph: &IndexedGraph<'label>) -> Result<Self> {
        let mut visuals = BTreeMap::new();
        let mut vertical_position = 0;
        for (label, &index) in graph.nodes() {
            let visual = NodeVisual::new(index, label, Position { horizontal: 0, vertical: vertical_position })?;
            vertical_position = visual.next_root_vertical_position()?;
            visuals.insert(index, visual);
        }
        Ok(Self { visuals })
    }

    #[must_use]
    fn visual(&self, index: usize) -> &NodeVisual<'label> {
        let Some(visual) = self.visuals.get(&index) else {
            unreachable!("Every visible hierarchy folder must have a computed layout");
        };
        visual
    }
}

#[must_use]
fn escaped_label(label: &str) -> String {
    // XML readers normalize literal CR to LF.
    quick_xml::escape::escape(label).replace('\r', "&#13;")
}

fn validate_graph(graph: &FolderGraph, cycle_group_count: usize) -> Result<()> {
    // Cycle group numbers are contiguous and one-based, so the count bounds every edge's group.
    i32::try_from(cycle_group_count).context("cycle group exceeds GraphML's signed int range")?;
    ensure!(
        graph.nodes().iter().all(|node| node.label().chars().all(|character| matches!(character,
            '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}'
        ))),
        "a folder label contains a character forbidden in XML 1.0"
    );
    for weight in graph.edges().values() {
        i64::try_from(weight.value()).context("edge weight exceeds GraphML's signed long range")?;
    }
    Ok(())
}

struct NodePresentation {
    index: usize,
    label: String,
    display_label: String,
    horizontal: usize,
    vertical: usize,
    width: usize,
    height: usize,
}

impl NodePresentation {
    #[must_use]
    fn new(visual: &NodeVisual<'_>) -> Self {
        Self {
            index: visual.index,
            label: escaped_label(visual.label),
            display_label: escaped_label(visual.display_label),
            horizontal: visual.position.horizontal,
            vertical: visual.position.vertical,
            width: visual.width,
            height: visual.height,
        }
    }
}

struct GroupRealizer {
    width: usize,
    height: usize,
    closed: bool,
}

struct GroupPresentation {
    node: NodePresentation,
    realizers: [GroupRealizer; 2],
}

enum NodeEvent {
    Leaf(NodePresentation),
    EnterGroup(GroupPresentation),
    LeaveGroup,
}

struct EdgePresentation {
    index: usize,
    source: usize,
    target: usize,
    weight: usize,
    kind: &'static str,
    label: String,
    color: RgbColor,
    line_style: &'static str,
    width: &'static str,
    cycle_group: Option<NonZeroUsize>,
}

#[derive(Template)]
#[template(path = "export/graphml/template.jinja2", escape = "none")]
struct GraphMlTemplate {
    graphml_namespace: &'static str,
    yworks_namespace: &'static str,
    default_graphics_color: RgbColor,
    has_cycle_groups: bool,
    node_events: Vec<NodeEvent>,
    edges: Vec<EdgePresentation>,
}

impl GraphMlTemplate {
    #[must_use]
    fn new(graph: &IndexedGraph<'_>, layout: &Layout<'_>, hierarchy: Option<&Hierarchy<'_>>) -> Self {
        let node_events = hierarchy.map_or_else(
            || layout.visuals.values().map(|visual| NodeEvent::Leaf(NodePresentation::new(visual))).collect(),
            |hierarchy| hierarchy.events().map(|event| match event {
                FolderEvent::Enter(folder) => {
                    let visual = layout.visual(folder.index());
                    let node = NodePresentation::new(visual);
                    if folder.children().is_empty() {
                        NodeEvent::Leaf(node)
                    } else {
                        NodeEvent::EnterGroup(GroupPresentation {
                            node,
                            realizers: [
                                GroupRealizer { width: visual.width, height: visual.height, closed: false },
                                GroupRealizer { width: 160, height: 50, closed: true },
                            ],
                        })
                    }
                }
                FolderEvent::Leave => NodeEvent::LeaveGroup,
            }).collect(),
        );
        let edges = graph.edges().iter().enumerate().map(|(index, edge)| {
            let (color, line_style) = match edge.kind() {
                DependencyKind::Production => (COLOR_GRAPHICS_DEFAULT, "line"),
                DependencyKind::Test => (COLOR_EDGE_TEST, "dashed"),
            };
            let cycle_color = edge.cycle_group().map(|group| group_color(group, graph.cycle_group_count()));
            EdgePresentation {
                index,
                source: edge.source(),
                target: edge.target(),
                weight: edge.weight().value(),
                kind: kind_name(edge.kind()),
                label: edge_label(edge.kind(), edge.weight()),
                color: cycle_color.unwrap_or(color),
                line_style,
                width: if edge.cycle_group().is_some() { CYCLE_EDGE_WIDTH } else { "1.0" },
                cycle_group: edge.cycle_group().map(|group| group.number()),
            }
        }).collect();
        Self {
            graphml_namespace: NAMESPACE_GRAPHML,
            yworks_namespace: NAMESPACE_YWORKS,
            default_graphics_color: COLOR_GRAPHICS_DEFAULT,
            has_cycle_groups: graph.cycle_group_count() != 0,
            node_events,
            edges,
        }
    }
}

impl Exporter for GraphMl {
    fn write(&self, graph: &FolderGraph, output: &mut dyn Write) -> Result<()> {
        self.write_with_options(graph, &Options::default(), output)
    }

    fn write_grouped(&self, graph: &FolderGraph, output: &mut dyn Write) -> Result<()> {
        self.write_with_options(graph, &Options::builder().group_folders(true).build(), output)
    }

    fn write_with_options(&self, graph: &FolderGraph, options: &Options<'_>, output: &mut dyn Write) -> Result<()> {
        let indexed_graph = IndexedGraph::with_cycles(graph, options.cycles())?;
        validate_graph(graph, indexed_graph.cycle_group_count())?;
        let hierarchy = if options.group_folders() { Some(Hierarchy::new(&indexed_graph)?) } else { None };
        let layout = if let Some(hierarchy) = hierarchy.as_ref() {
            Layout::grouped(hierarchy)?
        } else {
            Layout::flat(&indexed_graph)?
        };
        let template = GraphMlTemplate::new(&indexed_graph, &layout, hierarchy.as_ref());
        template.write_into(output)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use claims::assert_ok;
    use pretty_assertions::assert_eq;
    use rstest::rstest;

    use super::NodeVisual;
    use super::Position;
    use super::text_dimensions;
    use super::validate_graph;
    use crate::model::FolderGraph;

    #[rstest]
    #[case("", (40, 40))]
    #[case("ab\n\u{3bb}", (56, 60))]
    #[case("x\r\n", (48, 40))]
    fn test_label_dimensions(#[case] label: &str, #[case] expected_dimensions: (usize, usize)) {
        let system_under_test = NodeVisual::new(0, label, Position { horizontal: 0, vertical: 0 });

        let visual = assert_ok!(system_under_test, "Representable label must produce node geometry: {label:?}");
        let dimensions = (visual.width, visual.height);

        assert_eq!(dimensions, expected_dimensions, "Label measurement changed line or Unicode character handling");
    }

    #[rstest]
    #[case(usize::MAX, 1)]
    #[case(usize::MAX.div_euclid(8), 1)]
    #[case(0, usize::MAX)]
    #[case(0, usize::MAX.div_euclid(20))]
    fn test_label_dimension_overflow(#[case] longest_line: usize, #[case] line_count: usize) {
        let system_under_test = text_dimensions(longest_line, line_count);

        assert!(system_under_test.is_err(), "Unrepresentable label dimensions must be a size error");
    }

    #[test]
    fn test_label_dimension_boundary() {
        let longest_line = (usize::MAX - 40).div_euclid(8);
        let line_count = (usize::MAX - 20).div_euclid(20);

        let system_under_test = text_dimensions(longest_line, line_count);

        let dimensions = assert_ok!(system_under_test, "Label dimensions at the representable boundary must succeed");
        assert_eq!(dimensions, (longest_line * 8 + 40, line_count * 20 + 20), "Representable label dimensions were capped");
    }

    #[rstest]
    #[case(40, usize::MAX, 40, false)]
    #[case(40, usize::MAX - 39, 40, false)]
    #[case(1, 40, usize::MAX, false)]
    #[case(40, 40, usize::MAX - 40, false)]
    #[case(40, usize::MAX - 40, 40, true)]
    fn test_group_dimensions(
        #[case] parent_height: usize,
        #[case] child_width: usize,
        #[case] child_height: usize,
        #[case] representable: bool,
    ) {
        let mut system_under_test = NodeVisual {
            index: 0,
            label: "",
            display_label: "",
            position: Position { horizontal: 0, vertical: 0 },
            width: 40,
            height: parent_height,
        };
        let child = NodeVisual {
            index: 1,
            label: "",
            display_label: "",
            position: Position { horizontal: 20, vertical: 40 },
            width: child_width,
            height: child_height,
        };

        let result = system_under_test.include_child(&child);

        if representable {
            assert_ok!(result, "Representable group bounds including child dimensions and padding must succeed");
        } else {
            assert!(result.is_err(), "Group bounds must reject overflowing child dimensions or padding");
        }
    }

    #[rstest]
    #[case(usize::MAX, 0, 40, false)]
    #[case(0, usize::MAX, 40, false)]
    #[case(usize::MAX - 20, usize::MAX - 40, 40, true)]
    fn test_child_position(
        #[case] horizontal: usize,
        #[case] vertical: usize,
        #[case] height: usize,
        #[case] representable: bool,
    ) {
        let position = Position { horizontal, vertical };
        let system_under_test = NodeVisual { index: 0, label: "", display_label: "", position, width: 40, height };

        let result = system_under_test.child_position();

        if representable {
            assert_ok!(result, "Representable child coordinates including offsets must succeed");
        } else {
            assert!(result.is_err(), "Child coordinates must reject overflowing offsets");
        }
    }

    #[rstest]
    #[case(usize::MAX, 1, false)]
    #[case(usize::MAX - 40, 1, false)]
    #[case(usize::MAX - 80, 40, true)]
    fn test_root_spacing(#[case] vertical: usize, #[case] height: usize, #[case] representable: bool) {
        let system_under_test = NodeVisual {
            index: 0,
            label: "",
            display_label: "",
            position: Position { horizontal: 0, vertical },
            width: 40,
            height,
        };

        let result = system_under_test.next_root_vertical_position();

        if representable {
            assert_ok!(result, "Representable root coordinates including height and spacing must succeed");
        } else {
            assert!(result.is_err(), "Root coordinates must reject overflowing height or spacing");
        }
    }

    #[test]
    fn test_cycle_group_signed_int_range() {
        let fixture = FolderGraph::default();

        let maximum = usize::try_from(i32::MAX);
        let maximum = assert_ok!(maximum, "GraphML signed-int maximum must fit in the platform's index type");
        let system_under_test = validate_graph;
        let boundary = system_under_test(&fixture, maximum);
        let overflow = system_under_test(&fixture, maximum + 1);

        assert_ok!(boundary, "Cycle-group count at the GraphML signed-int maximum must be accepted");
        assert!(overflow.is_err(), "Cycle-group count above the GraphML signed-int maximum must be rejected");
    }
}