#!/bin/sh
# Checks that Radiance sources are in the canonical style, without changing
# them. Run from the repository top level.
#
# Usage: check-fmt [--staged | FILE...]
#
#   FILE...   check the given files in the working tree
#   --staged  check the staged versions of staged sources in the formatted scope
#   (none)    check every tracked source in the formatted scope
#
# The compiler is rebuilt first when it is stale. Every unformatted file is
# reported; the exit status is 1 if there is any.

# The scope globs below are git pathspecs, not shell patterns.
set -f

# Sources that are kept in the canonical style.
scope="lib/*.rad compiler/*.rad kernel/*.rad test/integration/*.rad
    test/host/*.rad"

# Memory and stack limits of hosted build tools.
limits=$(cat seed/emulator-args) || exit 2

rad=bin/radiance.rv64.dev
emulator=${RAD_EMULATOR:-emulator}

if ! make -s "$rad" >/dev/null; then
    echo "check-fmt: cannot build $rad" >&2
    exit 2
fi

tmp=
trap '[ -z "$tmp" ] || rm -rf "$tmp"' EXIT
prefix=

case ${1-} in
    --staged)
        [ $# -eq 1 ] || { echo "usage: check-fmt [--staged | FILE...]" >&2; exit 2; }
        # shellcheck disable=SC2086
        files=$(git diff --cached --name-only --diff-filter=ACMR -- $scope)
        [ -n "$files" ] || exit 0
        tmp=$(mktemp -d) || exit 2
        prefix=$tmp/
        # shellcheck disable=SC2086
        git checkout-index --prefix="$prefix" -- $files || exit 2
        ;;
    '')
        # shellcheck disable=SC2086
        files=$(git ls-files -- $scope)
        ;;
    *)
        files=$(printf '%s\n' "$@")
        ;;
esac

# Check one file per process, in parallel. xargs fails if any check does.
jobs=$(nproc 2>/dev/null || echo 4)
status=0
# shellcheck disable=SC2086
out=$(printf '%s\n' $files | sed "s|^|$prefix|" |
    xargs -P "$jobs" -n 1 "$emulator" $limits -run "$rad" -fmt.check 2>&1) ||
    status=1
if [ -n "$out" ]; then
    if [ -n "$prefix" ]; then
        out=$(printf '%s\n' "$out" | sed "s|$prefix||g")
    fi
    printf '%s\n' "$out" >&2
fi

if [ "$status" -ne 0 ]; then
    echo "check-fmt: run 'make fmt' or 'radiance -fmt' on the files above" >&2
fi
exit $status
