about summary refs log tree commit diff
path: root/pkgs/test/make-binary-wrapper/golden-test-utils.sh
blob: a0408b5a90896249755d31b8fcf509eb4304f95f (plain) (blame)
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
#!/usr/bin/env bash
# Split a generated C-file into the command used to generate it,
# and the outputted code itself.

# This is useful because it allows input and output to be inside the same file

# How it works:
# - The first line needs to start with '//' (and becomes the command).
# - Whitespace/padding between the comment and the generated code is ignored
# - To write a command using multiple lines, end each line with backslash (\)

# Count the number of lines before the output text starts
# commandLineCount FILE
commandLineCount() {
	local n state
	n=0
	state="init"
	while IFS="" read -r p || [ -n "$p" ]; do
		case $state in
			init)
				if [[ $p =~ ^//.*\\$ ]]; then state="comment"
				elif [[ $p =~ ^//.* ]]; then state="padding"
				else break
				fi
			;;
			comment) [[ ! $p =~ ^.*\\$ ]] && state="padding";;
			padding) [ -n "${p// }" ] && break;;
		esac
		n=$((n+1))
	done < "$1"
	printf '%s' "$n"
}

# getInputCommand FILE
getInputCommand() {
    n=$(commandLineCount "$1")
    head -n "$n" "$1" | awk '{ if (NR == 1) print substr($0, 3); else print $0 }'
}

# getOutputText FILE
getOutputText() {
    n=$(commandLineCount "$1")
    sed "1,${n}d" "$1"
}