From afd273d6365e9e99ace043920ffa40ae8a408db1 Mon Sep 17 00:00:00 2001 From: Liam Cervante Date: Tue, 19 Jul 2022 10:14:28 +0100 Subject: [PATCH] Add goimports as a check to the Github commit actions (#31432) * Add goimports as a check to the Github commit actions * check diff against main instead of last commit * goimports should fix the problems * fix up conditionals and wildcard matching * specify origin/main in diff * fetch main branch when checkout * back to origin main --- .github/workflows/checks.yml | 8 +++++++- Makefile | 5 ++++- scripts/goimportscheck.sh | 19 +++++++++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100755 scripts/goimportscheck.sh diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index dd92ecf722..56165d3934 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -141,6 +141,8 @@ jobs: steps: - name: "Fetch source code" uses: actions/checkout@v2 + with: + fetch-depth: 0 # We need to do comparisons against the main branch. - name: Determine Go version id: go @@ -178,9 +180,13 @@ jobs: restore-keys: | protobuf-tools- + - name: Install CI tooling + run: | + go install golang.org/x/tools/cmd/goimports@v0.1.11 + - name: "Code consistency checks" run: | - make fmtcheck generate staticcheck exhaustive protobuf + make fmtcheck importscheck generate staticcheck exhaustive protobuf if [[ -n "$(git status --porcelain)" ]]; then echo >&2 "ERROR: Generated files are inconsistent. Run 'make generate' and 'make protobuf' locally and then commit the updated files." git >&2 status --porcelain diff --git a/Makefile b/Makefile index e14991b6ab..f393c1fb3e 100644 --- a/Makefile +++ b/Makefile @@ -35,6 +35,9 @@ protobuf: fmtcheck: @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" +importscheck: + @sh -c "'$(CURDIR)/scripts/goimportscheck.sh'" + staticcheck: @sh -c "'$(CURDIR)/scripts/staticcheck.sh'" @@ -63,4 +66,4 @@ website/build-local: # under parallel conditions. .NOTPARALLEL: -.PHONY: fmtcheck generate protobuf website website-test staticcheck website/local website/build-local +.PHONY: fmtcheck importscheck generate protobuf website website-test staticcheck website/local website/build-local diff --git a/scripts/goimportscheck.sh b/scripts/goimportscheck.sh new file mode 100755 index 0000000000..6747d48d0d --- /dev/null +++ b/scripts/goimportscheck.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +# Check goimports +echo "==> Checking the code complies with goimports requirements..." +target_files=$(git diff --name-only origin/main | grep "\.go") + +if [[ -z ${target_files} ]]; then + exit 0 +fi + +goimports_files=$(goimports -w -l -local github.com/hashicorp/terraform/ ${target_files}) +if [[ -n ${goimports_files} ]]; then + echo 'goimports needs running on the following files:' + echo "${goimports_files}" + echo "You can use the command and flags \`goimports -w -l -local github.com/hashicorp/terraform/\` to reformat the code" + exit 1 +fi + +exit 0