diff --git a/README.md b/README.md index 3569e62e..dae1f939 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,21 @@ Now when the pre-commit hook runs, it will call `helm lint` with both `linter_va helm lint -f values.yaml -f linter_values.yaml . ``` +## terraform-fmt arguments + +By default, `terraform-fmt` will write changes back to the original file. +You can skip this by setting the `--no-autofix` flag. + +```yaml +repos: + - repo: https://github.com/gruntwork-io/pre-commit + rev: + hooks: + - id: terraform-fmt + args: ["--no-autofix"] +``` + + ## Shellcheck Arguments To enable optional shellcheck features you can use the `--enable` flag. diff --git a/hooks/terraform-fmt.sh b/hooks/terraform-fmt.sh index ba8c3741..b778c12e 100755 --- a/hooks/terraform-fmt.sh +++ b/hooks/terraform-fmt.sh @@ -7,11 +7,43 @@ set -e # workaround to allow GitHub Desktop to work, add this (hopefully harmless) setting here. export PATH=$PATH:/usr/local/bin +write_changes=true +FILES=() + +parse_arguments() { + while (($# > 0)); do + # Grab param and value splitting on " " or "=" with parameter expansion + local PARAMETER="${1%[ =]*}" + local VALUE="${1#*[ =]}" + if [[ "$PARAMETER" == "$VALUE" ]]; then VALUE="$2"; fi + shift + case "$PARAMETER" in + --no-autofix) + write_changes=false + ;; + -*) + echo "Error: Unknown option: $PARAMETER" >&2 + exit 1 + ;; + *) + FILES+=("$PARAMETER") + ;; + esac + done +} + +parse_arguments "$@" + # Store and return last failure from fmt so this can validate every directory passed before exiting FMT_ERROR=0 -for file in "$@"; do - terraform fmt -diff -check "$file" || FMT_ERROR=$? +for file in "$FILES"; do + file=$(dirname "$file") + if [ "$write_changes" = true ]; then + terraform fmt "$file" || FMT_ERROR=$? + else + terraform fmt -diff -check "$file" || FMT_ERROR=$? + fi done exit ${FMT_ERROR}