@leverege/build-tools 2.31.4 → 2.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,630 @@
1
+ #!/usr/bin/env node
2
+ /* eslint-disable security/detect-unsafe-regex */
3
+ /* eslint-disable no-console */
4
+ /* eslint-disable max-len */
5
+
6
+ import cliArgs from 'command-line-args'
7
+ import cliHelp from 'command-line-usage'
8
+ import { $, fs } from 'zx'
9
+ import pkg from 'enquirer'
10
+ import colors from 'ansi-colors'
11
+ import path from 'path'
12
+ import { readPackage } from 'read-pkg'
13
+
14
+ const { prompt } = pkg
15
+
16
+ const NPMJS_TAGS = {
17
+ ALPHA : 'alpha',
18
+ BETA : 'beta',
19
+ LATEST : 'latest',
20
+ }
21
+
22
+ const DEFAULT_PACKAGES_PATH = './packages/*'
23
+
24
+ /**
25
+ * Functions
26
+ */
27
+
28
+ const validateVersionArg = ( { args } ) => {
29
+ if ( !args.version ) {
30
+ return
31
+ }
32
+
33
+ const isValid = /^\d+\.\d+\.\d+(-[a-zA-Z]+\.\d+)?$/.test( args.version )
34
+ if ( !isValid ) {
35
+ console.log( `
36
+ ${colors.bold.red( 'ERROR:' )} Invalid version arg: ${colors.bold.yellow( args.version )}.
37
+ Use SemVer specs (e.g: ${colors.bold.yellow( '2.25.5-beta.1' )}).
38
+ ` )
39
+ process.exit( 1 )
40
+ }
41
+ }
42
+
43
+ const validateNpmjsTag = ( { args, config } ) => {
44
+ const npmjsTags = Object.values( NPMJS_TAGS )
45
+ if ( args['npmjs-tag'] && !npmjsTags.includes( args['npmjs-tag'] ) ) {
46
+ console.log( `
47
+ ${colors.bold.red( 'ERROR:' )} Invalid npmjs tag: ${colors.bold.yellow( args['npmjs-tag'] )}.
48
+ Possible values: ${colors.bold.yellow( npmjsTags.join( ', ' ) )}.
49
+ ` )
50
+ process.exit( 1 )
51
+ }
52
+
53
+ if (
54
+ ( config?.isBetaRelease === true || args?.version?.includes( '-beta.' ) ) &&
55
+ args['npmjs-tag'] === NPMJS_TAGS.LATEST
56
+ ) {
57
+ console.log( `
58
+ ${colors.bold.red( 'ERROR:' )} It's not possible to publish a beta release to npmjs with tag ${colors.bold.yellow( 'latest' )}.
59
+ ` )
60
+ process.exit( 1 )
61
+ }
62
+ }
63
+
64
+ const validateArgs = ( args ) => {
65
+ validateVersionArg( { args } )
66
+ validateNpmjsTag( { args } )
67
+ }
68
+
69
+ const getCurrentBranch = async () => {
70
+ const { stdout } =
71
+ await $`git branch --show-current`
72
+ .nothrow()
73
+ .quiet()
74
+
75
+ return stdout.split( '\n' )[0]
76
+ }
77
+
78
+ const getLatestBranches = async ( { n = 10, branchFilter } ) => {
79
+ const grepFilter = branchFilter || ''
80
+
81
+ const { stdout } =
82
+ await $`git branch -r --sort=-committerdate --format "%(refname:lstrip=3)" | grep "${grepFilter}"`
83
+ .nothrow()
84
+ .quiet()
85
+
86
+ const branches = stdout.split( '\n' ).slice( 0, -1 ).filter( branch => branch !== 'HEAD' )
87
+ return branches.slice( 0, n )
88
+ }
89
+
90
+ const promptForBranch = async ( latestBranches, currentBranch ) => {
91
+ if ( latestBranches.length === 0 ) {
92
+ console.log( `
93
+ ${colors.bold.red( 'ERROR:' )} Could not find git branches.
94
+ ` )
95
+ process.exit( 1 )
96
+ }
97
+
98
+ const { branch } = await prompt( {
99
+ type : 'select',
100
+ name : 'branch',
101
+ message : 'Which branch would you like to release?',
102
+ choices : latestBranches.map( option => ( { value : option } ) ),
103
+ initial : currentBranch
104
+ } )
105
+ return branch
106
+ }
107
+
108
+ const getBranch = async ( branchFilter ) => {
109
+ const currentBranch = await getCurrentBranch()
110
+ const latestBranches = await getLatestBranches( branchFilter )
111
+ return promptForBranch( latestBranches, currentBranch )
112
+ }
113
+
114
+ const getGitRootDirectory = async () => {
115
+ const { stdout } = await $`git rev-parse --show-toplevel`.quiet()
116
+ return stdout.split( '\n' )[0]
117
+ }
118
+
119
+ const getSubDirectories = async ( repositoryRoot, directory ) => {
120
+ const absolutePathDirectory = path.join( repositoryRoot, directory )
121
+ const relativeDirectory = path.relative( repositoryRoot, absolutePathDirectory )
122
+ try {
123
+ const entries = await fs.promises.readdir( absolutePathDirectory, { withFileTypes : true } )
124
+ const subDirectories = entries.filter( entry => entry.isDirectory() )
125
+ return subDirectories.map( entry => path.join( relativeDirectory, entry.name ) )
126
+ } catch ( err ) {
127
+ return []
128
+ }
129
+ }
130
+
131
+ const fileExists = async ( filePath ) => {
132
+ try {
133
+ await fs.promises.access( filePath )
134
+ return true
135
+ } catch ( err ) {
136
+ return false
137
+ }
138
+ }
139
+
140
+ const findPackagesInDirectories = async ( repositoryRoot, directories ) => {
141
+ return directories.reduce( async ( accPromise, directory ) => {
142
+ const acc = await accPromise
143
+ const hasWildcard = directory.endsWith( '*' )
144
+ const basePath = hasWildcard ? directory.slice( 0, -1 ) : directory
145
+ const directoriesToSearch = hasWildcard ?
146
+ await getSubDirectories( repositoryRoot, basePath ) :
147
+ [ basePath ]
148
+
149
+ for ( let i = 0; i < directoriesToSearch.length; i++ ) {
150
+ const currentDirectory = directoriesToSearch[i]
151
+ const pkgPath = path.join( directoriesToSearch[i], 'package.json' )
152
+ const pkgExists = await fileExists( path.join( repositoryRoot, pkgPath ) ) // eslint-disable-line no-await-in-loop
153
+ if ( pkgExists ) {
154
+ acc.push( currentDirectory )
155
+ }
156
+ }
157
+ return acc
158
+
159
+ }, Promise.resolve( [] ) )
160
+ }
161
+
162
+ const getMonorepoPackagePaths = async ( repositoryRoot, packagesPath ) => {
163
+ let pkg
164
+ try {
165
+ pkg = await readPackage( { cwd : repositoryRoot } )
166
+ } catch ( err ) {}
167
+
168
+ return findPackagesInDirectories( repositoryRoot, pkg?.workspaces || [ packagesPath ] )
169
+ }
170
+
171
+ const selectPackageToUpdate = async ( repositoryRoot, packagePaths ) => {
172
+ const currentPath = process.cwd()
173
+ const currentPackageRelativePath = path.relative( repositoryRoot, currentPath )
174
+
175
+ const { packageName } = await prompt( {
176
+ type : 'select',
177
+ name : 'packageName',
178
+ message : 'What package are you releasing?',
179
+ choices : packagePaths,
180
+ initial : currentPackageRelativePath
181
+ } )
182
+
183
+ return path.join( repositoryRoot, packageName )
184
+ }
185
+
186
+ const getPackagePath = async ( { repositoryRoot, packagesPath = DEFAULT_PACKAGES_PATH } ) => {
187
+ const packagePaths = await getMonorepoPackagePaths( repositoryRoot, packagesPath )
188
+ if ( packagePaths.length > 0 ) {
189
+ return selectPackageToUpdate( repositoryRoot, packagePaths )
190
+ }
191
+
192
+ return repositoryRoot
193
+ }
194
+
195
+ const checkoutToBranch = async ( branch ) => {
196
+ try {
197
+ await $`git checkout ${branch}`
198
+ } catch ( err ) {
199
+ console.log( err.stderr || err )
200
+ process.exit( 1 )
201
+ }
202
+ }
203
+
204
+ const getPackageJsonVersion = async ( packagePath ) => {
205
+ if ( !packagePath ) {
206
+ console.log( `
207
+ ${colors.bold.red( 'ERROR:' )} Could not find a package.json file.
208
+ The tag-release script must run from a npm project.
209
+ ` )
210
+ return process.exit( 1 )
211
+ }
212
+
213
+ const packageJson = await readPackage( { cwd : packagePath } )
214
+ return packageJson.version
215
+ }
216
+
217
+ const getNextVersions = ( currentVersion ) => {
218
+ const [ major, minor, patch, beta ] = currentVersion.split( /\.|-beta\./ ).map( Number )
219
+
220
+ const nextMajor = `${major + 1}.0.0`
221
+ const nextMinor = `${major}.${minor + 1}.0`
222
+ const nextPatch = `${major}.${minor}.${patch + 1}`
223
+ const nextBeta = beta ? `${major}.${minor}.${patch}-beta.${beta + 1}` : `${major}.${minor}.${patch + 1}-beta.1`
224
+
225
+ return {
226
+ nextMajor,
227
+ nextMinor,
228
+ nextPatch,
229
+ nextBeta,
230
+ }
231
+ }
232
+
233
+ const promptForVersion = async ( currentVersion ) => {
234
+ const { nextMajor, nextMinor, nextPatch, nextBeta } = getNextVersions( currentVersion )
235
+ const choices = [
236
+ { hint : '(major release)', value : nextMajor },
237
+ { hint : '(minor release)', value : nextMinor },
238
+ { hint : '(patch release)', value : nextPatch },
239
+ { hint : '(beta release)', value : nextBeta },
240
+ { hint : '(current version)', value : currentVersion },
241
+ { value : 'custom' },
242
+ ]
243
+ const { version } = await prompt( {
244
+ type : 'select',
245
+ name : 'version',
246
+ message : `What version are you releasing (current version is ${currentVersion})?`,
247
+ choices,
248
+ } )
249
+
250
+ if ( version === 'custom' ) {
251
+ const { customVersion } = await prompt( {
252
+ type : 'input',
253
+ name : 'customVersion',
254
+ message : `What custom version are you releasing (current version is ${currentVersion})?`,
255
+ initial : currentVersion
256
+ } )
257
+ return customVersion
258
+ }
259
+
260
+ return version
261
+ }
262
+
263
+ const getVersion = async ( { branch, packagePath } ) => {
264
+ await checkoutToBranch( branch )
265
+ const currentVersion = await getPackageJsonVersion( packagePath )
266
+ return promptForVersion( currentVersion )
267
+ }
268
+
269
+ const getPackageName = async ( { packagePath } ) => {
270
+ const noTrailingSlashPath = packagePath.slice( -1 ) === '/' ?
271
+ packagePath.substr( 0, packagePath.length - 1 ) :
272
+ packagePath
273
+ return noTrailingSlashPath.split( '/' ).slice( -1 )[0]
274
+ }
275
+
276
+ const getBuildMessage = ( { isPackageInRepositoryRoot, packageName, version } ) => {
277
+ if ( isPackageInRepositoryRoot ) {
278
+ return `BUILD v${version}`
279
+ }
280
+ return `BUILD ${packageName}/v${version}`
281
+ }
282
+
283
+ const getGitTagSuffix = async () => {
284
+ const { tagSuffix } = await prompt( {
285
+ type : 'input',
286
+ name : 'tagSuffix',
287
+ message : 'What suffix you like to add to the tag name for git? (e.g: "-RC.1" for v1.2.3-RC.1)',
288
+ } )
289
+ return tagSuffix
290
+ }
291
+
292
+ const confirmPushCommit = async ( buildMessage ) => {
293
+ const { confirm } = await prompt( [ {
294
+ type : 'confirm',
295
+ name : 'confirm',
296
+ message : `${colors.bold.red( '[Warning]' )} Commit and push ${colors.bold.yellow( buildMessage )} to git remote?`
297
+ } ] )
298
+ return confirm
299
+ }
300
+
301
+ const isPackageInRepositoryRoot = async ( { repositoryRoot, packagePath } ) => {
302
+ return repositoryRoot === packagePath
303
+ }
304
+
305
+ const promptForNpmjsTag = async ( { isBetaRelease } ) => {
306
+ const choices = Object.values( NPMJS_TAGS ).map( option => ( {
307
+ value : option,
308
+ ...( ( isBetaRelease && option === NPMJS_TAGS.LATEST ) && { disabled : '(not available for beta releases)' } )
309
+ } ) )
310
+ const { npmjsTag } = await prompt( {
311
+ type : 'select',
312
+ name : 'npmjsTag',
313
+ message : 'Which npmjs tag would you like to use when publishing?',
314
+ choices,
315
+ initial : isBetaRelease ? NPMJS_TAGS.BETA : NPMJS_TAGS.LATEST,
316
+ } )
317
+ return npmjsTag
318
+ }
319
+
320
+ const confirmTagRelease = async ( { isBetaRelease, publishable } ) => {
321
+ const message = [
322
+ 'Releasing will commit',
323
+ isBetaRelease ? ' and push' : ', push, and tag',
324
+ ' the version in git',
325
+ publishable ? ' and npm' : '',
326
+ '. Proceed?'
327
+ ].join( '' )
328
+
329
+ const { confirmResponse } = await prompt( {
330
+ type : 'select',
331
+ name : 'confirmResponse',
332
+ message,
333
+ choices : [ 'yes', 'no', 'advanced' ],
334
+ initial : 'yes',
335
+ } )
336
+
337
+ if ( confirmResponse === 'no' ) {
338
+ console.log( 'Aborting...' )
339
+ process.exit()
340
+ }
341
+
342
+ return confirmResponse
343
+ }
344
+
345
+ const isWorkspacePackage = async () => {
346
+ const gitRootDirectory = await getGitRootDirectory()
347
+ try {
348
+ const packageJson = await readPackage( { cwd : gitRootDirectory } )
349
+ return packageJson?.workspaces?.length > 0
350
+ } catch ( err ) {
351
+ return false
352
+ }
353
+ }
354
+
355
+ const updateNpmPackageJsonAndLock = async ( config ) => {
356
+ const { version, packagePath, isPackageInRepositoryRoot } = config
357
+
358
+ const isWorkspace = await isWorkspacePackage()
359
+
360
+ try {
361
+ if ( !isPackageInRepositoryRoot ) {
362
+ await $`npm version --no-git-tag-version ${version} --prefix ${packagePath}`.nothrow()
363
+ if ( isWorkspace ) {
364
+ await $`npm install`
365
+ } else {
366
+ await $`npm install --prefix ${packagePath}`
367
+ }
368
+ } else {
369
+ await $`npm version --no-git-tag-version ${version}`.nothrow()
370
+ }
371
+ } catch ( err ) {
372
+ console.log( err.stderr || err )
373
+ process.exit( 1 )
374
+ }
375
+ }
376
+
377
+ const createNewBuildCommit = async ( { buildMessage } ) => {
378
+ try {
379
+ await $`git add .`
380
+ await $`git commit -m ${buildMessage}`
381
+ } catch ( err ) {
382
+ console.log( err.stderr || err )
383
+ process.exit( 1 )
384
+ }
385
+ }
386
+
387
+ const pushToGitRemote = async () => {
388
+ try {
389
+ await $`git push`
390
+ } catch ( err ) {
391
+ console.log( err.stderr || err )
392
+ process.exit( 1 )
393
+ }
394
+ }
395
+
396
+ const commitAndPushNewBuild = async ( config ) => {
397
+ const { buildMessage, noConfirm } = config
398
+
399
+ const confirmAnswer = noConfirm || await confirmPushCommit( buildMessage )
400
+ if ( !confirmAnswer ) {
401
+ console.log( 'Aborting...' )
402
+ process.exit()
403
+ }
404
+
405
+ await updateNpmPackageJsonAndLock( config )
406
+ await createNewBuildCommit( config )
407
+ await pushToGitRemote()
408
+ }
409
+
410
+ const confirmPushTag = async ( tagName ) => {
411
+ const { confirm } = await prompt( [ {
412
+ type : 'confirm',
413
+ name : 'confirm',
414
+ message : `${colors.bold.red( '[Warning]' )} Push new tag ${colors.bold.yellow( tagName )} to git remote?`
415
+ } ] )
416
+ return confirm
417
+ }
418
+
419
+ const createGitTag = async ( tagName ) => {
420
+ try {
421
+ await $`git tag ${tagName}`
422
+ } catch ( err ) {
423
+ console.log( err.stderr || err )
424
+ process.exit( 1 )
425
+ }
426
+ }
427
+
428
+ const pushGitTag = async ( tagName ) => {
429
+ try {
430
+ await $`git push origin ${tagName}`
431
+ } catch ( err ) {
432
+ console.log( err.stderr || err )
433
+ process.exit( 1 )
434
+ }
435
+ }
436
+
437
+ const createAndPushGitTag = async ( { tagName, noConfirm } ) => {
438
+ const confirmAnswer = noConfirm || await confirmPushTag( tagName )
439
+ if ( confirmAnswer ) {
440
+ await createGitTag( tagName )
441
+ await pushGitTag( tagName )
442
+ }
443
+ }
444
+
445
+ const confirmPublishToNpmjs = async ( version, npmjsTag ) => {
446
+ const { confirm } = await prompt( [ {
447
+ type : 'confirm',
448
+ name : 'confirm',
449
+ message : `${colors.bold.red( '[Warning]' )} Publish new version ${colors.bold.yellow( version )} to npmjs with tag ${colors.bold.yellow( npmjsTag )}?`
450
+ } ] )
451
+ return confirm
452
+ }
453
+
454
+ const publishToNpmjs = async ( { version, npmjsTag, noConfirm } ) => {
455
+ const confirmAnswer = noConfirm || await confirmPublishToNpmjs( version, npmjsTag )
456
+ if ( !confirmAnswer ) {
457
+ console.log( 'Aborting...' )
458
+ process.exit()
459
+ }
460
+
461
+ try {
462
+ await $`npm publish --tag ${npmjsTag}`
463
+ } catch ( err ) {
464
+ console.log( err.stderr || err )
465
+ process.exit( 1 )
466
+ }
467
+ }
468
+
469
+ const displayReleaseInfo = ( config ) => {
470
+ const {
471
+ branch,
472
+ version,
473
+ repositoryRoot,
474
+ packageName,
475
+ packagePath,
476
+ buildMessage,
477
+ tagName,
478
+ publishable,
479
+ npmjsTag,
480
+ isBetaRelease
481
+ } = config
482
+
483
+ console.log( `
484
+
485
+ ${colors.bold.green( '============ Tag Release Summary ============' )}
486
+ ${colors.blue( 'Branch:' )} ${branch}
487
+ ${colors.blue( 'Version:' )} ${version}
488
+ ${colors.blue( 'Root directory:' )} ${repositoryRoot}
489
+ ${colors.blue( 'Package name:' )} ${packageName}
490
+ ${colors.blue( 'package.json path:' )} ${path.join( packagePath, 'package.json' )}${buildMessage ? `
491
+ ${colors.blue( 'Commit message:' )} ${buildMessage}` : ''}${isBetaRelease ? '' : `
492
+ ${colors.blue( 'Git tag:' )} ${tagName}`}${publishable ? `
493
+ ${colors.blue( 'Npmjs tag:' )} ${npmjsTag}` : ''}
494
+ ${colors.bold.green( '=============================================' )}
495
+ ` )
496
+ }
497
+
498
+ /**
499
+ * Script
500
+ */
501
+
502
+ const optionList = [
503
+ {
504
+ name : 'branch',
505
+ type : String,
506
+ alias : 'b',
507
+ description : 'branch where the tag will be created',
508
+ },
509
+ {
510
+ name : 'npmjs-tag',
511
+ type : String,
512
+ alias : 'n',
513
+ description : 'npmjs package tag to be used when publishing (for npmjs lib repositories)',
514
+ typeLabel : 'alpha|beta|latest'
515
+ },
516
+ {
517
+ name : 'version',
518
+ type : String,
519
+ alias : 'v',
520
+ description : 'version to be tagged',
521
+ },
522
+ {
523
+ name : 'publishable',
524
+ type : Boolean,
525
+ alias : 'p',
526
+ description : 'flag to indicate the repository is publishable to npmjs',
527
+ },
528
+ {
529
+ name : 'package-path',
530
+ type : String,
531
+ alias : 'a',
532
+ description : 'relative path to the package from the projec\'s root in case it\'s a monorepo',
533
+ },
534
+ {
535
+ name : 'tag-suffix',
536
+ type : String,
537
+ alias : 't',
538
+ description : 'tag suffix to be appended to the version when pushing to git',
539
+ },
540
+ {
541
+ name : 'branch-filter',
542
+ type : String,
543
+ alias : 'f',
544
+ description : 'branch filter used to filter available branches in interactive mode',
545
+ },
546
+ {
547
+ name : 'no-commit',
548
+ type : Boolean,
549
+ description : 'do not create a new commit on git (in case the goal is just tagging it)',
550
+ },
551
+ {
552
+ name : 'no-confirm',
553
+ type : Boolean,
554
+ description : 'push to git and publish to npmjs without asking for confirmation',
555
+ },
556
+ {
557
+ name : 'help',
558
+ type : Boolean,
559
+ alias : 'h',
560
+ description : 'show this help',
561
+ },
562
+ ]
563
+
564
+ const sections = [
565
+ {
566
+ header : 'Tag release script',
567
+ content : 'This script is intended to give users a simple way to create git tags, push them and publish to Npmjs (if the --publishable flag is passed)',
568
+ },
569
+ { header : 'Options',
570
+ optionList,
571
+ },
572
+ ]
573
+
574
+ const args = cliArgs( optionList, { partial : true } )
575
+ const help = cliHelp( sections )
576
+
577
+ if ( args.help ) {
578
+ console.log( help )
579
+ process.exit()
580
+ }
581
+
582
+ validateArgs( args )
583
+
584
+ const config = {}
585
+
586
+ config.noConfirm = !!args['no-confirm']
587
+
588
+ config.noCommit = !!args['no-commit']
589
+
590
+ config.repositoryRoot = await getGitRootDirectory()
591
+
592
+ config.branch = args.branch || await getBranch( { branchFilter : args['branch-filter'] } )
593
+
594
+ const argsPackagePath = args['package-path'] && path.join( config.repositoryRoot, args['package-path'] )
595
+ config.packagePath = argsPackagePath || await getPackagePath( config )
596
+
597
+ config.isPackageInRepositoryRoot = await isPackageInRepositoryRoot( config )
598
+
599
+ config.version = args.version || await getVersion( config )
600
+
601
+ config.packageName = await getPackageName( config )
602
+
603
+ config.buildMessage = config.noCommit ? '' : getBuildMessage( config )
604
+
605
+ config.isBetaRelease = config.version.includes( '-beta.' )
606
+
607
+ if ( !config.isBetaRelease ) {
608
+ const tagSuffix = args['tag-suffix'] ?? await getGitTagSuffix()
609
+ const tagPrefix = config.isPackageInRepositoryRoot ? '' : `${config.packageName}/`
610
+ config.tagName = `${tagPrefix}v${config.version}${tagSuffix}`
611
+ }
612
+
613
+ config.publishable = !!args.publishable
614
+ if ( config.publishable ) {
615
+ validateNpmjsTag( { config, args } )
616
+ config.npmjsTag = args['npmjs-tag'] || await promptForNpmjsTag( config )
617
+ }
618
+
619
+ displayReleaseInfo( config )
620
+
621
+ const confirmResponse = await confirmTagRelease( config )
622
+ if ( confirmResponse === 'yes' ) {
623
+ config.noConfirm = true
624
+ }
625
+
626
+ if ( !config.noCommit ) { await commitAndPushNewBuild( config ) }
627
+ if ( !config.isBetaRelease ) { await createAndPushGitTag( config ) }
628
+ if ( config.publishable ) { await publishToNpmjs( config ) }
629
+
630
+ process.exit()