Repository navigation
Expand file tree
/
Copy pathbranch-diff.js
More file actions
executable file
·221 lines (191 loc) · 7.68 KB
/
Copy pathbranch-diff.js
File metadata and controls
executable file
·221 lines (191 loc) · 7.68 KB
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
#!/usr/bin/env node
import fs from 'fs'
import { createRequire } from 'module'
import path from 'path'
import process from 'process'
import { pipeline } from 'stream/promises'
import { spawn } from 'child_process'
import { once } from 'events'
import { parseArgs } from 'util'
import commitStream from 'commit-stream'
import split2 from 'split2'
import pkgtoId from 'pkg-to-id'
import { isReleaseCommit } from 'changelog-maker/groups'
import { processCommits } from 'changelog-maker/process-commits'
import { collectCommitLabels } from 'changelog-maker/collect-commit-labels'
const pkgFile = path.join(process.cwd(), 'package.json')
const require = createRequire(import.meta.url)
const pkgData = fs.existsSync(pkgFile) ? require(pkgFile) : {}
const pkgId = pkgtoId(pkgData)
const refcmd = 'git rev-list --max-count=1 {{ref}}'
const commitdatecmd = '$(git show -s --format=%cd `{{refcmd}}`)'
const gitcmd = 'git log {{startCommit}}..{{branch}} --until="{{untilcmd}}"'
const ghId = {
user: pkgId.user || 'nodejs',
repo: pkgId.name || 'node'
}
function replace (s, m) {
Object.keys(m).forEach(function (k) {
s = s.replace(new RegExp('\\{\\{' + k + '\\}\\}', 'g'), m[k])
})
return s
}
async function spawnCollect (cmd, args, opts, consume) {
const cp = spawn(cmd, args, opts)
const [result, [code, signal]] = await Promise.all([consume(cp.stdout), once(cp, 'close')])
if (code !== 0) {
throw new Error(`Command "${[cmd, ...args].join(' ')}" exited with ${signal || code}`)
}
return result
}
export async function branchDiff (branch1, branch2, options) {
if (!branch1 || !branch2) {
throw new Error('Must supply two branch names to compare')
}
const repoPath = options.repoPath || process.cwd()
const commit = await findMergeBase(repoPath, branch1, branch2)
const branchCommits = await Promise.all([branch1, branch2].map(async (branch) => {
return collect(repoPath, branch, commit, branch === branch2 && options.endRef)
}))
return await diffCollected(options, branchCommits)
}
async function findMergeBase (repoPath, branch1, branch2) {
const chunks = await spawnCollect('git', ['merge-base', branch1, branch2], {
cwd: repoPath,
stdio: ['ignore', 'pipe', 'inherit']
}, stdout => stdout.toArray())
return Buffer.concat(chunks).toString('utf-8', 0, 10)
}
function normalizeIfTrailingSlash (commit) {
if (commit.prUrl && commit.prUrl.at(-1) === '/') {
commit.prUrl = commit.prUrl.slice(0, -1)
}
}
async function diffCollected (options, branchCommits) {
function isInList (commit) {
normalizeIfTrailingSlash(commit)
return branchCommits[0].some((c) => {
if (commit.sha === c.sha) { return true }
if (commit.summary === c.summary) {
normalizeIfTrailingSlash(c)
if (commit.prUrl && c.prUrl) {
return commit.prUrl === c.prUrl
} else if (commit.author.name === c.author.name &&
commit.author.email === c.author.email) {
if (process.stderr.isTTY) {
console.error(`Note: Commit fell back to author checking: "${commit.summary}" -`, commit.author)
}
return true
}
}
return false
})
}
let list = branchCommits[1].filter((commit) => !isInList(commit))
await collectCommitLabels(list)
if (options.excludeLabels.length > 0) {
list = list.filter((commit) => {
return !commit.labels || !commit.labels.some((label) => {
return options.excludeLabels.indexOf(label) >= 0
})
})
}
if (options.requireLabels.length > 0) {
list = list.filter((commit) => {
return commit.labels && commit.labels.some((label) => {
return options.requireLabels.indexOf(label) >= 0
})
})
}
return list
}
async function collect (repoPath, branch, startCommit, endRef) {
const endrefcmd = endRef && replace(refcmd, { ref: endRef })
const untilcmd = endRef ? replace(commitdatecmd, { refcmd: endrefcmd }) : ''
const _gitcmd = replace(gitcmd, { branch, startCommit, untilcmd })
const commitList = []
await spawnCollect(_gitcmd, [], {
shell: true,
cwd: repoPath,
stdio: ['ignore', 'pipe', 'inherit']
}, (stdout) => pipeline(
stdout,
split2(),
commitStream(ghId.user, ghId.repo),
async function * (source) {
for await (const commit of source) {
commitList.push(commit)
}
}
))
return commitList
}
// parseArgs ignores `arg` and `help`; they exist only to build the usage text.
const cliOptions = {
'commit-url': { type: 'string', arg: '<url>', help: 'commit URL template, with {ref}, {ghUser}, {ghRepo}' },
'end-ref': { type: 'string', arg: '<ref>', help: 'only list <comparison-branch> commits up to the\ncommit date of <ref>' },
'exclude-label': { type: 'string', multiple: true, arg: '<l,..>', help: 'drop commits from PRs with any of these labels' },
'filter-release': { type: 'boolean', help: 'drop Node-style release commits' },
'find-matching-prs': { type: 'boolean', help: 'look up PRs for commits without PR-URL metadata' },
format: { type: 'string', arg: '<format>', help: 'simple (default), sequence, sha, plaintext, markdown\nor messageonly' },
group: { type: 'boolean', short: 'g', help: 'group commits by subsystem prefix' },
help: { type: 'boolean', short: 'h', help: 'print this help' },
'patch-only': { type: 'boolean', help: 'alias for --exclude-label=semver-major,semver-minor' },
quiet: { type: 'boolean', short: 'q', help: 'do not print to stdout' },
repo: { type: 'string', arg: '<repo>', help: 'GitHub repository, default derived from package.json' },
'require-label': { type: 'string', multiple: true, arg: '<l,..>', help: 'keep only commits from PRs with one of these labels' },
reverse: { type: 'boolean', help: 'reverse the output order' },
'sequence-drop': { type: 'string', arg: '<l,..>', help: 'with --format=sequence, mark commits from PRs with\nthese labels as drop instead of pick' },
user: { type: 'string', arg: '<user>', help: 'GitHub user/org, default derived from package.json' },
version: { type: 'boolean', short: 'v', help: 'print the version' }
}
function usage () {
const flags = Object.entries(cliOptions).map(([name, { short, arg }]) =>
`${short ? `-${short}, ` : ''}--${name}${arg ? `=${arg}` : ''}`)
const width = Math.max(...flags.map((f) => f.length)) + 1
const lines = Object.values(cliOptions).map(({ help }, i) =>
` ${flags[i].padEnd(width)}${help.replaceAll('\n', `\n ${' '.repeat(width)}`)}`)
return `Usage: branch-diff [options] <base-branch> <comparison-branch>
List commits on <comparison-branch> that are not on <base-branch>, matching
loosely by summary and PR-URL (or author) so backported commits are excluded.
Options:
${lines.join('\n')}
`
}
async function main () {
const { values: argv, positionals } = parseArgs({ allowPositionals: true, options: cliOptions })
const [branch1, branch2] = positionals
const splitLabels = (labels = []) => labels.flatMap((l) => l.split(','))
if (argv.help) {
return process.stdout.write(usage())
}
if (argv.version) {
return console.log(`v ${require('./package.json').version}`)
}
const excludeLabels = splitLabels(argv['exclude-label'])
if (argv['patch-only']) {
excludeLabels.unshift('semver-minor', 'semver-major')
}
const requireLabels = splitLabels(argv['require-label'])
if (argv.user) {
ghId.user = argv.user
}
if (argv.repo) {
ghId.repo = argv.repo
}
const options = {
group: argv.group,
excludeLabels,
requireLabels,
endRef: argv['end-ref']
}
let list = await branchDiff(branch1, branch2, options)
if (argv['filter-release']) {
list = list.filter((commit) => !isReleaseCommit(commit.summary))
}
await processCommits(argv, ghId, list)
}
main().catch((err) => {
console.error(err)
process.exit(1)
})