summaryrefslogtreecommitdiff
path: root/tools/notsd-fixup
blob: 1d4287b2590998eab4cd2fd0fbc402b7c90c95bd (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
64
65
66
67
68
69
#!/usr/bin/env bash
# Copyright (C) 2015-2016  Luke Shumaker

# The reason we do `find`/`while read`-loops instead of `find -exec` commands
# is that we want errors from the inner loop to bubble up.

fixup_makefiles() (
	find "$@" -type f -name Makefile | while read -r filename; do
		{
			<"$filename" sed -r \
			 -e "s|(/\.\.)*/config.mk|/$(realpath -ms --relative-to="$(dirname -- "$filename")" config.mk)|" \
			 -e '/^nested\.subdirs/d' \
			 -e '/^include \$\(topsrcdir\)\/build-aux\/Makefile\.tail\.mk$/d'
			echo
			find "$(dirname "$filename")" -mindepth 2 -maxdepth 2 -name Makefile -print0 |
			    xargs -r0 dirname -z -- |
			    xargs -r0 basename -a -z |
			    xargs -r0 printf 'nested.subdirs += %s\n' | sort
			echo
			echo 'include $(topsrcdir)/build-aux/Makefile.tail.mk'
		} | cat -s | build-aux/write-ifchanged "$filename"
	done
)

fixup_includes() (
	dirs=($(find "$@" -type d -name include))
	if [[ ${#dirs[@]} -gt 0 ]]; then
		find "${dirs[@]}" -type d | while read -r dir; do
			lib="${dir##*/}"
			find "$dir" -type f | while read -r filename; do
				>&2 printf ' => sed -r %q < %q\n' "s|$lib/||" "$filename"
				sed -r "s|$lib/||" < "$filename" | build-aux/write-ifchanged "$filename"
			done
		done
	fi

	find "$@" \( -name '*.h' -o -name '*.c' -o -name '*.gperf' \) -type f | while read -r filename; do
		false
		# We copy the write-ifchanged logic to here, because we have a
		# higher-than usual chance of the main command failing.  In a
		# Makefile we would handle this by setting .DELETE_ON_ERROR:,
		# but we can't do that here, so we have to inter-mingle the
		# logics.
		local outfile="$filename"
		tmpfile="$(dirname "$outfile")/.tmp.${outfile##*/}.tmp"
		local r=0
		"$0"--includes "$filename" > "$tmpfile" || r=$?
		if [[ $r != 0 ]]; then
			rm -f "$tmpfile" || :
			(exit $r)
		fi
		if cmp -s "$tmpfile" "$outfile"; then
			rm -f "$tmpfile" || :
		else
			mv -f "$tmpfile" "$outfile"
		fi
	done
	rm -rf -- "$0"--includes.cache
)

main() {
	set -e
	set -o pipefail
	export LC_COLLATE=C
	fixup_makefiles "$@"
	fixup_includes "$@"
}

main "$@"