Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

upsert-pr-comment.mjs

159 lines3.8 KB

1#!/usr/bin/env node
2​
3import { promises as fsp } from 'node:fs'
4import path from 'node:path'
5import { parseArgs as parseNodeArgs } from 'node:util'
6​
7const DEFAULT_MARKER = '<!-- bundle-size-benchmark -->'
8​
9function parseArgs(argv) {
10 const { values } = parseNodeArgs({
11 args: argv,
12 allowPositionals: false,
13 strict: true,
14 options: {
15 pr: { type: 'string' },
16 'body-file': { type: 'string' },
17 repo: { type: 'string' },
18 token: { type: 'string' },
19 marker: { type: 'string' },
20 'api-url': { type: 'string' },
21 },
22 })
23​
24 const args = {
25 pr: values.pr ? Number.parseInt(values.pr, 10) : undefined,
26 bodyFile: values['body-file'],
27 repo: values.repo ?? process.env.GITHUB_REPOSITORY,
28 marker: values.marker ?? DEFAULT_MARKER,
29 token: values.token ?? (process.env.GITHUB_TOKEN || process.env.GH_TOKEN),
30 apiUrl:
31 values['api-url'] ??
32 (process.env.GITHUB_API_URL || 'https://api.github.com'),
33 }
34​
35 if (!Number.isFinite(args.pr) || args.pr <= 0) {
36 throw new Error('Missing required argument: --pr')
37 }
38​
39 if (!args.bodyFile) {
40 throw new Error('Missing required argument: --body-file')
41 }
42​
43 if (!args.repo || !args.repo.includes('/')) {
44 throw new Error(
45 'Missing repository context. Provide --repo or GITHUB_REPOSITORY.',
46 )
47 }
48​
49 if (!args.token) {
50 throw new Error('Missing token. Provide --token or GITHUB_TOKEN.')
51 }
52​
53 return args
55​
56async function githubRequest({ apiUrl, token, method, endpoint, body }) {
57 const url = `${apiUrl.replace(/\/$/, '')}${endpoint}`
58 const response = await fetch(url, {
59 method,
60 headers: {
61 Authorization: `Bearer ${token}`,
62 Accept: 'application/vnd.github+json',
63 'User-Agent': 'tanstack-router-bundle-size-bot',
64 'Content-Type': 'application/json',
65 },
66 body: body ? JSON.stringify(body) : undefined,
67 })
68​
69 if (!response.ok) {
70 const text = await response.text()
71 throw new Error(
72 `${method} ${endpoint} failed (${response.status} ${response.statusText}): ${text}`,
73 )
74 }
75​
76 if (response.status === 204) {
77 return undefined
78 }
79​
80 return response.json()
82​
83async function listIssueComments({ apiUrl, token, repo, pr }) {
84 const comments = []
85 let page = 1
86 const perPage = 100
87​
88 for (;;) {
89 const data = await githubRequest({
90 apiUrl,
91 token,
92 method: 'GET',
93 endpoint: `/repos/${repo}/issues/${pr}/comments?per_page=${perPage}&page=${page}`,
94 })
95​
96 comments.push(...data)
97​
98 if (!Array.isArray(data) || data.length < perPage) {
99 break
100 }
101​
102 page += 1
103 }
104​
105 return comments
107​
108async function main() {
109 const args = parseArgs(process.argv.slice(2))
110 const bodyPath = path.resolve(args.bodyFile)
111 const rawBody = await fsp.readFile(bodyPath, 'utf8')
112 const body = rawBody.includes(args.marker)
113 ? rawBody
114 : `${args.marker}\n${rawBody}`
115​
116 const comments = await listIssueComments({
117 apiUrl: args.apiUrl,
118 token: args.token,
119 repo: args.repo,
120 pr: args.pr,
121 })
122​
123 const existing = comments.find(
124 (comment) =>
125 typeof comment?.body === 'string' && comment.body.includes(args.marker),
126 )
127​
128 if (existing) {
129 await githubRequest({
130 apiUrl: args.apiUrl,
131 token: args.token,
132 method: 'PATCH',
133 endpoint: `/repos/${args.repo}/issues/comments/${existing.id}`,
134 body: { body },
135 })
136​
137 process.stdout.write(
138 `Updated PR #${args.pr} bundle-size comment (${existing.id}).\n`,
139 )
140 return
141 }
142​
143 const created = await githubRequest({
144 apiUrl: args.apiUrl,
145 token: args.token,
146 method: 'POST',
147 endpoint: `/repos/${args.repo}/issues/${args.pr}/comments`,
148 body: { body },
149 })
150​
151 process.stdout.write(
152 `Created PR #${args.pr} bundle-size comment (${created?.id ?? 'unknown'}).\n`,
153 )
155​
156main().catch((error) => {
157 console.error(error)
158 process.exit(1)
159})