| #!/bin/bash |
| # Copyright 2023 Google LLC |
| # |
| # 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. |
| |
| # Script to run gofmt, golint, and gazelle before commiting. |
| # To install, use the following command: |
| # ./scripts/install_precommit.sh |
| |
| set -e |
| |
| SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}") |
| source "${SCRIPT_DIR}/infra/common.sh" || exit $? |
| |
| cd "$(get_workspace_root)" |
| |
| STAGED_GO_FILES=$(git diff --cached --name-only --diff-filter=d | grep ".go$" || true) |
| |
| # Ensures that non-interactive shell sessions can run Go tools |
| if command -v go &>/dev/null; then |
| export PATH="$PATH:$(go env GOPATH)/bin" |
| fi |
| |
| # Use downloaded version of bazel instead of bazelisk |
| ./scripts/infra/bootstrap_prebuilts.sh |
| |
| # Run go mod tidy |
| run_go_mod_tidy |
| |
| GAZELLEPASS=true |
| echo Running Gazelle... |
| if ! run_bazel_tool //:gazelle; then |
| GAZELLEPASS=false |
| fi |
| |
| LINTPASS=true |
| echo Running gofmt... |
| run_bazel_tool @io_bazel_rules_go//go -- fmt ./... |
| |
| |
| |
| PASS=true |
| if ! $LINTPASS; then |
| printf "\033[0;30m\033[41mThere are lint errors. Please fix!\033[0m\n" |
| PASS=false |
| fi |
| |
| if ! $GAZELLEPASS; then |
| printf "\033[0;30m\033[41mbazelisk run //:gazelle failed. Please fix the errors and try again.\033[0m\n" |
| PASS=false |
| fi |
| |
| if ! git diff --exit-code &> /dev/null; then |
| printf "\033[0;30m\033[41mPrecommit made changes to source. Please check the changes and re-stage files.\033[0m\n" |
| PASS=false |
| fi |
| |
| if ! $PASS; then |
| printf "\033[0;30m\033[41mCOMMIT FAILED\033[0m\n" |
| exit 1 |
| else |
| printf "\033[0;30m\033[42mCOMMIT SUCCEEDED\033[0m\n" |
| fi |