-
Notifications
You must be signed in to change notification settings - Fork 8
/
generate-toc.pl
73 lines (52 loc) · 1.42 KB
/
generate-toc.pl
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
#!/usr/bin/env perl
use common::sense;
my $lines = '';
my $headers = [];
my $seenHeaders = {};
{
open(my $fh, '<', 'README.md') || die "unable to open README.md: $!";
while (<$fh>) {
next if /^<!-- START OF TOC -->/ .. /^<!-- END OF TOC -->/;
$lines .= $_;
if (/^[#]+ (.*)/) {
my $whole = $&;
my $title = $1;
my $link = title2link($1);
die "duplicate header: $link" if $seenHeaders->{$link};
$seenHeaders->{$link}++;
push @$headers, $whole;
}
}
}
my $toc = '';
for my $header (@$headers) {
$header =~ /^(#+) (.*)/;
my $prefix = $1;
my $title = $2;
next if $prefix eq '#';
$prefix =~ s/^##//;
$prefix =~ s/^\s+//;
$prefix =~ s/#/ /g;
$prefix = "$prefix*";
my $link = title2link($title);
$toc .= "$prefix [$title](#$link)\n";
}
{
open(my $ofh, '>', 'README.md.tmp') || die "unable to open README.md: $!";
$lines =~ s{<!-- TOC FOLLOWS -->}{<!-- TOC FOLLOWS -->\n<!-- START OF TOC -->\n$toc<!-- END OF TOC -->};
print $ofh $lines;
}
while ($lines =~ m{\[.*?\][(]#(.*?)[)]}g) {
my $link = $1;
if (!$seenHeaders->{$link}) {
print STDERR "WARNING: Unresolved link: $link\n";
}
}
system("mv -f README.md.tmp README.md");
sub title2link {
my $title = shift;
my $link = lc $title;
$link =~ s/\s+/-/g;
$link =~ s/[+]//g;
return $link;
}