|
| 1 | +#!/usr/bin/env node |
| 2 | +import {Buffer} from 'node:buffer' |
| 3 | +import {readFileSync} from 'node:fs' |
| 4 | + |
| 5 | +export const CHANGESET_PREFIX = 'dependabot-' |
| 6 | + |
| 7 | +function parseList(value) { |
| 8 | + if (!value) return [] |
| 9 | + if (Array.isArray(value)) return value.flatMap(parseList) |
| 10 | + |
| 11 | + return String(value) |
| 12 | + .split(/[\n,]+/) |
| 13 | + .map(item => item.trim()) |
| 14 | + .filter(Boolean) |
| 15 | +} |
| 16 | + |
| 17 | +function unique(values) { |
| 18 | + return [...new Set(values)] |
| 19 | +} |
| 20 | + |
| 21 | +function getUpdatedDependencyNames(metadata) { |
| 22 | + if (!metadata['updated-dependencies-json']) return [] |
| 23 | + |
| 24 | + try { |
| 25 | + const dependencies = JSON.parse(metadata['updated-dependencies-json']) |
| 26 | + if (!Array.isArray(dependencies)) return [] |
| 27 | + |
| 28 | + return dependencies |
| 29 | + .map(dependency => dependency.dependencyName ?? dependency['dependency-name'] ?? dependency.name) |
| 30 | + .filter(Boolean) |
| 31 | + } catch { |
| 32 | + return [] |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +export function getDependencyNames(metadata) { |
| 37 | + return unique([...getUpdatedDependencyNames(metadata), ...parseList(metadata['dependency-names'] ?? metadata['dependency-name'])]) |
| 38 | +} |
| 39 | + |
| 40 | +export function isSecurityUpdate(metadata) { |
| 41 | + const alertState = String(metadata['alert-state'] ?? '').trim().toLowerCase() |
| 42 | + return alertState === 'fixed' || parseList(metadata['ghsa-id']).length > 0 |
| 43 | +} |
| 44 | + |
| 45 | +export function getProductionRangeChanges({basePackage, headPackage, dependencyNames}) { |
| 46 | + const baseDependencies = basePackage.dependencies ?? {} |
| 47 | + const headDependencies = headPackage.dependencies ?? {} |
| 48 | + |
| 49 | + return dependencyNames.filter(name => { |
| 50 | + if (!(name in baseDependencies) && !(name in headDependencies)) return false |
| 51 | + return baseDependencies[name] !== headDependencies[name] |
| 52 | + }) |
| 53 | +} |
| 54 | + |
| 55 | +export function evaluatePolicy({basePackage, headPackage, metadata}) { |
| 56 | + const dependencyNames = getDependencyNames(metadata) |
| 57 | + const securityUpdate = isSecurityUpdate(metadata) |
| 58 | + const productionRangeChanges = getProductionRangeChanges({basePackage, headPackage, dependencyNames}) |
| 59 | + |
| 60 | + return { |
| 61 | + dependencyNames, |
| 62 | + qualifies: securityUpdate || productionRangeChanges.length > 0, |
| 63 | + reasons: { |
| 64 | + securityUpdate, |
| 65 | + productionRangeChanges, |
| 66 | + }, |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +function formatList(items) { |
| 71 | + if (items.length === 0) return 'dependencies' |
| 72 | + if (items.length === 1) return `\`${items[0]}\`` |
| 73 | + return `${items.slice(0, -1).map(item => `\`${item}\``).join(', ')} and \`${items.at(-1)}\`` |
| 74 | +} |
| 75 | + |
| 76 | +export function renderChangeset({packageName, prNumber, policy}) { |
| 77 | + const names = policy.dependencyNames |
| 78 | + const reason = policy.reasons.securityUpdate |
| 79 | + ? `Resolve Dependabot security alert(s) for ${formatList(names)}.` |
| 80 | + : `Bump production dependency range(s) for ${formatList(policy.reasons.productionRangeChanges)}.` |
| 81 | + |
| 82 | + return `---\n"${packageName}": patch\n---\n\n${reason}\n\nGenerated for Dependabot PR #${prNumber}.\n` |
| 83 | +} |
| 84 | + |
| 85 | +function encodePath(path) { |
| 86 | + return path.split('/').map(encodeURIComponent).join('/') |
| 87 | +} |
| 88 | + |
| 89 | +async function githubRequest(path, {method = 'GET', token, body, accept = 'application/vnd.github+json'} = {}) { |
| 90 | + const response = await fetch(`https://api.github.com${path}`, { |
| 91 | + method, |
| 92 | + headers: { |
| 93 | + accept, |
| 94 | + authorization: 'Bearer ' + token, |
| 95 | + 'content-type': 'application/json', |
| 96 | + 'x-github-api-version': '2022-11-28', |
| 97 | + }, |
| 98 | + body: body === undefined ? undefined : JSON.stringify(body), |
| 99 | + }) |
| 100 | + |
| 101 | + if (response.status === 404) return undefined |
| 102 | + if (!response.ok) { |
| 103 | + throw new Error(`${method} ${path} failed with ${response.status}: ${await response.text()}`) |
| 104 | + } |
| 105 | + |
| 106 | + return response.json() |
| 107 | +} |
| 108 | + |
| 109 | +async function readJsonContent({owner, repo, path, ref, token}) { |
| 110 | + const content = await githubRequest(`/repos/${owner}/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`, { |
| 111 | + token, |
| 112 | + }) |
| 113 | + if (!content?.content) throw new Error(`Unable to read ${path} at ${ref}`) |
| 114 | + return JSON.parse(Buffer.from(content.content, 'base64').toString('utf8')) |
| 115 | +} |
| 116 | + |
| 117 | +async function getContent({owner, repo, path, ref, token}) { |
| 118 | + return githubRequest(`/repos/${owner}/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`, {token}) |
| 119 | +} |
| 120 | + |
| 121 | +async function putContent({owner, repo, path, branch, content, token, message, sha}) { |
| 122 | + await githubRequest(`/repos/${owner}/${repo}/contents/${encodePath(path)}`, { |
| 123 | + method: 'PUT', |
| 124 | + token, |
| 125 | + body: { |
| 126 | + message, |
| 127 | + content: Buffer.from(content).toString('base64'), |
| 128 | + branch, |
| 129 | + sha, |
| 130 | + }, |
| 131 | + }) |
| 132 | +} |
| 133 | + |
| 134 | +async function deleteContent({owner, repo, path, branch, token, message, sha}) { |
| 135 | + await githubRequest(`/repos/${owner}/${repo}/contents/${encodePath(path)}`, { |
| 136 | + method: 'DELETE', |
| 137 | + token, |
| 138 | + body: {message, branch, sha}, |
| 139 | + }) |
| 140 | +} |
| 141 | + |
| 142 | +export async function applyDependabotChangeset({event, metadata, token}) { |
| 143 | + const pr = event.pull_request |
| 144 | + if (!pr) throw new Error('This script must run for a pull request event.') |
| 145 | + if (pr.user.login !== 'dependabot[bot]') throw new Error(`Refusing to modify PR authored by ${pr.user.login}.`) |
| 146 | + if (pr.head.repo.full_name !== event.repository.full_name) { |
| 147 | + throw new Error('Refusing to write to a pull request branch from a different repository.') |
| 148 | + } |
| 149 | + |
| 150 | + const [owner, repo] = event.repository.full_name.split('/') |
| 151 | + const basePackage = await readJsonContent({owner, repo, path: 'package.json', ref: pr.base.sha, token}) |
| 152 | + const headPackage = await readJsonContent({owner, repo, path: 'package.json', ref: pr.head.sha, token}) |
| 153 | + const policy = evaluatePolicy({basePackage, headPackage, metadata}) |
| 154 | + const changesetPath = `.changeset/${CHANGESET_PREFIX}${pr.number}.md` |
| 155 | + const existing = await getContent({owner, repo, path: changesetPath, ref: pr.head.ref, token}) |
| 156 | + |
| 157 | + if (!policy.qualifies) { |
| 158 | + if (existing) { |
| 159 | + await deleteContent({ |
| 160 | + owner, |
| 161 | + repo, |
| 162 | + path: changesetPath, |
| 163 | + branch: pr.head.ref, |
| 164 | + token, |
| 165 | + message: `Remove Dependabot changeset for #${pr.number}`, |
| 166 | + sha: existing.sha, |
| 167 | + }) |
| 168 | + return {action: 'removed', path: changesetPath, policy} |
| 169 | + } |
| 170 | + |
| 171 | + return {action: 'skipped', path: changesetPath, policy} |
| 172 | + } |
| 173 | + |
| 174 | + const content = renderChangeset({packageName: headPackage.name, prNumber: pr.number, policy}) |
| 175 | + if (existing && Buffer.from(existing.content, 'base64').toString('utf8') === content) { |
| 176 | + return {action: 'unchanged', path: changesetPath, policy} |
| 177 | + } |
| 178 | + |
| 179 | + await putContent({ |
| 180 | + owner, |
| 181 | + repo, |
| 182 | + path: changesetPath, |
| 183 | + branch: pr.head.ref, |
| 184 | + token, |
| 185 | + content, |
| 186 | + message: `Add Dependabot changeset for #${pr.number}`, |
| 187 | + sha: existing?.sha, |
| 188 | + }) |
| 189 | + |
| 190 | + return {action: existing ? 'updated' : 'created', path: changesetPath, policy} |
| 191 | +} |
| 192 | + |
| 193 | +if (import.meta.url === `file://${process.argv[1]}`) { |
| 194 | + const event = JSON.parse(process.env.GITHUB_EVENT_JSON ?? readFileSync(process.env.GITHUB_EVENT_PATH, 'utf8')) |
| 195 | + const metadata = JSON.parse(process.env.DEPENDABOT_METADATA_JSON) |
| 196 | + const token = process.env.GITHUB_TOKEN |
| 197 | + if (!token) throw new Error('GITHUB_TOKEN is required.') |
| 198 | + |
| 199 | + applyDependabotChangeset({event, metadata, token}) |
| 200 | + .then(result => { |
| 201 | + console.log(`${result.action} ${result.path}`) |
| 202 | + console.log(JSON.stringify(result.policy, null, 2)) |
| 203 | + }) |
| 204 | + .catch(error => { |
| 205 | + console.error(error) |
| 206 | + process.exitCode = 1 |
| 207 | + }) |
| 208 | +} |
0 commit comments