summaryrefslogtreecommitdiff
path: root/sandbox/rst2graph/sortDot.pl
blob: 85ea80cce2558edcc69faf2ed51539d3bb1d0aaf (plain)
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
#!/usr/bin/perl -w

# Sort the statements of a dot file produced by `rst2gv` so the sequence of
# lines is stable.

my @gather;

sub add($) {
  my( $ln ) = @_;

  push(@gather, $ln);
}

sub out(@) {
  my( @lns ) = @_;

  print(@lns);
}

sub flush(@) {
  my( @sfx ) = @_;

  out(sort(@gather), @sfx);
  @gather = ( );
}

while(defined($_ = <>)) {
  my $in;
  if($in = /\{\s*$/ .. /\}\s*$/) {
    if($in == 1)
      { out($_); }
    elsif($in =~ /E/)
      { flush($_); }
    elsif(/\{\s*$/)
      { die("Embedded graphs are not supported: $_"); }
    elsif(/\\$/)
      { die("Continuation lines are not supported: $_"); }
    elsif(/\/\*/ || /\/\// || /#/)
      { die("Comments are not supported: $_"); }
    elsif(/;\s*$/) { # A statement
      if(/^\s*(graph|node|edge)/) # An attribute statement
	{ flush($_); }
      # Note: The order of nodes output by `pygraphviz` is random. This changes
      # the semantic of the graph but unfortunately can not be controlled.
      else
	{ add($_); }
    }
    else
      { die("Unsupported line ending: $_"); }
  }
  else
    { out($_); }
}