|
| 1 | +import { realpathSync } from "node:fs"; |
| 2 | +import { pathToFileURL } from "node:url"; |
| 3 | +import { assert, labelsExactlyMatch, normalizeDescription, normalizeName } from "./lib/config-utils.mjs"; |
| 4 | +import { validateLabels } from "./lib/config-validation.mjs"; |
| 5 | +import { renderLabelSyncSection, writeChangelog } from "./lib/changelog-utils.mjs"; |
| 6 | +import { formatRepositoryLink, getRepositorySkipReason, parseTokenPermissions } from "./lib/repository-selection.mjs"; |
| 7 | + |
| 8 | +function resolveRepository(value, organization, inputName) { |
| 9 | + const name = typeof value === "string" ? value.trim() : ""; |
| 10 | + assert(name, `${inputName} is required.`); |
| 11 | + const fullName = name.includes("/") ? name : `${organization ?? ""}/${name}`; |
| 12 | + const parts = fullName.split("/"); |
| 13 | + assert( |
| 14 | + parts.length === 2 |
| 15 | + && /^[a-zA-Z0-9][a-zA-Z0-9-]*$/.test(parts[0]) |
| 16 | + && /^[a-zA-Z0-9_.-]+$/.test(parts[1]) |
| 17 | + && parts[1] !== "." && parts[1] !== "..", |
| 18 | + `${inputName} must be a repository name in the configured organization or owner/repo.`, |
| 19 | + ); |
| 20 | + return fullName; |
| 21 | +} |
| 22 | + |
| 23 | +async function githubRequest(token, method, apiPath, body) { |
| 24 | + const response = await fetch(`https://api.github.com${apiPath}`, { |
| 25 | + method, |
| 26 | + headers: { |
| 27 | + Accept: "application/vnd.github+json", |
| 28 | + Authorization: `Bearer ${token}`, |
| 29 | + "User-Agent": "label-sync", |
| 30 | + "X-GitHub-Api-Version": "2022-11-28", |
| 31 | + }, |
| 32 | + body: body ? JSON.stringify(body) : undefined, |
| 33 | + }); |
| 34 | + if (!response.ok) { |
| 35 | + throw new Error(`${method} ${apiPath} failed with ${response.status}: ${await response.text()}`); |
| 36 | + } |
| 37 | + return response.status === 204 ? null : response.json(); |
| 38 | +} |
| 39 | + |
| 40 | +async function getAllLabels(token, repository) { |
| 41 | + const labels = []; |
| 42 | + for (let page = 1; ; page += 1) { |
| 43 | + const batch = await githubRequest(token, "GET", `/repos/${repository}/labels?per_page=100&page=${page}`); |
| 44 | + assert(Array.isArray(batch), `Invalid label response for ${repository}.`); |
| 45 | + labels.push(...batch); |
| 46 | + if (batch.length < 100) { |
| 47 | + return validateLabels(labels.map((label) => ({ |
| 48 | + ...label, |
| 49 | + description: normalizeDescription(label.description), |
| 50 | + }))); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +export async function transferLabels({ |
| 56 | + token, |
| 57 | + organization, |
| 58 | + sourceRepository, |
| 59 | + targetRepository, |
| 60 | + dryRun = false, |
| 61 | + overrideExisting = false, |
| 62 | + tokenPermissions = null, |
| 63 | +}) { |
| 64 | + const result = { |
| 65 | + repository: "", |
| 66 | + hasChanges: false, |
| 67 | + createdLabels: [], |
| 68 | + updatedLabels: [], |
| 69 | + deletedConfiguredLabels: [], |
| 70 | + deletedGithubDefaultLabels: [], |
| 71 | + deletedMissingLabels: [], |
| 72 | + labelReplacements: [], |
| 73 | + }; |
| 74 | + const skippedRepositories = []; |
| 75 | + let sourceName; |
| 76 | + let targetName; |
| 77 | + let sourceCount = null; |
| 78 | + let initialTargetCount = null; |
| 79 | + let retainedCount = 0; |
| 80 | + let failure = null; |
| 81 | + |
| 82 | + try { |
| 83 | + sourceName = resolveRepository(sourceRepository, organization, "Source repository"); |
| 84 | + targetName = resolveRepository(targetRepository, organization, "Receiving repository"); |
| 85 | + assert(sourceName.toLowerCase() !== targetName.toLowerCase(), "Source and receiving repositories must be different repositories."); |
| 86 | + assert(token, "LABEL_SYNC_TOKEN is required."); |
| 87 | + const source = await githubRequest(token, "GET", `/repos/${sourceName}`); |
| 88 | + const target = await githubRequest(token, "GET", `/repos/${targetName}`); |
| 89 | + assert(source.id && target.id, "GitHub did not return valid repository IDs."); |
| 90 | + assert(source.id !== target.id, "Source and receiving repositories must be different repositories."); |
| 91 | + // Use canonical names after resolving renamed/transferred repository aliases. |
| 92 | + sourceName = resolveRepository(source.full_name, organization, "Source repository"); |
| 93 | + targetName = resolveRepository(target.full_name, organization, "Receiving repository"); |
| 94 | + result.repository = targetName; |
| 95 | + |
| 96 | + const skipReason = getRepositorySkipReason(target, { requireWriteAccess: !dryRun, tokenPermissions }); |
| 97 | + if (skipReason) { |
| 98 | + skippedRepositories.push({ repository: targetName, reason: skipReason }); |
| 99 | + return result; |
| 100 | + } |
| 101 | + |
| 102 | + // Read and validate both complete label sets before making any changes. |
| 103 | + const sourceLabels = await getAllLabels(token, sourceName); |
| 104 | + sourceCount = sourceLabels.length; |
| 105 | + const targetLabels = await getAllLabels(token, targetName); |
| 106 | + initialTargetCount = targetLabels.length; |
| 107 | + if (overrideExisting) { |
| 108 | + for (const label of targetLabels) { |
| 109 | + assert( |
| 110 | + label.name !== "." && label.name !== "..", |
| 111 | + `Receiving repository label "${label.name}" cannot be safely addressed by the GitHub API.`, |
| 112 | + ); |
| 113 | + } |
| 114 | + } |
| 115 | + const targetByName = new Map(targetLabels.map((label) => [normalizeName(label.name), label])); |
| 116 | + const sourceNames = new Set(sourceLabels.map((label) => normalizeName(label.name))); |
| 117 | + retainedCount = overrideExisting |
| 118 | + ? sourceLabels.filter((label) => { |
| 119 | + const existing = targetByName.get(normalizeName(label.name)); |
| 120 | + return existing && labelsExactlyMatch(existing, label); |
| 121 | + }).length |
| 122 | + : targetLabels.length; |
| 123 | + |
| 124 | + console.log(`${dryRun ? "Previewing" : "Applying"} ${overrideExisting ? "override" : "additive"} label transfer: ${sourceName} -> ${targetName}.`); |
| 125 | + for (const desired of sourceLabels) { |
| 126 | + const existing = targetByName.get(normalizeName(desired.name)); |
| 127 | + if (!existing) { |
| 128 | + if (!dryRun) { |
| 129 | + await githubRequest(token, "POST", `/repos/${targetName}/labels`, desired); |
| 130 | + } |
| 131 | + result.createdLabels.push(desired); |
| 132 | + result.hasChanges = true; |
| 133 | + console.log(` + ${desired.name}`); |
| 134 | + } else if (overrideExisting && !labelsExactlyMatch(existing, desired)) { |
| 135 | + if (!dryRun) { |
| 136 | + await githubRequest(token, "PATCH", `/repos/${targetName}/labels/${encodeURIComponent(existing.name)}`, { |
| 137 | + new_name: desired.name, |
| 138 | + color: desired.color, |
| 139 | + description: desired.description, |
| 140 | + }); |
| 141 | + } |
| 142 | + result.updatedLabels.push({ before: existing, after: desired }); |
| 143 | + result.hasChanges = true; |
| 144 | + console.log(` ~ ${desired.name}`); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + // Delete extras only after every create/update has succeeded. Updating shared |
| 149 | + // labels in place preserves their existing issue and pull request assignments. |
| 150 | + if (overrideExisting) { |
| 151 | + for (const existing of targetLabels) { |
| 152 | + if (sourceNames.has(normalizeName(existing.name))) continue; |
| 153 | + if (!dryRun) { |
| 154 | + await githubRequest(token, "DELETE", `/repos/${targetName}/labels/${encodeURIComponent(existing.name)}`); |
| 155 | + } |
| 156 | + result.deletedConfiguredLabels.push(existing); |
| 157 | + result.hasChanges = true; |
| 158 | + console.log(` - ${existing.name}`); |
| 159 | + } |
| 160 | + } |
| 161 | + return result; |
| 162 | + } catch (error) { |
| 163 | + failure = error; |
| 164 | + throw error; |
| 165 | + } finally { |
| 166 | + await writeChangelog({ |
| 167 | + workflowName: dryRun ? "Transfer-Labels Fake" : "Transfer-Labels", |
| 168 | + summaryLines: ({ generatedDate, metadata }) => [ |
| 169 | + `Generated On: ${generatedDate}`, |
| 170 | + `Actor: ${metadata.actor || "Unavailable"}`, |
| 171 | + `Test Mode: ${dryRun ? "True" : "False"}`, |
| 172 | + `Source Repository: ${sourceName ? formatRepositoryLink(sourceName) : "Unavailable"}`, |
| 173 | + `Receiving Repository: ${targetName ? formatRepositoryLink(targetName) : "Unavailable"}`, |
| 174 | + `Override Existing Labels: ${overrideExisting ? "True" : "False"}`, |
| 175 | + `Source Labels: ${sourceCount ?? "Unavailable"}`, |
| 176 | + `Receiving Labels Before Transfer: ${initialTargetCount ?? "Unavailable"}`, |
| 177 | + `Repositories Affected: ${result.hasChanges ? 1 : 0}`, |
| 178 | + `Repositories Skipped: ${skippedRepositories.length}`, |
| 179 | + `Created Labels: ${result.createdLabels.length}`, |
| 180 | + `Updated Labels: ${result.updatedLabels.length}`, |
| 181 | + `Deleted Labels: ${result.deletedConfiguredLabels.length}`, |
| 182 | + `Retained Labels: ${failure || initialTargetCount === null ? "Unavailable" : retainedCount}`, |
| 183 | + ], |
| 184 | + sections: [renderLabelSyncSection(result)], |
| 185 | + skippedRepositories, |
| 186 | + failure, |
| 187 | + }); |
| 188 | + } |
| 189 | +} |
| 190 | + |
| 191 | +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) { |
| 192 | + transferLabels({ |
| 193 | + token: process.env.LABEL_SYNC_TOKEN, |
| 194 | + organization: process.env.ORG_NAME ?? process.env.GITHUB_REPOSITORY_OWNER, |
| 195 | + sourceRepository: process.env.SOURCE_REPOSITORY, |
| 196 | + targetRepository: process.env.TARGET_REPOSITORY, |
| 197 | + dryRun: process.env.DRY_RUN === "true", |
| 198 | + overrideExisting: process.env.OVERRIDE_EXISTING === "true", |
| 199 | + tokenPermissions: parseTokenPermissions(process.env.LABEL_SYNC_TOKEN_PERMISSIONS), |
| 200 | + }).catch((error) => { |
| 201 | + console.error(error.message); |
| 202 | + process.exitCode = 1; |
| 203 | + }); |
| 204 | +} |
0 commit comments