forked from vweevers/dotnet-bump
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
306 lines (235 loc) · 8.24 KB
/
index.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
'use strict'
const semver = require('semver')
const findRoots = require('common-roots')
const parseGitStatus = require('parse-git-status')
const after = require('after')
const series = require('run-series')
const cp = require('child_process')
const path = require('path')
const Emitter = require('events').EventEmitter
const Finder = require('./lib/finder')
const TARGETS = new Set(['major', 'minor', 'patch', 'premajor', 'preminor', 'prepatch', 'prerelease'])
const kLog = Symbol('kLog')
module.exports = class Updater extends Emitter {
constructor (opts = {}) {
super()
// True by default
this.glob = opts.glob == null ? true : !!opts.glob
this.enableCommit = opts.commit == null ? true : !!opts.commit
// False by default
this.dryRun = !!opts.dryRun
this.force = !!opts.force
this.verbose = !!opts.verbose
this.finder = new Finder()
this.finder.on('warning', (...e) => this.emit('warning', ...e))
}
update (target, files, done) {
if (typeof files === 'function') {
done = files
files = '.'
}
if (!TARGETS.has(target) && !semver.valid(target)) {
const targets = Array.from(TARGETS).join(' | ')
const msg = `Target must be ${targets} | x.x.x`
return process.nextTick(done, new Error(msg))
}
this.finder.find(files, { glob: this.glob }, (err, files) => {
if (err) return done(err)
if (!files.length) return process.nextTick(done, null, files)
// I don't like this API very much, need to simplify / refocus.
findRoots(files.map(f => f.path), '.git', { map: true }, (err, roots, mapping) => {
if (err) return done(err)
const rootFiles = new Map()
for (const file of files) {
file.root = mapping[file.path]
if (rootFiles.has(file.root)) rootFiles.get(file.root).push(file)
else rootFiles.set(file.root, [file])
}
dirtyWorkingTrees(this, rootFiles.keys(), (err, dirtyTrees) => {
if (err) return done(err)
if (dirtyTrees.size && !this.force) {
const hint = 'continue with --force'
if (dirtyTrees.size > 1) {
const desc = 'Working trees are dirty'
const paths = Array.from(dirtyTrees.keys()).join('\n- ')
return done(new Error(`${desc} (${hint}):\n\n- ${paths}`))
} else {
const desc = 'Working tree is dirty'
const paths = Array.from(dirtyTrees.values())[0].join('\n ')
return done(new Error(`${desc} (${hint}):\n\n ${paths}`))
}
}
series([
(next) => readFiles(files, next),
(next) => updateFiles(files, target, next),
(next) => this.verify(files, next),
(next) => this.save(files, next),
(next) => this.stage(files, next),
(next) => this.commit(files, roots, next)
], (err) => err ? done(err) : done(null, files))
})
})
})
}
verify (files, done) {
const counts = {}
for (const { version } of files) {
counts[version] = (counts[version] || 0) + 1
}
if (Object.keys(counts).length > 1) {
const lines = []
const skip = new Set()
for (const { version, path } of files) {
if (skip.has(version)) {
continue
} else if (counts[version] > 3) {
skip.add(version)
lines.push(`- ${shortPath(path)} (and ${counts[version] - 1} more): ${version}`)
} else {
lines.push(`- ${shortPath(path)}: ${version}`)
}
}
return done(new Error(`Version mismatch between files:\n\n${lines.join('\n')}`))
}
done()
}
save (files, done) {
if (this.dryRun) return process.nextTick(done)
const next = after(files.length, done)
for (const file of files) {
file.write(next)
}
}
[kLog] (msg, ...rest) {
if (this.dryRun) {
console.log(`- Would ${lcfirst(msg)}`, ...rest)
} else {
console.log(`- ${msg}`, ...rest)
}
}
stage (files, done) {
const commands = new Map()
for (const file of files) {
if (commands.has(file.root)) commands.get(file.root).push(file.relative)
else commands.set(file.root, ['add', file.relative])
this[kLog]('Stage %s', file.relative)
}
if (this.dryRun) return process.nextTick(done)
const next = after(commands.size, done)
for (const [cwd, args] of commands) {
cp.execFile('git', args, { cwd }, next)
}
}
commit (files, roots, done) {
if (!this.enableCommit) return process.nextTick(done)
const version = files[0].version
const tag = 'v' + version
const next = after(roots.length, done)
for (const root of roots) {
if (!this.dryRun && this.verbose) {
const args = ['diff', '--staged', '--color']
const opts = { cwd: root, encoding: 'utf8' }
const staged = cp.execFileSync('git', args, opts)
console.error('\n' + staged.trim() + '\n')
}
if (roots.length > 1) {
this[kLog]('Commit and tag %s (%s)', tag, shortPath(root))
} else {
this[kLog]('Commit and tag %s', tag)
}
if (this.dryRun) {
next()
continue
}
cp.execFile('git', ['commit', '-m', version], { cwd: root }, (err) => {
if (err) return next(err)
cp.execFile('git', ['tag', '-a', tag, '-m', tag], { cwd: root }, next)
})
}
}
}
function dirtyWorkingTrees (updater, roots, done) {
const dirtyTrees = new Map()
const arr = Array.from(roots)
const next = after(arr.length, (err) => done(err, dirtyTrees))
function isDirty (cwd, callback) {
const args = ['status', '--porcelain', '--untracked-files=all', '--ignored=no', '-z']
const opts = { cwd, encoding: 'utf8' }
cp.execFile('git', args, opts, function (err, stdout) {
if (err) return callback(err)
const statusObjects = parseGitStatus(stdout)
const dirtyLines = []
for (const { x, y, from, to } of statusObjects) {
if (autoStage(to)) {
updater[kLog]('Stage %s', to)
if (!updater.dryRun) {
cp.execFileSync('git', ['add', to], { cwd })
}
} else {
dirtyLines.push(x + y + ' ' + (from ? `${from} -> ${to}` : to))
}
}
callback(null, dirtyLines)
})
}
for (const root of arr) {
isDirty(root, (err, dirtyLines) => {
if (err) return next(err)
if (dirtyLines.length) {
// Can't continue without --force
dirtyTrees.set(root, dirtyLines)
}
next()
})
}
}
function autoStage (file) {
// Allow changelog, upgrade guide and readme to be committed together with version
if (/^(CHANGELOG|CHANGES|HISTORY|UPGRADING|README)\.(md|markdown)$/i.test(file)) return true
// Same for resource files and version.h used in C++ projects
if (file.endsWith('.rc') || path.basename(file) === 'version.h') return true
return false
}
function readFiles (files, done) {
const next = after(files.length, done)
for (const file of files) {
file.read(next)
}
}
function updateFiles (files, target, done) {
for (let i = 0; i < files.length; i++) {
const file = files[i]
const currentRaw = file.version
if (!currentRaw) {
files.splice(i--, 1)
continue
}
if (typeof currentRaw !== 'string') {
return done(new Error(`Version is not a string in ${shortPath(file.path)}`))
}
const hasRevision = /^\d+\.\d+\.\d+\.\d+$/.test(currentRaw)
const current = hasRevision ? currentRaw.split('.', 3).join('.') : currentRaw
if (hasRevision) {
// TODO: warn: 'Stripping revision number (".0") from non-semver version'
// or require force.
}
if (!semver.valid(current)) {
return done(new Error(`Current version ${currentRaw} is not semver-valid in ${shortPath(file.path)}`))
}
const next = TARGETS.has(target) ? semver.inc(current, target) : target
if (current === next) {
return done(new Error(`Target is equal to current version ${currentRaw} in ${shortPath(file.path)}`))
}
file.version = next
}
if (!files.length) {
return done(new Error('None of the files contain a version'))
}
done()
}
function shortPath (file) {
return path.relative('.', file) || '.'
}
function lcfirst (str) {
return str[0].toLowerCase() + str.slice(1)
}