/
mdbooker.awk
executable file
·73 lines (68 loc) · 2.49 KB
/
mdbooker.awk
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/awk -f
BEGIN {
if (!(Repo = ENVIRON["REPO"]))
usage()
if (!(BOOK = ENVIRON["BOOK"]))
print "will use BOOK=" (BOOK = "book")
printf "" > (SUMMARY = (BOOK = BOOK "/") "SUMMARY.md")
LinkBase = "https://github.com/" Repo "/blob/main/"
RawBase = "https://github.com/" Repo "/raw/main/"
H = 0
Title = Content = ""
delete PathElements
delete Link2Path
delete ContentLinks
}
match($0, /^#+/) { handleTitle(RLENGTH, 1) }
function handleTitle(h,pass, indent,dir,i,path,title) {
title = trim(substr($0, h + 1))
if (Title) {
for (i = 2; i < H; i++)
dir = dir (dir ? "-" : "") fname(PathElements[i])
path = dir (dir ? "-" : "") fname(Title) ".md"
if (pass == 1) {
Link2Path[linkify(Title)] = path
if (H > 2)
ContentLinks[PathElements[H - 1]] = ContentLinks[PathElements[H - 1]] "- [" Title "](" path ")\n"
} else {
print "generating: " path "..."
if (!(Content = trim(Content))) {
Content = ContentLinks[Title]
}
print "# " Title > BOOK path
print Content >> BOOK path
if ((indent = H - 2) < 0)
indent = 0
printf "%" (indent * 4) "s%s[%s](%s)\n", "", 1 == H ? "" : "- ", Title, path >> SUMMARY
}
} else
print Content > BOOK fname(title) ".md" # pre-content
Content = ""
Title = PathElements[H = h] = title
}
END { if (!Exit) { handleTitle(0, 1); pass2() } }
function pass2( l,f,t) {
Title = Content = ""
while (getline < FILENAME > 0) {
if (match($0, /^#+/))
handleTitle(RLENGTH, 2)
else {
if (match(l = $0, /]\(#[^)]+\)/)) {
print " fix #link: #" (f = substr(l, RSTART + 3, RLENGTH - 4)) " -> " (t = Link2Path[f])
l = substr(l, 1, RSTART - 1) "](" t ")" substr(l, RSTART + RLENGTH)
} else if (match(l, /]\([^)]+\)/) && (f = substr(l, RSTART + 2, RLENGTH - 3)) !~ /https?:/) {
if (l ~ /!\[/)
print " fix image link: " f " -> " (t = RawBase f)
else
print " fix relative link: " f " -> " (t = LinkBase f)
l = substr(l, 1, RSTART - 1) "](" t ")" substr(l, RSTART + RLENGTH)
}
Content = Content "\n" l
}
}
handleTitle(0, 2)
}
function usage() { Exit = 1; print "Usage:\n REPO=username/reponame [BOOK=book_folder_path] awk -f mdbooker.awk README.md"; exit 1 }
function linkify(t) { t = tolower(t); gsub(/ /, "-", t); gsub(/[^-a-z0-9_]/, "", t); return t }
function fname(s) { gsub(/ /, "_", s); return s }
function trim(s) { sub(/^[ \t\r\n]+/, "", s); sub(/[ \t\r\n]+$/, "", s); return s }