-
Notifications
You must be signed in to change notification settings - Fork 1
/
shared.ts
1048 lines (867 loc) · 32.8 KB
/
shared.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 { exec } from '@actions/exec'
import * as core from '@actions/core'
import * as github from '@actions/github'
import * as tc from '@actions/tool-cache'
import * as io from "@actions/io"
import * as glob from "@actions/glob"
import path from 'path'
import fs from 'fs'
import * as taskcluster from "taskcluster-client"
import YAML from 'yaml'
import * as tmp from 'tmp'
import crypto from "crypto"
import { Security, downloadAppleWWDRCA } from './security'
// export const WINDOWS_SIGNING_HASH_ALGORITHM = "sha256"
export const RFC3161_URL = "http://ts.ssl.com"
const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(() => resolve(), ms));
export function tmpDir() {
const dir = process.env["RUNNER_TEMP"]
if (dir == null || dir.trim() == '') {
throw new Error("RUNNER_TEMP was not defined")
}
return dir
}
export function divvunConfigDir() {
return path.resolve(tmpDir(), "divvun-ci-config")
}
export function shouldDeploy() {
return github.context.ref === 'refs/heads/master'
}
// Generates a random string of 64 characters in length (48 bytes converted to base64)
export function randomString64() {
// Replace slashes just in case bad things in the terminal
return crypto.randomBytes(48).toString("base64")
}
export function randomHexBytes(count: number) {
return crypto.randomBytes(count).toString("hex")
}
export const DIVVUN_PFX = `${divvunConfigDir()}\\enc\\creds\\windows\\divvun.pfx`
let loadedSecrets: any = null
export async function secrets() {
if (loadedSecrets != null) {
return loadedSecrets
}
const secretService = new taskcluster.Secrets({
rootUrl: process.env.TASKCLUSTER_PROXY_URL
});
const secrets = await secretService.get("divvun");
loadedSecrets = secrets.secret
return loadedSecrets
}
function env() {
let langs = {
LANG: "C.UTF-8",
LC_ALL: "C.UTF-8",
}
if (process.platform === "darwin") {
langs.LANG = "en_US.UTF-8"
langs.LC_ALL = "en_US.UTF-8"
}
return {
...process.env,
...langs,
DEBIAN_FRONTEND: "noninteractive",
DEBCONF_NONINTERACTIVE_SEEN: "true",
PYTHONUTF8: "1",
}
}
function assertExit0(code: number) {
if (code !== 0) {
core.setFailed(`Process exited with exit code ${code}.`)
}
}
export class Apt {
static async update(requiresSudo: boolean) {
if (requiresSudo) {
assertExit0(await exec("sudo", ["apt-get", "-qy", "update"], { env: env() }))
} else {
assertExit0(await exec("apt-get", ["-qy", "update"], { env: env() }))
}
}
static async install(packages: string[], requiresSudo: boolean) {
if (requiresSudo) {
assertExit0(await exec("sudo", ["apt-get", "install", "-qfy", ...packages], { env: env() }))
} else {
assertExit0(await exec("apt-get", ["install", "-qfy", ...packages], { env: env() }))
}
}
}
export class Pip {
static async install(packages: string[]) {
assertExit0(await exec("pip3", ["install", "--user", ...packages], { env: env() }))
core.addPath(path.join(process.env.HOME!, ".local", "bin"))
}
}
export class Pipx {
static async ensurepath() {
assertExit0(await exec("pipx", ["ensurepath"], { env: env() }))
}
static async install(packages: string[]) {
assertExit0(await exec("pipx", ["install", ...packages], { env: env() }))
}
}
export class Powershell {
static async runScript(script: string, opts: {
cwd?: string,
env?: { [key: string]: string }
} = {}) {
const thisEnv = Object.assign({}, env(), opts.env)
const out: string[] = []
const err: string[] = []
const listeners = {
stdout: (data: Buffer) => {
out.push(data.toString())
},
stderr: (data: Buffer) => {
err.push(data.toString())
}
}
assertExit0(await exec("pwsh", ["-c", script], { env: thisEnv, cwd: opts.cwd, listeners }))
return [out.join(""), err.join("")]
}
}
export class DefaultShell {
static async runScript(script: string, args: {
sudo?: boolean,
cwd?: string,
env?: { [key: string]: string }
} = {}) {
if (process.platform === "win32") {
return await Powershell.runScript(script, args)
} else {
return await Bash.runScript(script, args)
}
}
}
export class Bash {
static async runScript(script: string, args: {
sudo?: boolean,
cwd?: string,
env?: { [key: string]: string }
} = {}) {
const thisEnv = Object.assign({}, env(), args.env)
const out: string[] = []
const err: string[] = []
const listeners = {
stdout: (data: Buffer) => {
out.push(data.toString())
},
stderr: (data: Buffer) => {
err.push(data.toString())
}
}
if (args.sudo) {
assertExit0(await exec("sudo", ["bash", "-c", script], { env: thisEnv, cwd: args.cwd, listeners }))
} else {
assertExit0(await exec("bash", ["-c", script], { env: thisEnv, cwd: args.cwd, listeners }))
}
return [out.join(""), err.join("")]
}
}
export class Tar {
static URL_XZ_WINDOWS = "https://tukaani.org/xz/xz-5.2.5-windows.zip"
static async bootstrap() {
if (process.platform !== "win32") {
return
}
const outputPath = path.join(tmpDir(), "xz", "bin_x86-64")
if (fs.existsSync(path.join(outputPath, "xz.exe"))) {
return
}
core.debug("Attempt to download xz tools")
const xzToolsZip = await tc.downloadTool(Tar.URL_XZ_WINDOWS)
await tc.extractZip(xzToolsZip, path.join(tmpDir(), "xz"))
core.addPath(outputPath)
}
static async extractTxz(filePath: string, outputDir?: string) {
const platform = process.platform
if (platform === "linux") {
return await tc.extractTar(filePath, outputDir || tmpDir(), "Jx")
} else if (platform === "darwin") {
return await tc.extractTar(filePath, outputDir || tmpDir())
} else if (platform === "win32") {
// Windows kinda can't deal with no xz.
await Tar.bootstrap()
// Now we unxz it
core.debug("Attempt to unxz")
await exec("xz", ["-d", filePath])
core.debug("Attempted to extract tarball")
return await tc.extractTar(`${path.dirname(filePath)}\\${path.basename(filePath, ".txz")}.tar`, outputDir || tmpDir())
} else {
throw new Error(`Unsupported platform: ${platform}`)
}
}
static async createFlatTxz(paths: string[], outputPath: string) {
const tmpDir = tmp.dirSync()
const stagingDir = path.join(tmpDir.name, "staging")
fs.mkdirSync(stagingDir)
core.debug(`Created tmp dir: ${tmpDir.name}`)
for (const p of paths) {
core.debug(`Copying ${p} into ${stagingDir}`)
await io.cp(p, stagingDir, { recursive: true })
}
core.debug(`Tarring`)
await Bash.runScript(`tar cf ../file.tar *`, { cwd: stagingDir })
core.debug("xz -9'ing")
await Bash.runScript(`xz -9 ../file.tar`, { cwd: stagingDir })
core.debug("Copying file.tar.xz to " + outputPath)
await io.cp(path.join(tmpDir.name, "file.tar.xz"), outputPath)
}
}
export enum RebootSpec { Install = "install", Uninstall = "uninstall", Update = "update" }
export enum WindowsExecutableKind { Inno = "inno", Nsis = "nsis", Msi = "msi" }
export class PahkatPrefix {
static URL_LINUX = "https://pahkat.uit.no/devtools/download/pahkat-prefix-cli?platform=linux&channel=nightly"
static URL_MACOS = "https://pahkat.uit.no/devtools/download/pahkat-prefix-cli?platform=macos&channel=nightly"
static URL_WINDOWS = "https://pahkat.uit.no/devtools/download/pahkat-prefix-cli?platform=windows&channel=nightly"
static get path(): string {
return path.join(tmpDir(), "pahkat-prefix")
}
static async bootstrap() {
const platform = process.platform
let txz
if (platform === "linux") {
txz = await tc.downloadTool(PahkatPrefix.URL_LINUX)
} else if (platform === "darwin") {
txz = await tc.downloadTool(PahkatPrefix.URL_MACOS)
} else if (platform === "win32") {
// Now we can download things
txz = await tc.downloadTool(PahkatPrefix.URL_WINDOWS,
path.join(tmpDir(), "pahkat-dl.txz"))
} else {
throw new Error(`Unsupported platform: ${platform}`)
}
// Extract the file
const outputPath = await Tar.extractTxz(txz)
const binPath = path.resolve(outputPath, "bin")
console.log(`Bin path: ${binPath}, platform: ${process.platform}`)
core.addPath(binPath)
// Init the repo
if (fs.existsSync(PahkatPrefix.path)) {
core.debug(`${PahkatPrefix.path} exists; deleting first.`)
fs.rmdirSync(PahkatPrefix.path, { recursive: true })
}
await DefaultShell.runScript(`pahkat-prefix init -c ${PahkatPrefix.path}`)
}
static async addRepo(url: string, channel?: string) {
if (channel != null) {
await DefaultShell.runScript(`pahkat-prefix config repo add -c ${PahkatPrefix.path} ${url} ${channel}`)
} else {
await DefaultShell.runScript(`pahkat-prefix config repo add -c ${PahkatPrefix.path} ${url}`)
}
}
static async install(packages: string[]) {
await DefaultShell.runScript(`pahkat-prefix install ${packages.join(" ")} -c ${PahkatPrefix.path}`)
for (const pkg of packages) {
core.addPath(path.join(PahkatPrefix.path, "pkg", pkg.split("@").shift()!, "bin"))
}
}
}
export enum MacOSPackageTarget {
System = "system",
User = "user"
}
export type ReleaseRequest = {
version: string,
platform: string,
arch?: string,
channel?: string,
authors?: string[],
license?: string,
licenseUrl?: string,
dependencies?: { [key: string]: string }
}
export class PahkatUploader {
static ARTIFACTS_URL: string = "https://pahkat.uit.no/artifacts/"
private static async run(args: string[]): Promise<string> {
if (process.env["PAHKAT_NO_DEPLOY"] === "true") {
core.debug("Skipping deploy because `PAHKAT_NO_DEPLOY` is true")
return ""
}
const sec = await secrets()
let output: string = ""
let exe: string
if (process.platform === "win32") {
exe = "pahkat-uploader.exe"
} else {
exe = "pahkat-uploader"
}
assertExit0(await exec(exe, args, {
env: Object.assign({}, env(), {
PAHKAT_API_KEY: sec.pahkat.apiKey
}),
listeners: {
stdout: (data: Buffer) => {
output += data.toString()
}
}
}))
return output
}
static async upload(artifactPath: string, artifactUrl: string, releaseMetadataPath: string, repoUrl: string, metadataJsonPath: string | null = null, manifestTomlPath: string| null = null, packageType: string | null = null) {
const fileName = path.parse(artifactPath).base
if (process.env["PAHKAT_NO_DEPLOY"] === "true") {
core.debug("Skipping upload because `PAHKAT_NO_DEPLOY` is true. Creating artifact instead")
process.stdout.write(`::create-artifact path=${fileName}::${artifactPath}`)
return
}
if (!fs.existsSync(releaseMetadataPath)) {
throw new Error(`Missing required payload manifest at path ${releaseMetadataPath}`)
}
const sec = await secrets()
console.log(`Uploading ${artifactPath} to S3`)
var retries = 0;
await exec("aws", ["configure", "set", "default.s3.multipart_threshold", "500MB"])
while (true) {
try {
await exec("aws", ["s3", "cp", "--cli-connect-timeout", "6000", "--endpoint", "https://ams3.digitaloceanspaces.com", "--acl", "public-read", artifactPath, `s3://divvun/pahkat/artifacts/${fileName}`], {
env: Object.assign({}, env(), {
AWS_ACCESS_KEY_ID: sec.aws.accessKeyId,
AWS_SECRET_ACCESS_KEY: sec.aws.secretAccessKey,
AWS_DEFAULT_REGION: "ams3"
})
})
console.log("Upload successful")
break;
} catch (err) {
console.log(err);
if (retries >= 5) {
throw err;
}
await delay(10000)
console.log("Retrying");
retries += 1
}
}
// Step 2: Push the manifest to the server.
const args = ["upload",
"--url", repoUrl,
"--release-meta", releaseMetadataPath,
]
if (metadataJsonPath != null) {
args.push("--metadata-json")
args.push(metadataJsonPath)
}
if (manifestTomlPath != null) {
args.push("--manifest-toml")
args.push(manifestTomlPath)
}
if (packageType != null) {
args.push("--package-type")
args.push(packageType)
}
console.log(await PahkatUploader.run(args))
}
static releaseArgs(release: ReleaseRequest) {
const args = [
"release",
]
if (release.authors) {
args.push("--authors")
for (const item of release.authors) {
args.push(item)
}
}
if (release.arch) {
args.push("--arch")
args.push(release.arch)
}
if (release.dependencies) {
const deps = Object.entries(release.dependencies)
.map(x => `${x[0]}::${x[1]}`)
.join(",")
args.push("-d")
args.push(deps)
}
if (release.channel) {
args.push("--channel")
args.push(release.channel)
}
if (release.license) {
args.push("-l")
args.push(release.license)
}
if (release.licenseUrl) {
args.push("--license-url")
args.push(release.licenseUrl)
}
args.push("-p")
args.push(release.platform)
args.push("--version")
args.push(release.version)
return args
}
static release = {
async windowsExecutable(
release: ReleaseRequest,
artifactUrl: string,
installSize: number,
size: number,
kind: WindowsExecutableKind | null,
productCode: string,
requiresReboot: RebootSpec[],
): Promise<string> {
const payloadArgs = [
"windows-executable",
"-i", (installSize | 0).toString(),
"-s", (size | 0).toString(),
"-p", productCode,
"-u", artifactUrl
]
if (kind != null) {
payloadArgs.push("-k")
payloadArgs.push(kind)
}
if (requiresReboot.length > 0) {
payloadArgs.push("-r")
payloadArgs.push(requiresReboot.join(","))
}
const releaseArgs = PahkatUploader.releaseArgs(release)
return await PahkatUploader.run([...releaseArgs, ...payloadArgs])
},
async macosPackage(
release: ReleaseRequest,
artifactUrl: string,
installSize: number,
size: number,
pkgId: string,
requiresReboot: RebootSpec[],
targets: MacOSPackageTarget[],
): Promise<string> {
const payloadArgs = [
"macos-package",
"-i", (installSize | 0).toString(),
"-s", (size | 0).toString(),
"-p", pkgId,
"-u", artifactUrl
]
if (targets.length > 0) {
payloadArgs.push("-t")
payloadArgs.push(targets.join(","))
}
if (requiresReboot.length > 0) {
payloadArgs.push("-r")
payloadArgs.push(requiresReboot.join(","))
}
const releaseArgs = PahkatUploader.releaseArgs(release)
return await PahkatUploader.run([...releaseArgs, ...payloadArgs])
},
async tarballPackage(
release: ReleaseRequest,
artifactUrl: string,
installSize: number,
size: number
): Promise<string> {
const payloadArgs = [
"tarball-package",
"-i", (installSize | 0).toString(),
"-s", (size | 0).toString(),
"-u", artifactUrl
]
const releaseArgs = PahkatUploader.releaseArgs(release)
return await PahkatUploader.run([...releaseArgs, ...payloadArgs])
},
}
}
// Since some state remains after the builds, don't grow known_hosts infinitely
const CLEAR_KNOWN_HOSTS_SH = `\
mkdir -pv ~/.ssh
ssh-keyscan github.com | tee -a ~/.ssh/known_hosts
cat ~/.ssh/known_hosts | sort | uniq > ~/.ssh/known_hosts.new
mv ~/.ssh/known_hosts.new ~/.ssh/known_hosts
`
export class Ssh {
static async cleanKnownHosts() {
await Bash.runScript(CLEAR_KNOWN_HOSTS_SH)
}
}
const PROJECTJJ_NIGHTLY_SH = `\
wget -q https://apertium.projectjj.com/apt/install-nightly.sh -O install-nightly.sh && bash install-nightly.sh
`
export class ProjectJJ {
static async addNightlyToApt(requiresSudo: boolean) {
await Bash.runScript(PROJECTJJ_NIGHTLY_SH, { sudo: requiresSudo })
}
}
export class Kbdgen {
static async fetchMetaBundle(metaBundlePath: string) {
await Bash.runScript(`kbdgen fetch -b ${metaBundlePath}`)
}
private static async resolveOutput(p: string): Promise<string> {
const globber = await glob.create(p, {
followSymbolicLinks: false
})
const files = await globber.glob()
if (files[0] == null) {
throw new Error("No output found for build.")
}
core.debug("Got file for bundle: " + files[0])
return files[0]
}
static loadTarget(bundlePath: string, target: string) {
return nonUndefinedProxy(YAML.parse(fs.readFileSync(
path.resolve(bundlePath, "targets", `${target}.yaml`), 'utf8')), true)
}
static loadProjectBundle(bundlePath: string) {
return nonUndefinedProxy(YAML.parse(fs.readFileSync(
path.resolve(bundlePath, "project.yaml"), 'utf8')), true)
}
static loadProjectBundleWithoutProxy(bundlePath: string) {
return YAML.parse(fs.readFileSync(
path.resolve(bundlePath, "project.yaml"), 'utf8'))
}
static async loadLayouts(bundlePath: string) {
const globber = await glob.create(path.resolve(bundlePath, "layouts/*.yaml"), {
followSymbolicLinks: false
})
const layoutFiles = await globber.glob()
var layouts: { [locale: string]: any } = {}
for (const layoutFile of layoutFiles) {
const locale = path.parse(layoutFile).base.split('.', 1)[0]
layouts[locale] = YAML.parse(fs.readFileSync(layoutFile, 'utf-8'))
}
return layouts
}
static async setNightlyVersion(bundlePath: string, target: string) {
const targetData = Kbdgen.loadTarget(bundlePath, target)
// Set to minute-based timestamp
targetData['version'] = await versionAsNightly(targetData['version'])
fs.writeFileSync(path.resolve(
bundlePath, "targets", `${target}.yaml`), YAML.stringify({ ...targetData }), 'utf8')
return targetData['version']
}
static async setBuildNumber(bundlePath: string, target: string, start: number = 0) {
const targetData = Kbdgen.loadTarget(bundlePath, target)
// Set to run number
const versionNumber = parseInt((await Bash.runScript("git rev-list --count HEAD"))[0], 10)
targetData['build'] = start + versionNumber
core.debug("Set build number to " + targetData['build'])
fs.writeFileSync(path.resolve(
bundlePath, "targets", `${target}.yaml`), YAML.stringify({ ...targetData }), 'utf8')
return targetData['build']
}
static async build_iOS(bundlePath: string): Promise<string> {
const abs = path.resolve(bundlePath)
const cwd = path.dirname(abs)
const sec = await secrets()
// await Bash.runScript("brew install imagemagick")
await Security.unlockKeychain("login", sec.macos.adminPassword)
const env = {
"GITHUB_USERNAME": sec.github.username,
"GITHUB_TOKEN": sec.github.token,
"MATCH_GIT_URL": sec.ios.matchGitUrl,
"MATCH_PASSWORD": sec.ios.matchPassword,
"FASTLANE_USER": sec.ios.fastlaneUser,
"PRODUCE_USERNAME": sec.ios.fastlaneUser,
"FASTLANE_PASSWORD": sec.ios.fastlanePassword,
"APP_STORE_KEY_JSON": path.join(divvunConfigDir(), sec.macos.appStoreKeyJson),
"MATCH_KEYCHAIN_NAME": "login.keychain",
"MATCH_KEYCHAIN_PASSWORD": sec.macos.adminPassword,
"LANG": "C.UTF-8",
"RUST_LOG": "kbdgen=debug",
}
core.debug("Gonna import certificates")
core.debug("Deleting previous keychain for fastlane")
try {
core.debug("Creating keychain for fastlane")
} catch (err) {
// Ignore error here, the keychain probably doesn't exist
}
core.debug("ok, next")
// Initialise any missing languages first
// XXX: this no longer works since changes to the API!
// await Bash.runScript(
// `kbdgen --logging debug build ios ${abs} init`,
// {
// cwd,
// env
// }
// )
// Do the build
await Bash.runScript(
`kbdgen target --output-path output --bundle-path ${abs} ios build`,
{
cwd,
env
}
)
const globber = await glob.create(path.resolve(abs, "../output/ipa/*.ipa"), {
followSymbolicLinks: false
})
const files = await globber.glob()
if (files[0] == null) {
throw new Error("No output found for build.")
}
return files[0]
}
static async buildAndroid(bundlePath: string, githubRepo: string): Promise<string> {
const abs = path.resolve(bundlePath)
const cwd = path.dirname(abs)
const sec = await secrets()
// await Bash.runScript("brew install imagemagick")
core.debug(`ANDROID_HOME: ${process.env.ANDROID_HOME}`)
await Bash.runScript(
`kbdgen target --output-path output --bundle-path ${abs} android build`,
{
cwd,
env: {
"GITHUB_USERNAME": sec.github.username,
"GITHUB_TOKEN": sec.github.token,
"NDK_HOME": process.env.ANDROID_NDK_HOME!,
"ANDROID_KEYSTORE": path.join(divvunConfigDir(), sec.android[githubRepo].keystore),
"ANDROID_KEYALIAS": sec.android[githubRepo].keyalias,
"STORE_PW": sec.android[githubRepo].storePassword,
"KEY_PW": sec.android[githubRepo].keyPassword,
"PLAY_STORE_P12": path.join(divvunConfigDir(), sec.android.playStoreP12),
"PLAY_STORE_ACCOUNT": sec.android.playStoreAccount,
"RUST_LOG": "debug",
}
}
)
return await Kbdgen.resolveOutput(path.join(cwd, "output/repo/app/build/outputs/apk/release", `*-release.apk`))
}
static async buildMacOS(bundlePath: string): Promise<string> {
const abs = path.resolve(bundlePath)
const cwd = path.dirname(abs)
const sec = await secrets()
// Install imagemagick if we're not using the self-hosted runner
if (process.env["ImageOS"] != null) {
await Bash.runScript("brew install imagemagick")
}
await Bash.runScript(`kbdgen -V`)
await Bash.runScript(
`kbdgen target --output-path output --bundle-path ${abs} macos generate`,
{
env: {
"DEVELOPER_PASSWORD_CHAIN_ITEM": sec.macos.passwordChainItem,
"DEVELOPER_ACCOUNT": sec.macos.developerAccount
}
}
)
await Bash.runScript(
`kbdgen target --output-path output --bundle-path ${abs} macos build`,
{
env: {
"DEVELOPER_PASSWORD_CHAIN_ITEM": sec.macos.passwordChainItem,
"DEVELOPER_ACCOUNT": sec.macos.developerAccount
}
}
)
return await Kbdgen.resolveOutput(path.join(cwd, "output", `*.pkg`))
}
static async buildWindows(bundlePath: string): Promise<string> {
const abs = path.resolve(bundlePath)
const cwd = process.cwd()
await Powershell.runScript(
`kbdgen target --output-path output --bundle-path ${abs} windows`,
)
return `${cwd}/output`
}
}
export class ThfstTools {
static async zhfstToBhfst(zhfstPath: string): Promise<string> {
await DefaultShell.runScript(`thfst-tools zhfst-to-bhfst ${zhfstPath}`)
return `${path.basename(zhfstPath, ".zhfst")}.bhfst`
}
}
const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/
export async function versionAsNightly(version: string): Promise<string> {
const verChunks = SEMVER_RE.exec(version)?.slice(1, 4)
if (verChunks == null) {
throw new Error(`Provided version '${version}' is not semantic.`)
}
const queueService = new taskcluster.Queue({
rootUrl: process.env.TASKCLUSTER_PROXY_URL
});
const task = await queueService.task(process.env.TASK_ID)
const nightlyTs = task.created.replace(/[-:\.]/g, "")
return `${verChunks.join(".")}-nightly.${nightlyTs}`
}
function deriveBundlerArgs(spellerPaths: SpellerPaths, withZhfst: boolean = true) {
const args = []
for (const [langTag, zhfstPath] of Object.entries(spellerPaths.desktop)) {
args.push("-l")
args.push(langTag)
if (withZhfst) {
args.push("-z")
args.push(zhfstPath)
}
}
return args
}
export type SpellerPaths = {
desktop: { [key: string]: string },
mobile: { [key: string]: string }
}
export class DivvunBundler {
static async bundleMacOS(
name: string,
version: string,
packageId: string,
langTag: string,
spellerPaths: SpellerPaths
): Promise<string> {
const sec = await secrets();
const args = [
"-R", "-o", "output", "-t", "osx",
"-H", name,
"-V", version,
"-a", `Developer ID Application: The University of Tromso (2K5J2584NX)`,
"-i", `Developer ID Installer: The University of Tromso (2K5J2584NX)`,
"-n", sec.macos.developerAccount,
"-p", sec.macos.appPassword,
"-d", sec.macos.teamId,
"speller",
"-f", langTag,
...deriveBundlerArgs(spellerPaths)
]
assertExit0(await exec("divvun-bundler", args, {
env: Object.assign({}, env(), {
"RUST_LOG": "trace"
})
}))
// FIXME: workaround bundler issue creating invalid files
await io.cp(
path.resolve(`output/${langTag}-${version}.pkg`),
path.resolve(`output/${packageId}-${version}.pkg`))
const outputFile = path.resolve(`output/${packageId}-${version}.pkg`)
return outputFile
}
// static async bundleWindows(
// name: string,
// version: string,
// manifest: WindowsSpellerManifest,
// packageId: string,
// langTag: string,
// spellerPaths: SpellerPaths
// ) {
// const sec = secrets();
// let exe: string
// if (process.platform === "win32") {
// exe = path.join(PahkatPrefix.path, "pkg", "divvun-bundler", "bin", "divvun-bundler.exe")
// } else {
// exe = "divvun-bundler"
// }
// const args = ["-R", "-t", "win", "-o", "output",
// "--uuid", productCode,
// "-H", name,
// "-V", version,
// "-c", DIVVUN_PFX,
// "speller",
// "-f", langTag,
// ...deriveBundlerArgs(spellerPaths)
// ]
// assertExit0(await exec(exe, args, {
// env: Object.assign({}, env(), {
// "RUST_LOG": "trace",
// "SIGN_PFX_PASSWORD": sec.windows.pfxPassword,
// })
// }))
// try {
// core.debug(fs.readdirSync("output").join(", "))
// } catch (err) {
// core.debug("Failed to read output dir")
// core.debug(err)
// }
// // FIXME: workaround bundler issue creating invalid files
// await io.cp(
// path.resolve(`output/${langTag}-${version}.exe`),
// path.resolve(`output/${packageId}-${version}.exe`))
// return path.resolve(`output/${packageId}-${version}.exe`)
// }
}
export function nonUndefinedProxy(obj: any, withNull: boolean = false): any {
return new Proxy(obj, {
get: (target, prop, receiver) => {
const v = Reflect.get(target, prop, receiver)
if (v === undefined) {
throw new Error(`'${String(prop)}' was undefined and this is disallowed. Available keys: ${Object.keys(obj).join(", ")}`)
}
if (withNull && v === null) {
throw new Error(`'${String(prop)}' was null and this is disallowed. Available keys: ${Object.keys(obj).join(", ")}`)
}
if (v != null && (Array.isArray(v) || typeof v === 'object')) {
return nonUndefinedProxy(v, withNull)
} else {
return v
}
}
})
}
export function validateProductCode(kind: WindowsExecutableKind, code: string): string {
if (kind === null) {
core.debug("Found no kind, returning original code")
return code
}
if (kind === WindowsExecutableKind.Inno) {
if (code.startsWith("{") && code.endsWith("}_is1")) {
core.debug("Found valid product code for Inno installer: " + code);
return code
}
let updatedCode = code;
if (!code.endsWith("}_is1") && !code.startsWith("{")) {
core.debug("Found plain UUID for Inno installer, wrapping in {...}_is1")
updatedCode = `{${code}}_is1`
}
else if (code.endsWith("}") && code.startsWith("{")) {
core.debug("Found wrapped GUID for Inno installer, adding _is1")
updatedCode = `${code}_is1`
} else {
throw new Error(`Could not handle invalid Inno product code: ${code}`)
}
core.debug(`'${code}' -> '${updatedCode}`)
return updatedCode
}
if (kind === WindowsExecutableKind.Nsis) {
if (code.startsWith("{") && code.endsWith("}")) {
core.debug("Found valid product code for Nsis installer: " + code)
return code
}
let updatedCode = code
if (!code.endsWith("}") && !code.startsWith("{")) {
core.debug("Found plain UUID for Nsis installer, wrapping in {...}")
updatedCode = `{${code}}`
} else {
throw new Error(`Could not handle invalid Nsis product code: ${code}`)
}
core.debug(`'${code}' -> '${updatedCode}`)
return updatedCode
}
throw new Error("Unhandled kind: " + kind)