#!/bin/sh
# script/fmt-check: check formatting (read-only). Fails instead of
# writing. It checks every Go file outside .tool, which is more than
# script/fmt formats: `go fmt ./...` skips `testdata` directories and
# files and directories whose names start with `.` or `_`. Fix a file
# only this reports with `gofmt -w`.
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"
    # .tool/go holds that toolchain's own sources, which are not ours.
    if ! unformatted="$(find . -path ./.tool -prune -o -name '*.go' -type f \
        -exec gofmt -l {} +)"; then
        echo "fmt-check: gofmt failed" >&2
        exit 1
    fi
    if [ -n "$unformatted" ]; then
        echo "Files not formatted:" >&2
        echo "$unformatted" >&2
        exit 1
    fi
}

main "$@"
