aboutsummaryrefslogtreecommitdiffstats
path: root/.githooks/pre-commit
blob: b286691a3d12c2be242ff42c9b578c1eff2ba14e (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
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
#!/bin/sh
#
# This hook checks that all local sources specified in the staged APKBUILDs
# are staged too or already committed and that checksums are correct.
#
set -eu

if ! command -v sha512sum >/dev/null; then
	# macOS / BSDs (?) don't have sha512sum, but shasum.
	alias sha512sum='shasum -a 512'
fi

error() {
	printf '\033[0;31mpre-commit:\033[0m %s\n' "$1" >&2  # red
}

# Prints paths of created or modified APKBUILDs being committed.
changed_apkbuilds() {
	git diff-index \
		--name-only \
		--cached \
		--diff-filter=ACMR HEAD \
		-- '**/APKBUILD'
}

# Prints file names and checksums (in format <SHA-512>:<filename>) of local
# sources specified in the APKBUILD ($1).
abuild_local_sources() {
	apkbuild="$1"

	set +eu
	. "$apkbuild" || {
		error "$apkbuild is invalid"
		return 1
	}
	set -eu

	status=0
	for src in $source; do
		# Skip remote sources.
		case "$src" in */*) continue;; esac

		echo "$sha512sums" | awk -v src="$src" '
				{ if ($2 == src) { ok=1; print($2 ":" $1) } }
				END { if (ok != 1) exit 1 }' || {
			status=1
			error "${apkbuild%/*}: file \"$src\" is missing in \$sha512sums (hint: run abuild checksum)"
		}
	done

	return $status
}

# Checks that all local sources specified in the APKBUILD file ($1) are
# available in git tree and checksums are correct.
check_local_sources() {
	local apkbuild="$1"
	local startdir="${apkbuild%/*}"
	local status=0
	local checksum_act checksum_exp content filename line sources

	sources=$(abuild_local_sources "$apkbuild")
	for line in $sources; do
		filename=${line%%:*}
		checksum_exp=${line#*:}

		if ! git cat-file -e ":$startdir/$filename" 2>/dev/null; then
			error "$startdir: missing file \"$filename\""
			status=1
			continue
		fi
		checksum_act=$(git show ":$startdir/$filename" | sha512sum)
		if [ "$checksum_act" != "$checksum_exp  -" ]; then
			error "$startdir: bad checksum for file \"$filename\" (hint: run abuild checksum)"
			status=1
		fi
	done

	return $status
}


for apkbuild in $(changed_apkbuilds); do
	check_local_sources "$apkbuild"
done