|
| 1 | +// Backend helpers for the release-cutter canvas. |
| 2 | +// |
| 3 | +// All GitHub interaction goes through the `gh` CLI (already authenticated in |
| 4 | +// the user's environment) and `git`. Nothing here writes to disk except a |
| 5 | +// short-lived temp file for the release notes body. |
| 6 | + |
| 7 | +import { execFile } from "node:child_process"; |
| 8 | +import { mkdtemp, writeFile, rm } from "node:fs/promises"; |
| 9 | +import { tmpdir } from "node:os"; |
| 10 | +import { join } from "node:path"; |
| 11 | + |
| 12 | +/** Run a command, resolving with stdout. Rejects with stderr on non-zero exit. */ |
| 13 | +function run(cmd, args, opts = {}) { |
| 14 | + return new Promise((resolve, reject) => { |
| 15 | + execFile(cmd, args, { maxBuffer: 16 * 1024 * 1024, ...opts }, (err, stdout, stderr) => { |
| 16 | + if (err) { |
| 17 | + const message = (stderr || err.message || "").toString().trim(); |
| 18 | + reject(new Error(message || `${cmd} exited with an error`)); |
| 19 | + return; |
| 20 | + } |
| 21 | + resolve(stdout.toString()); |
| 22 | + }); |
| 23 | + }); |
| 24 | +} |
| 25 | + |
| 26 | +const gh = (args, opts) => run("gh", args, opts); |
| 27 | + |
| 28 | +/** Resolve owner/repo for the workspace. Falls back to the git remote. */ |
| 29 | +export async function resolveRepo(cwd) { |
| 30 | + try { |
| 31 | + const out = await gh(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"], { cwd }); |
| 32 | + const repo = out.trim(); |
| 33 | + if (repo) return repo; |
| 34 | + } catch { |
| 35 | + // fall through to git remote parsing |
| 36 | + } |
| 37 | + const remote = (await run("git", ["remote", "get-url", "origin"], { cwd })).trim(); |
| 38 | + const match = remote.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/); |
| 39 | + if (!match) throw new Error(`Could not determine repository from remote: ${remote}`); |
| 40 | + return match[1]; |
| 41 | +} |
| 42 | + |
| 43 | +const SEMVER = /^v(\d+)\.(\d+)\.(\d+)$/; |
| 44 | + |
| 45 | +/** Parse a `vMAJOR.MINOR.PATCH` tag into numbers, or null. */ |
| 46 | +export function parseVersion(tag) { |
| 47 | + const m = typeof tag === "string" ? tag.match(SEMVER) : null; |
| 48 | + if (!m) return null; |
| 49 | + return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) }; |
| 50 | +} |
| 51 | + |
| 52 | +/** Compute suggested next tags from a base version. */ |
| 53 | +export function suggestVersions(baseTag) { |
| 54 | + const v = parseVersion(baseTag) || { major: 0, minor: 0, patch: 0 }; |
| 55 | + return { |
| 56 | + patch: `v${v.major}.${v.minor}.${v.patch + 1}`, |
| 57 | + minor: `v${v.major}.${v.minor + 1}.0`, |
| 58 | + major: `v${v.major + 1}.0.0`, |
| 59 | + }; |
| 60 | +} |
| 61 | + |
| 62 | +/** The floating major tag for a version tag, e.g. v4.2.1 -> v4. */ |
| 63 | +export function majorTagFor(tag) { |
| 64 | + const v = parseVersion(tag); |
| 65 | + return v ? `v${v.major}` : null; |
| 66 | +} |
| 67 | + |
| 68 | +/** Gather everything the canvas needs to render its initial state. */ |
| 69 | +export async function getStatus(cwd) { |
| 70 | + const repo = await resolveRepo(cwd); |
| 71 | + |
| 72 | + let latestRelease = null; |
| 73 | + try { |
| 74 | + const out = await gh([ |
| 75 | + "release", |
| 76 | + "view", |
| 77 | + "--repo", |
| 78 | + repo, |
| 79 | + "--json", |
| 80 | + "tagName,name,url,createdAt,isDraft,isPrerelease", |
| 81 | + ]); |
| 82 | + latestRelease = JSON.parse(out); |
| 83 | + } catch { |
| 84 | + latestRelease = null; // repo may have no releases yet |
| 85 | + } |
| 86 | + |
| 87 | + const defaultBranch = ( |
| 88 | + await gh(["repo", "view", repo, "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"]) |
| 89 | + ).trim(); |
| 90 | + |
| 91 | + const baseTag = latestRelease?.tagName || "v0.0.0"; |
| 92 | + const suggested = suggestVersions(baseTag); |
| 93 | + |
| 94 | + // Current target of the floating major tag (informational only). |
| 95 | + let majorTag = majorTagFor(suggested.patch); |
| 96 | + let majorTagSha = null; |
| 97 | + if (majorTag) { |
| 98 | + try { |
| 99 | + majorTagSha = (await gh(["api", `repos/${repo}/git/ref/tags/${majorTag}`, "--jq", ".object.sha"])).trim(); |
| 100 | + } catch { |
| 101 | + majorTagSha = null; |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + return { |
| 106 | + repo, |
| 107 | + defaultBranch, |
| 108 | + latestRelease, |
| 109 | + suggested, |
| 110 | + defaultTag: suggested.patch, |
| 111 | + majorTag, |
| 112 | + majorTagSha, |
| 113 | + }; |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * Classify a changelog line so we can pre-select which commits are relevant to |
| 118 | + * action consumers. Dependabot bumps to dev dependencies and to GitHub Actions |
| 119 | + * are excluded by default; everything else is included. |
| 120 | + */ |
| 121 | +export function classifyLine(text) { |
| 122 | + const isDependabot = /@dependabot(\[bot\])?/i.test(text); |
| 123 | + if (!isDependabot) { |
| 124 | + return { category: "change", include: true }; |
| 125 | + } |
| 126 | + const lower = text.toLowerCase(); |
| 127 | + // npm scoped packages (@scope/name) are dev/prod deps, not GitHub Actions, |
| 128 | + // so classify those before falling through to the actions heuristics. |
| 129 | + const isDev = |
| 130 | + /\bnpm-development\b/.test(lower) || |
| 131 | + /development group/.test(lower) || |
| 132 | + /@types\//.test(text); |
| 133 | + const isActions = |
| 134 | + /actions-(minor|major|patch)\b/.test(lower) || |
| 135 | + /\bthe actions[- ]/.test(lower) || |
| 136 | + /\bgithub-actions\b/.test(lower) || |
| 137 | + // Bump owner/name (no leading @) is an action repo, e.g. actions/checkout. |
| 138 | + /\bbump\s+(?!@)[\w.-]+\/[\w.-]+\s+from\b/.test(lower); |
| 139 | + if (isDev) return { category: "dependabot-dev", include: false }; |
| 140 | + if (isActions) return { category: "dependabot-actions", include: false }; |
| 141 | + return { category: "dependabot-prod", include: true }; |
| 142 | +} |
| 143 | + |
| 144 | +/** Split a generated-notes body into a header, item lines, and footer. */ |
| 145 | +export function parseNotesBody(body) { |
| 146 | + const lines = (body || "").split("\n"); |
| 147 | + const items = []; |
| 148 | + let footer = ""; |
| 149 | + for (const line of lines) { |
| 150 | + const trimmed = line.trimEnd(); |
| 151 | + if (/^\*\s+/.test(trimmed)) { |
| 152 | + const text = trimmed.replace(/^\*\s+/, ""); |
| 153 | + const { category, include } = classifyLine(text); |
| 154 | + items.push({ id: items.length, text, category, include }); |
| 155 | + } else if (/^\*\*Full Changelog\*\*:/.test(trimmed)) { |
| 156 | + footer = trimmed; |
| 157 | + } |
| 158 | + } |
| 159 | + return { items, footer }; |
| 160 | +} |
| 161 | + |
| 162 | +/** Ask GitHub to generate release notes for a tag range and parse them. */ |
| 163 | +export async function generateNotes(cwd, { tag, previousTag, targetCommitish }) { |
| 164 | + if (!parseVersion(tag)) { |
| 165 | + throw new Error(`Tag must be a v-prefixed semver like v4.2.1 (got: ${tag ?? "<missing>"})`); |
| 166 | + } |
| 167 | + const repo = await resolveRepo(cwd); |
| 168 | + const args = ["api", `repos/${repo}/releases/generate-notes`, "-f", `tag_name=${tag}`]; |
| 169 | + if (previousTag) args.push("-f", `previous_tag_name=${previousTag}`); |
| 170 | + if (targetCommitish) args.push("-f", `target_commitish=${targetCommitish}`); |
| 171 | + const out = await gh(args); |
| 172 | + const parsed = JSON.parse(out); |
| 173 | + const { items, footer } = parseNotesBody(parsed.body); |
| 174 | + const fallbackFooter = previousTag |
| 175 | + ? `**Full Changelog**: https://github.com/${repo}/compare/${previousTag}...${tag}` |
| 176 | + : `**Full Changelog**: https://github.com/${repo}/commits/${tag}`; |
| 177 | + return { |
| 178 | + repo, |
| 179 | + name: parsed.name || tag, |
| 180 | + items, |
| 181 | + footer: footer || fallbackFooter, |
| 182 | + }; |
| 183 | +} |
| 184 | + |
| 185 | +/** Rebuild a release body from the selected item lines plus the footer. */ |
| 186 | +export function composeBody(includedTexts, footer) { |
| 187 | + const parts = []; |
| 188 | + if (includedTexts.length > 0) { |
| 189 | + parts.push("## What's Changed"); |
| 190 | + for (const text of includedTexts) parts.push(`* ${text}`); |
| 191 | + } |
| 192 | + if (footer) { |
| 193 | + if (parts.length > 0) parts.push(""); |
| 194 | + parts.push(footer); |
| 195 | + } |
| 196 | + return parts.join("\n"); |
| 197 | +} |
| 198 | + |
| 199 | +/** |
| 200 | + * Publish the release (never draft, never with assets) then force-move the |
| 201 | + * floating major tag to the newly released commit. |
| 202 | + */ |
| 203 | +export async function publishRelease(cwd, { tag, name, body, targetCommitish }) { |
| 204 | + const repo = await resolveRepo(cwd); |
| 205 | + const version = parseVersion(tag); |
| 206 | + if (!version) throw new Error(`Tag must be a v-prefixed semver like v4.2.1 (got: ${tag})`); |
| 207 | + |
| 208 | + const dir = await mkdtemp(join(tmpdir(), "release-cutter-")); |
| 209 | + const notesFile = join(dir, "notes.md"); |
| 210 | + await writeFile(notesFile, body ?? "", "utf8"); |
| 211 | + |
| 212 | + try { |
| 213 | + const createArgs = [ |
| 214 | + "release", |
| 215 | + "create", |
| 216 | + tag, |
| 217 | + "--repo", |
| 218 | + repo, |
| 219 | + "--title", |
| 220 | + name || tag, |
| 221 | + "--notes-file", |
| 222 | + notesFile, |
| 223 | + ]; |
| 224 | + if (targetCommitish) createArgs.push("--target", targetCommitish); |
| 225 | + const createOut = await gh(createArgs); |
| 226 | + const releaseUrl = createOut.trim().split("\n").pop().trim(); |
| 227 | + |
| 228 | + // Resolve the commit the new tag points at, then move the major tag. |
| 229 | + const sha = (await gh(["api", `repos/${repo}/git/ref/tags/${tag}`, "--jq", ".object.sha"])).trim(); |
| 230 | + const majorTag = majorTagFor(tag); |
| 231 | + let movedMajor = null; |
| 232 | + if (majorTag) { |
| 233 | + try { |
| 234 | + await gh([ |
| 235 | + "api", |
| 236 | + "-X", |
| 237 | + "PATCH", |
| 238 | + `repos/${repo}/git/refs/tags/${majorTag}`, |
| 239 | + "-f", |
| 240 | + `sha=${sha}`, |
| 241 | + "-F", |
| 242 | + "force=true", |
| 243 | + ]); |
| 244 | + } catch { |
| 245 | + // Ref may not exist yet (first release of a major) -> create it. |
| 246 | + await gh(["api", "-X", "POST", `repos/${repo}/git/refs`, "-f", `ref=refs/tags/${majorTag}`, "-f", `sha=${sha}`]); |
| 247 | + } |
| 248 | + movedMajor = { tag: majorTag, sha }; |
| 249 | + } |
| 250 | + |
| 251 | + return { repo, tag, releaseUrl, sha, movedMajor }; |
| 252 | + } finally { |
| 253 | + await rm(dir, { recursive: true, force: true }); |
| 254 | + } |
| 255 | +} |
0 commit comments