-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrunner.js
654 lines (561 loc) · 19.1 KB
/
runner.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
// loop this runner with
// while true; do node runner.js; done
import fs from "fs";
import child_process from "child_process";
import semver from "semver";
import * as zip from "@zip.js/zip.js";
import dotenv from "dotenv";
import {
CreateMultipartUploadCommand,
UploadPartCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand,
S3Client
} from "@aws-sdk/client-s3";
import prettyMs from "pretty-ms";
const branch = "main";
const commit = child_process.execSync("git rev-parse HEAD").toString().trim();
const commitNumber = child_process
.execSync(`git rev-list --count ${branch}`)
.toString()
.trim();
const release = process.argv.includes("--release");
async function getLatestReleaseVersion() {
const response = await fetch(
"https://api.github.com/repos/fullstackedorg/editor/releases/latest"
);
const { tag_name } = await response.json();
return tag_name;
}
async function getLatestCommit() {
const response = await fetch(
`https://api.github.com/repos/fullstackedorg/editor/git/refs/heads/${branch}`
);
const {
object: { sha }
} = await response.json();
return sha;
}
function pullAndExit() {
console.log(`Pulling and exiting [${new Date().toLocaleString()}]`);
child_process.execSync("git checkout .", { stdio: "inherit" });
child_process.execSync("git pull", { stdio: "inherit" });
child_process.execSync("git submodule update --init --recursive", {
stdio: "inherit"
});
process.exit(0);
}
async function waitForNextCommit() {
console.log(`${new Date().toLocaleString()} - Current commit [${commit}]`);
console.log("Waiting for next commit.");
while (commit === (await getLatestCommit())) {
await new Promise((res) => setTimeout(res, 1000 * 60 * 3)); // 3 min
}
pullAndExit();
}
function notifyError(message, halt = true) {
console.log(`${new Date().toLocaleString()} - ${message}`);
if (halt) {
return waitForNextCommit();
}
}
const currentVersion = JSON.parse(
fs.readFileSync("package.json", { encoding: "utf-8" })
).version;
const latestReleaseVersion = await getLatestReleaseVersion();
const electronDirectory = "platform/electron";
const TEST_AND_BUILD = () => {
// child_process.execSync("docker info", { stdio: "inherit" });
child_process.execSync("npm ci", { stdio: "inherit" });
// child_process.execSync("npm ci", {
// cwd: electronDirectory,
// stdio: "inherit"
// });
// child_process.execSync("npm test", { stdio: "inherit" });
child_process.execSync("make ios-arm64 android macos-static -j8", {
cwd: "core/build",
stdio: "inherit"
});
child_process.execSync("npm run build -- --production", {
stdio: "inherit"
});
};
/////////// node /////////////
const nodeDirectory = "platform/node";
const NODE_BUILD = async () => {
const nodePackageJsonFile = `${nodeDirectory}/package.json`;
const nodePackageJson = JSON.parse(
fs.readFileSync(nodePackageJsonFile, { encoding: "utf-8" })
);
nodePackageJson.version = release
? currentVersion
: currentVersion + "-" + commitNumber;
fs.writeFileSync(
nodePackageJsonFile,
JSON.stringify(nodePackageJson, null, 4)
);
child_process.execSync("npm run build", {
cwd: nodeDirectory,
stdio: "inherit"
});
};
const NODE_DEPLOY = () => {
child_process.execSync(`npm publish${release ? "" : " --tag beta"}`, {
cwd: nodeDirectory,
stdio: "inherit"
});
};
////////////// electron ////////////////
const electronOutDirectory = `${electronDirectory}/out`;
async function zipExe(directory, filename) {
const zipFileStream = new TransformStream();
const zipFileBlobPromise = new Response(zipFileStream.readable).blob();
const data = fs.readFileSync(`${directory}/${filename}`);
const readableStream = new Blob([data]).stream();
const zipWriter = new zip.ZipWriter(zipFileStream.writable);
await zipWriter.add(filename, readableStream);
await zipWriter.close();
const zipBlob = await zipFileBlobPromise;
const zipFileName = filename.split(".").slice(0, -1).join(".") + ".zip";
fs.writeFileSync(
`${directory}/${zipFileName}`,
Buffer.from(await zipBlob.arrayBuffer())
);
}
const ELECTRON_MAKE = (platform) => {
console.log(`Starting Electron Forge make for [${platform}]`);
const makeProcess = child_process.exec(
`npx electron-forge make --arch=x64,arm64 --platform=${platform}`,
{
cwd: electronDirectory
}
);
return new Promise((resolve, reject) => {
let errored = false;
makeProcess.stdout.on("data", (chunk) =>
process.stdout.write(`[${platform}]: ${chunk.toString()}`)
);
makeProcess.stderr.on("data", (chunk) =>
process.stderr.write(`[${platform}]: ${chunk.toString()}`)
);
makeProcess.on("error", (error) => {
console.log(`Failed Electron Forge make for [${platform}]`);
errored = true;
reject(error);
});
makeProcess.on("exit", () => {
if (errored) return;
console.log(`Finished Electron Forge make for [${platform}]`);
resolve();
});
});
};
const ELECTRON_BUILD = async () => {
if (fs.existsSync(electronOutDirectory))
fs.rmSync(electronOutDirectory, { recursive: true, force: true });
const electronPackageJsonFile = `${electronDirectory}/package.json`;
const electronPackageJson = JSON.parse(
fs.readFileSync(electronPackageJsonFile, { encoding: "utf-8" })
);
electronPackageJson.version = currentVersion;
fs.writeFileSync(
electronPackageJsonFile,
JSON.stringify(electronPackageJson, null, 4)
);
child_process.execSync("npm run build", {
cwd: electronDirectory,
stdio: "inherit"
});
await Promise.all(["darwin", "win32", "linux"].map(ELECTRON_MAKE));
return Promise.all([
zipExe(
`${electronDirectory}/out/make/squirrel.windows/arm64`,
`FullStacked-${currentVersion} Setup.exe`
),
zipExe(
`${electronDirectory}/out/make/squirrel.windows/x64`,
`FullStacked-${currentVersion} Setup.exe`
)
]);
};
const releaseFileNames = [
{
file: `zip/darwin/arm64/FullStacked-darwin-arm64-${currentVersion}.zip`,
key: `fullstacked-${currentVersion}-darwin-arm64.zip`
},
{
file: `zip/darwin/x64/FullStacked-darwin-x64-${currentVersion}.zip`,
key: `fullstacked-${currentVersion}-darwin-x64.zip`
},
{
file: `squirrel.windows/arm64/FullStacked-${currentVersion} Setup.zip`,
key: `fullstacked-${currentVersion}-win32-arm64.zip`
},
{
file: `squirrel.windows/x64/FullStacked-${currentVersion} Setup.zip`,
key: `fullstacked-${currentVersion}-win32-x64.zip`
},
{
file: `deb/arm64/fullstacked_${currentVersion}_arm64.deb`,
key: `fullstacked-${currentVersion}-linux-arm64.deb`
},
{
file: `deb/x64/fullstacked_${currentVersion}_amd64.deb`,
key: `fullstacked-${currentVersion}-linux-x64.deb`
},
{
file: `rpm/arm64/FullStacked-${currentVersion}-1.arm64.rpm`,
key: `fullstacked-${currentVersion}-linux-arm64.rpm`
},
{
file: `rpm/x64/FullStacked-${currentVersion}-1.x86_64.rpm`,
key: `fullstacked-${currentVersion}-linux-x64.rpm`
}
];
const electronMakeDirectory = `${electronOutDirectory}/make`;
// const cloudflareKeys = dotenv.parse(
// fs.readFileSync(`${electronDirectory}/CLOUDFLARE.env`)
// );
// const Bucket = cloudflareKeys.BUCKET;
const tenMB = 10 * 1024 * 1024;
const UPLOAD = async ({ file, key }) => {
const s3Client = new S3Client({
region: "auto",
endpoint: `https://${cloudflareKeys.ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: cloudflareKeys.ACCESS_KEY_ID,
secretAccessKey: cloudflareKeys.SECRET_ACCESS_KEY
},
maxAttempts: 10,
retryMode: "standard"
});
const Key = `releases/${currentVersion}/${key}`;
const filePath = `${electronMakeDirectory}/${file}`;
console.log(`Uploading [${filePath}] to Bucket: [${Bucket}] Key: [${Key}]`);
const buffer = fs.readFileSync(filePath);
let UploadId;
try {
const multipartUpload = await s3Client.send(
new CreateMultipartUploadCommand({ Bucket, Key })
);
UploadId = multipartUpload.UploadId;
const partsCount = Math.ceil(buffer.byteLength / tenMB);
const uploadResults = [];
for (let i = 0; i < partsCount; i++) {
const start = i * tenMB;
const end = start + tenMB;
uploadResults.push(
await s3Client
.send(
new UploadPartCommand({
Bucket,
Key,
UploadId,
Body: buffer.subarray(start, end),
PartNumber: i + 1
})
)
.then((d) => {
console.log(
`Uploaded ${uploadResults.length + 1}/${partsCount} for [${key}]`
);
return d;
})
);
}
await s3Client.send(
new CompleteMultipartUploadCommand({
Bucket,
Key,
UploadId,
MultipartUpload: {
Parts: uploadResults.map(({ ETag }, i) => ({
ETag,
PartNumber: i + 1
}))
}
})
);
console.log(`Uploaded [${Key}]`);
} catch (err) {
if (UploadId) {
const abortCommand = new AbortMultipartUploadCommand({
Bucket,
Key,
UploadId
});
await s3Client.send(abortCommand);
}
throw err;
}
};
const tryUploadingUntilSuccess = async (item) => {
let tries = 0,
success = false;
while (!success) {
tries++;
try {
console.log(`Trying to upload [${item.key}] try ${tries}.`);
await UPLOAD(item);
success = true;
} catch (e) {
console.error(e);
}
}
console.log(`Managed to upload [${item.key}] after ${tries} try.`);
};
const ELECTRON_DEPLOY = async () => {
return Promise.all(releaseFileNames.map(tryUploadingUntilSuccess));
};
/////////////// apple /////////////////
const appleDirectory = "platform/apple";
const archivePathiOS = `${process.cwd()}/${appleDirectory}/FullStacked-iOS.xcarchive`;
const pkgDirectoryiOS = `${process.cwd()}/${appleDirectory}/pkg-ios`;
const archivePathMacOS = `${process.cwd()}/${appleDirectory}/FullStacked-MacOS.xcarchive`;
const pkgDirectoryMacOS = `${process.cwd()}/${appleDirectory}/pkg-macos`;
const appleKeys = dotenv.parse(
fs.readFileSync(`${appleDirectory}/APPLE_KEYS.env`)
);
const APPLE_BUILD = () => {
// child_process.execSync("make ios", {
// cwd: `${iosDirectory}/esbuild`,
// stdio: "inherit"
// });
const xcodeFile = `${appleDirectory}/FullStacked.xcodeproj/project.pbxproj`;
const xcodeFileContent = fs.readFileSync(xcodeFile, { encoding: "utf-8" });
const xcodeFileUpdated = xcodeFileContent
.replace(
/MARKETING_VERSION = .*?;/g,
`MARKETING_VERSION = ${currentVersion};`
)
.replace(
/CURRENT_PROJECT_VERSION = .*?;/g,
`CURRENT_PROJECT_VERSION = ${commitNumber};`
);
fs.writeFileSync(xcodeFile, xcodeFileUpdated);
[
archivePathiOS,
pkgDirectoryiOS,
archivePathMacOS,
pkgDirectoryMacOS
].forEach((d) => {
if (fs.existsSync(d)) fs.rmSync(d, { recursive: true, force: true });
});
child_process.execSync(
`xcodebuild -project ${appleDirectory}/FullStacked.xcodeproj -scheme FullStacked-iOS -sdk iphoneos -configuration Release clean`,
{
stdio: "inherit"
}
);
child_process.execSync(
`xcodebuild -project ${appleDirectory}/FullStacked.xcodeproj -scheme FullStacked-iOS -sdk iphoneos -configuration Release archive -archivePath ${archivePathiOS}`,
{
stdio: "inherit"
}
);
child_process.execSync(
`xcodebuild -exportArchive -archivePath ${archivePathiOS} -exportOptionsPlist ${process.cwd()}/${appleDirectory}/exportOptions.plist -exportPath ${pkgDirectoryiOS} -allowProvisioningUpdates`,
{
stdio: "inherit"
}
);
child_process.execSync(
`xcodebuild -project ${appleDirectory}/FullStacked.xcodeproj -scheme FullStacked-MacOS -sdk macosx -configuration Release clean`,
{
stdio: "inherit"
}
);
child_process.execSync(
`xcodebuild -project ${appleDirectory}/FullStacked.xcodeproj -scheme FullStacked-MacOS -sdk macosx -configuration Release archive -archivePath ${archivePathMacOS}`,
{
stdio: "inherit"
}
);
child_process.execSync(
`xcodebuild -exportArchive -archivePath ${archivePathMacOS} -exportOptionsPlist ${process.cwd()}/${appleDirectory}/exportOptions.plist -exportPath ${pkgDirectoryMacOS} -allowProvisioningUpdates`,
{
stdio: "inherit"
}
);
};
const APPLE_DEPLOY = () => {
child_process.execSync(
`xcrun altool --upload-app --file ${pkgDirectoryiOS}/FullStacked.ipa -t ios --apiKey ${appleKeys.APPLE_API_KEY_ID} --apiIssuer ${appleKeys.APPLE_API_ISSUER} --show-progress`,
{
stdio: "inherit",
env: {
API_PRIVATE_KEYS_DIR: appleKeys.APPLE_API_KEY_DIRECTORY
}
}
);
child_process.execSync(
`xcrun altool --upload-app --file ${pkgDirectoryMacOS}/FullStacked.pkg -t macosx --apiKey ${appleKeys.APPLE_API_KEY_ID} --apiIssuer ${appleKeys.APPLE_API_ISSUER} --show-progress`,
{
stdio: "inherit",
env: {
API_PRIVATE_KEYS_DIR: appleKeys.APPLE_API_KEY_DIRECTORY
}
}
);
};
///////////// android //////////////
const androidDirectory = "platform/android";
const androidKeys = dotenv.parse(
fs.readFileSync(`${androidDirectory}/ANDROID_KEYS.env`)
);
const aabFile = `${process.cwd()}/${androidDirectory}/studio/app/build/outputs/bundle/release/app-release.aab`;
const ANDROID_BUILD = () => {
// child_process.execSync("make android", {
// cwd: `${androidDirectory}/esbuild`,
// stdio: "inherit"
// });
const gradleFile = `${androidDirectory}/studio/app/build.gradle.kts`;
const gradleFileContent = fs.readFileSync(gradleFile, {
encoding: "utf-8"
});
const gradleFileUpdated = gradleFileContent
.replace(/versionName = ".*?"/g, `versionName = "${currentVersion}"`)
.replace(/versionCode = .*?\n/g, `versionCode = ${commitNumber}\n`);
fs.writeFileSync(gradleFile, gradleFileUpdated);
child_process.execSync("./gradlew bundleRelease", {
cwd: `${androidDirectory}/studio`,
stdio: "inherit"
});
child_process.execSync(
`jarsigner -keystore ${androidKeys.FILE} -storepass ${androidKeys.PASSPHRASE} ${aabFile} ${androidKeys.KEY}`,
{
cwd: `${androidDirectory}/studio`,
stdio: "inherit"
}
);
};
const ANDROID_DEPLOY = () => {
child_process.execSync(
`python upload.py org.fullstacked.editor ${aabFile} ${currentVersion}`,
{
stdio: "inherit",
cwd: androidDirectory
}
);
};
///////////// docker ///////////////
const dockerDirectory = "platform/docker";
const DOCKER_BUILD = () => {
child_process.execSync(`npm ci`, {
stdio: "inherit",
cwd: "lib/puppeteer-stream"
});
child_process.execSync(
`node build --image ${release ? "latest" : "beta"}`,
{
stdio: "inherit",
cwd: dockerDirectory
}
);
};
const DOCKER_DEPLOY = () => {
child_process.execSync(
`docker push fullstackedorg/editor:${release ? "latest" : "beta"}`,
{
stdio: "inherit"
}
);
};
async function run() {
const start = new Date();
if (!release && semver.lte(currentVersion, latestReleaseVersion)) {
await notifyError(
`Trying to run same or older version. Current [${currentVersion}] | Latest [${latestReleaseVersion}]`
);
}
/////// BUILD AND TESTS ////////
let tries = 5;
while (tries) {
try {
TEST_AND_BUILD();
break;
} catch (e) {
notifyError("Failed build and test", false);
}
tries--;
}
if (tries === 0) {
await notifyError("Failed 5 times to run build and test.");
}
///////// BUILD PLATFORMS ////////
// try {
// await NODE_BUILD();
// } catch (e) {
// console.error(e);
// await notifyError("Failed to build for node");
// }
if (!release) {
// try {
// await ELECTRON_BUILD();
// } catch (e) {
// console.error(e);
// await notifyError("Failed to build for electron");
// }
try {
APPLE_BUILD();
} catch (e) {
console.error(e);
await notifyError("Failed to build for ios");
}
try {
ANDROID_BUILD();
} catch (e) {
console.error(e);
await notifyError("Failed to build for android");
}
}
// try {
// DOCKER_BUILD();
// } catch (e) {
// console.error(e);
// await notifyError("Failed to build for docker");
// }
///////// DEPLOY PLATFORMS ////////
// try {
// NODE_DEPLOY();
// } catch (e) {
// console.error(e);
// notifyError("Failed to deploy for node", false);
// }
if (!release) {
// try {
// await ELECTRON_DEPLOY();
// } catch (e) {
// console.error(e);
// notifyError("Failed to deploy for electron", false);
// }
try {
APPLE_DEPLOY();
} catch (e) {
console.error(e);
notifyError("Failed to deploy for ios", false);
}
try {
ANDROID_DEPLOY();
} catch (e) {
console.error(e);
notifyError("Failed to deploy for android", false);
}
}
// try {
// DOCKER_DEPLOY();
// } catch (e) {
// console.error(e);
// notifyError("Failed to deploy for docker", false);
// }
const end = new Date();
console.log(
`${release ? "Released" : "Prereleased"} ${currentVersion} (${commitNumber}) - ${commit.slice(0, 8)} (${branch})`
);
console.log("----------------");
console.log(`Started at ${start.toLocaleString()}`);
console.log(`Ended at ${end.toLocaleString()}`);
console.log(`Took ${prettyMs(end.getTime() - start.getTime())}`);
setTimeout(waitForNextCommit, 1000 * 60 * 5); // 5 min
}
run();