about summary refs log tree commit diff stats
path: root/subtext.sh
blob: f3844686146a026096cd4013562c095c56d0f491 (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
#!/bin/sh

stawk() {
	awk -f subtext.awk "$@"
}

usage() {
	cat>&2 <<EOF
SUBTEXT v.meowmers (C) Case Duckworth
Usage:	subtext [OPTIONS] FILE...
	subtext < FILE
Options:
 -h		Show this help and exit.
 -n		Don't run the resulting script; just print it.
 -x		Trace sh execution (sh -x).
 -m FILE	Use macrofile FILE.
 -I DIRECTORY	Add DIRECTORY to the search path.
 -o FILE	Output to FILE instead of stdout.
EOF
	exit $1
}

configure() {
	## Initialize state variables
	: "${ST_MACROFILE:=}"
	: "${ST_SOPATH:=.:$HOME/.subtext}"
	: "${ST_PIPE_SH:=true}"
	: "${ST_TRACE=+x}"
	## Process options
	while getopts :hnxm:I:o: OPT
	do
		case "$OPT" in
			(h) usage ;;
			(n) ST_PIPE_SH=false ;;
			(x) ST_TRACE=-x ;;
			(m) ST_MACROFILE="$OPTARG.st.sh" ;;
			(I) ST_SOPATH="$ST_SOPATH:$OPTARG" ;;
			(o) exec > "$OPTARG" ;;
			## bad arguments
			(:) printf >&2 'Unknown option -%s\n' "$OPTARG";
			    usage 1 ;;
			(*) usage 1 ;;
		esac
	done
}

main() {
	configure "$@"
	shift $((OPTIND-1))
	stawk -vsopath="$ST_SOPATH" -vsofile="$ST_MACROFILE" "$@" |
		if "$ST_PIPE_SH"
		then sh "$ST_TRACE"
		else cat
		fi
}

die() {
	ec="$1"; shift
	printf >&2 '!! %s\n' "$*"
	exit "$ec"
}

main  "$@"