about summary refs log tree commit diff stats
path: root/vienna
blob: 9080571b8574d37e778fc6c6194a34bda8f54ae1 (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
#!/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:
 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
    ## Log configuration variables
    log config "domain: $DOMAIN"
    log config "workdir: $WORKD"
    log config "output: $OUTD"
    ## 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))"
    # Further argument processing --- pre-build
    preprocess "$@"
    # 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 "Can't find configuration \`$CONFIG'."
        exit 2
    fi
    ## Plugins
    # Plugins are .*.sh files in build directory.  They're sourced here.
    for plugin in ./.*.sh; do
	case "$plugin" in
	    *"$CONFIG"*) continue ;;
	    *)
		log plugin "source $plugin"
		. "$plugin"
		;;
	esac
    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 "${1:-ok}" in
        ok) ;;
        clean)
            log vienna "clean"
            rm -r "$OUTD"
            cleanup
            exit
            ;;
    esac
}

postprocess() {
    case "${1:-ok}" in
        ok) ;;
        publish)
            log vienna "publish"
            publish "$OUTD"
            ;;
        preview)
            log vienna "preview"
            preview "$OUTD"
            ;;
        *)
            log vienna "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.
Make a $CONFIG file in this directory and write a \`publish'
function telling me what to do.  I recommend using \`rsync',
but you live your life."

EOF
    exit 3
}

preview() {
    cat <<EOF >&2

I want to show you a preview of your website but I don't
know how.  Make a $CONFIG file in this directory and write
a \`preview' function telling me what to do.  I recommend
using something like \`python -m http.server', but you live
your life."

EOF
    exit 3
}

### Utility

log() {
    if "$LOG"; then
        t="$1"
        shift
        echo >&2 "[$t]" "$@"
    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 "$@" | sed 's/^-->$//'
                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;'
}

meta() { # meta FIELD [FILE] < INPUT
    ## 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.
    field="$1"
    file="${2:-$FILE}"
    metafile="${TMPD:=.}/${file}.meta"
    test -f "$metafile" ||
        sed '/<!--/!q;/<!--/n;/-->/q' >"$metafile"
    sed -n "s/^[ \t]*$field:[ \t]*//p" <"$metafile"
}

## 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

gencheckglob() { # gencheckglob PAGE...
    ## Sanity check for PAGE(s)	in generating functions.
    # When globbing is on, if no files matching the pattern exist then the shell
    # thinks I want to work on a file named the literal glob.  Ugh.  This
    # function checks for that weirdness.
    #
    # Returns success if there's more than one argument (i.e., the glob worked),
    # or failure if there's one argument of the pattern *.$PAGE_RAW_EXT.
    if [ $# -gt 1 ]; then
	return 0
    elif [ "$1" = "*.$PAGE_RAW_EXT" ]; then
	return 1
    else
	return 0
    fi
}

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
    gencheckglob "$@" || set --
    for FILE; do
        log genpage "$FILE"
        outd="$OUTD/${FILE%.$PAGE_RAW_EXT}"
        outf="$outd/index.html"
        tmpf="$TMPD/$FILE.tmp"
        mkdir -p "$outd"
        filters <"$FILE" >"$tmpf"
        expand "$PAGE_TEMPLATE" <"$tmpf" >"$outf"
    done
}

genlist() { # genlist PERITEM_FUNC TEMPLATE_FILE PAGE...
    peritem_func="$1"
    template_file="$2"
    tmpf="$TMPD/$1"
    shift 2 || return 2
    test -f "$template_file" || return 1
    gencheckglob "$@" || { echo | expand "$template_file"; return; }
    for FILE; do
        log genlist "$peritem_func: $template_file: $FILE"
        LINK="$DOMAIN${DOMAIN:+/}${FILE%.$PAGE_RAW_EXT}"
        "$peritem_func" "$FILE"
    done | expand "$template_file"
}

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
        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 "$@"