Skip to content

Commit b966ff2

Browse files
committed
Handle parse error during fmt
If there was is an error while parsing the terraform files, fmt won't return a list of unformatted files but will just print an error. Previously this would cause the action to print a malformed comment. Now we detect if parsing failed and just print the parse error.
1 parent 0ad9e41 commit b966ff2

File tree

1 file changed

+23
-12
lines changed

1 file changed

+23
-12
lines changed

fmt/entrypoint.sh

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ set -e
33
cd "${TF_ACTION_WORKING_DIR:-.}"
44

55
set +e
6-
UNFMT_FILES=$(sh -c "terraform fmt -check=true -write=false $*" 2>&1)
6+
OUTPUT=$(sh -c "terraform fmt -no-color -check -list -recursive $*" 2>&1)
77
SUCCESS=$?
8-
echo "$UNFMT_FILES"
8+
echo "$OUTPUT"
99
set -e
1010

1111
if [ $SUCCESS -eq 0 ]; then
@@ -16,27 +16,38 @@ if [ "$TF_ACTION_COMMENT" = "1" ] || [ "$TF_ACTION_COMMENT" = "false" ]; then
1616
exit $SUCCESS
1717
fi
1818

19-
# Iterate through each unformatted file and build up a comment.
20-
FMT_OUTPUT=""
21-
for file in $UNFMT_FILES; do
22-
FILE_DIFF=$(terraform fmt -write=false -diff=true "$file" | sed -n '/@@.*/,//{/@@.*/d;p}')
23-
FMT_OUTPUT="$FMT_OUTPUT
19+
if [ $SUCCESS -eq 2 ]; then
20+
# If it exits with 2, then there was a parse error and the command won't have
21+
# printed out the files that have failed. In this case we comment back with the
22+
# whole parse error.
23+
COMMENT="\`\`\`
24+
$OUTPUT
25+
\`\`\`
26+
"
27+
else
28+
# Otherwise the output will contain a list of unformatted filenames.
29+
# Iterate through each file and build up a comment containing the diff
30+
# of each file.
31+
COMMENT=""
32+
for file in $OUTPUT; do
33+
FILE_DIFF=$(terraform fmt -no-color -write=false -diff "$file" | sed -n '/@@.*/,//{/@@.*/d;p}')
34+
COMMENT="$COMMENT
2435
<details><summary><code>$file</code></summary>
2536
2637
\`\`\`diff
2738
$FILE_DIFF
2839
\`\`\`
2940
</details>
3041
"
31-
done
42+
done
43+
fi
3244

33-
COMMENT="#### \`terraform fmt\` Failed
34-
$FMT_OUTPUT
45+
COMMENT_WRAPPER="#### \`terraform fmt\` Failed
46+
$COMMENT
3547
*Workflow: \`$GITHUB_WORKFLOW\`, Action: \`$GITHUB_ACTION\`*
3648
"
37-
PAYLOAD=$(echo '{}' | jq --arg body "$COMMENT" '.body = $body')
49+
PAYLOAD=$(echo '{}' | jq --arg body "$COMMENT_WRAPPER" '.body = $body')
3850
COMMENTS_URL=$(cat /github/workflow/event.json | jq -r .pull_request.comments_url)
3951
curl -s -S -H "Authorization: token $GITHUB_TOKEN" --header "Content-Type: application/json" --data "$PAYLOAD" "$COMMENTS_URL" > /dev/null
4052

4153
exit $SUCCESS
42-

0 commit comments

Comments
 (0)