toMermaid function

String toMermaid(
  1. ImportGraph graph, {
  2. required Iterable<String> nodes,
  3. Set<String> unreachable = const {},
  4. int featureDepth = 1,
  5. List<List<String>>? cycles,
})

graph as a Mermaid flowchart — the form GitHub draws inline in a README, an issue or a pull request.

Only nodes are drawn, and only the edges between two of them. Files are boxed by the feature ImportGraph.featureOf puts them in at featureDepth; an edge inside an import cycle is red, and a file in unreachable is dashed. Ids are n0… in path order, so the same graph always prints the same text and a diff of two reports means something.

cycles is what ImportGraph.cycles returns; pass it when it is already at hand, or it is worked out again.

Implementation

String toMermaid(
  ImportGraph graph, {
  required Iterable<String> nodes,
  Set<String> unreachable = const {},
  int featureDepth = 1,
  List<List<String>>? cycles,
}) {
  final layout = _Layout(graph, nodes, featureDepth, cycles ?? graph.cycles());
  final out = StringBuffer('flowchart LR\n');

  var cluster = 0;
  for (final feature in layout.features.entries) {
    final name = feature.key;
    if (name == null) {
      for (final file in feature.value) {
        out.writeln('  ${layout.id[file]}["${_mermaid(file)}"]');
      }
      continue;
    }
    out.writeln('  subgraph f${cluster++}["${_mermaid(name)}"]');
    for (final file in feature.value) {
      out.writeln(
        '    ${layout.id[file]}["${_mermaid(layout.label(file, name))}"]',
      );
    }
    out.writeln('  end');
  }

  final cyclic = <int>[];
  for (final (index, edge) in layout.edges.indexed) {
    out.writeln('  ${layout.id[edge.$1]} --> ${layout.id[edge.$2]}');
    if (layout.inCycle(edge)) cyclic.add(index);
  }

  if (cyclic.isNotEmpty) {
    out.writeln('  linkStyle ${cyclic.join(',')} stroke:#d33,stroke-width:2px');
  }
  final dead = layout.files.where(unreachable.contains).toList();
  if (dead.isNotEmpty) {
    out
      ..writeln('  classDef dead stroke-dasharray:4 4,color:#888')
      ..writeln('  class ${dead.map((f) => layout.id[f]).join(',')} dead');
  }
  return out.toString();
}