#!/bin/sh
# script/gofumpt: run gofumpt over this repo's Go files.
#
# Takes exactly one mode argument, --write or --check, and runs the same
# gofumpt version over the same files in both modes. script/fmt and
# script/fmt-check both go through here, and so does the Docker lint
# stage, so what gets formatted and what gets verified cannot drift
# apart.
set -eu

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

# The gofumpt version is the one bin/tools/go.mod pins. `go tool` run in
# bin/tools builds it from source checked against the hashes in
# bin/tools/go.sum, so neither a developer machine nor the lint image needs
# it installed.

usage() {
    echo "usage: script/gofumpt --write|--check" >&2
    exit 2
}

main() {
    [ "$#" -eq 1 ] || usage
    cd "$ROOT/bin/tools"
    # Every Go file in the repo, from $ROOT down. gofumpt holds generated
    # files, such as mfer/mf.pb.go, to gofmt's rules only.
    case "$1" in
        --write) go tool gofumpt -l -w "$ROOT" ;;
        --check)
            # Own line: a failing command inside `[ -n "$(...)" ]` does
            # not trip `set -e`, so a gofumpt that never ran would pass.
            unformatted="$(go tool gofumpt -l "$ROOT")"
            if [ -n "$unformatted" ]; then
                echo "gofumpt: files need formatting (run make fmt):" >&2
                echo "$unformatted" >&2
                exit 1
            fi
            ;;
        *) usage ;;
    esac
}

main "$@"
