-
Notifications
You must be signed in to change notification settings - Fork 17
/
bumper.js
701 lines (613 loc) · 21.4 KB
/
bumper.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
'use strict'
require('./typedefs')
const __ = require('lodash')
const cpExec = require('child_process').exec
const prependFile = require('prepend-file')
const Promise = require('promise')
const versiony = require('versiony')
const path = require('path')
const fs = require('fs')
const pkgJson = require('../package.json')
// Compliance implementation
let dependencies = require('./compliance/dependencies')
// using let so stuff can be rewired in the test
let exec = Promise.denodeify(cpExec)
let prepend = Promise.denodeify(prependFile)
let readFile = Promise.denodeify(fs.readFile)
let writeFile = Promise.denodeify(fs.writeFile)
const logger = require('./logger')
const utils = require('./utils')
/**
* Adds the given filename to info.modifiedFiles if it doesn't already exist
* @param {PrInfo} info - the info for the PR
* @param {String[]} info.modifiedFiles - the list of modified files so far
* @param {String} filename - the filename to add to info.modifiedFiles if it's not already there
*/
function addModifiedFile (info, filename) {
if (info.modifiedFiles.indexOf(filename) === -1) {
info.modifiedFiles.push(filename)
}
}
/**
* Adds the a list of files to info.modifiedFiles if it doesn't already exist
* @param {PrInfo} info - the info for the PR
* @param {String[]} info.modifiedFiles - the list of modified files so far
* @param {String} filenames - the filenames to add to info.modifiedFiles if it's not already there
*/
function addModifiedFiles (info, filenames) {
filenames.forEach(filename => {
addModifiedFile(info, filename)
})
}
/**
* Perform the patch bump, either using .patch() or .preRelease() (the latter if there's a pre-release tag)
* @param {*} v - the versiony instance
*/
function performPatch (v) {
if (v.model.hasPreRelease()) {
v.preRelease()
} else {
v.patch()
}
}
class Cancel {
constructor (message) {
this.message = message
}
}
/**
* Interacts with a Vcs to achieive a version bump
* @class
*/
class Bumper {
// = Public Methods ===================================================================
/**
* @param {Object} params - params obj
* @param {Config} params.config - the bumper config object
* @param {Vcs} params.vcs - the vcs instance to use
* @param {Ci} params.ci - the ci instance to use
*/
constructor (params) {
this.config = params.config
this.vcs = params.vcs
this.ci = params.ci
}
/**
* Bump the version based on the last merged PR's version-bump comment
* @param {Object} options the cli options
* @returns {Promise} a promise resolved with the results of the push
*/
bump () {
if (__.get(this.config, 'computed.ci.isPr')) {
logger.log('Not a merge build, skipping bump')
return Promise.resolve()
}
return this.ci.getLastCommitMsg()
.then((commitMessage) => {
if (commitMessage.startsWith(`[${pkgJson.name}]`)) {
throw new Cancel(`Skipping bump on ${pkgJson.name} commit.`)
}
return Promise.resolve()
})
.then(() => {
return this._getMergedPrInfo()
})
.then((info) => {
return this._maybeBumpVersion(info, 'package.json')
})
.then((info) => {
if (fs.existsSync('package-lock.json')) {
return this._maybeBumpVersion(info, 'package-lock.json')
}
return info
})
.then((info) => {
return this._maybePrependChangelog(info)
})
.then((info) => {
return this._maybeGenerateDependencySnapshot(info)
})
.then((info) => {
return this._maybeGenerateDependencyComplianceReport(info)
})
.then((info) => {
return this._maybeUpdateBaselineCoverage(info)
})
.then((info) => {
return this._maybeCommitChanges(info)
})
.then((info) => {
return this._maybeCreateTag(info)
})
.then((info) => {
return this._maybePushChanges(info)
})
.then((info) => {
return this._maybeLogChanges(info)
})
}
getMergedPrScope () {
return this._getMergedPrInfo().then(info => {
return Promise.resolve(info.scope)
})
}
/**
* Check a PR for a version-bump comment
* @returns {Promise} a promise resolved when complete or rejected on error
*/
check () {
if (!this.config.computed.ci.isPr) {
logger.log('Not a PR build, skipping check')
return Promise.resolve()
}
return this._getOpenPrInfo()
.then((info) => {
logger.log(`Found a ${info.scope} bump for the current PR`)
return info.scope
})
}
/**
* Check a build to see if coverage decreased
* @returns {Promise} a promise resolved when complete or rejected on error
*/
checkCoverage () {
const link = 'https://github.com/ciena-blueplanet/pr-bumper#featurescoverage'
if (!this.config.isEnabled('coverage')) {
const msg = `Code coverage feature not enabled!\nSee ${link} for configuration info.`
return utils.maybePostComment(this.config, this.vcs, msg, true)
.then(() => {
return Promise.reject(msg)
})
}
const base = this.config.computed.baselineCoverage
if (!__.isNumber(base)) {
const msg = `Baseline coverage is not a number!\nSee ${link} for configuration info.`
return utils.maybePostComment(this.config, this.vcs, msg, true)
.then(() => {
return Promise.reject(msg)
})
}
const pct = utils.getCurrentCoverage(this.config)
if (pct < 0) {
const msg = `No current coverage info found!\nSee ${link} for configuration info.`
return utils.maybePostComment(this.config, this.vcs, msg, true)
.then(() => {
return Promise.reject(msg)
})
}
if (base > pct) {
const diffStr = (base - pct).toFixed(2)
const baseStr = base.toFixed(2)
const pctStr = pct.toFixed(2)
const msg = `Code Coverage: \`${pctStr}%\` (dropped \`${diffStr}%\` from \`${baseStr}%\`)`
return utils.maybePostComment(this.config, this.vcs, msg)
.then(() => {
return Promise.reject(msg)
})
}
const msg = this._getCoverageMsg(base, pct)
logger.log(msg, true)
return utils.maybePostComment(this.config, this.vcs, msg)
}
/**
* Prepend the changelogs of all the packages.
* @param {String} packagesJson - the package info in json format. Could be empty.
* @returns {Promise} a promise resolved with the results of the push
*/
prependChangelog (packagesJson) {
if (__.get(this.config, 'computed.ci.isPr')) {
logger.log('Not a merge build, skipping bump')
return Promise.resolve()
}
const packagesInfo = this._parsePackagesInfo(packagesJson)
return this._getMergedPrInfo().then(info => {
return this._maybePrependChangelogForPackages(info, packagesInfo)
}).then(info => {
return this._maybeCommitChanges(info, true)
}).then(info => {
return this._maybePushChanges(info)
}).then(info => {
return this._maybeLogChanges(info)
})
}
/**
* Get the last merge commit hash.
* @returns {Promise} last merge commit hash.
*/
getLastMergeCommitHash () {
// Get the commit hash
return this._getLastMergeCommit().then(mergeCommit => {
return Promise.resolve(mergeCommit.match(/(\w*) (Merge ){0,1}pull request #/i)[1])
})
}
// = Private Methods ==================================================================
/**
* Compute the log message to tell users whether coverage went up or stayed the same
* @param {Number} base - the base coverage percentage
* @param {Number} pct - the current coverage percentage
* @returns {String} the message to log to the user explaining what happened with coverage
*/
_getCoverageMsg (base, pct) {
const pctStr = pct.toFixed(2)
const baseStr = base.toFixed(2)
if (pct > base) {
const diffStr = (pct - base).toFixed(2)
return `Code Coverage: \`${pctStr}%\` (increased \`${diffStr}%\` from \`${baseStr}%\`)`
} else {
return `Code Coverage: \`${baseStr}%\` (no change)`
}
}
/**
* Grab the most recent PR
* @returns {PrPromise} a promise resolved with the most recent PR
*/
_getLastPr () {
return this._getLastMergeCommit().then((mergeCommit) => {
// Get the number from the PR commit
const prNumber = mergeCommit.match(/pull request #(\d*)/i)[1]
logger.log(`Fetching PR [${prNumber}]`)
return this.vcs.getPr(prNumber)
})
}
/**
* Get the last merge commit.
* @returns {Promise} the last merge commit.
*/
_getLastMergeCommit () {
return exec('git log -10 --oneline').then(stdout => {
// the --oneline format for `git log` puts each commit on a single line, with the hash and then
// the commit message, so we first split on \n to get an array of commits
const commits = stdout.split('\n')
// The commit that represents the merging of the PR will include the text 'pull request #' so
// we find that one
const mergeCommit = __.find(commits, (commit) => {
return commit.match(/pull request #/i) !== null
})
return Promise.resolve(mergeCommit)
})
}
/**
* Get the PR scope for the current (merged) pull request
* @returns {Promise} a promise - resolved with PR info (changelog and scope) or rejected on error
*/
_getMergedPrInfo () {
return this._getLastPr()
.then((pr) => {
let maxScope = 'major'
if (this.config.isEnabled('maxScope')) {
maxScope = this.config.features.maxScope.value
}
const scope = utils.getScopeForPr(pr, maxScope)
const getChangelog = this.config.isEnabled('changelog') && scope !== 'none'
return {
changelog: getChangelog ? utils.getChangelogForPr(pr) : '',
modifiedFiles: [],
number: pr.number,
scope,
url: pr.url
}
})
}
/**
* Get the pr scope for the current (open) pull request
* @returns {Promise} a promise - resolved with PR info (changelog and scope) or rejected on error
*/
_getOpenPrInfo () {
const vcs = this.vcs
return vcs.getPr(this.config.computed.ci.prNumber)
.then((pr) => {
let scope
return utils.maybePostCommentOnError(this.config, this.vcs, () => {
let maxScope = 'major'
if (this.config.isEnabled('maxScope')) {
maxScope = this.config.features.maxScope.value
}
scope = utils.getScopeForPr(pr, maxScope)
return {pr, scope}
})
})
.then((data) => {
const pr = data.pr
const scope = data.scope
const getChangelog = this.config.isEnabled('changelog') && scope !== 'none'
let changelog = ''
if (getChangelog) {
return utils.maybePostCommentOnError(this.config, this.vcs, () => {
changelog = utils.getChangelogForPr(pr)
return {changelog, number: pr.number, scope, url: pr.url}
})
}
return Promise.resolve({changelog, number: pr.number, scope, url: pr.url})
})
}
/**
* Maybe bump the version in package.json with the given scope (if it's not "none")
* @param {PrInfo} info - the pr info
* @param {String} pkgJsonFile - the full file path to the package.json to bump
* @returns {PrInfo} the pr info object passed in
*/
_maybeBumpVersion (info, pkgJsonFile) {
if (info.scope === 'none') {
return info
}
const v = versiony.from(pkgJsonFile)
switch (info.scope) {
case 'patch':
performPatch(v)
break
case 'minor':
v.newMinor()
break
case 'major':
v.newMajor()
break
default:
throw new Error(`Invalid scope [${info.scope}]`)
}
const versionInfo = v.to(pkgJsonFile).end({quiet: true})
info.version = versionInfo.version
addModifiedFile(info, pkgJsonFile)
return info
}
/**
* Commit the changed files that were modified by pr-bumper
* @param {PrInfo} info - the info for the PR being bumped
* @param {Boolean} isOnlyChangelogModified - true if we are only committing the changelog
* @returns {Promise} - a promise resolved with the results of the git commands
*/
_maybeCommitChanges (info, isOnlyChangelogModified = false) {
if (info.modifiedFiles.length === 0) {
logger.log('Skipping commit because no files were changed.')
return Promise.resolve(info)
}
const buildNumber = this.config.computed.ci.buildNumber
return this.ci.setupGitEnv()
.then(() => {
return this.ci.add(info.modifiedFiles)
})
.then(() => {
// Currently there are only two reasons we'll have a commit 1) we have a "none" bump with coverage
// change, or 2) we have a legit bump commit
let msg = `Automated version bump to ${info.version}`
if (isOnlyChangelogModified) {
msg = 'Automated changelog prepend'
} else if (info.scope === 'none') {
msg = 'Automated code coverage update'
}
return this.ci.commit(`[${pkgJson.name}] ${msg}`, `From CI build ${buildNumber}`)
.then(() => {
return info
})
})
}
/**
* Maybe create a tag based on the current version
* @param {PrInfo} info - the info for the PR being bumped
* @returns {Promise} - a promise resolved with the results of the git commands
*/
_maybeCreateTag (info) {
if (info.scope === 'none') {
logger.log('Skipping tag creation because of "none" scope.')
return Promise.resolve(info)
}
const buildNumber = this.config.computed.ci.buildNumber
return this.ci.tag(`v${info.version}`, `Generated tag from CI build ${buildNumber}`)
.then(() => {
return info
})
}
/**
* process a dependency report
* @param {PrInfo} info - the info for the PR being bumped
* @returns {Promise} a Promise
*/
_maybeGenerateDependencyComplianceReport (info) {
if (!this.config.isEnabled('compliance')) {
logger.log('Skipping generating dependency compliance report because of config option.')
return Promise.resolve(info)
}
if (info.scope === 'none') {
logger.log('Skipping generating dependency compliance report because of "none" scope.')
return Promise.resolve(info)
}
const outputPath = __.get(this.config, 'features.compliance.output.directory')
const cwd = process.cwd()
return dependencies.run(cwd, path.join(cwd, outputPath), this.config)
.then(() => {
addModifiedFile(info, outputPath)
return info
})
}
/**
* Maybe generate a dependency snapshot file by using `npm shrinkwrap`
* TODO: do we want to handle projects that include npm-shrinkwrap.json?
* @param {PrInfo} info - the info for the PR being bumped
* @returns {Promise} a promise resolved when operation completes
*/
_maybeGenerateDependencySnapshot (info) {
// We need to do the prune b/c of the following issue with npm-shrinkwrap
// https://github.com/SaltwaterC/aws2js/issues/58, apparently one of our deps
// installs things w/o having them in package.json, causing npm shrinkwrap to barf
if (!this.config.isEnabled('dependencies')) {
logger.log('Skipping generating dependency snapshot because of config option.')
return Promise.resolve(info)
}
if (info.scope === 'none') {
logger.log('Skipping generating dependency snapshot because of "none" scope.')
return Promise.resolve(info)
}
const snapshotFile = __.get(this.config, 'features.dependencies.snapshotFile')
return exec('npm prune')
.then(() => {
return exec('npm shrinkwrap --dev')
})
.then(() => {
return exec(`mv npm-shrinkwrap.json ${snapshotFile}`)
})
.then(() => {
addModifiedFile(info, snapshotFile)
return info
})
}
/**
* Maybe log changes to a file
* @param {PrInfo} info - the info for the PR being bumped
* @returns {Promise} - a promise resolved with the results of the git commands
*/
_maybeLogChanges (info) {
if (!this.config.isEnabled('logging')) {
logger.log('Skipping logging because of config option.')
return Promise.resolve(info)
}
const logInfo = __.cloneDeep(info)
delete logInfo.modifiedFiles
const filename = this.config.features.logging.file
return writeFile(filename, JSON.stringify(logInfo, null, 2))
.then(() => {
return info
})
}
/**
* Maybe prepend the changelog text from the PrInfo into the CHANGELOG.md file (unless there was no bump)
* @param {PrInfo} info - the pr info
* @returns {Promise} - a promise resolved when changelog has been prepended
*/
_maybePrependChangelog (info) {
if (!this.config.isEnabled('changelog')) {
logger.log('Skipping prepending changelog because of config option.')
return Promise.resolve(info)
}
if (info.scope === 'none') {
logger.log('Skipping prepending changelog because of "none" scope.')
return Promise.resolve(info)
}
const dateString = this._getChangelogTextDate()
const data = this._getChangelogText(info.version, dateString, info.changelog)
const filename = this.config.features.changelog.file
return prepend(filename, data)
.then(() => {
addModifiedFile(info, filename)
return info
})
}
/**
* Maybe push changes back to repo
* @param {PrInfo} info - the info for the PR being bumped
* @returns {Promise} - a promise resolved with the results of the git commands
*/
_maybePushChanges (info) {
if (info.modifiedFiles.length === 0) {
logger.log('Skipping push because nothing changed.')
return Promise.resolve(info)
}
return this.ci.push(this.vcs)
.then(() => {
return info
})
}
/**
* Maybe update the code coverage in package.json
* @param {PrInfo} info - the info for the PR being bumped
* @returns {Promise} a Promise
**/
_maybeUpdateBaselineCoverage (info) {
if (!this.config.isEnabled('coverage')) {
logger.log('Skipping updating baseline code coverage because of config option.')
return Promise.resolve(info)
}
const link = 'https://github.com/ciena-blueplanet/pr-bumper#featurescoverage'
const pct = utils.getCurrentCoverage(this.config)
if (pct < 0) {
const msg = `No current coverage info found!\nSee ${link} for configuration info.`
return Promise.reject(msg)
}
const pkgJsonPath = path.join(process.cwd(), 'package.json')
return readFile(pkgJsonPath, 'utf8')
.then((contents) => {
const pkgJsonContents = JSON.parse(contents)
// We want to write out the coverage info, even if it didn't exist yet (@job13er 2017-06-19)
__.set(pkgJsonContents, 'pr-bumper.coverage', pct)
return JSON.stringify(pkgJsonContents, null, 2)
})
.then((data) => {
return writeFile(pkgJsonPath, data)
})
.then(() => {
addModifiedFile(info, 'package.json')
return info
})
}
_parsePackagesInfo (packagesInfo = '[]') {
return JSON.parse(packagesInfo)
}
/**
* Maybe prepend the changelog text from the PrInfo into the CHANGELOG.md file for every packages
* (unless there was no bump).
* @param {PrInfo} info - the pr info
* @param {Object} packagesInfo - the package information (name, version, private, location)
* @returns {Promise} - a promise resolved when changelog has been prepended
*/
_maybePrependChangelogForPackages (info, packagesInfo = []) {
if (!this.config.isEnabled('changelog')) {
logger.log('Skipping prepending changelog because of config option.')
return Promise.resolve(info)
}
if (info.scope === 'none') {
logger.log('Skipping prepending changelog because of "none" scope.')
return Promise.resolve(info)
}
const dateString = this._getChangelogTextDate()
const {paths, promises} = packagesInfo.reduce(({promises, paths}, packageInfo) => {
const version = this._getNextVersion(packageInfo.version, info.scope)
const data = this._getChangelogText(version, dateString, info.changelog)
// We are assuming that all the packages CHANGELOG are under `packages/<package name>/<changelog file>`
const dir = packageInfo.location.replace(/[a-zA-Z/@].*packages\//gi, 'packages/')
const filename = this.config.features.changelog.file
const path = `${dir}/${filename}`
promises.push(prepend(path, data))
paths.push(path)
return {paths, promises}
}, {promises: [], paths: []})
return Promise.all(promises).then(() => {
addModifiedFiles(info, paths)
return info
})
}
_getNextVersion (currentVersion, scope) {
const v = versiony.version(currentVersion)
switch (scope) {
case 'patch':
performPatch(v)
break
case 'minor':
v.newMinor()
break
case 'major':
v.newMajor()
break
default:
throw new Error(`Invalid scope [${scope}]`)
}
return v.get()
}
/**
* Returns formatted date.
* @param {Date} now current date
* @returns {String} formatted date.
*/
_getChangelogTextDate (now = new Date()) {
return now.toISOString().split('T').slice(0, 1).join('')
}
/**
* Returns changelog text.
* @param {String} version - the package version
* @param {String} date - the date
* @param {String} changelog - the changelog content
* @returns {String} formatted
*/
_getChangelogText (version, date, changelog) {
return `# ${version} (${date})\n${changelog}\n\n`
}
}
Bumper.Cancel = Cancel
module.exports = Bumper