#!/bin/sh
# script/fmt-check: check formatting (read-only). Same scope as
# script/fmt, but fails instead of writing.
set -eu

ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"

main() {
    cd "$ROOT"
    # Where script/bootstrap installs Go when the host has none.
    PATH="$PATH:$ROOT/.tool/go/bin"
    # The Go files git lists, which leaves out the sources of that
    # toolchain in the ignored .tool/go. git still lists a tracked file
    # whose deletion is not staged yet, and gofmt fails on a missing file.
    listed="$(git ls-files --cached --others --exclude-standard '*.go')" || {
        echo "fmt-check: git ls-files failed; run it in a git checkout" >&2
        exit 1
    }
    files=""
    for f in $listed; do
        if [ -e "$f" ]; then
            files="$files $f"
        fi
    done
    # gofmt with no file arguments reads standard input.
    if [ -z "$files" ]; then
        exit 0
    fi
    # shellcheck disable=SC2086 # one argument per file name
    unformatted="$(gofmt -l $files)"
    if [ -n "$unformatted" ]; then
        echo "Files not formatted:" >&2
        echo "$unformatted" >&2
        exit 1
    fi
}

main "$@"
