forked from rust-lang/rust-by-example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcheck-links.sh
executable file
·94 lines (69 loc) · 2.35 KB
/
check-links.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
#!/bin/bash
#
# Extract links from Markdown documents, and check
# their HTTP status. Flag anything that doesn't
# return a 200.
#
DELIMITER="{{-%%-}}"
echo "Checking links..."
any_bad_links=false
files=$(find ./examples -name "*.md")
for file in $files ; do
#
# Extract the urls, if any, along with the line numbers.
#
reference_style_links=$(grep -n "^\[[^]]\+\]:\ http" $file | \
sed -e "s/:/$DELIMITER/" -e "s/\[[^]]*\]: //")
inline_links=$(grep -no "\[[^]]\+\]([^[:space:]]\+)" $file | \
sed -e "s/:/$DELIMITER/" -e "s/\[[^]]*\](//" -e "s/)$//")
if [[ $reference_style_links == "" && $inline_links == "" ]]; then
continue
elif [[ $reference_style_links == "" ]]; then
all_links="$inline_links"
elif [[ $inline_links == "" ]]; then
all_links="$reference_style_links"
else
all_links=$(echo "$reference_style_links"$'\n'"$inline_links" | sort -n)
fi
for link in $all_links ; do
url=$(echo $link | awk -F"$DELIMITER" '{print $2}')
# Check relative, internal, urls
if [[ ! $url == http://* ]] && [[ ! $url == https://* ]]; then
local_path=$url
# Remove the .html if present
if [[ $local_path == *.html ]]; then
local_path=${local_path:0:${#local_path}-5}
fi
# Build the local directory path
# This depends on the GitBook style directory structure
if [[ ! $local_path == /* ]]; then
local_path="./examples/$local_path"
else
local_path="./examples$local_path"
fi
if [[ -d $local_path ]]; then
continue
fi
status_code="404"
# Check external urls
else
# -s: silent
# -L: follow redirect
# -o: send output to /dev/null
# -I: load headers only
# -w: write the status code to stdout
status_code=$(curl -s -L -o /dev/null -I -w "%{http_code}" "$url")
if [[ $status_code == "200" ]]; then
continue
fi
fi
any_bad_links=true
line_number=$(echo $link | awk -F"$DELIMITER" '{print $1}')
echo -e "Bad link in $file:$line_number [$status_code] $url"
done
done
if $any_bad_links; then
echo "Some links were bad."
else
echo "All links are 200!"
fi