#!/usr/bin/env bash set -euo pipefail # === Inputs =========================================================== COMMENTER_TYPE="${1:-}" COMMENTER_INPUT="${2:-}" COMMENTER_EXITCODE="${3:-0}" WORKING_DIR="${4:-}" # === Move into working directory if specified ======================== if [[ -n "$WORKING_DIR" ]]; then echo "🔹 Changing to working directory: $WORKING_DIR" cd "${GITHUB_WORKSPACE}/${WORKING_DIR}" || { echo "❌ Error: Cannot change to working directory '${WORKING_DIR}'" exit 1 } else cd "${GITHUB_WORKSPACE:-.}" fi # === Environment Debug Info ========================================== echo "📁 Current working directory: $(pwd)" echo "📦 Repository root: ${GITHUB_WORKSPACE:-N/A}" # === Setup PATH for OpenTofu ========================================= export PATH="${PATH}:/home/runner/.opentofu/bin" # === Detect tofu / terraform command ================================= if command -v tofu >/dev/null 2>&1; then TOFU_CMD="tofu" elif command -v terraform >/dev/null 2>&1; then TOFU_CMD="terraform" else echo "❌ Neither 'tofu' nor 'terraform' found in PATH." exit 1 fi echo "🧰 Using IaC command: $TOFU_CMD" # === Validation ====================================================== if [[ -z "${COMMENTER_TYPE}" ]]; then echo "❌ commenter_type input is required." exit 1 fi # === Prepare Comment Body ============================================ EXIT_STATUS_MSG="" if [[ "$COMMENTER_EXITCODE" -eq 0 ]]; then EXIT_STATUS_MSG="✅ ${COMMENTER_TYPE^} succeeded." else EXIT_STATUS_MSG="❌ ${COMMENTER_TYPE^} failed with exit code ${COMMENTER_EXITCODE}." fi # Format comment body COMMENT_BODY="### ${COMMENTER_TYPE^} Results \`\`\` ${COMMENTER_INPUT} \`\`\` ${EXIT_STATUS_MSG} " # === Post Comment ==================================================== echo "📝 Posting PR comment to: ${PR_COMMENTS_URL:-N/A}" if [[ -z "${PR_COMMENTS_URL:-}" ]]; then echo "❌ Missing PR_COMMENTS_URL environment variable." exit 1 fi # Update comment if comment_id exists, otherwise create a new one if [[ -n "${PR_COMMENT_ID:-}" && -n "${PR_COMMENT_URI:-}" ]]; then echo "🌀 Updating existing comment (ID: ${PR_COMMENT_ID})" curl -sS -X PATCH \ -H "Authorization: token ${GITHUB_TOKEN}" \ -H "Content-Type: application/json" \ -d "$(jq -n --arg body "$COMMENT_BODY" '{body: $body}')" \ "${PR_COMMENT_URI}" \ || echo "⚠️ Failed to update existing comment." else echo "🆕 Creating a new PR comment" curl -sS -X POST \ -H "Authorization: token ${GITHUB_TOKEN}" \ -H "Content-Type: application/json" \ -d "$(jq -n --arg body "$COMMENT_BODY" '{body: $body}')" \ "${PR_COMMENTS_URL}" \ || echo "⚠️ Failed to create PR comment." fi echo "✅ Comment posted successfully."