github.com/pulumi/terraform@v1.4.0/scripts/goimportscheck.sh (about) 1 #!/usr/bin/env bash 2 3 set -euo pipefail 4 5 # Check goimports 6 echo "==> Checking the code complies with goimports requirements..." 7 8 # We only require goimports to have been run on files that were changed 9 # relative to the main branch, so that we can gradually create more consistency 10 # rather than bulk-changing everything at once. 11 12 declare -a target_files 13 # "readarray" will return an "unbound variable" error if there isn't already 14 # at least one element in the target array. "readarray" will overwrite this 15 # item, though. 16 target_files[0]="" 17 18 base_branch="origin/main" 19 20 # HACK: If we seem to be running inside a GitHub Actions pull request check 21 # then we'll use the PR's target branch from this variable instead. 22 if [[ -n "${GITHUB_BASE_REF:-}" ]]; then 23 base_branch="origin/$GITHUB_BASE_REF" 24 fi 25 26 # FIXME: "readarray' is a Bash 4 feature, which means that currently this script 27 # can't work on macOS which (at the time of writing this) ships with only Bash 3. 28 # We can probably replace this with something more clunky using an overridden 29 # "IFS" environment variable, but the primary place we want to run this right 30 # now is in our "quick checks" workflow and that _does_ have a reasonably 31 # modern version of Bash. 32 readarray -t target_files < <(git diff --name-only ${base_branch} --diff-filter=MA | grep "\.go" | grep -v ".pb.go" | grep -v ".go-version") 33 34 # NOTE: The above intentionally excludes .pb.go files because those are 35 # generated by a tool (protoc-gen-go) which itself doesn't produce 36 # style-compliant imports. 37 38 if [[ "${#target_files[@]}" -eq 0 ]]; then 39 echo "No files have changed relative to branch ${base_branch}, so there's nothing to check!" 40 exit 0 41 fi 42 43 declare -a incorrect_files 44 # Array must have at least one item before we can append to it. Code below must 45 # work around this extra empty-string element at the beginning of the array. 46 incorrect_files[0]="" 47 48 for filename in "${target_files[@]}"; do 49 if [[ -z "$filename" ]]; then 50 continue 51 fi 52 53 output=$(go run golang.org/x/tools/cmd/goimports -l "${filename}") 54 if [[ $? -ne 0 ]]; then 55 echo >&2 goimports failed for "$filename" 56 exit 1 57 fi 58 59 if [[ -n "$output" ]]; then 60 incorrect_files+=("$filename") 61 fi 62 done 63 64 if [[ "${#incorrect_files[@]}" -gt 1 ]]; then 65 echo >&2 'The following files have import statements that disagree with "goimports"': 66 for filename in "${incorrect_files[@]}"; do 67 if [[ -z "$filename" ]]; then 68 continue 69 fi 70 71 echo >&2 ' - ' "${filename}" 72 done 73 echo >&2 'Use `go run golang.org/x/tools/cmd/goimports -w -l` on each of these files to update these files.' 74 exit 1 75 fi 76 77 echo 'All of the changed files look good!' 78 exit 0