Repository navigation
Expand file tree
/
Copy pathdeploy.ts
More file actions
1103 lines (943 loc) · 38.9 KB
/
Copy pathdeploy.ts
File metadata and controls
1103 lines (943 loc) · 38.9 KB
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 * as child_process from 'child_process';
import * as fs from 'fs';
import * as https from 'https';
import * as path from 'path';
import ModSourceUtils from './modSourceUtils.js';
import { ExternalModListing, getExternalModListings } from './externalCatalog.js';
import { Feed } from 'feed';
import { OutgoingHttpHeaders } from 'http';
import MarkdownIt from 'markdown-it';
// Author name variations of the same github account. The first item of each
// pair is the canonical name.
const allowedAuthorNamePairs = [
['CatmanFan / Mr._Lechkar', 'CatmanFan'],
['Anixx', 'anixx'],
['Isabella Lulamoon (kawapure)', 'kawapure'],
];
// Github accounts of the same author, e.g. after a rename, where old mod
// versions still refer to the old account. The first item of each pair is the
// current account.
const allowedAuthorGithubPairs = [
['https://github.com/meteoni', 'https://github.com/meteony'],
['https://github.com/getrektbynoob15', 'https://github.com/getrektbynoob20'],
['https://github.com/sharexza', 'https://github.com/raviadityasetiawan-oss'],
];
type ModAuthorData = {
github: string;
// The numeric id of the github account, which, unlike the login, is never
// reused. Null if the account at the login isn't the author's. Kept from the
// last deploy once recorded.
githubId?: number | null;
author: string;
homepages: string[],
twitter?: string;
};
type CommitMeta = {
timestamp: number;
message: string;
};
type FileChange = {
changeType: string;
filePath: string;
};
// A row of the update server's reviews/get_all.php: approved reviews only,
// in ascending id. A reply is a review whose parentId names another.
type PublicReview = {
id: number;
modId: string;
parentId: number | null;
timestamp: number;
authorName: string;
modVersion: string | null;
content: string;
votes: number;
};
type ModReviews = {
// The number of top-level reviews (replies excluded), what the catalog
// carries.
count: number;
// The file's entries, in the order the server gave them.
reviews: Omit<PublicReview, 'modId'>[];
};
class GitCache {
commitMeta: Map<string, CommitMeta>;
commitOrder: string[];
modCommits: Map<string, { commit: string; changeType: string }[]>;
commitFiles: Map<string, FileChange[]>;
blobs: Map<string, string>;
constructor(data: {
commitMeta: Map<string, CommitMeta>;
commitOrder: string[];
modCommits: Map<string, { commit: string; changeType: string }[]>;
commitFiles: Map<string, FileChange[]>;
blobs: Map<string, string>;
}) {
this.commitMeta = data.commitMeta;
this.commitOrder = data.commitOrder;
this.modCommits = data.modCommits;
this.commitFiles = data.commitFiles;
this.blobs = data.blobs;
}
getCommitMeta(commit: string): CommitMeta {
const meta = this.commitMeta.get(commit);
if (!meta) {
throw new Error(`No metadata for commit ${commit}`);
}
return meta;
}
getModCommits(modId: string): { commit: string; changeType: string }[] {
const entries = this.modCommits.get(modId);
if (!entries || entries.length === 0) {
throw new Error(`No commit history for mod ${modId}`);
}
return entries;
}
getBlob(ref: string): string {
const content = this.blobs.get(ref);
if (content === undefined) {
throw new Error(`Blob not found in cache: ${ref}`);
}
return content;
}
}
class HttpError extends Error {
constructor(public statusCode: number | undefined, body: string) {
super('Request failed. status: ' + statusCode + ', body: ' + body);
}
}
// Inspired by https://gist.github.com/ktheory/df3440b01d4b9d3197180d5254d7fb65
async function fetchJson(url: string, headers?: OutgoingHttpHeaders) {
return new Promise<any>((resolve, reject) => {
const req = https.request(url,
{ headers: { 'User-Agent': 'nodejs', ...headers } },
(res) => {
let body = '';
res.on('data', (chunk) => (body += chunk.toString()));
res.on('error', reject);
res.on('end', () => {
if (res.statusCode && res.statusCode >= 200 && res.statusCode <= 299) {
resolve(JSON.parse(body));
} else {
reject(new HttpError(res.statusCode, body));
}
});
});
req.on('error', reject);
req.end();
});
}
// https://stackoverflow.com/a/53593328
function JSONstringifyOrder(obj: any, space: number) {
const allKeys = new Set<string>();
JSON.stringify(obj, (key, value) => {
allKeys.add(key);
return value;
});
return JSON.stringify(obj, Array.from(allKeys).sort(), space);
}
// Puts arrays of plain numbers in formatted JSON on a single line. Can't match
// inside strings, since JSON strings can't contain raw newlines.
function JSONcompactNumberArrays(json: string) {
return json.replace(/\[\s*(-?[\d.eE+-]+(?:,\s*-?[\d.eE+-]+)*)\s*\]/g,
(_match, items: string) => '[' + items.split(/,\s*/).join(', ') + ']');
}
function gitExec(args: string[]) {
const result = child_process.spawnSync('git', args, {
encoding: 'utf8',
maxBuffer: 512 * 1024 * 1024,
});
if (result.error) {
throw new Error('git ' + args.join(' ') + ' failed: ' + result.error.message);
}
if (result.status !== 0) {
throw new Error('git ' + args.join(' ') + ' failed with status ' + result.status + ' and stderr ' + result.stderr);
}
if (result.stderr) {
console.warn('git ' + args.join(' ') + ' produced stderr ' + result.stderr);
}
return result.stdout;
}
function batchReadBlobs(refs: string[]): Map<string, string> {
if (refs.length === 0) {
return new Map();
}
const result = child_process.spawnSync('git', ['cat-file', '--batch'], {
input: refs.join('\n') + '\n',
maxBuffer: 512 * 1024 * 1024,
});
if (result.status !== 0) {
throw new Error('git cat-file --batch failed with status ' + result.status +
' and stderr ' + (result.stderr?.toString() ?? ''));
}
const output = result.stdout;
const map = new Map<string, string>();
let offset = 0;
for (let i = 0; i < refs.length; i++) {
const headerEnd = output.indexOf(0x0A, offset);
if (headerEnd === -1) {
throw new Error(`Unexpected end of cat-file output at ref ${refs[i]}`);
}
const header = output.subarray(offset, headerEnd).toString('utf8');
if (header.endsWith('missing')) {
throw new Error(`git cat-file: ${refs[i]} → ${header}`);
}
const size = parseInt(header.split(' ')[2], 10);
const contentStart = headerEnd + 1;
const content = output.subarray(contentStart, contentStart + size).toString('utf8');
map.set(refs[i], content);
offset = contentStart + size + 1;
}
return map;
}
function buildGitCache(): GitCache {
console.log('Building git cache...');
// Bulk 1: All commit metadata (hash, timestamp, message).
// Uses double-null as record separator, single-null as field separator.
console.log(' Loading commit metadata...');
const metaOutput = gitExec(['log', '--format=%H%x00%ct%x00%B%x00%x00']);
const commitMeta = new Map<string, CommitMeta>();
const commitOrder: string[] = [];
for (const record of metaOutput.split('\0\0')) {
const trimmed = record.replace(/^\n/, '');
if (!trimmed) {
continue;
}
const firstNull = trimmed.indexOf('\0');
const secondNull = trimmed.indexOf('\0', firstNull + 1);
const hash = trimmed.slice(0, firstNull);
const timestamp = parseInt(trimmed.slice(firstNull + 1, secondNull), 10);
const message = trimmed.slice(secondNull + 1);
commitMeta.set(hash, { timestamp, message });
commitOrder.push(hash);
}
console.log(` ${commitMeta.size} commits`);
// Bulk 2: All commits with their changed files (name-status).
// Null byte before hash makes commit boundaries unambiguous.
console.log(' Loading commit file changes...');
const fileOutput = gitExec(['log', '--format=%x00%H', '--name-status', '--no-renames']);
const modCommits = new Map<string, { commit: string; changeType: string }[]>();
const commitFiles = new Map<string, FileChange[]>();
const chunks = fileOutput.split('\0');
// First chunk is always empty (before the leading null byte).
if (chunks[0].trim()) {
throw new Error('Unexpected content before first null byte in git log output');
}
for (let ci = 1; ci < chunks.length; ci++) {
const chunk = chunks[ci];
if (!chunk.trim()) {
// Trailing empty chunk after last null byte.
if (ci !== chunks.length - 1) {
throw new Error('Unexpected empty chunk in git log output');
}
break;
}
const lines = chunk.split('\n');
const hash = lines[0].trim();
if (!/^[0-9a-f]{40}$/.test(hash)) {
throw new Error(`Expected a commit hash, got '${hash}'`);
}
const files: FileChange[] = [];
for (let i = 1; i < lines.length; i++) {
const line = lines[i];
if (!line) {
// Blank lines separate the hash from file entries.
continue;
}
const statusMatch = line.match(/^([A-Z]\d*)\t(.+)$/);
if (!statusMatch) {
throw new Error(`Unexpected name-status line in commit ${hash}: '${line}'`);
}
const changeType = statusMatch[1][0];
const filePath = statusMatch[2].split('\t').pop()!; // last part handles renames
files.push({ changeType, filePath });
const match = filePath.match(/^mods\/(.+)\.wh\.cpp$/);
if (match) {
const modId = match[1];
if (!modCommits.has(modId)) {
modCommits.set(modId, []);
}
modCommits.get(modId)!.push({ commit: hash, changeType });
}
}
commitFiles.set(hash, files);
}
console.log(` ${modCommits.size} mods, ${commitFiles.size} commits with file data`);
// Bulk 3: Pre-fetch all mod blobs via cat-file --batch.
console.log(' Pre-fetching mod blobs...');
const blobRefs: string[] = [];
for (const [modId, entries] of modCommits) {
for (const entry of entries) {
if (entry.changeType !== 'D') {
blobRefs.push(`${entry.commit}:mods/${modId}.wh.cpp`);
}
}
}
const blobs = batchReadBlobs(blobRefs);
console.log(` ${blobs.size} blobs loaded`);
return new GitCache({ commitMeta, commitOrder, modCommits, commitFiles, blobs });
}
function getModCreatedTime(modId: string, cache: GitCache) {
const entries = cache.getModCommits(modId);
const oldest = entries[entries.length - 1];
if (oldest.changeType !== 'A') {
throw new Error(`Expected first commit for mod ${modId} to be an add, got '${oldest.changeType}'`);
}
return cache.getCommitMeta(oldest.commit).timestamp * 1000;
}
function getModModifiedTime(modId: string, cache: GitCache) {
const entries = cache.getModCommits(modId);
return cache.getCommitMeta(entries[0].commit).timestamp * 1000;
}
function findCachedMod(modId: string, version: string, arch: string) {
const lastDeployPath = process.env.WINDHAWK_MODS_LAST_DEPLOY_PATH;
if (!lastDeployPath) {
throw new Error('WINDHAWK_MODS_LAST_DEPLOY_PATH is not set');
}
const modFile = path.join(lastDeployPath, 'mods', modId, `${version}_${arch}.dll`);
return fs.existsSync(modFile) ? modFile : null;
}
function compileMod(modFilePath: string, output32FilePath: string, output64FilePath: string, outputArm64FilePath: string) {
const windhawkPath = process.env.WINDHAWK_PATH;
if (!windhawkPath) {
throw new Error('WINDHAWK_PATH is not set');
}
const result = child_process.spawnSync('py', [
'scripts/compile_mod.py',
'-w',
windhawkPath,
'-f',
modFilePath,
'-o32',
output32FilePath,
'-o64',
output64FilePath,
'-oarm64',
outputArm64FilePath,
], { encoding: 'utf8', stdio: 'inherit' });
if (result.status !== 0) {
throw new Error('Compiling ' + modFilePath + ' failed with status ' + result.status);
}
}
function validateAndUpdateAuthorData(
modId: string,
commit: string,
metadata: {
github: string;
author: string;
homepage?: string;
twitter?: string;
},
modAuthorData: Record<string, ModAuthorData>
) {
const authorKey = metadata.github.toLowerCase();
if (!modAuthorData[authorKey]) {
modAuthorData[authorKey] = {
github: metadata.github,
author: metadata.author,
homepages: [],
};
}
const entry = modAuthorData[authorKey];
if (metadata.homepage !== undefined) {
if (!entry.homepages.includes(metadata.homepage)) {
entry.homepages.push(metadata.homepage);
}
}
if (entry.twitter === undefined && metadata.twitter !== undefined) {
entry.twitter = metadata.twitter;
}
const inconsistencies: string[] = [];
if (metadata.github !== entry.github) {
inconsistencies.push(`github: expected '${entry.github}', got '${metadata.github}'`);
}
if (metadata.author !== entry.author) {
const matchedPair = allowedAuthorNamePairs.find(pair =>
pair.includes(metadata.author) && pair.includes(entry.author)
);
if (matchedPair) {
entry.author = matchedPair[0];
} else {
inconsistencies.push(`author: expected '${entry.author}', got '${metadata.author}'`);
}
}
if (metadata.twitter !== undefined && metadata.twitter !== entry.twitter) {
inconsistencies.push(`twitter: expected '${entry.twitter}', got '${metadata.twitter}'`);
}
if (inconsistencies.length > 0) {
throw new Error(
`Mod ${modId} has inconsistent author data in commit ${commit}:\n` +
inconsistencies.map(msg => ` - ${msg}`).join('\n')
);
}
}
function handleCompiledFiles(
modId: string,
modDir: string,
modVersionFilePath: string,
metadata: { version: string; architecture?: string[] }
) {
const modVersionCompiled32FilePath = path.join(modDir, `${metadata.version}_32.dll`);
const modVersionCompiled64FilePath = path.join(modDir, `${metadata.version}_64.dll`);
const modVersionCompiledArm64FilePath = path.join(modDir, `${metadata.version}_arm64.dll`);
const cachedMod32Path = findCachedMod(modId, metadata.version, '32');
const cachedMod64Path = findCachedMod(modId, metadata.version, '64');
const cachedModArm64Path = findCachedMod(modId, metadata.version, 'arm64');
if (cachedMod32Path || cachedMod64Path || cachedModArm64Path) {
const modHas32 = metadata.architecture?.includes('x86') ?? true;
const modHas64 =
(metadata.architecture?.includes('x86-64') ?? true) ||
(metadata.architecture?.includes('amd64') ?? true);
const modHasArm64 =
(metadata.architecture?.includes('x86-64') ?? true) ||
(metadata.architecture?.includes('arm64') ?? true);
if (modHas32 != !!cachedMod32Path || modHas64 != !!cachedMod64Path || modHasArm64 != !!cachedModArm64Path) {
throw new Error(`Mod ${modId} architecture mismatch`);
}
if (cachedMod32Path) {
fs.copyFileSync(cachedMod32Path, modVersionCompiled32FilePath);
}
if (cachedMod64Path) {
fs.copyFileSync(cachedMod64Path, modVersionCompiled64FilePath);
}
if (cachedModArm64Path) {
fs.copyFileSync(cachedModArm64Path, modVersionCompiledArm64FilePath);
}
} else {
compileMod(modVersionFilePath, modVersionCompiled32FilePath, modVersionCompiled64FilePath, modVersionCompiledArm64FilePath);
}
}
function generateChangelogEntry(modId: string, commit: string, lastCommit: string, metadata: { version: string }, cache: GitCache) {
const meta = cache.getCommitMeta(commit);
const commitTime = meta.timestamp;
const commitFormattedDate = new Date(commitTime * 1000)
.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
const modVersionUrl = `https://github.com/ramensoftware/windhawk-mods/blob/${commit}/mods/${modId}.wh.cpp`;
let changelogEntry = `## ${metadata.version} ([${commitFormattedDate}](${modVersionUrl}))\n\n`;
if (commit !== lastCommit) {
const changelogItem = getModChangelogTextForVersion(modId, metadata.version, meta.message);
changelogEntry += `${changelogItem}\n\n`;
} else {
changelogEntry += 'Initial release.\n';
}
return { changelogEntry, commitTime };
}
function generateModData(
modId: string,
changelogPath: string,
modDir: string,
modAuthorData: Record<string, ModAuthorData>,
authorFirstSubmission: Map<string, number>,
cache: GitCache
) {
if (!fs.existsSync(modDir)) {
fs.mkdirSync(modDir);
}
let changelog = '';
const versions: {
version: string;
timestamp: number;
prerelease?: boolean;
}[] = [];
let sawReleaseVersion = false;
const modSourceUtils = new ModSourceUtils('mods');
const commits = cache.getModCommits(modId).map(e => e.commit);
const lastCommit = commits[commits.length - 1];
for (const commit of commits) {
const modFile = cache.getBlob(`${commit}:mods/${modId}.wh.cpp`);
const metadata = modSourceUtils.extractMetadata(modFile, 'en-US');
if (!metadata.version || !metadata.github || !metadata.author) {
throw new Error(`Mod ${modId} has incomplete metadata in commit ${commit}`);
}
validateAndUpdateAuthorData(modId, commit, {
github: metadata.github,
author: metadata.author,
homepage: metadata.homepage,
twitter: metadata.twitter,
}, modAuthorData);
const authorKey = metadata.github.toLowerCase();
const submissionTime = cache.getCommitMeta(commit).timestamp * 1000;
const firstSubmission = authorFirstSubmission.get(authorKey);
if (firstSubmission === undefined || submissionTime < firstSubmission) {
authorFirstSubmission.set(authorKey, submissionTime);
}
const prerelease = metadata.version.includes('-');
if (prerelease && sawReleaseVersion) {
continue;
}
const modVersionFilePath = path.join(modDir, `${metadata.version}.wh.cpp`);
if (fs.existsSync(modVersionFilePath)) {
throw new Error(`Mod ${modId} has duplicate version ${metadata.version} in commit ${commit}`);
}
fs.writeFileSync(modVersionFilePath, modFile);
if (!prerelease && !sawReleaseVersion) {
// Override root file with the latest release version.
fs.copyFileSync(path.join('mods', `${modId}.wh.cpp`), modVersionFilePath);
sawReleaseVersion = true;
}
handleCompiledFiles(modId, modDir, modVersionFilePath, {
version: metadata.version,
architecture: metadata.architecture,
});
const { changelogEntry, commitTime } = generateChangelogEntry(modId, commit, lastCommit, {
version: metadata.version,
}, cache);
changelog += changelogEntry;
versions.unshift({
version: metadata.version,
timestamp: commitTime,
...(prerelease ? { prerelease: true } : {}),
});
}
fs.writeFileSync(changelogPath, changelog);
const versionsPath = path.join(modDir, 'versions.json');
fs.writeFileSync(versionsPath, JSON.stringify(versions));
}
async function fetchGithubUser(login: string): Promise<{ id: number; createdAt: number } | null> {
try {
const user = await fetchJson(`https://api.github.com/users/${encodeURIComponent(login)}`, {
Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
});
return { id: user.id, createdAt: Date.parse(user.created_at) };
} catch (e) {
if (e instanceof HttpError && e.statusCode === 404) {
return null;
}
throw e;
}
}
// Ids are looked up only for accounts with no id recorded in the last deploy,
// so that a deleted account whose login was registered again by someone else
// keeps the id of its original owner. A login with no account, or with an
// account created after the first submission under it, is recorded as null.
async function assignGithubIds(
modAuthorData: Record<string, ModAuthorData>,
authorFirstSubmission: Map<string, number>
) {
const lastDeployPath = process.env.WINDHAWK_MODS_LAST_DEPLOY_PATH;
if (!lastDeployPath) {
throw new Error('WINDHAWK_MODS_LAST_DEPLOY_PATH is not set');
}
const lastModAuthorDataPath = path.join(lastDeployPath, 'mod_author_data.json');
const lastModAuthorData: Record<string, ModAuthorData> = fs.existsSync(lastModAuthorDataPath)
? JSON.parse(fs.readFileSync(lastModAuthorDataPath, 'utf8'))
: {};
// The login of a renamed account no longer belongs to the author.
const renamedGithubs = new Set(allowedAuthorGithubPairs.flatMap(pair => pair.slice(1)));
for (const [authorKey, data] of Object.entries(modAuthorData)) {
if (renamedGithubs.has(authorKey)) {
data.githubId = null;
continue;
}
const lastGithubId = lastModAuthorData[authorKey]?.githubId;
if (lastGithubId !== undefined) {
data.githubId = lastGithubId;
continue;
}
const match = data.github.match(/^https:\/\/github\.com\/([A-Za-z0-9-]+)$/);
if (!match) {
throw new Error(`Unexpected github URL '${data.github}'`);
}
const user = await fetchGithubUser(match[1]);
if (user === null) {
console.warn(`Github account ${data.github} doesn't exist, recording a null id`);
data.githubId = null;
continue;
}
const firstSubmission = authorFirstSubmission.get(authorKey);
if (firstSubmission === undefined) {
throw new Error(`No submissions found for ${data.github}`);
}
if (!(user.createdAt < firstSubmission)) {
console.warn(
`Github account ${data.github} (id ${user.id}) was created at` +
` ${new Date(user.createdAt).toISOString()}, after its first submission at` +
` ${new Date(firstSubmission).toISOString()}, recording a null id`);
data.githubId = null;
continue;
}
console.log(`Recording github id ${user.id} for ${data.github}`);
data.githubId = user.id;
}
}
function validateModAuthorData(modAuthorData: Record<string, ModAuthorData>) {
const seenGithub = new Map<string, string>();
const seenGithubId = new Map<number, string>();
const seenAuthor = new Map<string, string>();
const seenHomepage = new Map<string, string>();
const seenTwitter = new Map<string, string>();
for (const [authorKey, data] of Object.entries(modAuthorData)) {
const githubLower = data.github.toLowerCase();
if (seenGithub.has(githubLower) && seenGithub.get(githubLower) !== authorKey) {
throw new Error(`Duplicate github '${data.github}' found for authors '${authorKey}' and '${seenGithub.get(githubLower)}'`);
}
seenGithub.set(githubLower, authorKey);
if (data.githubId !== undefined && data.githubId !== null) {
const seenGithubIdKey = seenGithubId.get(data.githubId);
if (seenGithubIdKey !== undefined) {
throw new Error(
`Duplicate github id ${data.githubId} found for authors '${authorKey}' and '${seenGithubIdKey}',` +
` a renamed account must be added to allowedAuthorGithubPairs`);
}
seenGithubId.set(data.githubId, authorKey);
}
const authorLower = data.author.toLowerCase();
const seenAuthorKey = seenAuthor.get(authorLower);
if (seenAuthorKey !== undefined && seenAuthorKey !== authorKey) {
const allowed = allowedAuthorGithubPairs.some(pair =>
pair.includes(authorKey) && pair.includes(seenAuthorKey)
);
if (!allowed) {
throw new Error(`Duplicate author name '${data.author}' found for authors '${authorKey}' and '${seenAuthorKey}'`);
}
}
seenAuthor.set(authorLower, authorKey);
for (const homepage of data.homepages) {
const homepageLower = homepage.toLowerCase();
if (seenHomepage.has(homepageLower) && seenHomepage.get(homepageLower) !== authorKey) {
throw new Error(`Duplicate homepage '${homepage}' found for authors '${authorKey}' and '${seenHomepage.get(homepageLower)}'`);
}
seenHomepage.set(homepageLower, authorKey);
}
if (data.twitter) {
const twitterLower = data.twitter.toLowerCase();
if (seenTwitter.has(twitterLower) && seenTwitter.get(twitterLower) !== authorKey) {
throw new Error(`Duplicate twitter '${data.twitter}' found for authors '${authorKey}' and '${seenTwitter.get(twitterLower)}'`);
}
seenTwitter.set(twitterLower, authorKey);
}
}
}
async function generateModsData(cache: GitCache) {
const changelogDir = 'changelogs';
if (!fs.existsSync(changelogDir)) {
fs.mkdirSync(changelogDir);
}
const modAuthorData: Record<string, ModAuthorData> = {};
const authorFirstSubmission = new Map<string, number>();
const modsSourceDir = fs.opendirSync('mods');
try {
let modsSourceDirEntry: fs.Dirent | null;
while ((modsSourceDirEntry = modsSourceDir.readSync()) !== null) {
if (modsSourceDirEntry.isFile() && modsSourceDirEntry.name.endsWith('.wh.cpp')) {
const modId = modsSourceDirEntry.name.slice(0, -'.wh.cpp'.length);
const changelogPath = path.join(changelogDir, `${modId}.md`);
const modDir = path.join('mods', modId);
generateModData(modId, changelogPath, modDir, modAuthorData, authorFirstSubmission, cache);
}
}
} finally {
modsSourceDir.closeSync();
}
await assignGithubIds(modAuthorData, authorFirstSubmission);
validateModAuthorData(modAuthorData);
fs.writeFileSync('mod_author_data.json', JSONstringifyOrder(modAuthorData, 2));
}
function groupReviews(allReviews: PublicReview[], knownModIds: Set<string>): Map<string, ModReviews> {
const byMod = new Map<string, ModReviews>();
for (const { modId, ...review } of allReviews) {
if (!knownModIds.has(modId)) {
// A review on a mod that is no longer in the repository has no
// page to be read on and no file name to trust.
console.warn(`Skipping review ${review.id} on unknown mod ${modId}`);
continue;
}
let entry = byMod.get(modId);
if (!entry) {
entry = { count: 0, reviews: [] };
byMod.set(modId, entry);
}
entry.reviews.push(review);
if (review.parentId === null) {
entry.count++;
}
}
return byMod;
}
// Writes reviews/<modId>.json for each mod with at least one top-level
// review. The directory is rebuilt from scratch every run, so a mod that lost
// its last review loses its file at the deploy step's git add -A.
function writeModReviews(byMod: Map<string, ModReviews>) {
const reviewsDir = 'reviews';
if (!fs.existsSync(reviewsDir)) {
fs.mkdirSync(reviewsDir);
}
for (const [modId, { count, reviews }] of byMod) {
if (count === 0) {
// The server omits replies whose review is unapproved, so this
// is unreachable today; kept as the file's own invariant.
continue;
}
fs.writeFileSync(
path.join(reviewsDir, `${modId}.json`),
JSONstringifyOrder({ modId, reviews }, 2),
);
}
}
function enrichCatalog(
catalog: Record<string, any>,
enrichment: any,
reviewsByMod: Map<string, ModReviews>,
modTimes: any,
cache: GitCache,
) {
const app = {
version: enrichment.app.version,
versionBleedingEdge: enrichment.app.versionBleedingEdge,
versionPreRelease: enrichment.app.versionPreRelease,
};
const mods: Record<string, any> = {};
for (const [id, metadata] of Object.entries(catalog)) {
const { id: idFromMetadata, ...rest } = metadata;
if (id !== idFromMetadata) {
throw new Error(`Expected ${id} === ${idFromMetadata}`);
}
modTimes[id] = modTimes[id] || {
published: getModCreatedTime(id, cache),
updated: getModModifiedTime(id, cache),
};
mods[id] = {
metadata: rest,
details: {
published: modTimes[id].published,
updated: modTimes[id].updated,
defaultSorting: 0,
trendingSorting: 0,
rating: 0,
users: 0,
ratingUsers: 0,
ratingBreakdown: [0, 0, 0, 0, 0],
...enrichment.mods[id]?.details,
// After the spread: the count must come from the same fetch
// as the mod's reviews file, whatever the enrichment carries.
reviews: reviewsByMod.get(id)?.count ?? 0,
},
};
if (enrichment.mods[id]?.featured) {
mods[id].featured = true;
}
}
return {
app,
mods,
};
}
function buildExternalCatalog(
listings: ExternalModListing[],
language: string,
enrichment: any,
modSourceUtils: ModSourceUtils,
) {
const mods: Record<string, any> = {};
for (const listing of listings) {
const { id: idFromMetadata, ...rest } = modSourceUtils.extractMetadata(listing.source, language);
if (listing.id !== idFromMetadata) {
throw new Error(`Expected ${listing.id} === ${idFromMetadata}`);
}
mods[listing.id] = {
metadata: rest,
details: {
published: listing.published,
updated: listing.updated,
defaultSorting: 0,
trendingSorting: 0,
rating: 0,
users: 0,
ratingUsers: 0,
ratingBreakdown: [0, 0, 0, 0, 0],
// Keyed by the id the app installs it under.
...enrichment.mods[`external@${listing.id}`]?.details,
},
source: {
url: listing.sourceUrl,
sha256: listing.sha256,
},
pullRequest: listing.pullRequestUrl,
};
}
return {
mods,
};
}
// Keeps the original (English) name and description for searching, copying
// each field only if the translation changed it.
function addMetadataEnglish(mods: Record<string, any>, englishMods: Record<string, any>) {
for (const [modId, mod] of Object.entries(mods)) {
const englishMod = englishMods[modId];
if (!englishMod) {
continue;
}
const metadata = mod.metadata;
const englishMetadata = englishMod.metadata;
const englishPartial: { name?: string; description?: string } = {};
if (metadata.name !== englishMetadata.name) {
englishPartial.name = englishMetadata.name;
}
if (metadata.description !== englishMetadata.description) {
englishPartial.description = englishMetadata.description;
}
if (Object.keys(englishPartial).length > 0) {
mod.metadataEnglish = englishPartial;
}
}
}
async function generateModCatalogs(cache: GitCache) {
const enrichmentUrl = 'https://update.windhawk.net/mods_catalog_enrichment.json';
const enrichment = await fetchJson(enrichmentUrl);
// A failed fetch fails the run, like the enrichment: a deploy that went on
// with an empty list would delete every reviews file and zero every
// count for a day.
const reviewsUrl = 'https://update.windhawk.net/reviews/get_all.php';
const allReviews: PublicReview[] = await fetchJson(reviewsUrl);
if (!Array.isArray(allReviews)) {
throw new Error(`Expected an array from ${reviewsUrl}`);
}
const translateFilesUrl = 'https://api.github.com/repos/ramensoftware/windhawk-translate/contents';
const translateFiles = await fetchJson(translateFilesUrl, {
Authorization: `Bearer ${process.env.GITHUB_TOKEN}`,
});
const modSourceUtils = new ModSourceUtils('mods');
const modTimes = {};
const englishCatalog = modSourceUtils.getMetadataOfMods('en-US');
const reviewsByMod = groupReviews(allReviews, new Set(Object.keys(englishCatalog)));
writeModReviews(reviewsByMod);
const englishCatalogEnriched = enrichCatalog(englishCatalog, enrichment, reviewsByMod, modTimes, cache);
fs.writeFileSync('catalog.json', JSONcompactNumberArrays(JSONstringifyOrder(englishCatalogEnriched, 2)));
// The external catalog is written even when it lists nothing, since the
// app reads a missing document as a failure.
const externalListings = await getExternalModListings(new Set(Object.keys(englishCatalog)));
const englishExternalCatalog = buildExternalCatalog(externalListings, 'en-US', enrichment, modSourceUtils);
fs.writeFileSync('catalog_external.json', JSONcompactNumberArrays(JSONstringifyOrder(englishExternalCatalog, 2)));
const catalogsDir = 'catalogs';
if (!fs.existsSync(catalogsDir)) {
fs.mkdirSync(catalogsDir);
}
const externalCatalogsDir = 'catalog_external';
if (!fs.existsSync(externalCatalogsDir)) {
fs.mkdirSync(externalCatalogsDir);
}
for (const translateFile of translateFiles) {
const translateFileName = translateFile.name;
if (!translateFileName.endsWith('.yml')) {
continue;
}
const language = translateFileName.slice(0, -'.yml'.length);
const catalog = modSourceUtils.getMetadataOfMods(language);
const catalogEnriched = enrichCatalog(catalog, enrichment, reviewsByMod, modTimes, cache);
addMetadataEnglish(catalogEnriched.mods, englishCatalogEnriched.mods);
fs.writeFileSync(path.join(catalogsDir, `${language}.json`), JSONcompactNumberArrays(JSONstringifyOrder(catalogEnriched, 2)));
const externalCatalog = buildExternalCatalog(externalListings, language, enrichment, modSourceUtils);
addMetadataEnglish(externalCatalog.mods, englishExternalCatalog.mods);
fs.writeFileSync(path.join(externalCatalogsDir, `${language}.json`), JSONcompactNumberArrays(JSONstringifyOrder(externalCatalog, 2)));
}
}
function getModChangelogTextForVersion(modId: string, modVersion: string, commitMessage: string) {
const overridePath = path.join('changelog_override', modId, `${modVersion}.md`);
if (fs.existsSync(overridePath)) {
return fs.readFileSync(overridePath, 'utf8').trim();
}
let messageTrimmed = commitMessage.trim();
if (messageTrimmed.includes('\n')) {
// Remove first line.
return messageTrimmed.replace(/^.* \(#\d+\)\n\n/, '').trim();
} else {
// Only remove trailing PR number if it's the only line.
return messageTrimmed.replace(/ \(#\d+\)$/, '').trim();
}
}
function generateRssFeed(feedType: 'updates' | 'releases', cache: GitCache) {
type FeedItem = {
commit: string;
title: string;
content: string;
url: string;
date: Date;
author: {
name?: string;
link?: string;
};
};
let feedItems: FeedItem[] = [];
const modSourceUtils = new ModSourceUtils('mods');
const allowedChangeTypes = feedType === 'releases' ? ['A'] : ['A', 'M'];