~ecs/wersh

wersh/wersh -rwxr-xr-x 1.7 KiB
b5d8cd01Eyal Sawady Miscellaneous fixes 2 months 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
#!/bin/sh -eu

usage() {
	echo "Usage: $0 input/ output/"
	exit 1
}

if [ -f ./wersh.awk ]
then
	_wershawk=./wersh.awk
else
	_wershawk=wersh.awk
fi
_single=
_n=0
for arg in "$@"
do
	case $arg in
		-s)
			_single=t
			_n=$((_n + 1))
			;;
		-*)
			usage
			;;
	esac
done
[ $_n -ne 0 ] && shift $_n

render() {
	cat
}

_rendering=
content=
emit() {
	if [ "$_rendering" = "t" ]
	then
		printf "%s\n" "$@"
	elif [ "z$content" = "z" ]
	then
		content="$*"
	else
		content="$content
$*"
	fi
}

escape() {
	sed -e 's/</\&lt;/g' -e 's/>/\&gt;/g'
}

wsource() {
	_file="$(mktemp)"
	"${_wershawk}" < "$1" > "$_file"
	. "$_file"
	rm "$_file"
}

preprocessor="cat"

if [ -n "$_single" ]
then
	[ $# -ne 4 ] && usage
	root="$1"
	outputdir="$2"
	output="$3"
	input="$4"
	cd "$root"
	[ -e "$root"/_config.sh ] && . "$root"/_config.sh
	wsource "$input"
	_rendering=t
	printf "%s" "$content" | $preprocessor | render
else
	[ $# -gt 2 ] && usage
	root="${1:-.}"
	_outputdir="${2:-_site}"
	if [ ! -d "$_outputdir" ] && [ -e "$_outputdir" ]
	then
		echo "$_outputdir exists and is not a directory"
		exit 1
	else
		rm -rf "$_outputdir"
	fi
	find "$root" -type f -name "*.w" -not -path "*/_*/*" -not -name "_*" -not -path "/.*" \
	| while read -r _input
	do
		_output="$_outputdir${_input#$root}"
		_output="${_output%.w}"
		echo "Generating $_output from $_input"
		mkdir -p "$(dirname "$_output")"
		$0 -s "$root" "$_outputdir" "$_output" "${_input#$root/}" > "$_output"
	done
	find "$root" -type f -not -name "*.w" -not -path "*/_*/*" -not -name "_*" -not -path "*/.*" \
	| while read -r _input
	do
		_output="$_outputdir${_input#$root}"
		echo "Copying $_input to $_output"
		mkdir -p "$(dirname "$_output")"
		cp "$_input" "$_output"
	done
fi