~jbauer/paritybit.ca

paritybit.ca/http/compile -rwxr-xr-x 8.8 KiB
eb78c56eJake Bauer Update links and blogroll a day ago
                                                                                
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#!/bin/sh

# compile
# A POSIX shell script to build pages and minify css for a simple website.
# NOTE: See the README for the expected format of md files.
#
# Copyright (C) 2020  Jake Bauer
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

### CONFIGURATION ###
# The name of the site in the <title> tags
siteName="paritybit.ca"
# Set to "false" to disable auto-upload
autoUpload="true"
# Where to upload files
remote="paritybit.ca:/var/www/paritybit.ca/"
# Where md files are
pageDir="pages/"
# Where compiled md -> html pages will go
htmlDir="public/html"
# Where minified css will go
cssDir="public/css"
# Where optimized images will go
imgDir="public/img"
# Your tinypng.com API key
apiKey=""
# Where intermediate build files will go
buildDir="build/"
### END CONFIGURATION ###

# POSIX Shell "Strict Mode"
set -o errexit
set -o nounset
IFS=$(printf '\n\t')

# Check that all the required programs are installed
if [ ! -x "$(command -v rsync)" ]; then
	echo "The program 'rsync' is needed but was not found."
	exit 1
fi
if [ ! -x "$(command -v curl)" ]; then
	echo "The program 'curl' is needed but was not found."
	exit 1
fi
if [ ! -x "$(command -v lowdown)" ]; then
	echo "The program 'lowdown' is needed but was not found."
	exit 1
fi
if [ ! -x "$(command -v convert)" ]; then
	echo "The program 'convert' from ImageMagick is needed but was not found."
	exit 1
fi

# Define colours
CLEAR="\033[0m"
RED="\033[0;31m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"

# Ensure configured directories exist
mkdir -p "$htmlDir"
mkdir -p "$cssDir"
mkdir -p "$imgDir"
mkdir -p "$buildDir"

# Prints the message passed as the 1st argument in red.
print_error_msg() { printf "$RED[ee] %s\n$CLEAR" "$1" ; }
# Prints the message passed as the 1st argument in green.
print_success_msg() { printf "$GREEN[ok] %s\n$CLEAR" "$1" ; }
# Prints the message passed as the 1st argument in yellow.
print_header_msg() { printf "$YELLOW[hh] %s\n$CLEAR" "$1" ; }
# Prints the message passed as the 1st argument with default colours.
print_info_msg() { printf "$CLEAR[ii] %s\n" "$1" ; }

auto_upload()
{
	if [ "$autoUpload" != "true" ]; then
		return 0
	fi
	print_info_msg "Auto-uploading file"
	if [ "$autoUpload" = "true" ]; then
		if [ "$fileExt" = "css" ] || [ "$fileExt" = "md" ]; then
			outputFile="$(echo "$outputFile" | cut -d'/' -f2-)"
			cd public && rsync -rR "$outputFile" "$remote" && cd ..
		fi
	fi
}

optimize_img()
{
	print_header_msg "OPTIMIZING IMG: $file"
	outputFile="$imgDir/$fileName.$fileExt"

	response=$(curl https://api.tinify.com/shrink \
		--user api:"$apiKey" \
		--data-binary @"$file" \
		--dump-header /dev/stdout)
	downloadURL=$(echo "$response" | grep location: | cut -d' ' -f2 | tr -d '\r')
	if [ $? != 0 ]; then
		print_error_msg "There was an issue minifying this image."
		exit 1
	fi

	curl --output "$outputFile" "$downloadURL"
	if [ $? != 0 ]; then
		print_error_msg "There was an issue downloading the minified image."
		exit 1
	fi
}

resize_img()
{
	print_header_msg "RESIZING IMG: $file"
	outputFile="$imgDir/$fileName.$fileExt"
	convert "$file" -resize "$resizeFactor"% "$outputFile"
	if [ $? != 0 ]; then
		print_error_msg "There was an error resizing the image."
		exit 1
	fi
}

minify_css()
{
	print_header_msg "MINIFYING CSS: $file"
	outputFile="$cssDir/$fileName.min.css"
	curl --data "input=$(cat "$file")" https://cssminifier.com/raw \
		> "$outputFile"
	if [ $? != 0 ]; then
		print_error_msg "There was an issue minifying this CSS."
		exit 1
	fi
}

compile_md()
{
	print_header_msg "COMPILING MARKDOWN: $file"
	mkdir -p "$buildDir"/"$subDir"
	mkdir -p "$htmlDir"/"$subDir"

	lowdown -o "$buildDir"/"$subDir"/"$fileName"-content.html -Thtml $file \
		--html-no-skiphtml --html-no-escapehtml

	cat "$buildDir"/header.html \
		"$buildDir"/"$subDir"/"$fileName"-content.html \
		"$buildDir"/footer.html \
		> "$htmlDir"/"$subDir"/"$fileName".html

	outputFile="$htmlDir/$subDir/$fileName.html"
	set_html_title
	set_html_meta
	set_html_csslink
	set_html_toc
}

set_html_title()
{
	title="$(head -n1 "$file" | cut -d' ' -f2-)"
	print_info_msg "Setting <title>: \"$title\""
	sed -i -e "s/<title>.*<\/title>/<title>$title - $siteName<\/title>/" \
		"$outputFile"
}

set_html_meta()
{
	meta="$(head -n3 "$file" | tail -n1 \
		| cut -d'#' -f2 | sed -e 's/^[[:space:]]*//')"
	print_info_msg "Setting <meta> description"
	sed -i -e "s/content=\"\"/content=$meta/" "$outputFile"
}

set_html_csslink()
{
	cssList="$(head -n5 "$file" | tail -n1 \
		| cut -d'#' -f2 | sed -e 's/^[[:space:]]*//')"
	print_info_msg "Adding CSS <link>s"
	echo "$cssList" | tr ' ' '\n' | while read cssFile; do
		cssFile="/css/$(echo "$cssFile" | tr -d '"')"
		sed -i -e "/<title>/a\\
			<link rel=\"stylesheet\" href=\"$cssFile\">" \
			"$outputFile"
	done
}

# This still feels a bit messy
set_html_toc()
{
	tocList="$(head -n7 "$file" | tail -n1 \
		| cut -d'#' -f2 | sed -e 's/^[[:space:]]*//' | tr -d '"')"
	print_info_msg "Adding Table of Contents"
	if [ -z "$tocList" ]; then
		return 0
	fi
	sed -i -e "/TOC/a\\
	<div id=\"table-of-contents\" aria-label=\"Table of Contents\">\n<h2 id=\"toc-title\">Table of Contents</h2>" \
		"$outputFile"
	sed -i -e "/toc-title/a\\
	</ul></div>" "$outputFile"
	echo "$tocList" | tr ';' '\n' \
		| awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' \
		| while read tocEntry; do
		tocEntry="$(echo "$tocEntry" | sed -e 's/^[[:space:]]*//')"
		if echo "$tocEntry" | grep -qi "^subsub:"; then
			tocEntry="$(echo "$tocEntry" | cut -d':' -f2-)"
			tocEntryId="$(echo "$tocEntry" | sed 's/ /%20/g' | tr -d ':' )"
			sed -i -e "/toc-title/a\\
			<ul><ul><li><a href=\"#$tocEntryId\">$tocEntry</a></li></ul></ul>" \
				"$outputFile"
			sed -i -e "/$tocEntry<\/h5>/i\\
			</section>\n<section>" \
				"$outputFile"
		elif echo "$tocEntry" | grep -qi "^sub:"; then
			tocEntry="$(echo "$tocEntry" | cut -d':' -f2-)"
			tocEntryId="$(echo "$tocEntry" | sed 's/ /%20/g' | tr -d ':' )"
			sed -i -e "/toc-title/a\\
			<ul><li><a href=\"#$tocEntryId\">$tocEntry</a></li></ul>" \
				"$outputFile"
			sed -i -e "/$tocEntry<\/h4>/i\\
			</section>\n<section>" \
				"$outputFile"
		else
			tocEntryId="$(echo "$tocEntry" | sed 's/ /%20/g' |  tr -d ':' )"
			sed -i -e "/toc-title/a\\
			<li><a href=\"#$tocEntryId\">$tocEntry</a></li>" \
				"$outputFile"
			sed -i -e "/$tocEntry<\/h3>/i\\
			</section\>\n<section>" \
				"$outputFile"
		fi
	done
	sed -i -e "/toc-title/a\\
	<ul>" "$outputFile"
	sed -i -e "/END OF HEADER FILE/a\\
	<section>" "$outputFile"
	sed -i -e "/<\/main>/i\\
	</section>" "$outputFile"
}

# Read and parse command line flags
resizeFactor="0"
while test $# -gt 0; do
	case "$1" in
		-h|--help)
			echo "compile - generate static web pages"
			echo ""
			echo "usage: compile [options] files"
			echo ""
			echo "options:"
			echo "-h|--help			   show brief help"
			echo "-a|--auto-upload	   auto-upload generated files"
			echo "-n|--no-auto-upload  do not auto-upload the generated files"
			echo "-r|--resize NUMBER   resize input image by NUMBER percent"
			exit 0
			;;
		-n|--no-auto-upload)
			autoUpload="false"
			shift
			;;
		-a|--auto-upload)
			autoUpload="true"
			shift
			;;
		-r|--resize)
			shift
			resizeFactor="$1"
			shift
			;;
		--|*)
			break
			;;
	esac
done

for file in "$@"; do
	if [ ! -f "$file" ]; then
		print_error_msg "ERROR: $file not found or is not a file."
		continue
	fi

	# First run of fileName needed because if the for loop operates on $file,
	# the extension will not be properly pruned
	fileName=$(basename -s .md "$file")
	for ext in md css png jpg jpeg; do
		fileName=$(basename -s ."$ext" "$fileName")
	done
	fileExt=$(echo "$file" | awk -F . '{if (NF>1) {print $NF}}')
	fileDir=$(dirname "$file")
	subDir=$(echo "$fileDir" | sed "s/^pages//")

	if [ "$fileExt" = "css" ]; then
		minify_css
		auto_upload
	elif [ "$fileExt" = "md" ]; then
		compile_md
		auto_upload
	elif [ "$fileExt" = "png" ] || [ "$fileExt" = "jpg" ] || [ "$fileExt" = "jpeg" ]; then
		if [ "$resizeFactor" -gt 0 ]; then
			fileName="$fileName-thumb"
			resize_img
		else
			optimize_img
			auto_upload
		fi
	else
		print_error_msg "ERROR: nothing to do."
	fi

	if [ "$fileExt" = "md" ]; then
		print_success_msg "FINISHED: https://$siteName/$subDir/$fileName.html"
	else
		print_success_msg "FINISHED: $fileName.$fileExt"
	fi
done