verify-gofmt.sh 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env bash
  2. # Copyright 2014 The Kubernetes Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # This script checks whether the source codes need to be formatted or not by
  16. # `gofmt`. We should run `hack/update-gofmt.sh` if actually formats them.
  17. # Usage: `hack/verify-gofmt.sh`.
  18. # Note: GoFmt apparently is changing @ head...
  19. set -o errexit
  20. set -o nounset
  21. set -o pipefail
  22. KUBE_ROOT=$(dirname "${BASH_SOURCE[0]}")/..
  23. source "${KUBE_ROOT}/hack/lib/init.sh"
  24. cd "${KUBE_ROOT}"
  25. # Prefer bazel's gofmt.
  26. gofmt="external/io_bazel_rules_go_toolchain/bin/gofmt"
  27. if [[ ! -x "${gofmt}" ]]; then
  28. gofmt=$(which gofmt)
  29. kube::golang::verify_go_version
  30. fi
  31. find_files() {
  32. find . -not \( \
  33. \( \
  34. -wholename './output' \
  35. -o -wholename './.git' \
  36. -o -wholename './_output' \
  37. -o -wholename './_gopath' \
  38. -o -wholename './release' \
  39. -o -wholename './target' \
  40. -o -wholename '*/third_party/*' \
  41. -o -wholename '*/vendor/*' \
  42. -o -wholename './staging/src/k8s.io/client-go/*vendor/*' \
  43. -o -wholename '*/bindata.go' \
  44. \) -prune \
  45. \) -name '*.go'
  46. }
  47. # gofmt exits with non-zero exit code if it finds a problem unrelated to
  48. # formatting (e.g., a file does not parse correctly). Without "|| true" this
  49. # would have led to no useful error message from gofmt, because the script would
  50. # have failed before getting to the "echo" in the block below.
  51. diff=$(find_files | xargs "${gofmt}" -d -s 2>&1) || true
  52. if [[ -n "${diff}" ]]; then
  53. echo "${diff}" >&2
  54. echo >&2
  55. echo "Run ./hack/update-gofmt.sh" >&2
  56. exit 1
  57. fi