-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
publish.ts
1370 lines (1210 loc) · 36.5 KB
/
publish.ts
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import slugify from '@sindresorhus/slugify'
import { IncomingWebhook } from '@slack/webhook'
import arg from 'arg'
import topo from 'batching-toposort'
import chalk from 'chalk'
import execa from 'execa'
import { promises as fs } from 'fs'
import globby from 'globby'
import fetch from 'node-fetch'
import pMap from 'p-map'
import pReduce from 'p-reduce'
import pRetry from 'p-retry'
import path from 'path'
import redis from 'redis'
import semver from 'semver'
import { promisify } from 'util'
import { cloneOrPull } from '../setup'
import { unique } from './unique'
export type Commit = {
date: Date
dir: string
hash: string
isMergeCommit: boolean
parentCommits: string[]
}
async function getLatestChanges(): Promise<string[]> {
return getChangesFromCommit(await getLatestCommit('.'))
}
async function getChangesFromCommit(commit: Commit): Promise<string[]> {
const hashes = commit.isMergeCommit
? commit.parentCommits.join(' ')
: commit.hash
const changes = await runResult(
commit.dir,
`git diff-tree --no-commit-id --name-only -r ${hashes}`,
)
if (changes.trim().length > 0) {
return changes.split('\n').map((change) => path.join(commit.dir, change))
} else {
throw new Error(`No changes detected. This must not happen!`)
}
}
async function getUnsavedChanges(dir: string): Promise<string | null> {
const result = await runResult(dir, `git status --porcelain`)
return result.trim() || null
}
async function getLatestCommit(dir: string): Promise<Commit> {
if (process.env.GITHUB_CONTEXT) {
const context = JSON.parse(process.env.GITHUB_CONTEXT)
return context.sha
}
const result = await runResult(
dir,
'git log --pretty=format:"%ad %H %P" --date=iso-strict -n 1',
)
const [date, commit, ...parents] = result.split(' ')
return {
date: new Date(date),
dir,
hash: commit,
isMergeCommit: parents.length > 1,
parentCommits: parents,
}
}
async function commitChanges(
dir: string,
message: string,
dry = false,
): Promise<void> {
await run(dir, `git commit -am "${message}"`, dry)
}
async function pull(dir: string, dry = false): Promise<void> {
const branch = await getBranch(dir)
if (process.env.BUILDKITE) {
if (!process.env.GITHUB_TOKEN) {
throw new Error(`Missing env var GITHUB_TOKEN`)
}
}
await run(dir, `git pull origin ${branch} --no-edit`, dry)
}
async function push(dir: string, dry = false, branch?: string): Promise<void> {
branch = branch ?? (await getBranch(dir))
if (process.env.BUILDKITE) {
if (!process.env.GITHUB_TOKEN) {
throw new Error(`Missing env var GITHUB_TOKEN`)
}
await run(dir, `git push --quiet --set-upstream origin ${branch}`, dry)
} else {
await run(dir, `git push origin ${branch}`, dry)
}
}
/**
* Runs a command and returns the resulting stdout in a Promise.
* @param cwd cwd for running the command
* @param cmd command to run
*/
async function runResult(cwd: string, cmd: string): Promise<string> {
try {
const result = await execa.command(cmd, {
cwd,
stdio: 'pipe',
shell: true,
})
return result.stdout
} catch (e) {
throw new Error(
chalk.red(
`Error running ${chalk.bold(cmd)} in ${chalk.underline(cwd)}:`,
) + (e.stderr || e.stack || e.message),
)
}
}
/**
* Runs a command and pipes the stdout & stderr to the current process.
* @param cwd cwd for running the command
* @param cmd command to run
*/
async function run(
cwd: string,
cmd: string,
dry = false,
hidden = false,
): Promise<void> {
const args = [chalk.underline('./' + cwd).padEnd(20), chalk.bold(cmd)]
if (dry) {
args.push(chalk.dim('(dry)'))
}
if (!hidden) {
console.log(...args)
}
if (dry) {
return
}
try {
await execa.command(cmd, {
cwd,
stdio: 'inherit',
shell: true,
env: {
...process.env,
PRISMA_SKIP_POSTINSTALL_GENERATE: 'true',
},
})
} catch (e) {
throw new Error(
chalk.red(
`Error running ${chalk.bold(cmd)} in ${chalk.underline(cwd)}:`,
) + (e.stderr || e.stack || e.message),
)
}
}
type RawPackage = {
path: string
packageJson: any
}
type RawPackages = { [packageName: string]: RawPackage }
export async function getPackages(): Promise<RawPackages> {
const packagePaths = await globby(['packages/*/package.json'], {
ignore: ['**/node_modules/**', '**/examples/**', '**/fixtures/**'],
})
const packages = await Promise.all(
packagePaths.map(async (p) => ({
path: p,
packageJson: JSON.parse(await fs.readFile(p, 'utf-8')),
})),
)
return packages.reduce<RawPackages>((acc, p) => {
if (p.packageJson.name) {
acc[p.packageJson.name] = p
}
return acc
}, {})
}
interface Package {
name: string
path: string
version: string
usedBy: string[]
usedByDev: string[]
uses: string[]
usesDev: string[]
packageJson: any
}
interface PackageWithNewVersion extends Package {
newVersion: string
}
type Packages = { [packageName: string]: Package }
type PackagesWithNewVersions = { [packageName: string]: PackageWithNewVersion }
export function getPackageDependencies(packages: RawPackages): Packages {
const packageCache = Object.entries(packages).reduce<Packages>(
(acc, [name, pkg]) => {
const usesDev = getPrismaDependencies(pkg.packageJson.devDependencies)
acc[name] = {
version: pkg.packageJson.version,
name,
path: pkg.path,
usedBy: [],
usedByDev: [],
uses: getPrismaDependencies(pkg.packageJson.dependencies),
usesDev,
packageJson: pkg.packageJson,
}
return acc
},
{},
)
for (const pkg of Object.values(packageCache)) {
for (const dependency of pkg.uses) {
if (packageCache[dependency]) {
packageCache[dependency].usedBy.push(pkg.name)
} else {
console.info(`Skipping ${dependency} as it's not in this workspace`)
}
}
for (const devDependency of pkg.usesDev) {
if (packageCache[devDependency]) {
packageCache[devDependency].usedByDev.push(pkg.name)
} else {
console.info(`Skipping ${devDependency} as it's not in this workspace`)
}
}
}
return packageCache
}
function getPrismaDependencies(dependencies?: {
[name: string]: string
}): string[] {
if (!dependencies) {
return []
}
return Object.keys(dependencies).filter(
(d) => d.startsWith('@prisma') && !d.startsWith('@prisma/studio'),
)
}
function getCircularDependencies(packages: Packages): string[][] {
const circularDeps = [] as string[][]
for (const pkg of Object.values(packages)) {
const uses = [...pkg.uses, ...pkg.usesDev]
const usedBy = [...pkg.usedBy, ...pkg.usedByDev]
const circles = intersection(uses, usedBy)
if (circles.length > 0) {
circularDeps.push(circles)
}
}
return circularDeps
}
async function getNewPackageVersions(
packages: Packages,
prisma2Version: string,
): Promise<PackagesWithNewVersions> {
return pReduce(
Object.values(packages),
async (acc, p) => {
acc[p.name] = {
...p,
newVersion: await newVersion(p, prisma2Version),
}
return acc
},
{},
)
}
export function getPublishOrder(packages: Packages): string[][] {
const dag: { [pkg: string]: string[] } = Object.values(packages).reduce(
(acc, curr) => {
acc[curr.name] = [...curr.usedBy, ...curr.usedByDev]
return acc
},
{},
)
return topo(dag)
}
function zeroOutPatch(version: string): string {
const parts = version.split('.')
parts[parts.length - 1] = '0'
return parts.join('.')
}
/**
* Takes the max dev version + 1
* For now supporting X.Y.Z-dev.#
* @param packages Local package definitions
*/
async function getNewDevVersion(packages: Packages): Promise<string> {
const before = Date.now()
console.log('\nCalculating new dev version...')
// Why are we calling zeroOutPatch?
// Because here we're only interested in the 2.5.0 <- the next minor stable version
// If the current version would be 2.4.7, we would end up with 2.5.7
const nextStable = zeroOutPatch((await getNextMinorStable())!)
console.log(`getNewDevVersion: Next minor stable: ${nextStable}`)
const versions = await getAllVersions(packages, 'dev', nextStable + '-dev')
const maxDev = getMaxDevVersionIncrement(versions)
const version = `${nextStable}-dev.${maxDev + 1}`
console.log(`Got ${version} in ${Date.now() - before}ms`)
return version
}
/**
* Takes the max dev version + 1
* For now supporting X.Y.Z-dev.#
* @param packages Local package definitions
*/
async function getNewIntegrationVersion(
packages: Packages,
branch: string,
): Promise<string> {
const before = Date.now()
console.log('\nCalculating new dev version...')
// Why are we calling zeroOutPatch?
// Because here we're only interested in the 2.5.0 <- the next minor stable version
// If the current version would be 2.4.7, we would end up with 2.5.7
const nextStable = zeroOutPatch((await getNextMinorStable())!)
console.log(`getNewIntegrationVersion: Next minor stable: ${nextStable}`)
const branchWithoutPrefix = branch.replace(/^integration\//, '')
const versionNameSlug = `${nextStable}-integration-${slugify(
branchWithoutPrefix,
)}`
const versions = await getAllVersions(
packages,
'integration',
versionNameSlug,
)
const maxIntegration = getMaxIntegrationVersionIncrement(versions)
const version = `${versionNameSlug}.${maxIntegration + 1}`
console.log(`Got ${version} in ${Date.now() - before}ms`)
return version
}
async function getCurrentPatchForMinor(minor: number): Promise<number> {
let versions = JSON.parse(
await runResult('.', 'npm show @prisma/client@* version --json'),
)
// inconsistent npm api
if (!Array.isArray(versions)) {
versions = [versions]
}
const relevantVersions: Array<{
major: number
minor: number
patch: number
}> = versions
.map((v) => {
const match = semverRegex.exec(v)
if (match?.groups) {
return {
major: Number(match.groups.major),
minor: Number(match.groups.minor),
patch: Number(match.groups.patch),
}
}
return null
})
.filter((group) => group && group.minor === minor)
if (relevantVersions.length === 0) {
return 0
}
// sort descending by patch
relevantVersions.sort((a, b) => {
return a.patch < b.patch ? 1 : -1
})
return relevantVersions[0].patch
}
async function getNewPatchDevVersion(
packages: Packages,
patchBranch: string,
): Promise<string> {
const patchVersions = getSemverFromPatchBranch(patchBranch)
if (!patchVersions) {
throw new Error(`Could not get versions for ${patchBranch}`)
}
const currentPatch = await getCurrentPatchForMinor(patchVersions.minor)
const newPatch = currentPatch + 1
const newVersion = `${patchVersions.major}.${patchVersions.minor}.${newPatch}`
const versions = [...(await getAllVersions(packages, 'dev', newVersion))]
const maxIncrement = getMaxPatchVersionIncrement(versions)
return `${newVersion}-dev.${maxIncrement + 1}`
}
function getMaxDevVersionIncrement(versions: string[]): number {
const regex = /2\.\d+\.\d+-dev\.(\d+)/
const increments = versions
.filter((v) => v.trim().length > 0)
.map((v) => {
const match = regex.exec(v)
if (match) {
return Number(match[1])
}
return 0
})
.filter((v) => v)
return Math.max(...increments, 0)
}
function getMaxIntegrationVersionIncrement(versions: string[]): number {
const regex = /2\.\d+\.\d+-integration.*\.(\d+)/
const increments = versions
.filter((v) => v.trim().length > 0)
.map((v) => {
const match = regex.exec(v)
if (match) {
return Number(match[1])
}
return 0
})
.filter((v) => v)
return Math.max(...increments, 0)
}
// TODO: Adjust this for stable releases
function getMaxPatchVersionIncrement(versions: string[]): number {
const regex = /2\.\d+\.\d+-dev\.(\d+)/
const increments = versions
.filter((v) => v.trim().length > 0)
.map((v) => {
const match = regex.exec(v)
if (match && match[1]) {
return Number(match[1])
}
return 0
})
.filter((v) => v)
return Math.max(...increments, 0)
}
async function getAllVersions(
packages: Packages,
channel: string,
prefix: string,
): Promise<string[]> {
return unique(
flatten(
await pMap(
Object.values(packages).filter(
(p) => p.name !== '@prisma/integration-tests',
),
async (pkg) => {
if (pkg.name === '@prisma/integration-tests') {
return []
}
const pkgVersions = [] as string[]
if (pkg.version.startsWith(prefix)) {
pkgVersions.push(pkg.version)
}
const remoteVersionsString = await runResult(
'.',
`npm info ${pkg.name} versions --json`,
)
const remoteVersions = JSON.parse(remoteVersionsString)
for (const remoteVersion of remoteVersions) {
if (
remoteVersion.includes(channel) &&
remoteVersion.startsWith(prefix) &&
!pkgVersions.includes(remoteVersion)
) {
pkgVersions.push(remoteVersion)
}
}
return pkgVersions
},
{ concurrency: 3 }, // Let's not spam npm too much
),
),
)
}
async function getNextMinorStable() {
const remoteVersion = await runResult('.', `npm info prisma version`)
return increaseMinor(remoteVersion)
}
function getSemverFromPatchBranch(version: string) {
const regex = /(\d+)\.(\d+)\.x/
const match = regex.exec(version)
if (match) {
return {
major: Number(match[1]),
minor: Number(match[2]),
}
}
return undefined
}
async function publish() {
const args = arg({
'--publish': Boolean,
'--repo': String,
'--dry-run': Boolean,
'--release': String, // TODO What does that do?
'--test': Boolean,
})
if (
process.env.BUILDKITE &&
process.env.PUBLISH_BUILD &&
!process.env.GITHUB_TOKEN
) {
throw new Error(`Missing env var GITHUB_TOKEN`)
}
if (process.env.DRY_RUN) {
console.log(
chalk.blue.bold(`\nThe DRY_RUN env var is set, so we'll do a dry run!\n`),
)
args['--dry-run'] = true
}
const dryRun = args['--dry-run'] ?? false
if (args['--publish'] && process.env.BUILDKITE_TAG) {
if (args['--release']) {
throw new Error(
`Can't provide env var BUILDKITE_TAG and --release at the same time`,
)
}
console.log(
`Setting --release to BUILDKITE_TAG = ${process.env.BUILDKITE_TAG}`,
)
args['--release'] = process.env.BUILDKITE_TAG
}
if (process.env.BUILDKITE_TAG && !process.env.RELEASE_PROMOTE_DEV) {
throw new Error(
`When BUILDKITE_TAG is provided, RELEASE_PROMOTE_DEV also needs to be provided`,
)
}
if (!args['--test'] && !args['--publish'] && !dryRun) {
throw new Error('Please either provide --test or --publish or --dry-run')
}
if (args['--release']) {
if (!semver.valid(args['--release'])) {
throw new Error(
`New release version ${chalk.bold.underline(
args['--release'],
)} is not a valid semver version.`,
)
}
const releaseRegex = /\d{1,2}\.\d{1,2}\.\d{1,2}/
if (!releaseRegex.test(args['--release'])) {
throw new Error(
`New release version ${chalk.bold.underline(
args['--release'],
)} does not follow the stable naming scheme: ${chalk.bold.underline(
'x.y.z',
)}`,
)
}
// If there is --release, it's always also --publish
args['--publish'] = true
}
let unlock: undefined | (() => void)
if (process.env.BUILDKITE && args['--publish']) {
console.log(
`We're in buildkite and will publish, so we will acquire a lock...`,
)
const before = Date.now()
unlock = await acquireLock()
const after = Date.now()
console.log(`Acquired lock after ${after - before}ms`)
}
try {
const rawPackages = await getPackages()
const packages = getPackageDependencies(rawPackages)
const circles = getCircularDependencies(packages)
if (circles.length > 0) {
throw new Error(`Oops, there are circular dependencies: ${circles}`)
}
if (!process.env.GITHUB_CONTEXT) {
const changes = await getLatestChanges()
console.log(chalk.bold(`Changed files:`))
console.log(changes.map((c) => ` ${c}`).join('\n'))
}
let prisma2Version
let tag: undefined | string
let tagForE2ECheck: undefined | string
const patchBranch = getPatchBranch()
console.log({ patchBranch })
const branch = await getPrismaBranch()
console.log({ branch })
// For branches that are named "integration/" we publish to the integration npm tag
if (branch && branch.startsWith('integration/')) {
prisma2Version = await getNewIntegrationVersion(packages, branch)
tag = 'integration'
}
// Is it a patch branch? (Like 2.20.x)
else if (patchBranch) {
prisma2Version = await getNewPatchDevVersion(packages, patchBranch)
tag = 'patch-dev'
if (args['--release']) {
tagForE2ECheck = 'patch-dev' //?
prisma2Version = args['--release']
tag = 'latest'
}
} else if (args['--release']) {
prisma2Version = args['--release']
tag = 'latest'
tagForE2ECheck = 'dev'
} else {
prisma2Version = await getNewDevVersion(packages)
tag = 'dev'
}
console.log({ patchBranch, tag, tagForE2ECheck, prisma2Version })
const packagesWithVersions = await getNewPackageVersions(
packages,
prisma2Version,
)
if (process.env.UPDATE_STUDIO) {
console.log(
chalk.bold(
`UPDATE_STUDIO is set, so we only update Prisma Client and all dependants.`,
),
)
// We know, that Prisma Client and Prisma CLI are always part of the release.
// Therefore, also Migrate is also always part of the release, as it depends on Prisma Client.
// We can therefore safely update Studio, as migrate and Prisma CLI are depending on Studio
const latestStudioVersion = await runResult(
'.',
'npm info @prisma/studio-server version',
)
console.log(
`UPDATE_STUDIO set true, so we're updating it to ${latestStudioVersion}`,
)
console.log(`Active branch`)
await run('.', 'git branch')
console.log(`Let's check out main!`)
await run('.', 'git checkout main')
await run(
'.',
`pnpm update -r @prisma/studio-server@${latestStudioVersion}`,
)
}
if (!dryRun && args['--test']) {
console.log(chalk.bold('\nTesting packages'))
await testPackages(packages, getPublishOrder(packages))
}
if (args['--publish'] || dryRun) {
if (args['--release']) {
if (!tagForE2ECheck) {
throw new Error(`tagForE2ECheck missing`)
}
const passing = await areEndToEndTestsPassing(tagForE2ECheck)
if (!passing && !process.env.SKIP_E2E_CHECK) {
throw new Error(`We can't release, as the e2e tests are not passing for the ${tag} npm tag!
Check them out at https://github.com/prisma/e2e-tests/actions?query=workflow%3Atest+branch%3A${tag}`)
}
}
const publishOrder = filterPublishOrder(getPublishOrder(packages), [
'@prisma/integration-tests',
])
if (!dryRun) {
console.log(`Let's first do a dry run!`)
await publishPackages(
packages,
packagesWithVersions,
publishOrder,
true,
prisma2Version,
tag,
args['--release'],
)
console.log(`Waiting 5 sec so you can check it out first...`)
await new Promise((r) => setTimeout(r, 5000))
}
await publishPackages(
packages,
packagesWithVersions,
publishOrder,
dryRun,
prisma2Version,
tag,
args['--release'],
)
const enginesCommit = await getEnginesCommit()
const enginesCommitInfo = await getCommitInfo(
'prisma-engines',
enginesCommit,
)
const prismaCommit = await getLatestCommit('.')
const prismaCommitInfo = await getCommitInfo('prisma', prismaCommit.hash)
try {
await sendSlackMessage({
version: prisma2Version,
enginesCommit: enginesCommitInfo,
prismaCommit: prismaCommitInfo,
})
} catch (e) {
console.error(e)
}
if (!process.env.PATCH_BRANCH && !args['--dry-run']) {
try {
await tagEnginesRepo(prisma2Version, enginesCommit, dryRun)
} catch (e) {
console.error(e)
}
}
}
} catch (e) {
if (unlock) {
unlock()
unlock = undefined
}
throw e
} finally {
if (unlock) {
unlock()
unlock = undefined
}
}
}
async function getEnginesCommit(): Promise<string> {
const prisma2Path = path.resolve(process.cwd(), './packages/cli/package.json')
const pkg = JSON.parse(await fs.readFile(prisma2Path, 'utf-8'))
// const engineVersion = pkg.prisma.version
const engineVersion = pkg.dependencies['@prisma/engines']
?.split('.')
.slice(-1)[0]
return engineVersion
}
async function tagEnginesRepo(
prismaVersion: string,
engineVersion: string,
dryRun = false,
) {
console.log(`Going to tag the engines repo dryRun: ${dryRun}`)
/** Get ready */
await cloneOrPull('prisma-engines', dryRun)
/** Get previous tag */
const previousTag = await runResult(
'prisma-engines',
`git describe --tags --abbrev=0`,
)
/** Get commits between previous tag and engines sha1 */
const changelog = await runResult(
'prisma-engines',
`git log ${previousTag}..${engineVersion} --pretty=format:' * %h - %s - by %an' --`,
)
const changelogSanitized = changelog
.replace(/"/gm, '\\"')
.replace(/`/gm, '\\`')
const remotes = dryRun
? []
: (await runResult('prisma-engines', `git remote`)).trim().split('\n')
if (!remotes.includes('origin-push')) {
await run(
'prisma-engines',
`git remote add origin-push https://${process.env.GITHUB_TOKEN}@github.com/prisma/prisma-engines.git`,
dryRun,
true,
)
}
await run(
'.',
`git config --global user.email "prismabots@gmail.com"`,
dryRun,
)
await run('.', `git config --global user.name "prisma-bot"`, dryRun)
/** Tag */
await run(
'prisma-engines',
`git tag -a ${prismaVersion} ${engineVersion} -m "${prismaVersion}" -m "${engineVersion}" -m "${changelogSanitized}"`,
dryRun,
)
/** Push */
await run(`prisma-engines`, `git push origin-push ${prismaVersion}`, dryRun)
}
/**
* Tests packages in "publishOrder"
* @param packages Packages
* @param publishOrder string[][]
*/
async function testPackages(
packages: Packages,
publishOrder: string[][],
): Promise<void> {
let order = flatten(publishOrder)
// If paralelism is set in builkite we split the testing
// Job 0 all but client
// Job 1 only client
if (process.env.BUILDKITE_PARALLEL_JOB === '0') {
console.log(
'BUILDKITE_PARALLEL_JOB === 0 - running all tests excluding client',
)
const index = order.indexOf('@prisma/client')
if (index > -1) {
order.splice(index, 1)
}
} else if (process.env.BUILDKITE_PARALLEL_JOB === '1') {
console.log('BUILDKITE_PARALLEL_JOB === 1 - running client only')
order = ['@prisma/client']
} else if (process.env.BUILDKITE_PARALLEL_JOB === '2') {
// This is to test Node-API
console.log(
'BUILDKITE_PARALLEL_JOB === 2 - running Node API tests for [sdk, migrate, client, cli, integration-tests]',
)
order = [
'@prisma/sdk',
'@prisma/migrate',
'@prisma/client',
'prisma',
'@prisma/integration-tests',
]
}
console.log(chalk.bold(`\nRun ${chalk.cyanBright('tests')}. Testing order:`))
console.log(order)
for (const pkgName of order) {
const pkg = packages[pkgName]
if (pkg.packageJson.scripts.test) {
console.log(`\nTesting ${chalk.magentaBright(pkg.name)}`)
if (process.env.BUILDKITE_PARALLEL_JOB === '2') {
await run(
path.dirname(pkg.path),
'PRISMA_FORCE_NAPI=true pnpm run test',
)
} else {
await run(path.dirname(pkg.path), 'pnpm run test')
}
} else {
console.log(
`\nSkipping ${chalk.magentaBright(pkg.name)}, as it doesn't have tests`,
)
}
}
}
function flatten<T>(arr: T[][]): T[] {
return arr.reduce((acc, val) => acc.concat(val), [])
}
function intersection<T>(arr1: T[], arr2: T[]): T[] {
return arr1.filter((value) => arr2.includes(value))
}
// Parent "version updating function", uses `patch` and `patchVersion`
async function newVersion(pkg: Package, prisma2Version: string) {
const isPrisma2OrPhoton = [
'@prisma/cli',
'prisma',
'@prisma/client',
].includes(pkg.name)
return isPrisma2OrPhoton ? prisma2Version : await patch(pkg)
}
const semverRegex =
/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/
function patchVersion(version: string) {
// Thanks 🙏 to https://github.com/semver/semver/issues/232#issuecomment-405596809
const match = semverRegex.exec(version)
if (match?.groups) {
return `${match.groups.major}.${match.groups.minor}.${
Number(match.groups.patch) + 1
}`
}
return undefined
}
function increaseMinor(version: string) {
const match = semverRegex.exec(version)
if (match?.groups) {
return `${match.groups.major}.${Number(match.groups.minor) + 1}.${
match.groups.patch
}`
}
return undefined
}
async function patch(pkg: Package) {
// if done locally, no need to get the latest version from npm (saves time)
// if done in buildkite, we definitely want to check, if there's a newer version on npm
// in buildkite, saving a few sec is not worth it
if (!process.env.BUILDKITE) {
return patchVersion(pkg.version)
}
const localVersion = pkg.version
if (pkg.name === '@prisma/integration-tests') {
return localVersion
}
const npmVersion = await runResult('.', `npm info ${pkg.name} version`)
const maxVersion = semver.maxSatisfying([localVersion, npmVersion], '*', {
loose: true,
includePrerelease: true,
})
return patchVersion(maxVersion)
}
function filterPublishOrder(
publishOrder: string[][],
packages: string[],
): string[][] {
return publishOrder.reduce<string[][]>((acc, curr) => {
if (Array.isArray(curr)) {
curr = curr.filter((pkg) => !packages.includes(pkg))
if (curr.length > 0) {
acc.push(curr)
}
} else if (!packages.includes(curr)) {
acc.push(curr)
}
return acc
}, [])
}
async function publishPackages(
packages: Packages,
changedPackages: PackagesWithNewVersions,
publishOrder: string[][],