-
Notifications
You must be signed in to change notification settings - Fork 28
/
gulpfile.mjs
642 lines (548 loc) · 15.1 KB
/
gulpfile.mjs
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
import assert from "node:assert/strict";
import child_process from "node:child_process";
import fs from "node:fs/promises";
import path from "node:path";
import stream from "node:stream";
import innoSetup from "@quanle94/innosetup";
import { sync as commandExistsSync } from "command-exists";
import cordovaPkg from "cordova-lib";
import { glob } from "glob";
import gulp from "gulp";
import deb from "gulp-debian";
import jeditor from "gulp-json-editor";
import rename from "gulp-rename";
import replace from "gulp-replace";
import logger from "gulplog";
import minimist from "minimist";
import nwbuild from "nw-builder";
import buildRpm from "rpm-builder";
import source from "vinyl-source-stream";
import * as vite from "vite";
import pkg from "./package.json" with { type: "json" };
// Replace dev mode paths
pkg.main = "src/main.html";
pkg.window.icon = "images/rf_icon.png";
delete pkg["node-remote"];
const { cordova } = cordovaPkg;
const argv = minimist(process.argv.slice(2));
const BUNDLE_DIR = "./bundle";
const APP_DIR = "./app";
const REDIST_DIR = "./redist";
const LINUX_INSTALL_DIR = "/opt/rotorflight";
const NWJS_CACHE_DIR = "nwjs_cache";
const NWJS_VERSION = "0.89.0";
const NWJS_ARCH = {
x86: "ia32",
x86_64: "x64",
arm64: "arm64",
};
const context = {};
parseArgs();
export const app = build_app();
export const bundle = build_bundle();
export const redist = build_redist();
export const dev_client = run_dev_client();
export const debug = run_debug();
function clean_app() {
return fs.rm(APP_DIR, { recursive: true, force: true });
}
function clean_bundle() {
return fs.rm(BUNDLE_DIR, { recursive: true, force: true });
}
function clean_redist() {
return fs.rm(REDIST_DIR, { recursive: true, force: true });
}
function build_bundle() {
return gulp.series(clean_bundle, bundle_vite, bundle_src, bundle_deps);
}
function bundle_vite() {
const backend = context.target.platform === "android" ? "cordova" : "nwjs";
return vite.build({ define: { __BACKEND__: JSON.stringify(backend) } });
}
function bundle_src() {
const distSources = ["./src/tabs/*", "!./src/tabs/receiver_msp.html"];
const packageJson = new stream.Readable();
packageJson.push(JSON.stringify(pkg, undefined, 2));
packageJson.push(null);
return packageJson
.pipe(source("package.json"))
.pipe(gulp.src(distSources, { base: "." }))
.pipe(gulp.src("pnpm-lock.yaml"))
.pipe(gulp.dest(BUNDLE_DIR));
}
function bundle_deps() {
return new Promise((resolve, reject) =>
child_process.exec(
"pnpm install --prod --frozen-lockfile",
{ cwd: BUNDLE_DIR },
(err) => (err ? reject(err) : resolve()),
),
);
}
function helper_build_app_cordova() {
context.appdir = `${APP_DIR}/${context.target.platform}`;
return gulp.series(
build_bundle(),
cordova_copy_www,
cordova_resources,
cordova_include_www,
cordova_copy_src,
cordova_rename_src_config,
cordova_rename_src_package,
cordova_packagejson,
cordova_configxml,
cordova_deps,
cordova_build,
);
}
function build_app() {
const app_helper =
context.target.platform === "android"
? helper_build_app_cordova
: helper_build_app_nwjs;
return gulp.series(clean_app, app_helper());
}
function helper_build_app_nwjs() {
const tasks = [build_bundle(), build_app_nwjs];
switch (context.target.platform) {
case "linux":
tasks.push(build_nwjs_unix_permissions);
tasks.push(build_nwjs_linux_assets);
break;
case "osx":
tasks.push(build_nwjs_unix_permissions);
break;
}
return gulp.series(tasks);
}
function build_app_nwjs() {
const { platform, arch, flavor } = context.target;
context.appdir = `${APP_DIR}/${platform}_${arch}`;
const platformOpts = {
osx: {
icon: "./src/images/rf_icon.icns",
CFBundleDisplayName: "Rotorflight Configurator",
},
win: {
icon: "./src/images/rf_icon.ico",
},
};
return nwbuild({
platform,
arch: NWJS_ARCH[arch],
outDir: context.appdir,
flavor: flavor === "debug" ? "sdk" : "normal",
app: platformOpts[platform],
version: NWJS_VERSION,
cacheDir: NWJS_CACHE_DIR,
glob: false,
srcDir: BUNDLE_DIR,
});
}
function build_nwjs_linux_assets() {
return gulp.src("assets/linux/**").pipe(gulp.dest(context.appdir));
}
/**
* Nw.js archives do not have any permissions set for group and other.
* Apply the correct permissions.
*/
async function build_nwjs_unix_permissions() {
const ignore = [
// bundle - linux
`${context.appdir}/package.nw/**/*`,
// bundle - osx
`${context.appdir}/${pkg.name}.app/Contents/Resources/app.nw/**/*`,
];
const dirs = await glob(`${context.appdir}/**/*/`, { ignore });
for (const dir of dirs) {
await fs.chmod(dir, 0o755);
}
const files = await glob(`${context.appdir}/**/*`, { nodir: true, ignore });
for (const file of files) {
let mode = 0o644;
const stats = await fs.stat(file);
if (stats.mode & fs.constants.S_IXUSR) {
mode |=
fs.constants.S_IXUSR | fs.constants.S_IXGRP | fs.constants.S_IXOTH;
}
await fs.chmod(file, mode);
}
}
function build_redist() {
return gulp.series(
clean_redist,
build_app(),
mkdir_redist,
helper_build_redist(),
);
}
function mkdir_redist() {
return fs.mkdir(REDIST_DIR, { recursive: true });
}
function helper_build_redist() {
switch (context.target.platform) {
case "linux":
return build_redist_linux();
case "osx":
return build_redist_osx;
case "win":
return build_redist_win;
case "android":
return build_redist_apk;
default:
return nop;
}
}
function build_redist_linux() {
return gulp.parallel(build_redist_tar_xz, build_redist_deb, build_redist_rpm);
}
function build_redist_tar_xz() {
const { platform, arch } = context.target;
const filename = `${pkg.name}_${pkg.version}_${platform}_${arch}.tar.xz`;
const output = `${path.relative(context.appdir, REDIST_DIR)}/${filename}`;
const command = `tar -cJf '${output}' --transform 's|^\./|rotorflight-configurator/|' .`;
return new Promise((resolve, reject) =>
child_process.exec(command, { cwd: context.appdir }, (err) =>
err ? reject(err) : resolve(),
),
);
}
function build_redist_deb(done) {
const { arch } = context.target;
if (!commandExistsSync("dpkg-deb")) {
logger.warn(
`dpkg-deb command not found, not generating deb package for ${arch}`,
);
done();
return;
}
const archmap = {
x86: "i386",
x86_64: "amd64",
arm64: "arm64",
};
return gulp.src([`${context.appdir}/*`]).pipe(
deb({
package: pkg.name,
version: pkg.version,
section: "base",
priority: "optional",
architecture: archmap[arch],
maintainer: pkg.author,
description: pkg.description,
preinst: [`rm -rf ${LINUX_INSTALL_DIR}/${pkg.name}`],
postinst: [
`chown root:root ${LINUX_INSTALL_DIR}`,
`chown -R root:root ${LINUX_INSTALL_DIR}/${pkg.name}`,
`xdg-desktop-menu install ${LINUX_INSTALL_DIR}/${pkg.name}/${pkg.name}.desktop`,
],
prerm: [`xdg-desktop-menu uninstall ${pkg.name}.desktop`],
changelog: [],
_target: `${LINUX_INSTALL_DIR}/${pkg.name}`,
_out: REDIST_DIR,
_copyright: "assets/linux/copyright",
_clean: true,
}),
);
}
async function build_redist_rpm() {
const { arch } = context.target;
if (!commandExistsSync("rpmbuild")) {
console.warn(
`rpmbuild command not found, not generating rpm package for ${arch}`,
);
return;
}
const regex = /-/g;
const archmap = {
x86: "i386",
x86_64: "x86_64",
arm64: "aarch64",
};
const options = {
name: pkg.name,
version: pkg.version.replace(regex, "_"), // RPM does not like release candidate versions
buildArch: archmap[arch],
vendor: pkg.author,
summary: pkg.description,
license: "GNU General Public License v3.0",
prefix: "/opt",
files: [
{
cwd: context.appdir,
src: "*",
dest: `${LINUX_INSTALL_DIR}/${pkg.name}`,
},
],
postInstallScript: [
`xdg-desktop-menu install ${LINUX_INSTALL_DIR}/${pkg.name}/${pkg.name}.desktop`,
],
preUninstallScript: [`xdg-desktop-menu uninstall ${pkg.name}.desktop`],
tempDir: `${REDIST_DIR}/tmp-rpm-build-${arch}`,
keepTemp: false,
verbose: false,
rpmDest: REDIST_DIR,
execOpts: { maxBuffer: 1024 * 1024 * 16 },
};
await new Promise((resolve, reject) =>
buildRpm(options, (err) => (err ? reject(err) : resolve())),
);
}
async function build_redist_osx() {
const appdmg = (await import("appdmg")).default;
const targetPath = `${REDIST_DIR}/${pkg.name}_${pkg.version}_macOS.dmg`;
await new Promise((resolve, reject) => {
const builder = appdmg({
target: targetPath,
basepath: context.appdir,
specification: {
title: "Rotorflight Configurator",
contents: [
{ x: 448, y: 342, type: "link", path: "/Applications" },
{
x: 192,
y: 344,
type: "file",
path: `${pkg.name}.app`,
name: "Rotorflight Configurator.app",
},
],
background: `${import.meta.dirname}/assets/osx/dmg-background.png`,
format: "UDZO",
window: {
size: {
width: 638,
height: 479,
},
},
},
});
builder.on("progress", (info) =>
logger.info(
info.current +
"/" +
info.total +
" " +
info.type +
" " +
(info.title || info.status),
),
);
builder.on("error", reject);
builder.on("finish", resolve);
});
}
function build_redist_win() {
const { arch } = context.target;
const parameters = [
// Extra parameters to replace inside the iss file
`/Dversion=${pkg.version}`,
`/DarchName=${arch}`,
`/DarchAllowed=${arch === "win32" ? "x86 x64" : "x64"}`,
`/DarchInstallIn64bit=${arch === "ia32" ? "" : "x64"}`,
`/DsourceFolder=${context.appdir}`,
`/DtargetFolder=${REDIST_DIR}`,
// Show only errors in console
"/Q",
// Script file to execute
"assets/windows/installer.iss",
];
return new Promise((resolve, reject) =>
innoSetup(parameters, {}, (err) => (err ? reject(err) : resolve())),
);
}
function run_dev_client() {
switch (context.target.platform) {
case "android":
return () => Promie.reject(Error("android dev client not supported"));
case "linux":
case "osx":
case "win":
return run_nwjs_dev_client;
}
}
function run_debug() {
context.target.flavor = "debug";
const tasks = [build_app()];
switch (context.target.platform) {
case "android":
tasks.push(run_debug_cordova);
case "linux":
case "osx":
case "win":
tasks.push(run_debug_nwjs);
}
return gulp.series(...tasks);
}
function run_debug_nwjs() {
const exe = getNwjsExePath(context.target.platform);
return new Promise((resolve, reject) =>
child_process.execFile(`${context.appdir}/${exe}`, (err) =>
err ? reject(err) : resolve(),
),
);
}
function getNwjsExePath(platform) {
switch (platform) {
case "linux":
return pkg.name;
case "win":
return `${pkg.name}.exe`;
case "osx":
return `${pkg.name}.app/Contents/MacOS/nwjs`;
default:
throw new Error(`Unsupported NW.js platform: ${platform}`);
}
}
function run_nwjs_dev_client() {
const { platform, arch } = context.target;
return nwbuild({
mode: "run",
platform,
arch: NWJS_ARCH[arch],
flavor: "sdk",
version: NWJS_VERSION,
cacheDir: NWJS_CACHE_DIR,
glob: false,
srcDir: ".",
});
}
function run_debug_cordova() {
return cordova.run();
}
function cordova_copy_www() {
return gulp
.src(`${BUNDLE_DIR}/**`, { base: BUNDLE_DIR, follow: true })
.pipe(gulp.dest(`${context.appdir}/www/`));
}
function cordova_resources() {
return gulp
.src("assets/android/**")
.pipe(gulp.dest(`${context.appdir}/resources/android/`));
}
function cordova_include_www() {
return gulp
.src(`${context.appdir}/www/src/main.html`)
.pipe(
replace(
"<!-- CORDOVA_INCLUDE cordova.js -->",
'<script type="text/javascript" src="/cordova.js"></script>',
),
)
.pipe(gulp.dest(`${context.appdir}/www/src/`));
}
function cordova_copy_src() {
return gulp
.src([
`cordova/**`,
`!cordova/config_template.xml`,
`!cordova/package_template.json`,
])
.pipe(gulp.dest(context.appdir));
}
function cordova_rename_src_config() {
return gulp
.src("cordova/config_template.xml")
.pipe(rename("config.xml"))
.pipe(gulp.dest(context.appdir));
}
function cordova_rename_src_package() {
return gulp
.src("cordova/package_template.json")
.pipe(rename("package.json"))
.pipe(gulp.dest(context.appdir));
}
function cordova_packagejson() {
return gulp
.src(`${context.appdir}/package.json`)
.pipe(
jeditor({
name: pkg.name,
description: pkg.description,
version: pkg.version,
author: pkg.author,
license: pkg.license,
}),
)
.pipe(gulp.dest(context.appdir));
}
function cordova_configxml() {
return gulp
.src([`${context.appdir}/config.xml`])
.pipe(replace("{{name}}", pkg.productName))
.pipe(replace("{{description}}", pkg.description))
.pipe(replace("{{author}}", pkg.author))
.pipe(replace("{{version}}", pkg.version))
.pipe(gulp.dest(context.appdir));
}
function cordova_deps() {
return new Promise((resolve, reject) =>
child_process.exec(
"pnpm install --prod --frozen-lockfile",
{ cwd: context.appdir },
(err) => (err ? reject(err) : resolve()),
),
);
}
async function cordova_build() {
const cwd = process.cwd();
process.chdir(context.appdir);
try {
await cordova.platform("add", ["android"]);
await cordova.build({
platforms: ["android"],
options: {
release: context.target.flavor !== "debug",
buildConfig: "build.json",
},
});
} finally {
process.chdir(cwd);
}
}
function build_redist_apk() {
const { flavor } = context.target;
const filename = `${pkg.name}_${pkg.version}_android.apk`;
return gulp
.src(
`${context.appdir}/platforms/android/app/build/outputs/apk/${flavor}/app-${flavor}.apk`,
)
.pipe(rename(filename))
.pipe(gulp.dest(REDIST_DIR));
}
function parseArgs() {
const platforms = ["linux", "osx", "win", "android"];
const arches = ["x86", "x86_64", "arm64"];
const target = {
platform: argv.platform ?? getHostPlatform(),
arch: argv.arch ?? getHostArch(),
flavor: argv.debug ? "debug" : "release",
};
if (target.platform) {
assert(
platforms.includes(target.platform),
`unsupported platform: ${target.platform}`,
);
if (target.platform === "android") {
target.arch = null;
} else {
assert(arches.includes(target.arch), `unsupported arch: ${target.arch}`);
}
}
context.target = target;
}
function getHostPlatform() {
return {
linux: "linux",
darwin: "osx",
win32: "win",
}[process.platform];
}
function getHostArch() {
return {
x64: "x86_64",
arm64: "arm64",
ia32: "x86",
}[process.arch];
}
async function nop() {}