-
Notifications
You must be signed in to change notification settings - Fork 0
/
changelog.js
399 lines (344 loc) · 11.8 KB
/
changelog.js
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/* eslint no-shadow:2 */
'use strict'
const { execSync } = require('child_process')
const semver = require('semver')
const fs = require('fs')
const config = require('@npmcli/template-oss')
const { resolve, relative } = require('path')
const exec = (...args) => execSync(...args).toString().trim()
const usage = () => `
node ${relative(process.cwd(), __filename)} [--read|-r] [--write|-w] [tag]
Generates changelog entries in our format starting from the most recent tag.
By default this script will print the release notes to stdout.
[tag] (defaults to most recent tag)
A tag to generate release notes for. Helpful for testing this script against
old releases. Leave this empty to look for the most recent tag.
[--write|-w] (default: false)
When set it will update the changelog with the new release.
If a release with the same version already exists it will replace it, otherwise
it will prepend it to the file directly after the top level changelog title.
[--read|-r] (default: false)
When set it will read the release notes for the [tag] from the CHANGELOG.md,
instead of fetching it. This is useful after release notes have been manually
edited and need to be pasted somewhere else.
`
// this script assumes that the tags it looks for all start with this prefix
const TAG_PREFIX = 'v'
// a naive implementation of console.log/group for indenting console
// output but keeping it in a buffer to be output to a file or console
const logger = (init) => {
let indent = 0
const step = 2
const buffer = [init]
return {
toString () {
return buffer.join('\n').trim()
},
group (s) {
this.log(s)
indent += step
},
groupEnd () {
indent -= step
},
log (s) {
if (!s) {
buffer.push('')
} else {
buffer.push(s.split('\n').map((l) => ' '.repeat(indent) + l).join('\n'))
}
},
}
}
// some helpers for generating common parts
// of our markdown release notes
const RELEASE = {
sep: '\n\n',
heading: '## ',
// versions in titles must be prefixed with a v
versionRe: semver.src[11].replace(TAG_PREFIX + '?', TAG_PREFIX),
get h1 () {
return '# Changelog' + this.sep
},
version (s) {
return s.startsWith(TAG_PREFIX) ? s : TAG_PREFIX + s
},
date (d) {
return `(${d || exec('date +%Y-%m-%d')})`
},
title (v, d) {
return `${this.heading}${this.version(v)} ${this.date(d)}`
},
}
// a map of all our changelog types that go into the release notes to be
// looked up by commit type and return the section title
const CHANGELOG = new Map(
config.changelogTypes.filter(c => !c.hidden).map((c) => [c.type, c.section]))
const assertArgs = (args) => {
if (args.help) {
console.log(usage())
return process.exit(0)
}
if (args.unsafe) {
// just to make manual testing easier
return args
}
// we dont need to be up to date to read from our local changelog
if (!args.read) {
exec(`git fetch ${args.remote}`)
const remoteBranch = `${args.remote}/${args.branch}`
const current = exec(`git rev-parse --abbrev-ref HEAD`)
if (current !== args.branch) {
throw new Error(`Must be on branch "${args.branch}"`)
}
const localLog = exec(`git log ${remoteBranch}..HEAD`).length > 0
const remoteLog = exec(`git log HEAD..${remoteBranch}`).length > 0
if (current !== args.branch || localLog || remoteLog) {
throw new Error(`Must be in sync with "${remoteBranch}"`)
}
}
return args
}
const parseArgs = (argv) => {
const result = {
tag: null,
file: resolve(__dirname, '..', 'CHANGELOG.md'),
branch: 'latest',
remote: 'origin',
type: 'md', // or 'gh'
write: false,
read: false,
help: false,
unsafe: false,
}
for (const arg of argv) {
if (arg.startsWith('--')) {
// dash to camel case. no value means boolean true
const [key, value = true] = arg.slice(2).split('=')
result[key.replace(/-([a-z])/g, (a) => a[1].toUpperCase())] = value
} else if (arg.startsWith('-')) {
// shorthands for read and write
const short = arg.slice(1)
const key = short === 'w' ? 'write' : short === 'r' ? 'read' : null
result[key] = true
} else {
// anything else without a -- or - is the tag
// force tag to start with a "v"
result.tag = arg.startsWith(TAG_PREFIX) ? arg : TAG_PREFIX + arg
}
}
// previous tag to requested tag OR most recent tag and everything after
// only matches tags prefixed with "v" since only the cli is prefixed with v
const getTag = (t = '') => exec(['git', 'describe', '--tags', '--abbrev=0',
`--match="${TAG_PREFIX}*" ${t}`].join(' '))
return assertArgs({
...result,
// if a tag is passed in get the previous tag to make a range between the two
// this is mostly for testing to generate release notes from old releases
startTag: result.tag ? getTag(`${result.tag}~1`) : getTag(),
endTag: result.tag || '',
})
}
// find an entire section of a release from the changelog from a version
const findRelease = (args, version) => {
const changelog = fs.readFileSync(args.file, 'utf-8')
const escRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const titleSrc = (v) => [
'^',
RELEASE.heading,
v ? escRegExp(v) : RELEASE.versionRe,
' ',
escRegExp(RELEASE.date()).replace(/\d/g, '\\d'),
'$',
].join('')
const releaseSrc = [
'(',
titleSrc(RELEASE.version(version)),
'[\\s\\S]*?',
RELEASE.sep,
')',
titleSrc(),
].join('')
const [, release = ''] = changelog.match(new RegExp(releaseSrc, 'm')) || []
return {
release: release.trim(),
changelog,
}
}
const generateRelease = async (args) => {
const range = `${args.startTag}...${args.endTag}`
const log = exec(`git log --reverse --pretty='format:%h' ${range}`)
.split('\n')
.filter(Boolean)
// prefix with underscore so its always a valid identifier
.map((sha) => `_${sha}: object (expression: "${sha}") { ...commitCredit }`)
if (!log.length) {
throw new Error(`No commits found for "${range}"`)
}
const query = `
fragment commitCredit on GitObject {
... on Commit {
message
url
abbreviatedOid
authors (first:10) {
nodes {
user {
login
url
}
email
name
}
}
associatedPullRequests (first:10) {
nodes {
number
url
merged
}
}
}
}
query {
repository (owner:"npm", name:"cli") {
${log}
}
}
`
const res = JSON.parse(exec(`gh api graphql -f query='${query}'`))
// collect commits by valid changelog type
const commits = [...CHANGELOG.values()].reduce((acc, c) => {
acc[c] = []
return acc
}, {})
const allCommits = Object.values(res.data.repository)
for (const commit of allCommits) {
// get changelog type of commit or bail if there is not a valid one
const [, type] = /(^\w+)[\s(:]?/.exec(commit.message) || []
const changelogType = CHANGELOG.get(type)
if (!changelogType) {
continue
}
const message = commit.message
.trim() // remove leading/trailing spaces
.replace(/(\r?\n)+/gm, '\n') // replace multiple newlines with one
.replace(/([^\s]+@\d+\.\d+\.\d+.*)/gm, '`$1`') // wrap package@version in backticks
// the title is the first line of the commit, 'let' because we change it later
let [title, ...body] = message.split('\n')
const prs = commit.associatedPullRequests.nodes.filter((pull) => pull.merged)
for (const pr of prs) {
title = title.replace(new RegExp(`\\s*\\(#${pr.number}\\)`, 'g'), '')
}
body = body
.map((line) => line.trim()) // remove artificial line breaks
.filter(Boolean) // remove blank lines
.join('\n') // rejoin on new lines
.split(/^[*-]/gm) // split on lines starting with bullets
.map((line) => line.trim()) // remove spaces around bullets
.filter((line) => !title.includes(line)) // rm lines that exist in the title
// replace new lines for this bullet with spaces and re-bullet it
.map((line) => `* ${line.trim().replace(/\n/gm, ' ')}`)
.join('\n') // re-join with new lines
commits[changelogType].push({
hash: commit.abbreviatedOid,
url: commit.url,
title,
type: changelogType,
body,
prs,
credit: commit.authors.nodes.map((author) => {
if (author.user && author.user.login) {
return {
name: `@${author.user.login}`,
url: author.user.url,
}
}
// if the commit used an email that's not associated with a github account
// then the user field will be empty, so we fall back to using the committer's
// name and email as specified by git
return {
name: author.name,
url: `mailto:${author.email}`,
}
}),
})
}
if (!Object.values(commits).flat().length) {
const messages = allCommits.map((c) => c.message.trim().split('\n')[0])
throw new Error(`No changelog commits found for "${range}":\n${messages.join('\n')}`)
}
// this doesnt work with majors but we dont do those very often
const semverBump = commits.Features.length ? 'minor' : 'patch'
const version = TAG_PREFIX + semver.parse(args.startTag).inc(semverBump).version
const date = args.endTag && exec(`git log -1 --date=short --format=%ad ${args.endTag}`)
const output = logger(RELEASE.title(version, date) + '\n')
for (const key of Object.keys(commits)) {
if (commits[key].length > 0) {
output.group(`### ${key}\n`)
for (const commit of commits[key]) {
let groupCommit = `* [\`${commit.hash}\`](${commit.url})`
for (const pr of commit.prs) {
groupCommit += ` [#${pr.number}](${pr.url})`
}
groupCommit += ` ${commit.title}`
if (key !== 'Dependencies') {
for (const user of commit.credit) {
if (args.type === 'gh') {
groupCommit += ` (${user.name})`
} else {
groupCommit += ` ([${user.name}](${user.url}))`
}
}
}
output.group(groupCommit)
if (commit.body && commit.body.length) {
output.log(commit.body)
}
output.groupEnd()
}
output.log()
output.groupEnd()
}
}
return {
version,
release: output.toString(),
}
}
const main = async (argv) => {
const args = parseArgs(argv)
if (args.read) {
// this reads the release notes for that version
let { release } = findRelease(args, args.endTag || args.startTag)
if (args.type === 'gh') {
// changelog was written in markdown so convert user links to gh release style
// XXX: this needs to be changed if the `generateRelease` format changes
release = release.replace(/\(\[(@[a-z\d-]+)\]\(https:\/\/github.com\/[a-z\d-]+\)\)/g, '($1)')
}
return console.log(release)
}
// otherwise fetch the requested release from github
const { release, version } = await generateRelease(args)
let msg = 'Edit release notes and run:\n'
msg += `git add CHANGELOG.md && git commit -m 'chore: changelog for ${version}'`
if (args.write) {
const { release: existing, changelog } = findRelease(args, version)
fs.writeFileSync(
args.file,
existing
// replace existing release with the newly generated one
? changelog.replace(existing, release)
// otherwise prepend a new release at the start of the changelog
: changelog.replace(RELEASE.h1, RELEASE.h1 + release + RELEASE.sep),
'utf-8'
)
return console.error([
`Release notes for ${version} written to "./${relative(process.cwd(), args.file)}".`,
msg,
].join('\n'))
}
console.log(release)
console.error('\n' + msg)
}
main(process.argv.slice(2))