-
Notifications
You must be signed in to change notification settings - Fork 5
/
pbb
executable file
·532 lines (450 loc) · 11.5 KB
/
pbb
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
#!/usr/bin/env bash
shopt -s extglob nullglob
# Globals
declare -r \
conf='.pbbconfig' \
calicon='assets/calendar.svg' \
cssfile='assets/pbb.css' \
favicon='includes/favicon.html' \
headerlinks='includes/headerlinks.html' \
feedpath='docs/feed.xml' \
goatcounter='includes/goatcounter.html' \
header='includes/header.html' \
metadata='.metadata.yml'
declare -rA features=(
['math']=1
['bibliography']=1
)
# Print warning message and continue
warn() {
printf '%s\n' "$*" >&2
}
# Print error message and exit
die() {
warn "$*"
exit 1
}
# Print usage hint
usage() {
cat <<- EOF >&2
usage:
pbb help | init TITLE | set PROPERTY VALUE | build | serve | deploy
pbb enable FEATURE | disable FEATURE
help Display this message
init Initialize new blog in empty Git repository
set Set configuration property to value; valid properties are
title New blog title
gccode GoatCounter code to enable analytics
baseurl Base URL for use in Atom feed
authorname Author name for Atom feed
authoremail Author email for Atom feed
build Generate HTML files and store them in docs directory
serve Serve blog on localhost:8000
deploy Commit changes in docs directory and push to remote
enable Turn on feature
disable Turn off feature
EOF
}
# Get the language setting from the environment
getlang() {
local lang=${LANGUAGE:-${LC_ALL:-${LC_MESSAGES:-$LANG}}}
# Shorten and replace underscore with hyphen to get IETF tag
lang=${lang%%[.:@]*}
lang=${lang/_/-}
if [[ -z $lang ]] || [[ $lang == @(C|POSIX) ]]; then
lang='en-US'
fi
printf '%s' "$lang"
}
# Check if the current directory is the root directory of a git repository
checkgit() {
local topdir
if ! topdir=$(git rev-parse --show-toplevel 2> /dev/null); then
warn "not in a git repo"
echo 'run "git init" first'
return 1
fi
if [[ $PWD != "$topdir" ]]; then
warn "in git repo, but not in root directory"
echo "run \"pbb init\" from the repository root, $topdir"
return 1
fi
return 0
}
# Initialize new blog
init() {
local blogtitle=$1
local msg
if ! msg=$(checkgit); then
die "$msg"
fi
if [[ -e $conf ]]; then
die "conf file exists already, aborting"
fi
mkdir --parents assets images includes
# Store title to config file
setblogtitle "$blogtitle"
git add "$conf"
# Symlink assets
ln --symbolic "${XDG_DATA_HOME:-$HOME/.local/share}/pbb/pbb.css" "$cssfile"
ln --symbolic "${XDG_DATA_HOME:-$HOME/.local/share}/pbb/calendar.svg" "$calicon"
git add "$cssfile" "$calicon"
# Header links for Google Font style sheet
printf '%s\n%s%s%s\n' \
'<link href="https://fonts.gstatic.com" rel="preconnect" crossorigin>' \
'<link href="https://fonts.googleapis.com/css?family=' \
'Source+Code+Pro:400,400i,700,700i|Source+Sans+Pro:400,400i,700,700i' \
'&display=swap" rel="stylesheet">' \
> "$headerlinks"
# Atom feed link
printf '%s %s\n' \
'<link href="/feed.xml" type="application/atom+xml" rel="alternate"' \
"title=\"$blogtitle Feed\">" >> "$headerlinks"
# Favicon for header
printf '%s\n' \
'<link rel="icon" href="/favicon.png" sizes="32x32" type="image/png">' \
> "$favicon"
# Template for GoatCounter snippet
printf '%s\n' \
'<script data-goatcounter="https://{{code}}.goatcounter.com/count"' \
' async src="//gc.zgo.at/count.js"></script>' \
> "$goatcounter"
git add includes
# Metadata file
printf '%s\n' \
'toc: false' \
'toc-title: Table of contents' \
> "$metadata"
git add "$metadata"
# Publishing source
mkdir docs
touch docs/.nojekyll
git add docs
git commit -m "Initialize blog with pbb"
# Example post
cat <<- EOF > "$(printf '%(%F)T' -1)-my-first-post.md"
---
summary: >-
A wild post appeared
---
# My first post
Hello world!
EOF
}
# Set a new blog title
setblogtitle() {
local blogtitle=$1
setconfvalue 'blogtitle' "$blogtitle"
printf '<div id="blogtitle"><a href="./">%s</a></div>\n' \
"$blogtitle" > "$header"
}
# Extract the title from a markdown file
extracttitle() {
local file=$1
sed -n '/^# /{s///p;q}' "$file"
}
# Convert a markdown file to HTML and store it in the docs directory
md2html() {
local file=$1
[[ $file == *.md ]] || die "not a markdown file: $file"
echo "Building $file..." >&2
local args=(
"--css=/pbb.css"
"--email-obfuscation=references"
"--from=markdown+emoji"
"--highlight-style=${XDG_DATA_HOME:-$HOME/.local/share}/pandoc/solarizeddark.theme"
"--include-before-body=$header"
"--include-in-header=$headerlinks"
"--lua-filter=dotgraph.lua"
"--metadata=document-css:true"
"--metadata=lang:$(getlang)"
"--metadata-file=.metadata.yml"
"--output=docs/${file/%.md/.html}"
"--shift-heading-level-by=-1"
"--standalone"
"--table-of-contents=true"
"--to=html"
"--toc-depth=4"
)
if [[ $(getconfvalue 'bibliography') == 'on' ]]; then
args+=("--citeproc")
fi
if [[ -n $(getconfvalue 'goatcountercode') ]]; then
args+=("--include-after-body=$goatcounter")
fi
if [[ -f docs/favicon.png ]]; then
args+=("--include-in-header=$favicon")
fi
if [[ $(getconfvalue 'math') == 'on' ]]; then
args+=("--mathjax")
fi
if [[ $file == ????-??-??-* ]]; then
args+=("--metadata=date:${file:0:10}")
fi
if [[ $file == 'index.md' ]]; then
args+=("--metadata=pagetitle:$(getconfvalue 'blogtitle')")
fi
pandoc "${args[@]}" "$file" || die "error while converting $file"
}
# Empty docs and copy images directory
clean() {
rm --recursive --force docs/!(CNAME|.nojekyll)
mkdir docs/diagrams
cp --recursive images docs
}
# Get value from config file
getconfvalue() {
local key=$1
(
# shellcheck source=/dev/null
source "$conf"
printf '%s' "${!key}"
)
}
# Set value in config file
setconfvalue() {
local key=$1
local value=$2
if [[ -f $conf ]]; then
sed -i "/$key=/d" "$conf"
fi
printf '%s=%q\n' "$key" "$value" >> "$conf"
}
# Set the GoatCounter code
setgccode() {
local code=$1
setconfvalue 'goatcountercode' "$code"
sed -E -i "s|(https://).*(\.goatcounter)|\1$code\2|" "$goatcounter"
}
# Toggle feature
setfeature() {
local feature=$1
local value=$2
if [[ ! -v features["$feature"] ]]; then
die "invalid feature: $feature"
fi
setconfvalue "$feature" "$value"
}
# Convert favicon image file to 32x32 PNG
favicon() {
local infile=(assets/favicon.*)
if ((${#infile[@]} > 1)); then
warn "found more than one favicon image in assets"
return 1
elif ((${#infile[@]} == 0)); then
warn "found no favicon image in assets"
return 1
fi
# Make sure to only use first frame if animated GIF
convert "${infile[0]}[0]" -resize 32x32^ -gravity center -background none \
-extent 32x32 docs/favicon.png
}
# Build all pages
build() {
clean
if ! favicon; then
warn "could not find or convert favicon; skipping"
fi
# Build index file and convert posts
{
printf '%s\n' '# All posts'
local f
for f in ????-??-??-*.md; do
printf -- ':::\n[%s](%s)\n:::index-title\n\n:::\n%s\n:::index-date\n\n' \
"$(extracttitle "$f")" "${f/%.md/.html}" "${f:0:10}"
md2html "$f"
done | tac
} > index.md
# Convert index file
md2html index.md
# Add Atom feed
buildfeed > "$feedpath"
rm index.md
cp "$cssfile" docs
cp "$calicon" docs/images
}
# Build Atom feed entry for the provided file, in YAML
buildentry() {
local file=$1
title=$(extracttitle "$file") \
url=$(getconfvalue 'baseurl') \
fname=${file/%md/html} \
updated=$(git log --max-count=1 --format=format:%aI -- "$file") \
summary=$(yq --front-matter=extract '.summary' "$file") \
published=$(git log --format=format:%aI -- "$file" | tail --lines=1) \
yq --null-input '
[{
"title": {
"+@type": "html",
"+content": strenv(title)
},
"id": strenv(url) + "/" + strenv(fname),
"updated": strenv(updated),
"content": {
"+@src": strenv(url) + "/" + strenv(fname),
"+@type": "text/html"
},
"link": {
"+@href": strenv(url) + "/" + strenv(fname),
"+@rel": "alternate",
"+@type": "text/html",
"+@title": strenv(title)
},
"summary": {
"+@type": "html",
"+content": strenv(summary)
},
"published": strenv(published)
}]
'
}
# Build feed entries, truncate to 10 most recent posts, reverse chronologically
buildentries() {
local files=(????-??-??-*.md)
if ((${#files[@]} > 10)); then
files=("${files[@]: -10}")
fi
local i
for ((i = 0; i < ${#files[@]}; ++i)); do
buildentry "${files[-(1 + i)]}"
done
}
# Build Atom feed, in XML
buildfeed() {
echo "Buiding Atom feed..." >&2
title=$(getconfvalue 'blogtitle') \
url=$(getconfvalue 'baseurl') \
name=$(getconfvalue 'authorname') \
email=$(getconfvalue 'authoremail') \
icon=$([[ -f docs/favicon.png ]] && echo "/favicon.png") \
entries=$(buildentries) \
yq --null-input --output-format=xml '
.+p_xml = "version=\"1.0\" encoding=\"utf-8\""
| .feed = {
"+@xmlns": "http://www.w3.org/2005/Atom",
"+@xmlns:webfeeds": "http://webfeeds.org/rss/1.0",
"title": strenv(title),
"id": strenv(url) + "/",
"updated": now,
"author": {
"name": strenv(name),
"email": strenv(email),
"uri": strenv(url) + "/"
},
"link": [
{
"+@href": strenv(url) + "/feed.xml",
"+@rel": "self",
"+@type": "application/atom+xml"
},
{
"+@href": strenv(url) + "/",
"+@rel": "alternate",
"+@type": "text/html"
}
],
"generator": {
"+@uri": "https://bewuethr/pandoc-bash-blog",
"+content": "pandoc-bash-blog"
},
"icon": strenv(icon),
"webfeeds:icon": strenv(icon),
"webfeeds:cover": {
"+@image": strenv(icon)
},
"entry": env(entries)
}
'
}
# Monitor directory for file modifications and print names of modified files
monitor() {
# Use unbuffered uniq to suppress multiple events within the same second,
# then throw away timestamp column
inotifywait --monitor --quiet --recursive --event modify,moved_to \
--exclude '\.sw.$' --timefmt '%s' --format $'%T\t%w%f' . \
| stdbuf --output=L uniq \
| stdbuf --output=L cut --field 2
}
# Serve blog from localhost
serve() {
if [[ ! -e docs/index.html ]]; then
die "can't find index file; try \"pbb build\""
fi
python -m http.server --directory docs &
local pid=$!
trap 'kill $pid' EXIT
# Rebuild only changed files
local fname
while IFS= read -r fname; do
case $fname in
./*.md)
echo "Rebuilding $fname..."
md2html "${fname#./}"
;;
./images/*)
echo "Copying $fname to images..."
cp "$fname" docs/images
;;
esac
done < <(monitor)
}
# Commit changes in publishing source and push them
deploy() {
if [[ ! -e docs/index.html ]]; then
die "can't find index file; try \"pbb build\""
fi
git add docs
git commit --message='Publish blog'
git push "${args[@]}"
}
main() {
set -o errexit -o pipefail
if (($# < 1)); then
usage
exit 1
fi
local subcmd=$1
case $subcmd in
help) usage ;;
init)
if (($# < 2)); then
die "usage: pbb init TITLE"
fi
init "${*:2}"
;;
set)
if (($# < 3)); then
die "usage: pbb set PROPERTY VALUE"
fi
local property=$2
case $property in
title) setblogtitle "${*:3}" ;;
gccode) setgccode "$3" ;;
baseurl | authorname | authoremail) setconfvalue "$property" "$3" ;;
*) die "invalid property \"$3\"" ;;
esac
;;
enable)
if (($# < 2)); then
die "usage: pbb enable FEATURE"
fi
setfeature "$2" 'on'
;;
disable)
if (($# < 2)); then
die "usage: pbb disable FEATURE"
fi
setfeature "$2" 'off'
;;
build) build ;;
serve) serve ;;
deploy) deploy ;;
*)
usage
exit 1
;;
esac
}
if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
main "$@"
fi