#!/usr/bin/env bash
#
# Copyright 2024 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set -o nounset
set -o pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." &> /dev/null && pwd -P)"
cd "${REPO_ROOT}"

echo -n "Checking gofmt: "

function git_find() {
    # Similar to find but faster and easier to understand. We want to include
    # modified and untracked files because this might be running against code
    # which is not tracked by git yet.
    git ls-files -cmo --exclude-standard \
        ':!:vendor/*'        `# Exclude vendor/...` \
        ':!:*/vendor/*'      `# Exclude any subdir/vendor/...` \
        ':!:third_party/*'   `# Exclude third_party/...` \
        ':!:*/third_party/*' `# Exclude any subdir/third_party/...` \
        ':(glob)**/*.go'     `# Include only .go files` \
        "$@"
}

ERRS=$(git_find -z | xargs -0 gofmt -l 2>&1 || true)
if [ -n "${ERRS}" ]; then
    echo "FAIL - the following files need to be gofmt'ed:"
    for e in ${ERRS}; do
        echo "    $e"
    done
    echo
    exit 1
fi
echo "PASS"
echo
