-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecompiler.js
More file actions
769 lines (651 loc) · 29.4 KB
/
decompiler.js
File metadata and controls
769 lines (651 loc) · 29.4 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
const { spawn, exec, execSync } = require('child_process');
const { promises: fs, existsSync, createWriteStream, createReadStream } = require('fs');
const path = require('path');
const os = require('os');
const config = require("./config")
const {BrowserWindow} = require("electron");
const { platform } = require('process');
const { download } = require('grape-electron-dl');
const tar = require("tar")
const extract = require("extract-zip");
const unzipper = require('unzipper');
function run(cmd, args, opts = {})
{
return new Promise((resolve, reject) =>
{
const p = spawn(cmd, args, { stdio: opts.stdio || 'inherit', shell: false });
p.on('error', (err) => {console.error(err); reject(err)});
p.on('message', (...args) => console.log)
p.on('close', (code) =>
{
if (code === 0) resolve();
else reject(new Error(`${cmd} ${args.join(' ')} exited with ${code}`));
});
});
}
async function asyncExec(command, options, log = false)
{
return new Promise((resolve) =>
{
exec(command, options, (...args) => { if(log){console.log(...args)} resolve(...args) })
})
}
async function asyncSpawn(command, args, options, onMessage = (m)=>{}, log = false)
{
return new Promise((resolve) =>
{
let childProcess = spawn(command, args, options)
childProcess.stdout.setEncoding('utf8');
childProcess.stdout.on('data', function(data)
{
onMessage(data.toString())
});
childProcess.stderr.setEncoding('utf8');
childProcess.stderr.on('data', function(data)
{
onMessage(data.toString())
});
childProcess.on('close', function(code)
{
resolve();
});
})
}
async function findSingleFileRecursive(dir, ext, p = "/")
{
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const e of entries)
{
const full = path.join(dir, e.name);
if(e.isDirectory())
{
const found = await findSingleFileRecursive(full, ext, path.join(p, e.name));
if (found) return {file: found.file, path: found.path};
}
else if(e.isFile() && full.endsWith(ext))
{
return {file: full, path: path.join(p, e.name)};
}
}
return null;
}
async function recusriveDirectory(p, file = (f) => {}, directory = (d) => {})
{
for(let e of await fs.readdir(p, { withFileTypes: true }))
{
if(e.isDirectory()) { await directory(path.join(p, e.name)); await recusriveDirectory(path.join(p,e.name), file, directory); }
else if(e.isFile()) { await file(path.join(p, e.name)); }
}
}
async function main()
{
const jarPath = "/Users/coconuts/Library/Application Support/Modpack Maker/instances/Structure Test/minecraft/mods/aether-1.20.1-1.5.2-neoforge.jar";
const classFile = "/Users/coconuts/Downloads/Aether.class";
const cfrJar = path.resolve(__dirname, 'cfr-0.152.jar');
if(!classFile)
{
console.error('ERREUR: précise --class path/to/MyClass.class');
return
}
if(!existsSync(cfrJar))
{
console.error(`ERREUR: cfr.jar introuvable à ${cfrJar}. Télécharge cfr.jar et indique --cfr path/to/cfr.jar`);
return
}
if(!existsSync(classFile))
{
console.error(`ERREUR: class introuvable: ${classFile}`);
return
}
if(jarPath && !existsSync(jarPath))
{
console.error(`ERREUR: jar introuvable: ${jarPath}`);
return
}
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'decompile-'));
const decompOut = path.join(tmp, 'src');
await fs.mkdir(decompOut);
// cfr peut décompiler le .class directement
await run('java', ['-jar', cfrJar, '--outputdir', decompOut, classFile]);
// trouver le .java décompilé
const javaFile = await findSingleFileRecursive(decompOut, '.java');
if(!javaFile)
{
console.error('ERREUR: .java non trouvé après décompilation');
return
}
console.log('Fichier Java trouvé :', javaFile);
// MODIFY
// Recompilation
const compiledOut = path.join(tmp, 'classes');
await fs.mkdir(compiledOut);
console.log('2) (Re)compilation avec javac ->', compiledOut);
// Si on a un jar d'origine, on le met au classpath pour résoudre d'éventuelles dépendances
const cp = jarPath ? jarPath : '';
const javacArgs = [];
if (cp) javacArgs.push('-classpath', cp);
javacArgs.push('-d', compiledOut, javaFile);
await run('javac', javacArgs);
// Trouver le .class recompilé correspondant (même nom)
// On suppose que le .class compilé a le même nom de fichier que le .java (MyClass.class)
const javaBase = path.basename(javaFile, '.java');
const compiledClassFile = await findSingleFileRecursive(compiledOut, `${javaBase}.class`);
if(!compiledClassFile)
{
console.error('ERREUR: .class recompilé non trouvé');
process.exit(1);
}
console.log('Classe recompilée trouvée :', compiledClassFile);
// Replace dans le jar si demandé
if(jarPath)
{
console.log('3) Remplacement dans le jar:', jarPath);
// il faut connaître le chemin interne du .class dans le jar (package path). On calcule la partie relative depuis compiledOut
const relPath = path.relative(compiledOut, compiledClassFile).replace(/\\/g, '/'); // ex: com/example/MyClass.class
// commande jar update:
// jar uf original.jar -C compiledOut com/example/MyClass.class
await run('jar', ['uf', jarPath, '-C', compiledOut, relPath]);
console.log('Jar mis à jour. Classe remplacée:', relPath);
}
else
{
// si pas de jar fourni, on peut remplacer le .class source sur le disque
const destClass = path.join(path.dirname(classFile), path.basename(compiledClassFile));
await fs.copyFile(compiledClassFile, destClass);
console.log(`Aucun jar fourni — .class recompilé copié sur ${destClass}`);
}
console.log('Terminé. Dossier temporaire (garde si tu veux):', tmp);
}
async function deleteFolderRecursive(dirPath)
{
if(existsSync(dirPath))
{
let file = await fs.readFile(dirPath)
file.forEach(async (file) =>
{
const curPath = path.join(dirPath, file);
if (await fs.lstat(curPath).isDirectory())
{
deleteFolderRecursive(curPath);
}
else
{
await fs.unlink(curPath);
}
});
await fs.rmdir(dirPath);
console.log(`Dossier supprimé : ${dirPath}`);
}
}
async function decompileMinecraft(version)
{
const dir = path.join(config.directories.unobfuscated, version+'.jar');
if(existsSync(dir)) { return dir; }
if(!existsSync(config.directories.unobfuscated)) { await fs.mkdir(config.directories.unobfuscated, {recursive: true}) }
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'vanilla-decompile'));
const outputTmp = path.normalize(path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'vanilla-decompile')), 'output.jar'))
const javaVersion = (await (await fetch((await (await fetch("https://piston-meta.mojang.com/mc/game/version_manifest.json")).json()).versions.find(v=>v.id==version).url)).json()).javaVersion.majorVersion
// await run(path.normalize(await getJava(javaVersion)), ['-jar', path.normalize(path.resolve(__dirname, 'minecraft-decompiler.jar')), '--version', version, '--side', 'CLIENT', '--decompile', '--decompiled-output', path.normalize(tmp), '--output', path.normalize(path.join(outputTmp, 'output.jar'))])
await run(path.normalize(await getJava(javaVersion)), ['-jar', path.normalize(path.resolve(__dirname, 'minecraft-decompiler.jar')), '--version', version, '--side', 'CLIENT', '--output', outputTmp])
fs.rm(path.resolve(__dirname, 'downloads'), { recursive: true, force: true })
fs.copyFile(outputTmp, dir)
return dir;
async function walk(dir)
{
var results = [];
const list = await fs.readdir(dir)
for(let file of list)
{
file = path.resolve(dir, file);
const stat = await fs.stat(file)
if (stat && stat.isDirectory())
{
results = results.concat(await walk(file));
}
else
{
results.push(file.slice(tmp.length+1));
}
}
return results;
};
return await walk(tmp)
}
module.exports =
{
decompileClass: async function(buffer)
{
if(!Buffer.isBuffer(buffer)){buffer = Buffer.from(buffer);}
if(!Buffer.isBuffer(buffer)){ console.warn("Cannot decompile, invalid buffer."); return; }
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'decompile-'));
const original = path.join(tmp, "original.class");
await fs.writeFile(original, buffer)
const destinationOut = path.join(tmp, 'src');
await fs.mkdir(destinationOut);
// java -jar fernflower.jar -r /path/to/class_folder /path/to/output_src
if(true)
{
await run(await getJava('22'), ['-jar', path.resolve(__dirname, "fernflower.jar"), original, destinationOut]);
let result = {path: path.join(destinationOut, 'original.java'), file: null}
result.file = (await fs.readFile(result.path)).toString();
return result
}
else
{
await run(await getJava('22'), ['-jar', path.resolve(__dirname, "cfr.jar"), '--outputdir', destinationOut, original]);
let result = await findSingleFileRecursive(destinationOut, '.java');
result.file = (await fs.readFile(result.file)).toString();
return result;
}
},
decompileMinecraft: decompileMinecraft,
decompileInstance: async function(instance, version, includes = {minecraft: true, mods: true, packs: true, libraries: false, onlyJava: true})
{
// Paths
const instancePath = path.join(config.directories.instances, instance)
if(!existsSync(instancePath)){return}
const combinePath = path.join(config.directories.combinedInstances, instance)
if(existsSync(combinePath)){await fs.rm(combinePath, {recursive: true})}
await fs.mkdir(combinePath, {recursive: true})
const decompilePath = path.join(config.directories.decompiledInstances, instance)
if(existsSync(decompilePath)){await fs.rm(decompilePath, {recursive: true})}
await fs.mkdir(decompilePath, {recursive: true})
// Copy
if(includes.libraries)
{
await libraryWalk(path.join(instancePath, "minecraft", "libraries"))
async function libraryWalk(parent)
{
for(const c of await fs.readdir( parent ))
{
const p = path.join(parent, c);
if(p.endsWith("net"+path.sep+"minecraft")){continue}
if((await fs.stat( p )).isDirectory())
{
await libraryWalk(p)
}
else if(p.endsWith(".jar"))
{
try
{
await createReadStream(p).pipe(unzipper.Parse()).on('entry', async entry =>
{
const type = entry.type;
if(type === 'File' && (!includes.onlyJava || entry.path.endsWith('.class')))
{
const dest = path.join(combinePath, entry.path);
await fs.mkdir(path.dirname(dest), { recursive: true });
await entry.pipe(createWriteStream(dest))
}
else
{
entry.autodrain();
}
})
.promise()
}
catch(err){console.warn(err)}
}
}
}
}
if(includes.minecraft)
{
const minecraftDecompiledPath = await decompileMinecraft(version);
await createReadStream(minecraftDecompiledPath).pipe(unzipper.Parse()).on('entry', async entry =>
{
const type = entry.type;
if(type === 'File' && (!includes.onlyJava || entry.path.endsWith('.class')))
{
const dest = path.join(combinePath, entry.path);
await fs.mkdir(path.dirname(dest), { recursive: true });
await entry.pipe(createWriteStream(dest))
}
else
{
entry.autodrain();
}
})
.promise()
}
if(includes.mods)
{
const modsPath = path.join(instancePath, "minecraft", "mods");
for(const mods of await fs.readdir( modsPath ))
{
if(!mods.endsWith(".jar")){continue}
await createReadStream(path.join(modsPath, mods)).pipe(unzipper.Parse()).on('entry', async entry =>
{
const type = entry.type;
if(type === 'File' && (!includes.onlyJava || entry.path.endsWith('.class')))
{
const dest = path.join(combinePath, entry.path);
await fs.mkdir(path.dirname(dest), { recursive: true });
await entry.pipe(createWriteStream(dest))
}
else
{
entry.autodrain();
}
})
.promise()
}
}
if(includes.packs)
{
// TODO: Use actual hierarchy priority
const packsPath = path.join(combinePath, "packs");
if(!existsSync(packsPath)){fs.mkdir(packsPath, {recursive: true})}
const rpPath = path.join(instancePath, "minecraft", "resourcepacks");
for(const rp of await fs.readdir( rpPath ))
{
if(rp.endsWith(".zip"))
{
await extract( path.join(rpPath, rp), { dir: path.join(packsPath, rp) } )
}
else if((await fs.stat( path.join(rpPath, rp) )).isDirectory())
{
await fs.cp(path.join(rpPath, rp), packsPath, { recursive: true, force: false })
}
}
}
// Decompile
await run(await getJava('22'), ['-jar', path.resolve(__dirname, "fernflower.jar"), '-r', combinePath, decompilePath]);
return decompilePath
},
decompile: async function(jarPath)
{
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'decompile-'));
const destinationOut = path.join(tmp, 'src');
await fs.mkdir(destinationOut);
await run(await getJava('22'), ['-jar', path.resolve(__dirname, 'procyon.jar'), '-jar', jarPath, '-o', destinationOut]);
return destinationOut;
},
compile: async function(classFile, classPath, jarTarget, parameters = {minecraft: '1.20.1', forge: '47.0.0', java: '17', group: 'com.aetherteam', version: '1.5.2', name: 'aether', gradle: '8.5'})
{
// I just gave up... 🥀
return
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'compile-'));
// Copy Jar & Extract
let jarCopy = path.join(tmp, "jar.jar")
await fs.copyFile(jarTarget, jarCopy)
let decompiled = path.join(tmp, "jar")
await fs.mkdir(path.join(tmp, "jar/src/main/java"), {recursive: true})
await fs.mkdir(path.join(tmp, "jar/src/main/resources"), {recursive: true})
await fs.mkdir(path.join(tmp, "jar/libs"), {recursive: true})
// await asyncExec(`java -jar ${path.resolve(__dirname, 'jd-cli.jar')} -od ${path.join(tmp, "jar/src/main/resources")} ${jarCopy}`)
await asyncExec(`java -jar ${path.resolve(__dirname, 'vineflower.jar')} -dgs=1 ${jarCopy} ${path.join(tmp, "first-decompile")}`)
// await fs.copyFile(jarTarget, jarCopy)
// await extract(jarCopy, {dir: path.join(tmp, "jar/src/main/resources")});
// Dependencies
let dependenciesList = "";
let dependenciesArgs = "";
for(let jar of JSON.parse(await fs.readFile(path.join(tmp, "first-decompile/META-INF/jarjar/metadata.json"))).jars)
{
console.log(jar)
await fs.rename(path.join(path.join(tmp, "first-decompile/", jar.path)), path.join(path.join(tmp, "jar/libs", jar.path.slice(jar.path.lastIndexOf("/")))))
dependenciesList += `\ncompileOnly files('${path.join("libs", jar.path.slice(jar.path.lastIndexOf("/")))}')`
// if(jar.isObfuscated){dependenciesList += `\nruntimeOnly files('${path.join("libs", jar.path.slice(jar.path.lastIndexOf("/")))}')`}
// else{dependenciesList += `\nimplementation '${jar.identifier.group}:${jar.identifier.artifact}:${jar.version.artifactVersion}'`}
dependenciesArgs += `--add-external ${path.join(path.join(tmp, "jar/libs", jar.path.slice(jar.path.lastIndexOf("/"))))} \\ `
}
await asyncExec(`java -jar ${path.resolve(__dirname, 'vineflower.jar')} ${dependenciesArgs} -dgs=1 ${jarCopy} ${path.join(tmp, "jar/src/main/resources")}`)
// for(let f of await fs.readdir(path.join(tmp, "jar/src/main/resources/META-INF/jarjar")))
// {
// await fs.rename(path.join(path.join(tmp, "jar/src/main/resources/META-INF/jarjar", f)), path.join(path.join(tmp, "jar/libs", f)))
// if(f.slice(f.lastIndexOf(".")) == ".jar")
// {
// dependenciesList += `\nimplementation files('${path.join("libs", f)}')`
// }
// }
// Detect group/file.class and add to java/
for(let f of await fs.readdir(path.join(tmp, "jar/src/main/resources")))
{
if((await fs.stat(path.join(path.join(tmp, "jar/src/main/resources", f)))).isDirectory())
{
let ok = false;
await recusriveDirectory(path.join(tmp, "jar/src/main/resources", f), (f)=>{if(f.slice(f.lastIndexOf("."))==".java"){ok=true;}})
if(ok)
{
await fs.rename(path.join(path.join(tmp, "jar/src/main/resources", f)), path.join(path.join(tmp, "jar/src/main/java", f)))
}
}
}
// // Convert .class to java
// await recusriveDirectory(path.join(tmp, "jar/src/main/java"), async (f) =>
// {
// await fs.writeFile(f.slice(0, f.lastIndexOf('.'))+".java", (await this.decompileClass(await fs.readFile(f))).file);
// await fs.unlink(f);
// })
console.log(decompiled)
// Settings
function generateGradleBuild(errorMessage = true)
{
return `buildscript {
repositories {
maven {
name = "forge"
url = "https://maven.minecraftforge.net/"
}
mavenCentral()
}
dependencies {
classpath "net.minecraftforge.gradle:ForgeGradle:6.0.+"
}
}
apply plugin: "net.minecraftforge.gradle"
apply plugin: "java"
group = '${parameters.group}'
version = '${parameters.version}'
archivesBaseName = '${parameters.name}'
repositories {
maven {
name = 'Forge'
url = uri('https://maven.minecraftforge.net')
}
mavenCentral()
}
configurations.all {
resolutionStrategy {
eachDependency { details ->
def group = details.requested.group
def name = details.requested.name
def version = details.requested.version
def artifactPath = file("libs/\${name}-\${version}.jar")
if (!artifactPath.exists()) {
${errorMessage?`println "DEPENDENCY TO ADD \${group}:\${name}:\${version}\\n"`:''}
}
}
}
}
sourceSets {
main {
java {
exclude 'top/theillusivec4/curios/common/integration/**'
exclude 'com/aetherteam/aether/integration/**'
exclude 'com/aetherteam/nitrogen/integration/**'
}
}
}
tasks.withType(JavaCompile)
{
options.failOnError = true
}
dependencies {
minecraft 'net.minecraftforge:forge:${parameters.minecraft}-${parameters.forge}'${dependenciesList}
}
minecraft {
mappings channel: 'official', version: '${parameters.minecraft}'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(${parameters.java})
}
}`
}
await fs.writeFile(path.join(decompiled, "build.gradle"), generateGradleBuild())
await fs.writeFile(path.join(decompiled, "settings.gradle"), `rootProject.name = '${parameters.name}'`)
// Cleanup Gradle
await deleteFolderRecursive(path.join(decompiled, 'gradle', 'wrapper'));
if(existsSync(path.join(decompiled, 'gradlew'))) { await fs.unlink(path.join(decompiled, 'gradlew')) }
if(existsSync(path.join(decompiled, 'gradlew.bat'))) { await fs.unlink(path.join(decompiled, 'gradlew.bat')) }
// SDKMAN
if (!existsSync(path.join(process.env.HOME, '.sdkman')))
{
console.log('SDKMAN installation...');
await asyncExec(`curl -s "https://get.sdkman.io" | bash`, { shell: '/bin/bash' });
}
const sdkmanInit = path.join(process.env.HOME, '.sdkman', 'bin', 'sdkman-init.sh');
if(!existsSync(sdkmanInit)) { throw new Error('sdkman-init.sh unfound after installation.'); }
// Install Gradle
const installGradleScript = `source "${sdkmanInit}"\nsdk install gradle ${parameters.gradle}\ngradle -v`
console.log('Gradle', parameters.gradle, 'installation via SDKMAN...');
await asyncExec(installGradleScript, { shell: '/bin/bash' });
const blank = await fs.mkdtemp(path.join(os.tmpdir(), 'empty-gradle-'));
console.log('Gradle init...');
await asyncExec("gradle init", { cwd: blank })
console.log('Gradle wrapping...');
await asyncExec(`gradle wrapper --gradle-version ${parameters.gradle}`, { cwd: blank })
await fs.rename(path.join(blank, "gradle/"), path.join(decompiled, "gradle/"))
await fs.rename(path.join(blank, "gradlew"), path.join(decompiled, "gradlew"))
await fs.rename(path.join(blank, "gradlew.bat"), path.join(decompiled, "gradlew.bat"))
console.log('Building...');
const env = { ...process.env };
let javaHome = null;
if (process.platform != 'win32') {javaHome = execSync(`/usr/libexec/java_home -v ${parameters.java}`).toString().trim()}
if (javaHome) {env.JAVA_HOME = javaHome}
await asyncSpawn(process.platform === "win32"?"gradlew.bat":"./gradlew", ['build'], { cwd: decompiled, env, shell: true }, (m) =>
{
for(let p of m.split("\n"))
{
if(!p.includes('DEPENDENCY TO ADD ')){continue}
p = p.replace("DEPENDENCY TO ADD ", '').replaceAll('\n','');
if(p.length == ""){continue;}
dependenciesList += `\ncompileOnly "${p}"`
}
})
await fs.writeFile(path.join(decompiled, "build.gradle"), generateGradleBuild(false))
console.log(path.join(decompiled, "build.gradle"))
let missingDependencies = [];
await asyncSpawn(process.platform === "win32"?"gradlew.bat":"./gradlew", ['build'], { cwd: decompiled, env, shell: true }, (m) =>
{
const cannotFindSymbolRegex = /error: cannot find symbol[\s\S]*?symbol:\s*(?:class|method|variable)?\s*(\S+)/g;
const packageDoesNotExistRegex = /error: package (\S+) does not exist/g;
let match;
const missingSymbols = [];
while((match = cannotFindSymbolRegex.exec(m)) !== null)
{
missingSymbols.push(match[1]);
}
while((match = packageDoesNotExistRegex.exec(m)) !== null)
{
missingSymbols.push(match[1]);
}
missingDependencies = missingDependencies.concat(missingSymbols)
})
console.log(missingDependencies)
let jdepsResult = path.join(tmp, "jdeps.txt")
await asyncExec(`jdeps -verbose:class build/classes/java/main > ${jdepsResult}`)
console.log(jdepsResult)
// await asyncSpawn(process.platform === "win32"?"gradlew.bat":"./gradlew", ['build'], { cwd: decompiled, env, shell: true }, (m) =>
// {
// console.log(m)
// })
// console.log(`cd ${decompiled}\nJAVA_HOME=$(/usr/libexec/java_home -v ${parameters.java}) ${process.platform === "win32"?"gradlew.bat":"./gradlew"} build`)
// await asyncSpawn(`JAVA_HOME=$(/usr/libexec/java_home -v ${parameters.java}) ${process.platform === "win32"?"gradlew.bat":"./gradlew"} build`, { cwd: decompiled }, (m) =>
// {
// console.log(m);
// })
// for(let jar of await fs.readdir(path.join(decompiled, "build", "libs")))
// {
// console.log(path.join(decompiled, "build", "libs", jar))
// }
}
}
async function getJava(version, listeners = null)
{
version = version.toString()
if(existsSync(path.join(config.directories.jre, `java-${version}`, 'Contents','Home','bin','java')))
{ return path.join(config.directories.jre, `java-${version}`, 'Contents','Home','bin','java') }
else if(existsSync(path.join(config.directories.jre, `java-${version}`, 'bin', 'javaw.exe')))
{ return path.join(config.directories.jre, `java-${version}`, 'bin', 'javaw.exe') }
else if(existsSync(path.join(config.directories.jre, `java-${version}`, 'bin', 'java.exe')))
{ return path.join(config.directories.jre, `java-${version}`, 'bin', 'java.exe') }
else if(existsSync(path.join(config.directories.jre, `java-${version}`, 'bin', 'java')))
{ return path.join(config.directories.jre, `java-${version}`, 'bin', 'java') }
let win = BrowserWindow.getAllWindows()[0] || BrowserWindow.getFocusedWindow();
let createdWin = win==undefined;
if(createdWin)
{
win = new BrowserWindow({});
win.hide();
}
// https://api.adoptium.net/v3/binary/latest/<major_version>/<release_type>/<os>/<arch>/<image_type>/<jvm_impl>/<heap_size>/<vendor>?project=jdk
let os = 'windows';
switch(platform)
{
case "win32": os = "windows"; break;
case "darwin": os = "mac"; break;
case "linux": os = "linux"; break;
default: throw new Error(`Unsupported os: ${platform}`);
}
let arch = "aarch64";
switch (process.arch)
{
case 'x64': arch = 'x64'; break;
case 'arm64': arch = 'aarch64'; break;
case 'arm': arch = 'arm'; break;
default: throw new Error(`Unsupported arch: ${process.arch}`);
}
await fs.mkdir(path.join(config.directories.jre, `java-${version}`), {recursive: true})
let link = `https://api.adoptium.net/v3/binary/latest/${version}/ga/${os}/${arch}/jre/hotspot/normal/adoptium?project=jdk`
let res = await fetch(link, { method: "HEAD" })
if(!res.ok){arch="x64"; link = `https://api.adoptium.net/v3/binary/latest/${version}/ga/${os}/${arch}/jre/hotspot/normal/adoptium?project=jdk`}
await download(win, link, {filename: `java-${version}.tar`, directory: config.directories.jre, onProgress: async (progress) =>
{
if(listeners) { listeners.log('javaProgress', Math.round(progress.percent*100).toString()) }
}});
// await new Promise((resolve, reject) =>
// {
// fs.createReadStream(path.join(config.directories.jre, `java-${version}.tar`))
// .pipe(unzipper.Extract({ path: path.join(config.directories.jre, `java-${version}`) }))
// .on("close", resolve)
// .on("error", reject);
// });
try
{
await tar.x
({
file: path.join(config.directories.jre, `java-${version}.tar`),
cwd: path.join(config.directories.jre, `java-${version}`),
gzip: true
});
}
catch(err)
{
await extract(path.join(config.directories.jre, `java-${version}.tar`), { dir: path.join(config.directories.jre, `java-${version}`) });
}
// Direct Directory
const baseDir = path.join(config.directories.jre, `java-${version}`);
const subDirs = await fs.readdir(baseDir);
if (subDirs.length === 1)
{
const nestedDir = path.join(baseDir, subDirs[0]);
const items = await fs.readdir(nestedDir);
for(const item of items)
{
await fs.rename(path.join(nestedDir, item), path.join(baseDir, item));
}
await fs.rmdir(nestedDir);
}
await fs.unlink(path.join(config.directories.jre, `java-${version}.tar`))
if(createdWin) { win.close(); }
if(existsSync(path.join(config.directories.jre, `java-${version}`, 'Contents','Home','bin','java')))
{ return path.join(config.directories.jre, `java-${version}`, 'Contents','Home','bin','java') }
else if(existsSync(path.join(config.directories.jre, `java-${version}`, 'bin', 'javaw.exe')))
{ return path.join(config.directories.jre, `java-${version}`, 'bin', 'javaw.exe') }
else if(existsSync(path.join(config.directories.jre, `java-${version}`, 'bin', 'java.exe')))
{ return path.join(config.directories.jre, `java-${version}`, 'bin', 'java.exe') }
else if(existsSync(path.join(config.directories.jre, `java-${version}`, 'bin', 'java')))
{ return path.join(config.directories.jre, `java-${version}`, 'bin', 'java') }
}