From f87b781ebc3a4f8f5d7c0f8c07941cbbe6154cad Mon Sep 17 00:00:00 2001 From: hc-github-team-secure-vault-core <82990506+hc-github-team-secure-vault-core@users.noreply.github.com> Date: Tue, 11 Jul 2023 10:44:40 -0400 Subject: [PATCH] backport of commit a9778be3f2735ea242c5ea05a2a805fa18e7df4f (#21756) Co-authored-by: Mike Palmiotto --- .hooks/pre-commit | 7 +++++-- scripts/gofmtcheck.sh | 11 +++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/.hooks/pre-commit b/.hooks/pre-commit index 18857f33f..d2d52a71a 100755 --- a/.hooks/pre-commit +++ b/.hooks/pre-commit @@ -62,11 +62,14 @@ ui_lint() { backend_lint() { # Silently succeed if no changes staged for Go code files. - if git diff --name-only --cached --exit-code -- '*.go'; then + staged=$(git diff --name-only --cached --exit-code -- '*.go') + ret=$? + if [ $ret -eq 0 ]; then return 0 fi - ./scripts/gofmtcheck.sh || block "Backend linting failed; run 'make fmt' to fix." + # Only run fmtcheck on staged files + ./scripts/gofmtcheck.sh "${staged}" || block "Backend linting failed; run 'make fmt' to fix." } for CHECK in $CHECKS; do diff --git a/scripts/gofmtcheck.sh b/scripts/gofmtcheck.sh index 886f1968d..19d4adbff 100755 --- a/scripts/gofmtcheck.sh +++ b/scripts/gofmtcheck.sh @@ -2,10 +2,17 @@ # Copyright (c) HashiCorp, Inc. # SPDX-License-Identifier: MPL-2.0 - echo "==> Checking that code complies with gofmt requirements..." -gofmt_files="$(find . -name '*.go' | grep -v pb.go | grep -v vendor | xargs go run mvdan.cc/gofumpt -l)" +files=$(echo $1 | xargs) +if [ -n "$files" ]; then + echo "Checking changed files..." + gofmt_files="$(echo $1 | grep -v pb.go | grep -v vendor | xargs go run mvdan.cc/gofumpt -l)" +else + echo "Checking all files..." + gofmt_files="$(find . -name '*.go' | grep -v pb.go | grep -v vendor | xargs go run mvdan.cc/gofumpt -l)" +fi + if [[ -n "${gofmt_files}" ]]; then echo 'gofumpt needs running on the following files:' echo "${gofmt_files}"