This repository has been archived by the owner on Oct 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.js
536 lines (505 loc) · 14 KB
/
node.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
#!/usr/bin/env node
'use strict'
const meow = require('meow')
const fs = require('fs')
const fsPromises = fs.promises
const { dim, red, cyan, underline, green } = require('kleur')
const path = require('path')
const { inc } = require('semver')
const { promisify } = require('util')
const recommendedBump = promisify(require(`conventional-recommended-bump`))
const { Listr } = require('listr2')
const { textSync: figlet } = require('figlet')
const indentString = require('indent-string')
const execa = require('execa')
const { ProjectsBundle } = require('@gitbeaker/node')
require('dotenv').config()
const {
version: currentVersion,
projectRoot,
generateChangelog,
getLatestChangelog,
} = require('./utils')
/**
* This is a tool to simplify some git tasks. See it as an extension like git-flow.
*
* @description
* Use `melody --help` to get a detailed help and usage information.
*
* @package {@link https://github.com/muuvmuuv/melody}
*/
const cli = meow(
`
${underline('Usage')}
${dim('$')} melody <task> [...options]
${underline('Tasks')}
- release
${underline('Options')}
--finish, -f Finish a task
--publish, -p Publish a task
--project, -i GitLab repository project id
--allow-dirty Force run task
--dry-run Just tell what will happen
--delete Deletes a branch or tag (default: true)
${underline('Examples')}
${dim('$')} melody release --publish
`,
{
description: cyan(
indentString(
figlet('Melody', {
font: 'Bigfig',
}),
2
).trim()
),
version: currentVersion,
inferType: true,
flags: {
verbose: {
type: 'boolean',
},
dryRun: {
type: 'boolean',
},
allowDirty: {
type: 'boolean',
},
finish: {
type: 'boolean',
alias: 'f',
},
publish: {
type: 'boolean',
alias: 'p',
},
delete: {
type: 'boolean',
default: true,
},
project: {
type: 'string',
},
},
}
)
const allowedTasks = ['release']
const {
input: { 0: task },
flags: { dryRun, verbose, allowDirty, delete: deletes, project, ...flags },
} = cli
const renderer = verbose ? 'verbose' : 'default'
if (!task) {
cli.showHelp(0)
}
if (!allowedTasks.includes(task)) {
console.log(`
${red(`Task '${task}' is not a valid task`)}
Possible values are: ${allowedTasks.join(', ')}
`)
cli.showHelp(1)
}
/**
* Global handle for all task2 task errors.
*
* @param {*} errors - an unknown error array
*/
function handleTaskError(errors) {
console.log()
console.log(errors)
process.exit(1)
}
/**
* Retrive GitLab services to do GitLab tasks.
*/
function getGitLabServices() {
if (!process.env.GITLAB_ACCESS_TOKEN) {
throw new Error('Could not get GitLab Access Token')
}
return new ProjectsBundle({
host: process.env.GITLAB_HOST,
token: process.env.GITLAB_ACCESS_TOKEN,
})
}
const cleanWorkingTreeTask = {
title: 'Checking working tree',
skip: () => allowDirty,
task: async () => {
const { stdout } = await execa('git', ['status', '--short'])
if (stdout) {
throw new Error('Working tree is not clean')
}
return Promise.resolve()
},
}
const taskOptions = {
renderer: renderer,
}
//
// ---------------------------------------------------------------------------------------
// Tasks
//
/**
* Create a release.
*
* @see {@link https://github.com/muuvmuuv/melody/blob/master/IDEA.md#release}
*/
class Release {
constructor() {
this.services = getGitLabServices()
this.SEMVER_INCREMENTS = [
'patch',
'minor',
'major',
'prepatch',
'preminor',
'premajor',
'prerelease',
]
}
run(step) {
switch (step) {
case 'publish':
console.log('PUBLISH')
break
case 'finish':
console.log(cyan(' Finishing current release...\n'))
return this.finish()
default:
console.log(cyan(' Starting a new release...\n'))
return this.start()
}
}
start() {
return this.__getStartTasks()
.run()
.catch(handleTaskError)
.then(({ version }) => {
this.version = version
process.env.VERSION = version
console.log(`
You are now working on a new release (release/${version}).
To publish or finish the release, use this command:
${dim('$')} melody release --publish|--finish
`)
})
}
__getStartTasks() {
return new Listr(
[
cleanWorkingTreeTask,
{
title: 'Already in release branch',
task: async () => {
try {
const { stdout } = await execa('git', ['branch', '--show-current'])
const currentBranchName = stdout.trim()
if (currentBranchName.includes('release')) {
throw new Error(
'Already checked out in release branch: ' + currentBranchName
)
}
} catch (error) {
throw new Error(error)
}
},
},
{
title: 'Prompt new version',
task: async (ctx, task) => {
const { releaseType } = await recommendedBump({
preset: 'angular',
})
ctx.version = await task.prompt([
{
type: 'select',
name: 'version',
message: 'New version',
initial: this.SEMVER_INCREMENTS.findIndex((inc) => inc === releaseType),
choices: this.SEMVER_INCREMENTS.map((increment) => ({
name: inc(currentVersion, increment),
message: inc(currentVersion, increment),
hint:
releaseType === increment ? `${increment} (recommended)` : increment,
})),
},
])
},
},
{
title: 'Fetching remote branches',
task: () => {
return execa('git', ['fetch'])
},
},
{
title: 'Getting remote branches',
task: async (ctx) => {
try {
const { stdout } = await execa('git', [
'branch',
'--no-color',
'--format',
'%(refname)',
])
const branches = stdout.split('\n')
ctx.branches = branches
} catch (error) {
throw new Error(error)
}
},
},
{
title: 'Validating existing releases',
task: (ctx) => {
const releaseBranchName = `release/${ctx.version}`
const existingBranch = ctx.branches.find((branch) =>
branch.includes(releaseBranchName)
)
if (existingBranch) {
throw new Error('Release branch already exists: ' + existingBranch)
}
},
},
{
title: 'Creating new release branch',
task: (ctx) => {
return dryRun
? Promise.resolve()
: execa('git', ['checkout', '-b', `release/${ctx.version}`])
},
},
{
title: 'Bumping package version',
task: async (ctx) => {
const pkgJsonPath = path.join(projectRoot, 'package.json')
const contents = await fsPromises.readFile(pkgJsonPath)
const json = JSON.parse(contents)
json.version = ctx.version
return dryRun
? Promise.resolve()
: fsPromises.writeFile(pkgJsonPath, JSON.stringify(json, null, 2))
},
},
{
title: 'Bumping package lock version',
task: async (ctx) => {
const pkgJsonPath = path.join(projectRoot, 'package-lock.json')
const contents = await fsPromises.readFile(pkgJsonPath)
const json = JSON.parse(contents)
json.version = ctx.version
return dryRun
? Promise.resolve()
: fsPromises.writeFile(pkgJsonPath, JSON.stringify(json, null, 2))
},
},
{
title: 'Generating changelog',
task: async () => {
try {
let changelog = await generateChangelog()
const changelogPath = path.join(projectRoot, 'CHANGELOG.md')
const oldChangelog = await fsPromises.readFile(changelogPath)
changelog = changelog + '\n\n\n\n' + oldChangelog
if (!dryRun) {
await fsPromises.writeFile(changelogPath, changelog)
}
} catch (error) {
throw new Error(error)
}
},
},
],
taskOptions
)
}
finish() {
return this.__getFinishTasks()
.run()
.catch(handleTaskError)
.then(() => {
console.log(`
Yippie! A new release has been made.
Check out the merge request for your release here:
${green(underline('https://example.com'))}
`)
})
}
__getFinishTasks() {
return new Listr(
[
{
title: 'Verify project',
task: async () => {
if (!project) {
throw new Error('You must pass the `--project` flag to continue')
}
try {
await this.services.ProjectMembers.all(project)
} catch (error) {
throw new Error('Project could not be found!')
}
},
},
cleanWorkingTreeTask,
{
title: 'Is release branch',
task: async () => {
try {
const { stdout } = await execa('git', ['branch', '--show-current'])
const currentBranchName = stdout.trim()
if (!currentBranchName.includes('release')) {
throw new Error(
'Current branch is not a release branch: ' + currentBranchName
)
}
} catch (error) {
throw new Error(error)
}
},
},
{
title: 'Fetching remote tags',
task: () => {
return execa('git', ['fetch', '--tags'])
},
},
{
title: 'Tag already present',
task: async (ctx, task) => {
try {
await execa(
'git',
['rev-parse', '--verify', '--quiet', `"refs/tags/v${currentVersion}"`],
{ shell: true }
)
ctx.forceTag = await task.prompt({
type: 'Confirm',
message: `Tag v${currentVersion} already created, do you want to assign to a new commit?`,
initial: true,
})
} catch {
return Promise.resolve()
}
},
},
{
title: 'Checking out to develop',
task: () => {
return dryRun ? Promise.resolve() : execa('git', ['checkout', 'develop'])
},
},
{
title: 'Merge into develop',
task: () => {
return dryRun
? Promise.resolve()
: execa('git', ['merge', `release/${currentVersion}`])
},
},
{
title: 'Creating tag',
skip: (ctx) => ctx.forceTag === false,
task: (ctx) => {
const args = [
'tag',
'--annotate',
`v${currentVersion}`,
'--message',
`"chore: new tag v${currentVersion}"`,
]
if (ctx.forceTag) {
args.push('--force')
}
return dryRun ? Promise.resolve() : execa('git', args)
},
},
{
title: 'Pushing develop changes',
task: () => {
return dryRun
? Promise.resolve()
: execa('git', ['push', 'origin', 'develop', '-o', 'ci.skip'])
},
},
{
title: 'Pushing release tag',
task: () => {
return dryRun
? Promise.resolve()
: execa('git', ['push', 'origin', `v${currentVersion}`])
},
},
{
title: 'Removing local release branch',
skip: () => !deletes,
task: () => {
return dryRun
? Promise.resolve()
: execa('git', ['branch', '--delete', `release/${currentVersion}`])
},
},
{
title: 'Removing remote release branch',
skip: () => !deletes,
task: async () => {
try {
await execa('git', [
'push',
'origin',
'--delete',
`release/${currentVersion}`,
])
} catch {
// nothing because if it does not exists, it is OK
}
},
},
{
title: 'Creating merge request',
// BUG: https://github.com/jdalrymple/gitbeaker/issues/1146
skip: () => true,
task: async () => {
if (dryRun) return Promise.resolve()
try {
const changelog = await getLatestChangelog(false)
await this.services.MergeRequests.create({
projectId: project,
sourceBranch: 'develop',
targetBranch: 'master',
title: `New release v${currentVersion}`,
options: {
description: changelog,
removeSourceBranch: false,
labels: 'release',
showExpanded: true,
},
})
} catch (error) {
throw new Error(error)
}
},
},
],
taskOptions
)
}
}
//
// ---------------------------------------------------------------------------------------
//
function getStep() {
if (flags.finish) {
return 'finish'
} else if (flags.publish) {
return 'publish'
}
return null
}
const step = getStep()
switch (task) {
case 'release':
const release = new Release()
release.run(step)
break
}