This repository has been archived by the owner on Apr 26, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.mjs
356 lines (314 loc) · 9.34 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// This script reads the input `./lib/modules.json` data file, iterates
// the items within it, and builds the deprecation modules in the `./out/`
// directory.
import dotenv from 'dotenv'
dotenv.config()
import { boolean } from 'boolean'
let DRY_RUN = true
if (process.env.DRY_RUN) {
DRY_RUN = boolean(process.env.DRY_RUN)
}
import { spawn } from "child_process"
import { setTimeout } from 'timers/promises'
import fs from 'fs/promises'
import path from 'path'
import PackageJson from '@npmcli/package-json'
import { Client } from 'undici'
const client = new Client('https://api.github.com')
const headers = {
'user-agent': 'fastify/deprecator',
accept: 'application/vnd.github.v3+json',
authorization: `token ${process.env.GITHUB_TOKEN}`,
'content-type': 'application/json'
}
import umeta from 'umeta'
const { dirName } = umeta(import.meta)
const modulesSource = await fs.readFile('./lib/modules.json')
const modules = JSON.parse(modulesSource.toString('utf8'))
import {
indexTmpl,
pkgTmpl,
readmeTmpl,
pullRequestMessageTmpl
} from './templates/index.mjs'
/**
* This name to be used for branches when updating modules's names and versions.
*/
const REPO_BRANCH_NAME = 'rename-module'
const statuses = {}
for (const mod of modules) {
const status = {
deprecationModule: {
published: false
},
replacementModule: {
prCreated: false
}
}
statuses[mod.name] = status
console.error(`${mod.name}: starting to process`)
// We need to wait a few seconds to avoid GitHub's secondary rate limits.
// See https://docs.github.com/en/rest/guides/best-practices-for-integrators#dealing-with-secondary-rate-limits
// We choose 30 seconds in an effort to avoid hitting the undisclosed limits.
// The work we are doing generates notifications and is thus more severely
// limited.
await setTimeout(30000)
try {
console.error(`${mod.name}: building deprecation module`)
await buildDeprecationModule(mod)
status.deprecationModule.published = true
status.deprecationModule.versionPublished = mod.versionToPublish
} catch (cause) {
status.deprecationModule.error = cause.message
status.deprecationModule.stack = cause.stack
continue
}
try {
console.error(`${mod.name}: building replacement module`)
const prUrl = await buildReplacementModule(mod)
status.replacementModule.prCreated = true
status.replacementModule.prUrl = prUrl
} catch (cause) {
status.replacementModule.error = cause.message
status.replacementModule.stack = cause.stack
continue
}
}
console.log(JSON.stringify(statuses, null, 2))
/**
* Write a skeleton wrapper module that will act as the deprecation
* module when published to npmjs.com.
*
* @param {object} mod A module description from the input `modules.json`.
*/
async function buildDeprecationModule(mod) {
const outDir = path.join('out', mod.name)
const indexOut = path.join(outDir, 'index.js')
const pkgOut = path.join(outDir, 'package.json')
const readmeOut = path.join(outDir, 'README.md')
await fs.mkdir(outDir, { recursive: true })
const index = replaceAll(indexTmpl, mod)
await fs.writeFile(indexOut, index)
const pkg = replaceAll(pkgTmpl, mod)
await fs.writeFile(pkgOut, pkg)
const readme = replaceAll(readmeTmpl, mod)
await fs.writeFile(readmeOut, readme)
}
/**
* Utility function to replace all placeholder values in a template
* with the corresponding values for a module being deprecated.
*
* @param {string} str The template string with placeholder values.
* @param {object} mod A module description from the input `modules.json`.
*
* @returns {string} The updated string.
*/
function replaceAll (str, mod) {
return str
.slice(0)
.replaceAll('<<module_name>>', mod.name)
.replaceAll('<<module_current_version>>', mod.currentVersion)
.replaceAll('<<module_version>>', mod.versionToPublish)
.replaceAll('<<module_license>>', mod.license)
.replaceAll('<<new_module_name>>', mod.newModule.name)
.replaceAll('<<new_module_version>>', mod.newModule.version)
}
/**
* This function clones the remote repository, creates a new branch,
* updates the module's `package.json`, and creates a new pull request.
*
* @param {object} mod A module description from the input `modules.json`.
*/
async function buildReplacementModule(mod) {
const reposDir = path.join(dirName, 'repos')
await fs.mkdir(reposDir, { recursive: true })
const repoDir = path.join(reposDir, mod.name)
try {
// Clean up previous runs and start over. It's easier than managing
// all of the ceremony around making sure branches exist and are in the
// right state.
const dirStats = await fs.stat(repoDir)
if (dirStats.isDirectory()) {
await fs.rm(repoDir, { recursive: true })
}
} catch {}
await cloneRepo({ repoName: mod.name, reposDir })
await createBranch({ repoDir })
await updatePackageJson({ repoDir, mod })
await stageChanges({ repoDir })
await commitChanges({ repoDir })
let prUrl = 'dry run: did not create pr'
if (DRY_RUN !== true) {
await pushChanges({ repoDir })
prUrl = await createPullRequest({ repoDir, mod })
}
return prUrl
}
/**
* Clone a repository from the GitHub organzation into our local working
* tree.
*/
function cloneRepo({ repoName, reposDir }) {
const gitUrl = `git@github.com:fastify/${repoName}.git`
const proc = spawn(
'git',
['clone', '--depth=1', gitUrl, repoName ],
{ cwd: reposDir }
)
return new Promise((resolve, reject) => {
proc.on('error', reject)
proc.on('exit', (code) => {
if (code !== 0) {
return reject(Error(`process exited with code: ${code}`))
}
resolve()
})
})
}
/**
* Create the branch to be used for automating the change of a module's version
* and name.
*/
function createBranch({ repoDir }) {
const proc = spawn(
'git',
['checkout', '-b', REPO_BRANCH_NAME],
{ cwd: repoDir }
)
return new Promise((resolve, reject) => {
proc.on('error', reject)
proc.on('exit', (code) => {
if (code !== 0) {
return reject(Error(`process exited with code: ${code}`))
}
resolve()
})
})
}
/**
* Update a module's version and name with the new module version and name.
*/
async function updatePackageJson({ repoDir, mod }) {
const pkg = await PackageJson.load(repoDir)
pkg.update({
version: mod.newModule.version,
name: mod.newModule.name,
publishConfig: {
access: 'public'
}
})
await pkg.save()
}
/**
* Stage the changes to the module in preparation for commit.
*/
function stageChanges({ repoDir }) {
const proc = spawn(
'git',
['add', '.'],
{ cwd: repoDir }
)
return new Promise((resolve, reject) => {
proc.on('error', reject)
proc.on('exit', (code) => {
if (code !== 0) {
return reject(Error(`process exited with code: ${code}`))
}
resolve()
})
})
}
/**
* Commit the staged changes and use a templated commit message.
*/
function commitChanges({ repoDir }) {
const proc = spawn(
'git',
['commit', '-F', path.join(dirName, 'templates', 'module-rename-commit.msg')],
{ cwd: repoDir }
)
return new Promise((resolve, reject) => {
proc.on('error', reject)
proc.on('exit', (code) => {
if (code !== 0) {
return reject(Error(`process exited with code: ${code}`))
}
resolve()
})
})
}
/**
* Push the staged changes to the remote GitHub repository.
*/
function pushChanges({ repoDir }) {
const proc = spawn(
'git',
['push', '-u', 'origin', REPO_BRANCH_NAME],
{ cwd: repoDir }
)
return new Promise((resolve, reject) => {
proc.stderr.pipe(process.stderr)
proc.on('error', reject)
proc.on('exit', (code) => {
if (code !== 0) {
return reject(Error(`process exited with code: ${code}`))
}
resolve()
})
})
}
/**
* Determine the name of the main branch for the repository on GitHub.
* This is needed for creating the pull request. We cannot assume a specific
* name, e.g. "master", as it may be different per repository.
*/
function getRemoteMainBranch({ repoDir }) {
const proc = spawn(
'git',
['remote', 'show', 'origin'],
{ cwd: repoDir }
)
let output = ''
proc.stdout.on('data', d => {
output += d.toString()
})
return new Promise((resolve, reject) => {
proc.on('error', reject)
proc.on('exit', (code) => {
if (code !== 0) {
return reject(Error(`process exited with code: ${code}`))
}
const branch = output.split(/\r?\n/)
.filter(line => line.trim().startsWith('HEAD branch:'))
?.pop()
?.split(': ')
?.pop();
resolve(branch)
})
})
}
/**
* Generate a new templated pull request that will rename the module and
* set the new version.
*/
async function createPullRequest({ repoDir, mod }) {
const remoteBase = await getRemoteMainBranch({ repoDir })
const response = await client.request({
method: 'POST',
path: `/repos/fastify/${mod.name}/pulls`,
headers,
body: JSON.stringify({
title: 'Rename module',
body: pullRequestMessageTmpl,
head: REPO_BRANCH_NAME,
base: remoteBase
})
})
if (response.statusCode !== 201) {
console.error(`${mod}: failed to create pull request`)
console.error(await response.body.text())
throw Error(`pr create failed with code ${response.statusCode}`)
}
const data = await response.body.json()
return data.html_url
}