-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathxsl-transform
101 lines (91 loc) · 2.68 KB
/
xsl-transform
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
#!/usr/bin/env bash
SHAREDIR=$(cd $(dirname "$0") && pwd)
function log {
echo >&2 "$(date +%T.%3N) $LEVEL ocrd-import - $1"
}
function critical { LEVEL=CRITICAL log "$1"; }
function error { LEVEL=ERROR log "$1"; }
function warning { LEVEL=WARNING log "$1"; }
function info { LEVEL=INFO log "$1"; }
function debug { LEVEL=DEBUG log "$1"; }
((BASH_VERSINFO<4 || BASH_VERSINFO==4 && BASH_VERSINFO[1]<4)) && critical "bash $BASH_VERSION is too old. Please install 4.4 or newer" && exit 2
name=$(basename $0)
if [[ "$name" =~ ^page- ]]; then
type="PAGE-XML"
elif [[ "$name" =~ ^mets- ]]; then
type="METS-XML"
else
type="input"
fi
parameters=()
pretty=0
inplace=0
diff=0
while (($#)); do
case "${1:--h}" in
-h|-[-]help)
cat <<EOF
Usage: $name [OPTIONS] [FILE]
with options:
-s name=value set param NAME to string literal VALUE (repeatable)
-p name=value set param NAME to XPath expression VALUE (repeatable)
-i|--inplace overwrite input file with result of transformation
-P|--pretty pretty-print output (line breaks with indentation)
-d|--diff show diff between input and output
-D|--dump just print the transformation stylesheet (XSL)
-h|--help just show this message
Open $input file FILE (or stdin) and apply the XSL transformation "$name.xsl"
Write the result to stdout, unless...
-i / --inplace is given - in which case the result is written back to the
file silently, or
-d / --diff is given - in which case the result will be compared to the
input and a patch shown on stdout.
EOF
exit
;;
-s|-p)
[[ "$2" =~ .*=.* ]] || critical "invalid parameter syntax '$2'"
parameters+=( "$1" "$2" )
shift
shift
;;
-D|--dump)
cat "$SHAREDIR"/$name.xsl
exit
;;
-P|--pretty)
pretty=1
shift
;;
-i|--inplace)
inplace=1
shift
;;
-d|--diff)
diff=1
shift
;;
*)
break
;;
esac
done
(($#>1)) && warning "non-first argument(s) will be ignored: '${@:2}'"
file="${1:--}"
set -e
test -e "$SHAREDIR"/$name.xsl
if test "x$file" = x-; then
file=$(mktemp)
cat > $file
fi
output="$(xmlstarlet tr "$SHAREDIR"/$name.xsl "${parameters[@]}" "$file")"
if ((pretty)); then
output="$(echo "$output" | xmlstarlet fo -s 2 -)"
fi
if ((diff)); then
diff -u <(cat "$file" | if ((pretty)); then xmlstarlet fo -s 2 -; fi) <(echo "$output")
elif ((inplace)); then
echo "$output" > "$file"
else
echo "$output"
fi