-
Notifications
You must be signed in to change notification settings - Fork 1
/
gen-docs.sh
executable file
·141 lines (120 loc) · 2.73 KB
/
gen-docs.sh
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
#!/bin/bash
#
# Generate markdown documentation from bash.sh.
#
#
# Write a function block to stdout.
#
output_func_block() {
echo
echo -n '```bash'
echo "$@"
echo '```'
}
#
# Write a markdown block to stdout.
#
output_markdown_block() {
echo
IFS=$'\n'
for line in $@; do
case "$line" in
"#")
echo
;;
"#"*)
echo "${line#\# }"
;;
*)
echo "ERROR: Unexpected data: $line" >&2
exit 1
;;
esac
done
}
#
# Write a header to stdout.
#
output_markdown_header() {
echo
IFS=$'\n'
for line in $@; do
if [[ "$line" =~ ^\#+$ ]]; then
continue
else
text="$line"
text="${text#\# }"
text="${text% \#}"
echo "## $text"
return
fi
done
}
main() {
local -i body_started=0
local -i block_open=0
local -i func_open=0
local buf=
local prevline=
_add_to_buffer() {
buf="$buf"$'\n'"$@"
}
_reset_buffer() {
buf=
}
_reset_all() {
buf=
prevline=
}
_process_end_of_block() {
# Process/output previous block
if [ "$prevline" == "}" ]; then
output_func_block "$buf"
elif [[ "$prevline" =~ ^\#\#\#+ ]]; then
output_markdown_header "$buf"
else
output_markdown_block "$buf"
fi
}
while read -r line; do
case "$line" in
# Func def start
*"() {")
func_open=1
_add_to_buffer "$line"
;;
# Func def end
"}")
func_open=0
_add_to_buffer "$line"
;;
# End of block
"")
# Only start processing from the first header encountered
if [[ "$prevline" =~ ^\#\#\#+ ]]; then
body_started=1
fi
if [ $body_started -eq 0 ]; then
_reset_all
continue
fi
# Continue if we're inside a func dec
if [ $func_open -eq 1 ]; then
_add_to_buffer "$line"
continue
fi
_process_end_of_block
# Clear buffer, ready for new block
_reset_buffer
;;
# Add line to buffer
*)
_add_to_buffer "$line"
;;
esac
prevline="$line"
done
# End of file, process the remaining contents of the buffer
_process_end_of_block
}
main "$@" <bash.sh