Skip to content

Commit b273973

Browse files
committed
Added structure into code & support for wget.
* Added support for wget (now it selects between curl or wget) * Added support for option --help/--version * Added user-agent into http requests
1 parent b767d76 commit b273973

File tree

1 file changed

+66
-3
lines changed

1 file changed

+66
-3
lines changed

gh-md-toc

Lines changed: 66 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,69 @@
1919
# substr($4, 7)
2020
#
2121

22-
echo "Table of Contents"
23-
echo "================="
24-
curl -s $1 | awk '/user-content-/ {print sprintf("%*s", substr($NF, length($NF)-1, 1)*2, " ") "* [" substr($0, match($0, /a>.*<\/h/)+2, RLENGTH-5)"](" substr($4, 7, length($4)-7) ")"}'
22+
gh_toc_version="0.1.0"
23+
24+
#
25+
# Download rendered into html README.md by it's url.
26+
#
27+
#
28+
gh_toc_load() {
29+
local gh_url=$1
30+
local gh_user_agent=$2
31+
32+
if type curl &>/dev/null; then
33+
curl --user-agent "$gh_user_agent" -s "$gh_url"
34+
elif type wget &>/dev/null; then
35+
wget --user-agent="$user_agent" -qO- "$gh_url"
36+
else
37+
echo "Please, install 'curl' or 'wget' and try again."
38+
exit 1
39+
fi
40+
}
41+
42+
#
43+
# TOC generator
44+
#
45+
gh_toc(){
46+
local gh_url=$1
47+
local gh_user_agent=${2:-"gh-md-toc"}
48+
49+
if [ "$gh_url" = "" ]; then
50+
echo "Please, enter URL for a README.md"
51+
exit 1
52+
fi
53+
54+
echo "Table of Contents"
55+
echo "================="
56+
gh_toc_load "$gh_url" "$gh_user_agent" | \
57+
awk '/user-content-/ {print sprintf("%*s", substr($NF, length($NF)-1, 1)*2, " ") "* [" substr($0, match($0, /a>.*<\/h/)+2, RLENGTH-5)"](" substr($4, 7, length($4)-7) ")"}'
58+
}
59+
60+
#
61+
# Options hendlers
62+
#
63+
gh_toc_app() {
64+
local app_name=${0/\.\//}
65+
66+
if [ "$1" = '--help' ]; then
67+
echo "GitHub TOC generator ($app_name): $gh_toc_version"
68+
echo ""
69+
echo "Usage:"
70+
echo " $app_name <url> Create TOC for passed url of a README file"
71+
echo " $app_name --help Show help"
72+
echo " $app_name --version Show help"
73+
return
74+
fi
75+
76+
if [ "$1" = '--version' ]; then
77+
echo "$gh_toc_version"
78+
return
79+
fi
80+
81+
gh_toc "$1" "$app_name"
82+
}
83+
84+
#
85+
# Entry point
86+
#
87+
gh_toc_app "$@"

0 commit comments

Comments
 (0)