|
| 1 | +// Resolves PR number from environment or context, and determines if dry-run mode is enabled. |
| 2 | +function resolveExecutionContext(context) { |
| 3 | + const isDryRun = /^true$/i.test(process.env.DRY_RUN || ""); |
| 4 | + const prNumber = Number(process.env.PR_NUMBER) || context.payload.pull_request?.number; |
| 5 | + return { prNumber, isDryRun, owner: context.repo.owner, repo: context.repo.repo }; |
| 6 | +} |
| 7 | + |
| 8 | +// Validates that PR number is available. |
| 9 | +function validatePrNumber(prNumber) { |
| 10 | + if (!prNumber) { |
| 11 | + throw new Error("PR number could not be determined."); |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +// Checks if the given login belongs to a bot account. |
| 16 | +function isBotLogin(login = "") { |
| 17 | + return /\[bot\]$/i.test(login) || /dependabot/i.test(login); |
| 18 | +} |
| 19 | + |
| 20 | +// Extracts linked issue numbers from PR body. |
| 21 | +function extractLinkedIssueNumbers(prBody = "") { |
| 22 | + const closingReferenceRegex = |
| 23 | + /\b(?:fix(?:es|ed)?|close(?:s|d)?|resolve(?:s|d)?)\s*:?\s*((?:#\d+)(?:\s*(?:,|and)\s*#\d+)*)/gi; |
| 24 | + const numbers = new Set(); |
| 25 | + let referenceMatch; |
| 26 | + |
| 27 | + while ((referenceMatch = closingReferenceRegex.exec(prBody)) !== null) { |
| 28 | + const referencesText = referenceMatch[1] || ""; |
| 29 | + const issueMatches = referencesText.matchAll(/#(\d+)/g); |
| 30 | + |
| 31 | + for (const issueMatch of issueMatches) { |
| 32 | + numbers.add(Number(issueMatch[1])); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return [...numbers]; |
| 37 | +} |
| 38 | + |
| 39 | +// Normalizes label objects/strings to trimmed label names. |
| 40 | +function normalizeLabelNames(labels = []) { |
| 41 | + const names = []; |
| 42 | + for (const label of labels) { |
| 43 | + if (typeof label === "string" && label.trim()) { |
| 44 | + names.push(label.trim()); |
| 45 | + continue; |
| 46 | + } |
| 47 | + |
| 48 | + if (label && typeof label.name === "string" && label.name.trim()) { |
| 49 | + names.push(label.name.trim()); |
| 50 | + } |
| 51 | + } |
| 52 | + return names; |
| 53 | +} |
| 54 | + |
| 55 | +// Fetches PR data from payload or API. |
| 56 | +async function getPullRequestData({ github, context, prNumber }) { |
| 57 | + if (context.payload.pull_request) { |
| 58 | + return context.payload.pull_request; |
| 59 | + } |
| 60 | + |
| 61 | + const response = await github.rest.pulls.get({ |
| 62 | + owner: context.repo.owner, |
| 63 | + repo: context.repo.repo, |
| 64 | + pull_number: prNumber, |
| 65 | + }); |
| 66 | + |
| 67 | + return response.data; |
| 68 | +} |
| 69 | + |
| 70 | +// Determines if PR should be skipped. |
| 71 | +function shouldSkipPR(prData, linkedIssueNumbers) { |
| 72 | + const prAuthor = prData?.user?.login || ""; |
| 73 | + |
| 74 | + if (isBotLogin(prAuthor)) { |
| 75 | + return { skip: true, reason: `Skipping bot-authored PR from ${prAuthor}.` }; |
| 76 | + } |
| 77 | + |
| 78 | + if (!linkedIssueNumbers.length) { |
| 79 | + return { skip: true, reason: "No linked issue references found in PR body." }; |
| 80 | + } |
| 81 | + |
| 82 | + return { skip: false }; |
| 83 | +} |
| 84 | + |
| 85 | +// Collects labels from linked issues. |
| 86 | +async function collectLabelsFromLinkedIssues({ github, owner, repo, linkedIssueNumbers }) { |
| 87 | + const labelsFromIssues = new Set(); |
| 88 | + |
| 89 | + for (const issueNumber of linkedIssueNumbers) { |
| 90 | + try { |
| 91 | + const issueResponse = await github.rest.issues.get({ |
| 92 | + owner, |
| 93 | + repo, |
| 94 | + issue_number: issueNumber, |
| 95 | + }); |
| 96 | + |
| 97 | + if (issueResponse?.data?.pull_request) { |
| 98 | + console.log(`[sync-issue-labels] Skipping #${issueNumber}: reference points to a pull request.`); |
| 99 | + continue; |
| 100 | + } |
| 101 | + |
| 102 | + const issueLabelNames = normalizeLabelNames(issueResponse?.data?.labels || []); |
| 103 | + console.log( |
| 104 | + `[sync-issue-labels] Issue #${issueNumber} labels: ${ |
| 105 | + issueLabelNames.length ? issueLabelNames.join(", ") : "(none)" |
| 106 | + }` |
| 107 | + ); |
| 108 | + |
| 109 | + for (const label of issueLabelNames) { |
| 110 | + labelsFromIssues.add(label); |
| 111 | + } |
| 112 | + } catch (error) { |
| 113 | + if (error?.status === 404) { |
| 114 | + console.log(`[sync-issue-labels] Linked issue #${issueNumber} not found. Skipping.`); |
| 115 | + continue; |
| 116 | + } |
| 117 | + |
| 118 | + throw error; |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + return labelsFromIssues; |
| 123 | +} |
| 124 | + |
| 125 | +// Computes labels to add (missing from PR but present in issues). |
| 126 | +function computeLabelsToAdd(prData, labelsFromIssues) { |
| 127 | + const prLabelNames = new Set(normalizeLabelNames(prData?.labels || [])); |
| 128 | + const labelsToAdd = [...labelsFromIssues].filter((label) => !prLabelNames.has(label)); |
| 129 | + return { labelsToAdd, prLabelNames }; |
| 130 | +} |
| 131 | + |
| 132 | +// Logs label operations for debugging. |
| 133 | +function logLabelOperation(operation, prNumber, labels, prLabelNames) { |
| 134 | + console.log(`[sync-issue-labels] ${operation} PR #${prNumber}.`); |
| 135 | + console.log(`[sync-issue-labels] Existing labels: ${prLabelNames.size ? [...prLabelNames].join(", ") : "(none)"}`); |
| 136 | + console.log(`[sync-issue-labels] Labels to add: ${labels.length ? labels.join(", ") : "(none)"}`); |
| 137 | +} |
| 138 | + |
| 139 | +// Main orchestrator function. |
| 140 | +async function syncLabels({ github, context }) { |
| 141 | + const { prNumber, isDryRun, owner, repo } = resolveExecutionContext(context); |
| 142 | + |
| 143 | + validatePrNumber(prNumber); |
| 144 | + |
| 145 | + console.log(`[sync-issue-labels] Processing PR #${prNumber} in ${owner}/${repo} (dry_run=${isDryRun}).`); |
| 146 | + |
| 147 | + const prData = await getPullRequestData({ github, context, prNumber }); |
| 148 | + |
| 149 | + const linkedIssueNumbers = extractLinkedIssueNumbers(prData?.body || ""); |
| 150 | + const skipResult = shouldSkipPR(prData, linkedIssueNumbers); |
| 151 | + |
| 152 | + if (skipResult.skip) { |
| 153 | + console.log(`[sync-issue-labels] ${skipResult.reason}`); |
| 154 | + return { labels: [] }; |
| 155 | + } |
| 156 | + |
| 157 | + console.log(`[sync-issue-labels] Linked issues: ${linkedIssueNumbers.map((n) => `#${n}`).join(", ")}`); |
| 158 | + |
| 159 | + const labelsFromIssues = await collectLabelsFromLinkedIssues({ github, owner, repo, linkedIssueNumbers }); |
| 160 | + |
| 161 | + if (!labelsFromIssues.size) { |
| 162 | + console.log("[sync-issue-labels] No labels on linked issues. Nothing to sync."); |
| 163 | + return { labels: [] }; |
| 164 | + } |
| 165 | + |
| 166 | + const { labelsToAdd, prLabelNames } = computeLabelsToAdd(prData, labelsFromIssues); |
| 167 | + |
| 168 | + logLabelOperation("Processing", prNumber, labelsToAdd, prLabelNames); |
| 169 | + |
| 170 | + if (!labelsToAdd.length) { |
| 171 | + console.log("[sync-issue-labels] PR already has all labels from linked issues."); |
| 172 | + return { labels: [] }; |
| 173 | + } |
| 174 | + |
| 175 | + if (isDryRun) { |
| 176 | + console.log(`[sync-issue-labels] DRY_RUN enabled; would add: ${labelsToAdd.join(", ")}`); |
| 177 | + return { labels: labelsToAdd }; |
| 178 | + } |
| 179 | + |
| 180 | + await github.rest.issues.addLabels({ |
| 181 | + owner, |
| 182 | + repo, |
| 183 | + issue_number: prNumber, |
| 184 | + labels: labelsToAdd, |
| 185 | + }); |
| 186 | + |
| 187 | + console.log(`[sync-issue-labels] Added labels: ${labelsToAdd.join(", ")}`); |
| 188 | + |
| 189 | + return { labels: labelsToAdd }; |
| 190 | +} |
| 191 | + |
| 192 | +module.exports = syncLabels; |
0 commit comments