about summary refs log tree commit diff stats
path: root/vienna
blob: 7a7818d6e7beea83b12e29fc4fe49cac29a4539b (plain)
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
#!/bin/sh
# vienna --- a tiny, tasty ssg
# by C. Duckworth <acdw@acdw.net>
# shellcheck disable=1090,2035

### Entry point

usage() {
    cat <<EOF
VIENNA: a tiny, tasty ssg
by C. Duckworth <acdw@acdw.net>

USAGE: vienna [-h]
       vienna [-q] [-c CONFIG] [-C DIR] [-d DOMAIN] [-o DIR] [COMMAND]

FLAGS:
 -h         view this help
 -q         don't output any diagnostic information

OPTIONS:
 -c CONFIG  source CONFIG instead of \$VIENNA_CONFIG when building
 -C DIR     operate in DIR, instead of \$PWD.
 -d DOMAIN  use DOMAIN as basis for urls. default: example.com
 -o DIR     output built site to DIR. default: ./out

PARAMETERS:
 init	    initialize a vienna site with default files and exit.
 clean      remove output directory before building.
 publish    publish the site after building.
            NOTE: this requires a .vienna.sh file in the site root.
            you'll have to define a \`publish' function there.
 preview    preview the site locally after building.
            NOTE: this requires a .vienna.sh file in the site root.
            you'll have to define a \`preview' function there.

you can redefine any variables or functions vienna uses in \$VIENNA_CONFIG,
which by default is ./.vienna.sh.  vienna uses heredoc-inspired templating, so
you can include shell snippets and variables by doubling the dollar signs.

EOF
    exit "${1:-0}"
}

configure() {
    ## Set up environment
    DOMAIN="${VIENNA_DOMAIN:-https://www.example.com}"
    TMPD="${VIENNA_TMPD:-/tmp/vienna}"
    WORKD="${VIENNA_WORKD:-$PWD}"
    OUTD="${VIENNA_OUTD:-out}"
    CONFIG="${VIENNA_CONFIG:-./.vienna.sh}"
    # Templates
    PAGE_TEMPLATE="${VIENNA_PAGE_TEMPLATE:-.page.tmpl.html}"
    INDEX_TEMPLATE="${VIENNA_INDEX_TEMPLATE:-.index.tmpl.html}"
    FEED_TEMPLATE="${VIENNA_FEED_TEMPLATE:-.feed.tmpl.xml}"
    # File extensions
    PAGE_RAW_EXT="${VIENNA_PAGE_RAW_EXT:-htm}"
    # Logging
    LOG=true
    ## Parse command line arguments
    while getopts C:c:d:ho:q opt; do
        case "$opt" in
            C) WORKD="$OPTARG" ;;
            c)
                CONFIG="$OPTARG"
                # To error later if a config is specified on the command
                # line but doesn't exist.
                CONFIG_ARG=1
                ;;
            d) DOMAIN="$OPTARG" ;;
            h) usage 0 ;;
            o) OUTD="$OPTARG" ;;
            q) LOG=false ;;
            *) exit 1 ;;
        esac
    done
    ## Initialize state
    FILE=
    ## Cleanup after we're done
    trap cleanup INT QUIT
}

main() {
    # State predicates
    alias pagep=false indexp=false feedp=false
    # Convenience aliases
    alias body=cat title='meta title' pubdate='meta date'
    # Configure
    configure "$@"
    shift "$((OPTIND - 1))"
    # Prepare
    cd "$WORKD" || exit 2
    if test -f "$CONFIG"; then
        # Source ./.vienna.sh, if it exists.
        . "$CONFIG"
    elif test -n "$CONFIG_ARG"; then
        # If a -c option was passed on the command line but the file
        # doesn't exist, that's an error.  If we're just looking for the
        # default file, however, there is no error---the user might want
        # to use the default configuration.
        log error "Can't find configuration \`$CONFIG'."
        exit 2
    fi
    # Further argument processing --- pre-build
    preprocess "$@" || shift
    ## Log configuration variables
    log config domain: "$DOMAIN"
    log config workdir: "$WORKD"
    log config output: "$OUTD"
    log config page.tmpl: "$PAGE_TEMPLATE"
    log config index.tmpl: "$INDEX_TEMPLATE"
    log config feed.tmpl: "$FEED_TEMPLATE"
    ## Plugins
    # Plugins are *.sh files in $WORKD/.plugins/.  They're sourced here.
    for plugin in ./.*.sh; do
	test -f "$plugin" || continue
	log plugin "$plugin"
	. "$plugin"
    done
    mkdir -p "$OUTD" || exit 2
    mkdir -p "$TMPD" || exit 2
    # Build pages
    alias pagep=true
    genpage *."$PAGE_RAW_EXT" || exit 2
    alias pagep=false
    # Build index
    alias indexp=true
    genlist index_item "$INDEX_TEMPLATE" *."$PAGE_RAW_EXT" >"$OUTD/index.html" || exit 2
    alias indexp=false
    # Build feed
    alias feedp=true
    genlist feed_item "$FEED_TEMPLATE" *."$PAGE_RAW_EXT" >"$OUTD/feed.xml" || exit 2
    alias feedp=false
    # Copy static files
    static * || exit 2
    # Further argument processing --- post-build
    postprocess "$@"
}

preprocess() {
    case "$*" in
	*preview*) DOMAIN=http://localhost:${VIENNA_PREVIEW_PORT:-8000} ;;
    esac

    case "${1:-ok}" in
        ok) ;;
	init)
	    log vienna initializing...
	    shift
	    initialize "$@"
	    log vienna initialized.
	    exit
	    ;;
        clean)
	    log vienna clean
	    rm -r "$OUTD"
	    cleanup
	    if [ $# -eq 0 ]; then
		exit		# Quit when only cleaning
	    else
		return 1	# Otherwise, continue processing
	    fi
	    ;;
    esac
}

postprocess() {
    case "${1:-ok}" in
        ok) ;;
        publish)
            log vienna publish
            publish "$OUTD"
            ;;
        preview)
            log vienna preview
            preview "$OUTD"
            ;;
        *)
            log error "Don't know command \`$1'."
            exit 1
            ;;
    esac
}

cleanup() {
    test -z "$DEBUG" &&
        test -z "$NODEP_RM" &&
        rm -r "$TMPD"
}

_publish() {
    cat <<EOF >&2

I want to publish your website but I don't know how.
$(if test -f "$CONFIG";
then echo "Edit the";
else echo "Write a";
fi) \`publish' function in the \`$CONFIG' file in this
directory that tells me what to do.

EOF
    exit 3
}
alias publish=_publish

_preview() {
    cat <<EOF >&2

I want to show you a preview of your website but I don't
know how.  $(if test -f "$CONFIG";
then echo "Edit the";
else echo "Write a";
fi) \`preview' function in the \`$CONFIG' file
in this directory that tells me what to do.

EOF
    exit 3
}
alias preview=_preview

initialize() { # initialize
    cat >"$CONFIG" <<EOF
# .vienna.sh
DOMAIN="$DOMAIN"
OUTD="$OUTD"
PAGE_TEMPLATE="$PAGE_TEMPLATE"
INDEX_TEMPLATE="$INDEX_TEMPLATE"
FEED_TEMPLATE="$FEED_TEMPLATE"

# Edit this with your web server's file path
WWW_ROOT=

preview() {
    export _PYTHON="$(command -v python3 || command -v python)"
    if [ -n "$_PYTHON" ]; then
	pkill -x "$_PYTHON"
	"$_PYTHON" -m http.server -d "$OUTD" &
	export _VIENNA_PID="$!"
	find . -type f -not -path "*/$OUTD/*" |
            OUTD="$OUTD" entr -rp \
		sh -c 'kill "$_VIENNA_PID" >/dev/null 2>&1;
	    vienna && "$_PYTHON" -m http.server -d "$OUTD"'
    else
	log error "\`python' not found."
	_preview
    fi
}

publish() {
    if [ -n "$WWW_ROOT" ]; then
	rsync -avzP --delete "$OUTD/" "$WWW_ROOT/"
    else
	_preview
    fi
}
EOF
    cat >"$PAGE_TEMPLATE" <<\EOF
<title>$$(title)</title>
$$(body)
EOF
    cat >"$INDEX_TEMPLATE" <<\EOF
<title>a home page!</title>
<h1>hey! it's a home page of some sort!</h1>
<ul>
$$(body)
</ul>
EOF
    cat >"$FEED_TEMPLATE" <<\EOF
<rss version="2.0">
  <channel>
    <title>a feed!</title>
    <link>$$BASEURL</link>
    $$(body)
  </channel>
</rss>
EOF
}

### Utility

log() {
    if "$LOG"; then
	printf >&2 '[%s] ' "$1"
        shift
        printf >&2 "%s\t" "$@"
	echo >&2
    fi
}

print() {
    printf '%s\n' "$*"
}

### File processing

## Building block functions

shellfix() { # shellfix FILE...
    ## Replace ` with \`, $ with \$, and $$ with $
    # shellcheck disable=2016
    sed -E \
        -e 's/`/\\`/g' \
        -e 's/(^|[^\$])\$([^\$]|$)/\1\\$\2/g' \
        -e 's/\$\$/$/g' \
        "$@"
}

expand() { # expand TEMPLATE... < INPUT
    ## Print TEMPLATE to stdout, expanding shell constructs.
    end="expand_:_${count:=0}_:_end"
    eval "$(
                echo "cat<<$end"
                shellfix "$@"
                echo
                echo "$end"
        )" && count=$((count + 1))
}

phtml() { # phtml < INPUT
    ## Output HTML, pretty much.
    # Paragraphs unadorned with html tags will be wrapped in <p> tags, and
    # &, <, > will be escaped unless prepended with \.  Paragraphs where the
    # first character is < will be left as-is, excepting indentation on the
    # first line (an implementation detail).
    sed -E \
        '/./{H;1h;$!d;}; x;
                s#^[ \n\t]+[^<].*#&#;
                t par; b;
                :par;
                        s#([^\\])&#\1\&amp;#g; s#\\&#\&#g;
                        s#([^\\])<#\1\&lt;#g; s#\\<#<#g;
                        s#([^\\])>#\1\&gt;#g; s#\\>#>#g;
			s#.*#<p>&</p>#'
}

meta_init() { # meta_init FILE
    ## Extract metadata from FILE for later processing.
    # Metadata should exist as colon-separated data in HTML comments in the
    # input file.
    metafile=
    m=false
    t=false
    while read -r line; do
	case "$line" in
	    '<!--') m=true ;;
	    '-->') m=false ;;
	    *title:*) t=true && print "$line" ;;
	    *) "$m" && print "$line" ;;
	esac
    done <"$1"
    if ! "$t"; then
	title="${1##*/}"
	title="${title%.*}"
	print "title: ${title%.*}"
    fi
}

meta() { # meta FIELD [FILE]
    ## Extract metadata FIELDS from INPUT.
    # FILE gives the filename to save metadata to in the $WORKD.  It
    # defaults to the current value for $FILE.
    #
    # Metadata should exist as colon-separated data in an HTML comment at
    # the beginning of an input file.
    sed -n "s/^[ \t]*$1:[ \t]*//p" <"${2:-$META}"
}

## Customizable bits

filters() { # filters < INPUT
    ## The filters to run input through.
    # This is a good candidate for customization in .vienna.sh.
    phtml | expand
}

### Site building

genpage() { # genpage PAGE...
    ## Compile PAGE(s) into $OUTD for publication.
    # Outputs a file of the format $OUTD/<PAGE>/index.html.
    test -f "$PAGE_TEMPLATE" || return 1
    for FILE; do
	test -f "$FILE" || continue
	log genpage "$FILE"
        outd="$OUTD/${FILE%.$PAGE_RAW_EXT}"
        outf="$outd/index.html"
        tmpf="$TMPD/$FILE.tmp"
	META="$TMPD/$FILE.meta"
        mkdir -p "$outd"
	meta_init "$FILE" >"$META"
        filters <"$FILE" >"$tmpf"
        expand "$PAGE_TEMPLATE" <"$tmpf" >"$outf"
    done
}

genlist() { # genlist PERITEM_FUNC TEMPLATE_FILE PAGE...
    ## Generate a list.
    peritem_func="$1"
    template_file="$2"
    tmpf="$TMPD/$1"
    shift 2 || return 2
    test -f "$template_file" || return 1
    printf '%s\n' "$@" | sort_items |
	while read -r FILE; do
	    test -f "$FILE" || continue
            log genlist "$peritem_func" "$FILE"
            LINK="$DOMAIN${DOMAIN:+/}${FILE%.$PAGE_RAW_EXT}"
	    META="$TMPD/$FILE.meta"
            "$peritem_func" "$FILE"
	done | expand "$template_file"
}

sort_items() { # sort_items < ITEMS
    ## Sort ITEMS separated by newlines.
    # This function assumes that no ITEM contains a newline.
    cat
}

index_item() { # index_item PAGE
    ## Construct a single item in an index.html.
    echo "<li><a href=\"$LINK\">$(meta title "$1")</a></li>"
}

feed_item() { # feed_item PAGE
    ## Construct a single item in an RSS feed.
    date="$(meta date "$1")"
    echo "<item>"
    echo "<title>$(meta title "$1")</title>"
    echo "<link>$LINK</link>"
    echo "<guid>$LINK</guid>"
    test -n "$date" && echo "<pubDate>$date</pubDate>"
    echo "</item>"
}

static() { # static FILE...
    ## Copy static FILE(s) to $OUTD as-is.
    # Performs a simple heuristic to determine whether to copy a file or
    # not.
    for FILE; do
	test -f "$FILE" || continue
        case "$FILE" in
            .*) continue ;;
            *.htm) continue ;;
            "$OUTD") continue ;;
            *) cp -r "$FILE" "$OUTD/" ;;
        esac
    done
}

### Do the thing!

test -n "$DEBUG" && set -x
test -n "$SOURCE" || main "$@"