|
| 1 | +import fs from 'node:fs/promises'; |
| 2 | +import path from 'node:path'; |
| 3 | + |
| 4 | +const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN; |
| 5 | +const repository = process.env.GH_REPO || process.env.GITHUB_REPOSITORY; |
| 6 | +const tag = process.env.RELEASE_TAG; |
| 7 | +const binaryPath = path.resolve( |
| 8 | + process.env.RELEASE_BINARY_PATH || 'target/release/simprint-runtime.exe' |
| 9 | +); |
| 10 | +const latestJsonPath = path.resolve(process.env.RELEASE_LATEST_JSON_PATH || 'latest.json'); |
| 11 | + |
| 12 | +if (!token) throw new Error('GH_TOKEN or GITHUB_TOKEN is not set'); |
| 13 | +if (!repository) throw new Error('GH_REPO or GITHUB_REPOSITORY is not set'); |
| 14 | +if (!tag) throw new Error('RELEASE_TAG is not set'); |
| 15 | + |
| 16 | +const [owner, repo] = repository.split('/'); |
| 17 | +if (!owner || !repo) throw new Error(`Invalid repository: ${repository}`); |
| 18 | + |
| 19 | +const tagNotes = await readTagNotes(tag); |
| 20 | +const release = await ensureRelease(tagNotes); |
| 21 | + |
| 22 | +await uploadAsset(release, binaryPath, 'application/octet-stream'); |
| 23 | +await uploadAsset(release, latestJsonPath, 'application/json'); |
| 24 | + |
| 25 | +console.log(`GitHub release publish finished for ${tag}`); |
| 26 | + |
| 27 | +async function readTagNotes(tagName) { |
| 28 | + try { |
| 29 | + const refResponse = await githubApi(`/repos/${owner}/${repo}/git/ref/tags/${encodeURIComponent(tagName)}`, { |
| 30 | + okStatuses: [200, 404], |
| 31 | + }); |
| 32 | + |
| 33 | + if (refResponse.status === 404) { |
| 34 | + console.log(`Tag ref ${tagName} not found on GitHub, fallback to generated release notes`); |
| 35 | + return ''; |
| 36 | + } |
| 37 | + |
| 38 | + const target = refResponse.json?.object; |
| 39 | + if (!target || target.type !== 'tag' || !target.sha) { |
| 40 | + console.log(`Tag ${tagName} is not an annotated tag on GitHub, fallback to generated release notes`); |
| 41 | + return ''; |
| 42 | + } |
| 43 | + |
| 44 | + const tagObject = await githubApi(`/repos/${owner}/${repo}/git/tags/${target.sha}`, { |
| 45 | + okStatuses: [200, 404], |
| 46 | + }); |
| 47 | + |
| 48 | + if (tagObject.status === 404) { |
| 49 | + console.log(`Annotated tag object for ${tagName} not found on GitHub, fallback to generated release notes`); |
| 50 | + return ''; |
| 51 | + } |
| 52 | + |
| 53 | + return (tagObject.json?.message || '').trim(); |
| 54 | + } catch (error) { |
| 55 | + console.warn(`Failed to read GitHub tag notes for ${tagName}: ${error.message}`); |
| 56 | + return ''; |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +async function ensureRelease(tagNotes) { |
| 61 | + const existing = await githubApi( |
| 62 | + `/repos/${owner}/${repo}/releases/tags/${encodeURIComponent(tag)}`, |
| 63 | + { okStatuses: [200, 404] } |
| 64 | + ); |
| 65 | + |
| 66 | + if (existing.status === 200) { |
| 67 | + console.log(`Using existing GitHub release for ${tag}`); |
| 68 | + return await syncExistingRelease(existing.json, tagNotes); |
| 69 | + } |
| 70 | + |
| 71 | + console.log(`Creating GitHub release for ${tag}`); |
| 72 | + const created = await githubApi(`/repos/${owner}/${repo}/releases`, { |
| 73 | + method: 'POST', |
| 74 | + json: buildReleasePayload(tagNotes), |
| 75 | + okStatuses: [201, 422], |
| 76 | + }); |
| 77 | + |
| 78 | + if (created.status === 201) { |
| 79 | + return created.json; |
| 80 | + } |
| 81 | + |
| 82 | + const refetched = await githubApi(`/repos/${owner}/${repo}/releases/tags/${encodeURIComponent(tag)}`); |
| 83 | + return refetched.json; |
| 84 | +} |
| 85 | + |
| 86 | +async function syncExistingRelease(release, tagNotes) { |
| 87 | + const desiredBody = tagNotes || ''; |
| 88 | + const currentBody = release.body || ''; |
| 89 | + const shouldUpdateBody = Boolean(tagNotes) && currentBody !== desiredBody; |
| 90 | + const shouldEnableGeneratedNotes = !tagNotes && !currentBody; |
| 91 | + |
| 92 | + if (!shouldUpdateBody && !shouldEnableGeneratedNotes) { |
| 93 | + return release; |
| 94 | + } |
| 95 | + |
| 96 | + console.log(`Updating GitHub release metadata for ${tag}`); |
| 97 | + const updated = await githubApi(`/repos/${owner}/${repo}/releases/${release.id}`, { |
| 98 | + method: 'PATCH', |
| 99 | + json: buildReleasePayload(tagNotes), |
| 100 | + okStatuses: [200], |
| 101 | + }); |
| 102 | + |
| 103 | + return updated.json; |
| 104 | +} |
| 105 | + |
| 106 | +function buildReleasePayload(tagNotes) { |
| 107 | + const payload = { |
| 108 | + tag_name: tag, |
| 109 | + name: tag, |
| 110 | + }; |
| 111 | + |
| 112 | + if (tagNotes) { |
| 113 | + payload.body = tagNotes; |
| 114 | + } else { |
| 115 | + payload.generate_release_notes = true; |
| 116 | + } |
| 117 | + |
| 118 | + return payload; |
| 119 | +} |
| 120 | + |
| 121 | +async function uploadAsset(release, filePath, contentType) { |
| 122 | + const fileName = path.basename(filePath); |
| 123 | + const fileBuffer = await fs.readFile(filePath); |
| 124 | + |
| 125 | + await deleteExistingAsset(release, fileName); |
| 126 | + |
| 127 | + const uploadUrl = release.upload_url.replace('{?name,label}', `?name=${encodeURIComponent(fileName)}`); |
| 128 | + console.log(`Uploading ${fileName}`); |
| 129 | + |
| 130 | + await retry(`upload ${fileName}`, async () => { |
| 131 | + const response = await fetch(uploadUrl, { |
| 132 | + method: 'POST', |
| 133 | + headers: { |
| 134 | + Authorization: `Bearer ${token}`, |
| 135 | + Accept: 'application/vnd.github+json', |
| 136 | + 'Content-Type': contentType, |
| 137 | + 'Content-Length': String(fileBuffer.length), |
| 138 | + }, |
| 139 | + body: fileBuffer, |
| 140 | + }); |
| 141 | + |
| 142 | + if (!response.ok) { |
| 143 | + const text = await response.text(); |
| 144 | + throw new Error(`upload failed ${response.status}: ${text}`); |
| 145 | + } |
| 146 | + }); |
| 147 | +} |
| 148 | + |
| 149 | +async function deleteExistingAsset(release, fileName) { |
| 150 | + const asset = (release.assets || []).find((item) => item.name === fileName); |
| 151 | + if (!asset) return; |
| 152 | + |
| 153 | + console.log(`Deleting existing asset ${fileName}`); |
| 154 | + await githubApi(`/repos/${owner}/${repo}/releases/assets/${asset.id}`, { |
| 155 | + method: 'DELETE', |
| 156 | + okStatuses: [204], |
| 157 | + }); |
| 158 | +} |
| 159 | + |
| 160 | +async function githubApi(apiPath, options = {}) { |
| 161 | + const url = apiPath.startsWith('http') ? apiPath : `https://api.github.com${apiPath}`; |
| 162 | + const headers = { |
| 163 | + Authorization: `Bearer ${token}`, |
| 164 | + Accept: 'application/vnd.github+json', |
| 165 | + 'X-GitHub-Api-Version': '2022-11-28', |
| 166 | + ...options.headers, |
| 167 | + }; |
| 168 | + |
| 169 | + let body; |
| 170 | + if (options.json !== undefined) { |
| 171 | + body = JSON.stringify(options.json); |
| 172 | + headers['Content-Type'] = 'application/json'; |
| 173 | + } else if (options.body !== undefined) { |
| 174 | + body = options.body; |
| 175 | + } |
| 176 | + |
| 177 | + const response = await fetch(url, { |
| 178 | + method: options.method || 'GET', |
| 179 | + headers, |
| 180 | + body, |
| 181 | + }); |
| 182 | + |
| 183 | + const okStatuses = options.okStatuses || [200]; |
| 184 | + const contentType = response.headers.get('content-type') || ''; |
| 185 | + const payload = contentType.includes('application/json') |
| 186 | + ? await response.json().catch(() => null) |
| 187 | + : await response.text().catch(() => ''); |
| 188 | + |
| 189 | + if (!okStatuses.includes(response.status)) { |
| 190 | + throw new Error(`${options.method || 'GET'} ${url} failed ${response.status}: ${formatPayload(payload)}`); |
| 191 | + } |
| 192 | + |
| 193 | + return { status: response.status, json: payload }; |
| 194 | +} |
| 195 | + |
| 196 | +async function retry(label, fn, attempts = 4) { |
| 197 | + let lastError; |
| 198 | + for (let attempt = 1; attempt <= attempts; attempt += 1) { |
| 199 | + try { |
| 200 | + await fn(); |
| 201 | + return; |
| 202 | + } catch (error) { |
| 203 | + lastError = error; |
| 204 | + if (attempt === attempts) break; |
| 205 | + const delayMs = attempt * 2000; |
| 206 | + console.warn(`${label} failed on attempt ${attempt}/${attempts}: ${error.message}`); |
| 207 | + console.warn(`Retrying in ${delayMs}ms`); |
| 208 | + await new Promise((resolve) => setTimeout(resolve, delayMs)); |
| 209 | + } |
| 210 | + } |
| 211 | + throw lastError; |
| 212 | +} |
| 213 | + |
| 214 | +function formatPayload(payload) { |
| 215 | + if (typeof payload === 'string') return payload; |
| 216 | + try { |
| 217 | + return JSON.stringify(payload); |
| 218 | + } catch { |
| 219 | + return String(payload); |
| 220 | + } |
| 221 | +} |
0 commit comments