Skip to content

Instantly share code, notes, and snippets.

@TylerHendrickson
Created November 16, 2023 00:00
Show Gist options
  • Select an option

  • Save TylerHendrickson/7221cabbabf7351317953acd7d00efe7 to your computer and use it in GitHub Desktop.

Select an option

Save TylerHendrickson/7221cabbabf7351317953acd7d00efe7 to your computer and use it in GitHub Desktop.
Bash script for extracting PR suggestions from `terraform fmt` diffs
#!/bin/bash
# Parses terraform fmt diff and writes temp files that can be used to create suggestion comments
tmpdir=$(mktemp -d -t terraform-fmt-suggestions.XXXXX)
tmpfile=""
source_file=""
inchunk=false
regex_header_start='^[-]{3} old/(.*)$'
regex_chunk_start='^@@ [-]([0-9]+),([0-9]+) [+][0-9]+,[0-9]+ @@$' # Captures start line & total lines
regex_include_line='^[+[:space:]].*$'
while IFS='' read -r line; do
if [[ $line =~ $regex_header_start ]]; then
# The line is a header line that indicates a new file
source_file=$(echo "$line" | awk -Fold/ '{print $NF}')
inchunk=false
elif [[ $line =~ $regex_chunk_start ]]; then
# The line indicates the start of a new chunk in the diff
inchunk=true
# Set and output the filename for the comment
tmpfile="$tmpdir/$source_file.${BASH_REMATCH[1]}.${BASH_REMATCH[2]}"
mkdir -p $(dirname $tmpfile)
echo $tmpfile
elif [[ "$inchunk" = true && $line =~ $regex_include_line ]]; then
# The line is an addition or non-modified (not a removal)
# Write the suggested line to the comment file for the current chunk
echo "${line:1}" >> $tmpfile
fi
done < <(terraform fmt -diff -write=false -recursive)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment