|
| 1 | +name: Branch Monitor |
| 2 | + |
| 3 | +on: |
| 4 | + push: |
| 5 | + branches: ['master'] |
| 6 | + |
| 7 | +env: |
| 8 | + ISSUE_NUMBER: ${{ vars.MONITOR_ISSUE_NUMBER }} |
| 9 | + |
| 10 | +concurrency: |
| 11 | + group: branch-monitor-master |
| 12 | + cancel-in-progress: true |
| 13 | + |
| 14 | +jobs: |
| 15 | + monitor: |
| 16 | + runs-on: ubuntu-latest |
| 17 | + permissions: |
| 18 | + issues: write |
| 19 | + checks: read |
| 20 | + timeout-minutes: 60 |
| 21 | + |
| 22 | + steps: |
| 23 | + - name: Monitor Branch Status |
| 24 | + uses: actions/github-script@v7 |
| 25 | + with: |
| 26 | + script: | |
| 27 | + const branchName = process.env.GITHUB_REF_NAME; |
| 28 | + const issueNumber = parseInt(process.env.ISSUE_NUMBER); |
| 29 | +
|
| 30 | + if (!issueNumber) { |
| 31 | + console.log('ERROR: ISSUE_NUMBER environment variable is not set. Please configure MONITOR_ISSUE_NUMBER in repository variables.'); |
| 32 | + process.exit(1); |
| 33 | + } |
| 34 | +
|
| 35 | + const currentJobName = process.env.GITHUB_JOB; |
| 36 | + const COMMENT_MARKER = '<!-- branch-monitor-failure-comment -->'; |
| 37 | + const POLL_INTERVAL = 30; // seconds |
| 38 | + const MAX_POLLS = 120; // 60 minutes total |
| 39 | +
|
| 40 | + // Get commit data from the push event |
| 41 | + const commitSha = context.sha; |
| 42 | + const commitUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/commit/${commitSha}`; |
| 43 | + const commitMessage = context.payload.head_commit.message; |
| 44 | + const commitAuthor = context.payload.head_commit.author.username |
| 45 | + ? `@${context.payload.head_commit.author.username}` |
| 46 | + : context.payload.head_commit.author.name; |
| 47 | + const commitDate = context.payload.head_commit.timestamp; |
| 48 | + console.log(JSON.stringify(context, null, 2)); |
| 49 | +
|
| 50 | + console.log(`Monitoring checks for commit ${commitSha} on branch ${branchName}`); |
| 51 | +
|
| 52 | + // Poll for check completion |
| 53 | + let polls = 0; |
| 54 | + let overallStatus = 'pending'; |
| 55 | +
|
| 56 | + while (polls < MAX_POLLS) { |
| 57 | + polls++; |
| 58 | + console.log(`Poll ${polls}/${MAX_POLLS} - checking status...`); |
| 59 | +
|
| 60 | + // Get combined status (external checks like CircleCI) |
| 61 | + const { data: combinedStatus } = await github.rest.repos.getCombinedStatusForRef({ |
| 62 | + owner: context.repo.owner, |
| 63 | + repo: context.repo.repo, |
| 64 | + ref: commitSha |
| 65 | + }); |
| 66 | +
|
| 67 | + // Get check runs (GitHub Actions and modern checks) |
| 68 | + const { data: checks } = await github.rest.checks.listForRef({ |
| 69 | + owner: context.repo.owner, |
| 70 | + repo: context.repo.repo, |
| 71 | + ref: commitSha, |
| 72 | + per_page: 100 |
| 73 | + }); |
| 74 | +
|
| 75 | + // Combine into single array with normalized structure |
| 76 | + const allChecks = [ |
| 77 | + // External statuses |
| 78 | + ...combinedStatus.statuses.map(status => ({ |
| 79 | + name: status.context, |
| 80 | + state: status.state, |
| 81 | + type: 'status' |
| 82 | + })), |
| 83 | + // GitHub check runs |
| 84 | + ...checks.check_runs.map(check => ({ |
| 85 | + name: check.name, |
| 86 | + state: check.conclusion || check.status, |
| 87 | + type: 'check' |
| 88 | + })) |
| 89 | + ]; |
| 90 | +
|
| 91 | + console.log(`Found ${allChecks.length} total checks for commit ${commitSha}`); |
| 92 | + allChecks.forEach(check => { |
| 93 | + console.log(`- ${check.type}: ${check.name}: ${check.state}`); |
| 94 | + }); |
| 95 | +
|
| 96 | + // Filter out the current workflow run (this monitor job) |
| 97 | + const currentJobName = process.env.GITHUB_JOB; |
| 98 | + const otherChecks = allChecks.filter(check => check.name !== currentJobName); |
| 99 | + |
| 100 | + console.log(`Filtered out current job '${currentJobName}', ${otherChecks.length} other checks remaining`); |
| 101 | +
|
| 102 | + if (otherChecks.length === 0) { |
| 103 | + console.log('No other checks found, continuing to poll...'); |
| 104 | + await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL * 1000)); |
| 105 | + continue; |
| 106 | + } |
| 107 | +
|
| 108 | + // Check if all other checks are completed |
| 109 | + const otherStates = otherChecks.map(check => check.state); |
| 110 | + const completedStates = otherStates.filter(s => |
| 111 | + s === 'success' || s === 'failure' || s === 'error' || s === 'cancelled' || s === 'timed_out' || s === 'skipped' |
| 112 | + ); |
| 113 | + const allOtherCompleted = completedStates.length === otherChecks.length; |
| 114 | +
|
| 115 | + console.log(`Completed: ${completedStates.length}/${otherChecks.length} other checks`); |
| 116 | + console.log(`All other checks completed: ${allOtherCompleted}`); |
| 117 | +
|
| 118 | + if (allOtherCompleted) { |
| 119 | + // Determine overall status from completed checks only |
| 120 | + if (completedStates.every(s => s === 'success' || s === 'skipped')) { |
| 121 | + overallStatus = 'success'; |
| 122 | + } else if (completedStates.some(s => s === 'failure' || s === 'timed_out' || s === 'cancelled' || s === 'error')) { |
| 123 | + overallStatus = 'failure'; |
| 124 | + } else { |
| 125 | + overallStatus = 'success'; // fallback |
| 126 | + } |
| 127 | + console.log(`All other checks completed with overall status: ${overallStatus}`); |
| 128 | + break; |
| 129 | + } else { |
| 130 | + console.log(`Still waiting for more checks to complete, waiting ${POLL_INTERVAL}s...`); |
| 131 | + await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL * 1000)); |
| 132 | + } |
| 133 | + } |
| 134 | +
|
| 135 | + if (polls >= MAX_POLLS) { |
| 136 | + console.log('Timeout reached, using current status'); |
| 137 | + overallStatus = 'timeout'; |
| 138 | + } |
| 139 | +
|
| 140 | + // Generate status display |
| 141 | + const statusEmojis = { |
| 142 | + success: '✅', |
| 143 | + failure: '❌', |
| 144 | + timeout: '⏰', |
| 145 | + pending: '⏳' |
| 146 | + }; |
| 147 | +
|
| 148 | + const emoji = statusEmojis[overallStatus] || '❓'; |
| 149 | + const shortSha = commitSha.substring(0, 7); |
| 150 | + const date = new Date(commitDate).toISOString(); |
| 151 | +
|
| 152 | + const issueTitle = `Status Monitor for the \`${branchName}\` branch`; |
| 153 | + const issueBody = `<!-- This issue is automatically updated by the branch-monitor workflow. Do not edit manually as changes will be overwritten. --> |
| 154 | +
|
| 155 | + This issue automatically tracks the CI status of the \`${branchName}\` branch. It monitors all checks and updates whenever new commits are pushed. |
| 156 | +
|
| 157 | + **Latest Commit**: [\`${shortSha}\`](${commitUrl}) ${commitMessage.split('\n')[0]} ${emoji} **${overallStatus}** |
| 158 | +
|
| 159 | + --- |
| 160 | + *Last updated: ${new Date().toISOString()}*`; |
| 161 | +
|
| 162 | + // Update issue title and body |
| 163 | + await github.rest.issues.update({ |
| 164 | + owner: context.repo.owner, |
| 165 | + repo: context.repo.repo, |
| 166 | + issue_number: issueNumber, |
| 167 | + title: issueTitle, |
| 168 | + body: issueBody |
| 169 | + }); |
| 170 | +
|
| 171 | + console.log(`Updated issue #${issueNumber} with status: ${overallStatus}`); |
| 172 | +
|
| 173 | + // Handle failure comments |
| 174 | + const hasFailure = overallStatus === 'failure'; |
| 175 | +
|
| 176 | + // Get existing comments |
| 177 | + const { data: comments } = await github.rest.issues.listComments({ |
| 178 | + owner: context.repo.owner, |
| 179 | + repo: context.repo.repo, |
| 180 | + issue_number: issueNumber |
| 181 | + }); |
| 182 | +
|
| 183 | + const existingFailureComment = comments.find(comment => |
| 184 | + comment.body.includes(COMMENT_MARKER) |
| 185 | + ); |
| 186 | +
|
| 187 | + if (hasFailure && !existingFailureComment) { |
| 188 | + // Post failure comment |
| 189 | + const failureComment = `${COMMENT_MARKER} |
| 190 | + 🚨 **Build Failure Detected** |
| 191 | +
|
| 192 | + The latest commit on branch \`${branchName}\` has failed checks: |
| 193 | + - **Commit**: [\`${shortSha}\`](${commitUrl}) |
| 194 | + - **Message**: ${commitMessage.split('\n')[0]} |
| 195 | + - **Author**: ${commitAuthor} |
| 196 | +
|
| 197 | + Please investigate and fix the failing checks.`; |
| 198 | +
|
| 199 | + await github.rest.issues.createComment({ |
| 200 | + owner: context.repo.owner, |
| 201 | + repo: context.repo.repo, |
| 202 | + issue_number: issueNumber, |
| 203 | + body: failureComment |
| 204 | + }); |
| 205 | +
|
| 206 | + console.log('Posted failure comment'); |
| 207 | + } else if (!hasFailure && existingFailureComment) { |
| 208 | + // Remove failure comment when status is green |
| 209 | + await github.rest.issues.deleteComment({ |
| 210 | + owner: context.repo.owner, |
| 211 | + repo: context.repo.repo, |
| 212 | + comment_id: existingFailureComment.id |
| 213 | + }); |
| 214 | +
|
| 215 | + console.log('Removed failure comment - status is now green'); |
| 216 | + } |
0 commit comments