11#! /bin/sh
2+
3+ # wrap takes some output and wraps it in a collapsible markdown section if
4+ # it's over $TF_ACTION_WRAP_LINES long.
5+ wrap () {
6+ if [[ $( echo " $1 " | wc -l) -gt ${TF_ACTION_WRAP_LINES:- 20} ]]; then
7+ echo "
8+ <details><summary>Show Output</summary>
9+
10+ \`\`\` diff
11+ $1
12+ \`\`\`
13+
14+ </details>
15+ "
16+ else
17+ echo "
18+ \`\`\` diff
19+ $1
20+ \`\`\`
21+ "
22+ fi
23+ }
24+
225set -e
326
427cd " ${TF_ACTION_WORKING_DIR:- .} "
@@ -16,21 +39,32 @@ if [ "$TF_ACTION_COMMENT" = "1" ] || [ "$TF_ACTION_COMMENT" = "false" ]; then
1639 exit $SUCCESS
1740fi
1841
42+ # Build the comment we'll post to the PR.
1943COMMENT=" "
20-
21- # If not successful, post failed plan output.
2244if [ $SUCCESS -ne 0 ]; then
45+ OUTPUT=$( wrap " $OUTPUT " )
2346 COMMENT=" #### \` terraform plan\` Failed
24- \`\`\`
25- $OUTPUT
26- \`\`\` "
47+ $OUTPUT "
2748else
28- FMT_PLAN=$( echo " $OUTPUT " | sed -r -e ' s/^ \+/\+/g' | sed -r -e ' s/^ ~/~/g' | sed -r -e ' s/^ -/-/g' )
29- COMMENT=" \`\`\` diff
30- $FMT_PLAN
31- \`\`\` "
49+ # Remove "Refreshing state..." lines by only keeping output after the
50+ # delimiter (72 dashes) that represents the end of the refresh stage.
51+ # We do this to keep the comment output smaller.
52+ if echo " $OUTPUT " | egrep ' ^-{72}$' ; then
53+ OUTPUT=$( echo " $OUTPUT " | sed -n -r ' /-{72}/,/-{72}/{ /-{72}/d; p }' )
54+ fi
55+
56+ # Remove whitespace at the beginning of the line for added/modified/deleted
57+ # resources so the diff markdown formatting highlights those lines.
58+ OUTPUT=$( echo " $OUTPUT " | sed -r -e ' s/^ \+/\+/g' | sed -r -e ' s/^ ~/~/g' | sed -r -e ' s/^ -/-/g' )
59+
60+ # Call wrap to optionally wrap our output in a collapsible markdown section.
61+ OUTPUT=$( wrap " $OUTPUT " )
62+
63+ COMMENT=" #### \` terraform plan\` Success
64+ $OUTPUT "
3265fi
3366
67+ # Post the comment.
3468PAYLOAD=$( echo ' {}' | jq --arg body " $COMMENT " ' .body = $body' )
3569COMMENTS_URL=$( cat /github/workflow/event.json | jq -r .pull_request.comments_url)
3670curl -s -S -H " Authorization: token $GITHUB_TOKEN " --header " Content-Type: application/json" --data " $PAYLOAD " " $COMMENTS_URL " > /dev/null
0 commit comments