forked from MinecraftForge/MCPConfig
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbuild.gradle
1485 lines (1380 loc) · 70.1 KB
/
build.gradle
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
buildscript {
repositories {
mavenLocal()
mavenCentral()
jcenter()
maven { url = 'https://files.minecraftforge.net/maven/'}
maven { url = 'https://plugins.gradle.org/m2/' }
}
dependencies {
classpath 'net.minecraftforge:mapping-verifier:1.2.3'
classpath 'de.siegmar:fastcsv:1.0.3'
classpath 'net.minecraftforge:srgutils:0.2.12'
}
}
import de.undercouch.gradle.tasks.download.Download
import groovy.io.FileType
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import java.util.zip.ZipFile
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import java.security.MessageDigest
import net.minecraftforge.lex.ExtractInheritance
import net.minecraftforge.mappingverifier.MappingVerifier
import net.minecraftforge.mcpconfig.tasks.*
import net.minecraftforge.srgutils.IMappingFile
import net.minecraftforge.srgutils.MinecraftVersion
import uk.jamierocks.propatcher.task.*
import de.siegmar.fastcsv.reader.CsvContainer
import de.siegmar.fastcsv.reader.CsvReader
import de.siegmar.fastcsv.writer.CsvWriter
import de.siegmar.fastcsv.reader.CsvRow
import java.util.stream.Collectors
import java.nio.file.Files
plugins {
id 'de.undercouch.download' version '4.0.4'
id 'uk.jamierocks.propatcher' version '1.3.2' apply false
id 'net.rdrei.android.buildtimetracker' version '0.11.0'
}
apply plugin: 'maven'
archivesBaseName = 'mcp_config'
group = 'de.oceanlabs.mcp'
ext {
META_CACHE_FILE = 'meta_cache.json'
META_CACHE = !file(META_CACHE_FILE).exists() ? [:] : new JsonSlurper().parseText(file(META_CACHE_FILE).text)
VERSIONS = subprojects.collect{it.name}.sort{a,b -> compareVersion(a, b)} as List
NULL_OUPUT = new OutputStream() { public void write(int b){} }
TIMESTAMP = (new Date()).format('yyyyMMdd.HHmmss')
// java versions to run decompile+recompile tests with
JAVA_VERSIONS_JSON = rootProject.file("java_versions.json").exists() ? new JsonSlurper().parseText(file(rootProject.file("java_versions.json")).text) : null
JAVA_RUNTIME_PATH = JAVA_VERSIONS_JSON?.remove('runtime')
}
String.metaClass.rsplit = { chr -> [delegate.substring(0, delegate.lastIndexOf(chr)), delegate.substring(delegate.lastIndexOf(chr)+1)] }
logger.lifecycle('Timestamp: ' + TIMESTAMP)
task downloadVersionManifest(type: Download) {
src 'https://launchermeta.mojang.com/mc/game/version_manifest.json'
dest file('build/versions/version_manifest.json')
overwrite true
doLast {
def json = new JsonSlurper().parseText(downloadVersionManifest.dest.text)
//Update the cache of all versions we can.
rootProject.subprojects.each { sub ->
def entry = json.versions.find{it.id == sub.name}
if (entry != null)
META_CACHE.get(sub.name, [:])['json'] = entry.url
}
META_CACHE = META_CACHE.sort{a,b -> compareVersion(a.key, b.key)} //I like it pretty so lets sort it.
file(META_CACHE_FILE).write(new JsonBuilder(META_CACHE).toPrettyString())
downloadVersionManifest.dest.write(new JsonBuilder(json).toPrettyString()) //Pretty it up
}
}
def compareVersion(a, b) {
return MinecraftVersion.from(a).compareTo(MinecraftVersion.from(b))
}
File.metaClass.getSha1 = { !delegate.exists() ? null : MessageDigest.getInstance('SHA-1').digest(delegate.bytes).encodeHex().toString() }
task extractRuntimeAPI(type: ExtractAPI) {
if (JAVA_RUNTIME_PATH != null) {
file(JAVA_RUNTIME_PATH + '/lib').eachFileRecurse(FileType.FILES) {
if (it.name.endsWith('.jar'))
libs.add(it)
}
}
dest = file('build/runtime_api.json')
}
buildtimetracker {
reporters {
summary {
ordered true
threshold 50
barstyle 'none'
shortenTaskNames false
}
}
}
subprojects {
apply plugin: 'de.undercouch.download'
apply plugin: 'maven'
apply plugin: 'maven-publish'
archivesBaseName = rootProject.archivesBaseName
group = rootProject.group
version = name
ext {
FORGE_MAVEN = 'https://files.minecraftforge.net/maven/'
PATH_BUILD = rootProject.file('build').absolutePath
PATH_VERSION = project.projectDir.absolutePath + '/'
PATH_DISTRO = PATH_BUILD + '/distributions'
PATH_CACHED_LIBRARIES = PATH_BUILD + '/libraries/'
PATH_CACHED_VERSIONS = PATH_BUILD + '/versions/'
PATH_CACHED_VERSION = PATH_CACHED_VERSIONS + project.version + '/'
PATH_CACHED_VERSION_DATA = PATH_CACHED_VERSION + 'data/'
PATH_ASTYLE = file('astyle.cfg').exists() ? 'astyle.cfg' : rootProject.file('config/astyle.cfg').absolutePath
PATH_INJECT = file('inject').exists() ? file('inject') : null
PATH_INJECT_TEMPLATE = PATH_INJECT == null || !new File(PATH_INJECT, 'package-info-template.java').exists() ? null : new File(PATH_INJECT, 'package-info-template.java')
PROJECT_TEMPLATE = file('project_template.gradle').exists() ? file('project_template.gradle') : rootProject.file('project_template.gradle')
PATH_TSRG = PATH_VERSION + 'joined.tsrg'
PATH_CTRS = PATH_VERSION + 'constructors.txt'
PATH_ASSETS = PATH_BUILD + '/assets'
PATH_NATIVES = PATH_VERSION + 'natives'
PATH_MOJMAP = PATH_CACHED_VERSION + '/mojmapped/'
MCPNAMES = null
if (rootProject.hasProperty('mapping_version')) {
MCPNAMES = [
version: rootProject.properties.mapping_version,
path: mavenPath(rootProject.properties.mapping_version),
repo: rootProject.hasProperty('mapping_repo') ? rootProject.properties.mapping_repo : FORGE_MAVEN
]
}
CONFIG = file('config.json').exists() ? new JsonSlurper().parse(file('config.json')) : [:]
MCINJECTOR = [
version: CONFIG.get('mcinjector', [:]).version,
args: CONFIG.mcinjector.get('args', []),
path: mavenPath(CONFIG.mcinjector.version),
repo: CONFIG.mcinjector.get('repo', FORGE_MAVEN)
]
FERNFLOWER = [
version: CONFIG.get('fernflower', [:]).version,
args: CONFIG.fernflower.get('args', []),
jvmargs: CONFIG.fernflower.get('jvmargs', []),
path: mavenPath(CONFIG.fernflower.version),
repo: CONFIG.fernflower.get('repo', FORGE_MAVEN)
]
def mergeDefault = [
version: 'net.minecraftforge:mergetool:1.0.4:fatjar',
args: ["--client", "{client}", "--server", "{server}", "--ann", "{version}", "--output", "{output}"]
]
MERGETOOL = [
version: CONFIG.get('merge', mergeDefault).version,
args: CONFIG.merge.get('args', []),
jvmargs: CONFIG.merge.get('jvmargs', []),
path: mavenPath(CONFIG.merge.version),
repo: CONFIG.merge.get('repo', FORGE_MAVEN)
]
def renameDefault = [
version: 'net.md-5:SpecialSource:1.8.3:shaded',
args: ['--in-jar', '{input}', '--out-jar', '{output}', '--srg-in', '{mappings}'],
repo: 'https://repo1.maven.org/maven2/'
]
RENAMETOOL = [
version: CONFIG.get('rename', renameDefault).version,
args: CONFIG.rename.get('args', []),
jvmargs: CONFIG.rename.get('jvmargs', []),
path: mavenPath(CONFIG.rename.version),
repo: CONFIG.rename.get('repo', FORGE_MAVEN)
]
}
tasks.whenTaskAdded {task ->
def name = task.name.toLowerCase()
if (MCINJECTOR.version == null && name.contains('mcinject')) {
task.enabled = false
}
if ((MCINJECTOR.version == null || FERNFLOWER.version == null) && (name.contains('fernflower') || name.contains('project'))) {
task.enabled = false
}
}
task downloadJson(type: SingleFileOutput, dependsOn: rootProject.downloadVersionManifest) {
inputs.file rootProject.downloadVersionManifest.dest
dest file(PATH_CACHED_VERSION + 'version.json')
doLast {
def json = new JsonSlurper().parseText(inputs.files.singleFile.text)
def entry = json.versions.find{it.id == project.version}
def url = entry != null ? entry.url : rootProject.META_CACHE.get(project.version, ['json':null]).json
if (url == null)
url = 'https://s3.amazonaws.com/Minecraft.Download/versions/' + project.version + '/' + project.version + '.json'
download {
src url
dest downloadJson.dest
overwrite false
}
json = new JsonSlurper().parseText(downloadJson.dest.text)
downloadJson.dest.write(new JsonBuilder(json).toPrettyString()) //Pretty it up
}
}
task downloadClient(type: SingleFileOutput, dependsOn: downloadJson) {
inputs.file downloadJson.dest
dest file(PATH_CACHED_VERSION + 'client.jar')
doLast {
def json = new JsonSlurper().parseText(inputs.files.singleFile.text)
download {
src json.downloads.client.url
dest downloadClient.dest
overwrite false
}
}
}
task downloadServer(type: SingleFileOutput, dependsOn: downloadJson) {
inputs.file downloadJson.dest
dest file(PATH_CACHED_VERSION + 'server.jar')
doLast {
def json = new JsonSlurper().parseText(inputs.files.singleFile.text)
download {
src json.downloads.server.url
dest downloadServer.dest
overwrite false
}
}
}
task downloadLibraries(dependsOn: downloadJson) {
inputs.file downloadJson.dest
doLast {
def json = new JsonSlurper().parseText(downloadJson.dest.text)
json.libraries.each {lib ->
def artifacts = (lib.downloads.artifact == null ? [] : [lib.downloads.artifact]) + lib.downloads.get('classifiers', [:]).values()
artifacts.each{ art ->
def target = file(PATH_CACHED_LIBRARIES + art.path)
if (!target.exists()) {
download {
src art.url
dest target
}
}
}
}
for (def side : ['client', 'server', 'joined']) {
if (CONFIG?.libraries?.get(side) != null) {
CONFIG.libraries.get(side).each { art ->
def path = mavenPath(art)
def target = file(PATH_CACHED_LIBRARIES + path)
if (!target.exists()) {
download {
src FORGE_MAVEN + path //TODO: Config this somehow?
dest target
}
}
}
}
}
}
}
task downloadMCInjector(type: Download) {
inputs.property('url', MCINJECTOR.repo + MCINJECTOR.path)
src MCINJECTOR.repo + MCINJECTOR.path
dest file(PATH_CACHED_LIBRARIES + MCINJECTOR.path)
overwrite false
}
task downloadFernflower(type: Download) {
inputs.property('url', FERNFLOWER.repo + FERNFLOWER.path)
src FERNFLOWER.repo + FERNFLOWER.path
dest file(PATH_CACHED_LIBRARIES + FERNFLOWER.path)
overwrite false
}
task downloadMergeTool(type: Download) {
inputs.property('url', MERGETOOL.repo + MERGETOOL.path)
src MERGETOOL.repo + MERGETOOL.path
dest file(PATH_CACHED_LIBRARIES + MERGETOOL.path)
overwrite false
}
task downloadRenameTool(type: Download) {
inputs.property('url', RENAMETOOL.repo + RENAMETOOL.path)
src RENAMETOOL.repo + RENAMETOOL.path
dest file(PATH_CACHED_LIBRARIES + RENAMETOOL.path)
overwrite false
}
task downloadAssets(dependsOn: downloadJson) {
inputs.file downloadJson.dest
doFirst {
def dl = new JsonSlurper().parse(downloadJson.dest).assetIndex
def index = file(PATH_ASSETS + '/indexes/' + dl.id + '.json')
if (index.sha1 != dl.sha1) {
download {
src dl.url
dest index
}
}
new JsonSlurper().parse(index).objects.each { asset ->
def key = asset.value.hash.take(2) + '/' + asset.value.hash
def target = file(PATH_ASSETS + '/objects/' + key)
if (!target.exists()) {
download {
src 'https://resources.download.minecraft.net/' + key
dest target
}
}
}
}
}
if (MCPNAMES != null) {
task downloadMCPNames(type: Download) {
inputs.property('version', MCPNAMES.version)
src MCPNAMES.repo + MCPNAMES.path
dest file(PATH_CACHED_LIBRARIES + MCPNAMES.path)
overwrite false
}
}
def hasMojmap = false
task downloadMojMap(dependsOn: downloadJson) {
inputs.file downloadJson.dest
doFirst {
def dl = new JsonSlurper().parse(downloadJson.dest).downloads
if (dl.find { a -> a.key.toString().endsWith("_mappings")} != null) {
hasMojmap = true
for (def map : ["client", "server"]) {
download {
src map.equals("client") ? dl.client_mappings.url : dl.server_mappings.url
dest file(PATH_MOJMAP + map + ".txt")
}
}
}
}
}
task generateMojMap(dependsOn: downloadMojMap) {
doFirst {
//Stripped from ForgeGradle MCPRepo but adapted to SrgUtils
// Converts the PG files to a mapping zip.
def client = file(PATH_MOJMAP + "client.txt")
def server = file(PATH_MOJMAP + "server.txt")
def tsrg = file(PATH_TSRG)
def mappings = file(PATH_MOJMAP + "mappings.zip")
if (!mappings.getParentFile().exists())
mappings.getParentFile().mkdirs();
IMappingFile pg_client = IMappingFile.load(client);
IMappingFile pg_server = IMappingFile.load(server);
IMappingFile srg = IMappingFile.load(tsrg);
Map<String, String> cfields = new TreeMap<>();
Map<String, String> sfields = new TreeMap<>();
Map<String, String> cmethods = new TreeMap<>();
Map<String, String> smethods = new TreeMap<>();
for (IMappingFile.IClass cls : pg_client.getClasses()) {
IMappingFile.IClass obf = srg.getClass(cls.getMapped());
if (obf == null) continue
for (IMappingFile.IField fld : cls.getFields()) {
String name = obf.remapField(fld.getMapped());
if (name.startsWith("field_"))
cfields.put(name, fld.getOriginal());
}
for (IMappingFile.IMethod mtd : cls.getMethods()) {
String name = obf.remapMethod(mtd.getMapped(), mtd.getMappedDescriptor());
if (name.startsWith("func_"))
cmethods.put(name, mtd.getOriginal());
}
}
for (IMappingFile.IClass cls : pg_server.getClasses()) {
IMappingFile.IClass obf = srg.getClass(cls.getMapped());
if (obf == null) continue
for (IMappingFile.IField fld : cls.getFields()) {
String name = obf.remapField(fld.getMapped());
if (name.startsWith("field_"))
sfields.put(name, fld.getOriginal());
}
for (IMappingFile.IMethod mtd : cls.getMethods()) {
String name = obf.remapMethod(mtd.getMapped(), mtd.getMappedDescriptor());
if (name.startsWith("func_"))
smethods.put(name, mtd.getOriginal());
}
}
def header = ["searge", "name", "side", "desc"] as String[]
List<String[]> fields = new ArrayList<>()
List<String[]> methods = new ArrayList<>()
fields.add(header)
methods.add(header)
for (String name : cfields.keySet()) {
String cname = cfields.get(name)
String sname = sfields.get(name)
if (cname.equals(sname)) {
fields.add([name, cname, "2", ""] as String[])
sfields.remove(name)
} else
fields.add([name, cname, "0", ""] as String[])
}
for (String name : cmethods.keySet()) {
String cname = cmethods.get(name)
String sname = smethods.get(name)
if (cname.equals(sname)) {
methods.add([name, cname, "2", ""] as String[])
smethods.remove(name);
} else
methods.add([name, cname, "0", ""] as String[])
}
sfields.forEach { k, v -> fields.add([k, v, "1", ""] as String[]) }
smethods.forEach { k, v -> methods.add([k, v, "1", ""] as String[]) }
CsvWriter csv = new CsvWriter();
new ZipOutputStream(new FileOutputStream(mappings)).withCloseable { out ->
out.putNextEntry(new ZipEntry("fields.csv"));
csv.write(new OutputStreamWriter(out), fields);
out.closeEntry();
out.putNextEntry(new ZipEntry("methods.csv"));
csv.write(new OutputStreamWriter(out), methods);
out.closeEntry();
}
}
}
generateMojMap.onlyIf { hasMojmap }
task filterClient(type: Zip, dependsOn: [downloadClient]) {
archiveName = 'client.slim.jar'
destinationDir = file(PATH_CACHED_VERSION)
from zipTree(downloadClient.dest)
IMappingFile.load(file(PATH_TSRG)).classes.each { include it.original + '.class' }
}
task filterClientExtra(type: Zip, dependsOn: [downloadClient]) {
archiveName = 'client.extra.jar'
destinationDir = file(PATH_CACHED_VERSION)
from zipTree(downloadClient.dest)
IMappingFile.load(file(PATH_TSRG)).classes.each { exclude it.original + '.class' }
}
task filterServer(type: Zip, dependsOn: [downloadServer]) {
archiveName = 'server.slim.jar'
destinationDir = file(PATH_CACHED_VERSION)
from zipTree(downloadServer.dest)
IMappingFile.load(file(PATH_TSRG)).classes.each { include it.original + '.class' }
}
task filterServerExtra(type: Zip, dependsOn: [downloadServer]) {
archiveName = 'server.extra.jar'
destinationDir = file(PATH_CACHED_VERSION)
from zipTree(downloadServer.dest)
IMappingFile.load(file(PATH_TSRG)).classes.each { exclude it.original + '.class' }
}
task filterJars(dependsOn: [filterClient, filterClientExtra, filterServer, filterServerExtra]){}
task mergeJars(type: MergeJar, dependsOn: [downloadMergeTool, filterClient, filterServer]) {
jar downloadMergeTool.dest
jvmArgs MERGETOOL.jvmargs
client filterClient.archivePath
server filterServer.archivePath
version project.version
dest file(PATH_CACHED_VERSION + 'joined.jar')
args MERGETOOL.args
}
task renameClient(type: RemapJar, dependsOn: [downloadRenameTool, downloadLibraries, filterClient]) {
jar downloadRenameTool.dest
jvmArgs RENAMETOOL.jvmargs
input filterClient.archivePath
mappings file(PATH_VERSION + 'joined.tsrg')
args RENAMETOOL.args
dest file(PATH_CACHED_VERSION + 'client.mapped.jar')
}
task renameServer(type: RemapJar, dependsOn: [downloadRenameTool, downloadLibraries, filterServer]) {
jar downloadRenameTool.dest
jvmArgs RENAMETOOL.jvmargs
input filterServer.archivePath
mappings file(PATH_VERSION + 'joined.tsrg')
args RENAMETOOL.args
dest file(PATH_CACHED_VERSION + 'server.mapped.jar')
}
task renameJoined(type: RemapJar, dependsOn: [downloadRenameTool, downloadLibraries, mergeJars]) {
jar downloadRenameTool.dest
jvmArgs RENAMETOOL.jvmargs
input mergeJars.dest
mappings file(PATH_VERSION + 'joined.tsrg')
args RENAMETOOL.args
dest file(PATH_CACHED_VERSION + 'joined.mapped.jar')
}
task renameJars(dependsOn: [renameClient, renameServer, renameJoined]){}
task extractInheritance(type: ExtractInheritance, dependsOn: [downloadLibraries, mergeJars]) {
input mergeJars.dest
inputs.file downloadJson.dest
dest file(PATH_CACHED_VERSION_DATA + 'inheritance.json')
doFirst {
def json = new JsonSlurper().parseText(downloadJson.dest.text)
json.libraries.stream().map{ it?.downloads?.artifact?.path }.findAll{ it != null }.each{ addLibrary(file(PATH_CACHED_LIBRARIES + it)) }
}
}
task extractInheritanceNamed(type: ExtractInheritance, dependsOn: [renameJoined]) {
input renameJoined.dest
inputs.file downloadJson.dest
dest file(PATH_CACHED_VERSION_DATA + 'inheritance_named.json')
doFirst {
def json = new JsonSlurper().parseText(downloadJson.dest.text)
json.libraries.stream().map{ it?.downloads?.artifact?.path }.findAll{ it != null }.each{ addLibrary(file(PATH_CACHED_LIBRARIES + it)) }
}
}
task makeSRG(type: SingleFileOutput) {
inputs.file(PATH_TSRG)
dest file(PATH_CACHED_VERSION_DATA + 'joined.srg')
doLast {
IMappingFile.load(inputs.files.singleFile).write(dest.toPath(), IMappingFile.Format.SRG, false)
}
}
task fixAccessLevels(type: CreateAccessFixes, dependsOn: [extractInheritance]) {
srg file(PATH_TSRG)
meta extractInheritance.dest
dest file(PATH_CACHED_VERSION_DATA + 'access.txt')
}
task dumpOverrides(type: DumpOverrides, dependsOn: [extractInheritance, makeSRG]) {
srg makeSRG.dest
meta extractInheritance.dest
dest file(PATH_CACHED_VERSION_DATA + 'overrides.txt')
}
task dumpStatic(type: DumpStatics, dependsOn: [extractInheritance, makeSRG]) {
srg makeSRG.dest
meta extractInheritance.dest
dest file(PATH_CACHED_VERSION_DATA + 'static_methods.txt')
}
task makeExceptions(type: DumpExceptions, dependsOn: [extractInheritance, makeSRG]) {
exec file('exceptions.txt').exists() ? file('exceptions.txt') : rootProject.file('config/exceptions.txt')
srg makeSRG.dest
meta extractInheritance.dest
dest file(PATH_CACHED_VERSION_DATA + 'exceptions.txt')
}
task fernflowerLibrariesClient(type: SingleFileOutput, dependsOn: [downloadLibraries]) {
inputs.file downloadJson.dest
dest file(PATH_CACHED_VERSION + 'client.fernflower.libs.txt')
doLast {
def json = new JsonSlurper().parseText(downloadJson.dest.text)
dest.withWriter('UTF-8'){ writer ->
def libs = json.libraries.collect{lib -> lib.downloads.artifact?.path}
if (CONFIG?.libraries?.client != null) {
CONFIG.libraries.client.collect{ mavenPath(it) }.each { libs.add(it) }
}
libs.findAll{ it != null }.unique{a,b -> a <=> b}.each { lib -> writer.write('-e=' + file(PATH_CACHED_LIBRARIES + lib).absolutePath + '\n') }
}
}
}
task fernflowerLibrariesJoined(type: SingleFileOutput, dependsOn: [downloadLibraries]) {
inputs.file downloadJson.dest
dest file(PATH_CACHED_VERSION + 'joined.fernflower.libs.txt')
doLast {
def json = new JsonSlurper().parseText(downloadJson.dest.text)
dest.withWriter('UTF-8'){ writer ->
def libs = json.libraries.collect{lib -> lib.downloads.artifact?.path}
if (CONFIG?.libraries?.joined != null) {
CONFIG.libraries.joined.collect{ mavenPath(it) }.each { libs.add(it) }
}
libs.findAll{ it != null }.unique{a,b -> a <=> b}.each { lib -> writer.write('-e=' + file(PATH_CACHED_LIBRARIES + lib).absolutePath + '\n') }
}
}
}
task fernflowerLibrariesServer(type: SingleFileOutput, dependsOn: [filterServerExtra, downloadLibraries]) {
inputs.file filterServerExtra.archivePath
dest file(PATH_CACHED_VERSION + 'server.fernflower.libs.txt')
doLast {
dest.withWriter('UTF-8'){ writer ->
if (CONFIG?.libraries?.server != null) {
CONFIG.libraries.server.collect{ mavenPath(it) }.each { lib -> writer.write('-e=' + file(PATH_CACHED_LIBRARIES + lib).absolutePath + '\n') }
}
writer.write('-e=' + filterServerExtra.archivePath.absolutePath + '\n')
}
}
}
def sides = [
[name: 'Client', jsonlibs: true, extra: 'Client', assets: true],
[name: 'Server', jsonlibs: false, extra: 'Server', assets: false],
[name: 'Joined', jsonlibs: true, extra: 'Client', assets: true]
]
task mcinjectAll
task fernflowerAll
task fernflowerInject
task testJvmsAllDecompile
task testJvmsAllCompile
task testJvmsAllApi
task testJvmsAll
task testCompileMojang
task projectAll
task projectDelete
task projectReset
task projectApplyPatches
task projectMakePatches
task testAllCompiles(dependsOn: [testCompileMojang, testJvmsAllCompile])
if (FERNFLOWER.version != null) {
testJvmsAll.dependsOn(testCompileMojang)
}
task projectRoot(type: SingleFileOutput) {
dest file('projects/settings.gradle')
doLast {
dest.text =
"def sides = [" + sides.collect{"'${it.name.toLowerCase()}'"}.join(', ') + "]\n" +
"file('.').eachDir{ dir ->\n" +
" if (sides.contains(dir.name)) {\n" +
" include dir.name\n" +
" project(':' + dir.name).name = '${project.name}-' + dir.name\n" +
" }\n" +
"}"
}
}
task extractNatives(type: ExtractNatives, dependsOn: [downloadJson, downloadLibraries]) {
meta downloadJson.dest
cache file(PATH_CACHED_LIBRARIES)
dest file(PATH_NATIVES)
}
for (def child_outer : sides) {
def child = child_outer
def dir = file("projects/${child.name.toLowerCase()}")
def dir_patches = file("patches/${child.name.toLowerCase()}")
if (MCINJECTOR.version != null) {
task "mcinject${child.name}"(type: MCInjectTask, dependsOn: [downloadMCInjector, "rename${child.name}", makeExceptions, fixAccessLevels]) {
jar downloadMCInjector.dest
access fixAccessLevels.dest
constructors file(PATH_CTRS)
exceptions makeExceptions.dest
standardOutput rootProject.NULL_OUPUT
log file(PATH_CACHED_VERSION + child.name.toLowerCase() + '.mci.log')
args MCINJECTOR.args
input tasks.getByName("rename${child.name}").dest
dest file(PATH_CACHED_VERSION + child.name.toLowerCase() + '.mci.jar')
}
mcinjectAll.dependsOn "mcinject${child.name}"
if (FERNFLOWER.version != null) {
// this creates one "normal" fernflower and follwing task(s)
// as well as extra tasks for each jvm entry in java_versions.json
def javaExecutables = new LinkedHashMap<>()
javaExecutables.put("", null)
if (rootProject.ext.JAVA_VERSIONS_JSON != null) {
javaExecutables.putAll(rootProject.ext.JAVA_VERSIONS_JSON)
}
task "testJvms${child.name}"
task "testJvms${child.name}Decompile"
task "testJvms${child.name}Compile"
task "testJvms${child.name}Api"
testJvmsAll.dependsOn("testJvms${child.name}")
testJvmsAllDecompile.dependsOn("testJvms${child.name}Decompile")
testJvmsAllCompile.dependsOn("testJvms${child.name}Compile")
testJvmsAllApi.dependsOn("testJvms${child.name}Api")
javaExecutables.each {
def jvmName = it.key
def jvmNameExt = jvmName.isEmpty() ? "" : "_${jvmName}"
def jvmHome = it.value
def isMainDecompile = jvmName.isEmpty()
task "fernflower${child.name}${jvmNameExt}"(type: FernflowerTask, dependsOn: [downloadFernflower, "mcinject${child.name}", "fernflowerLibraries${child.name}"]) {
if (jvmHome != null) {
executable = new File(jvmHome, "bin/java")
}
jar downloadFernflower.dest
jvmArgs FERNFLOWER.jvmargs
libraries tasks.getByName("fernflowerLibraries${child.name}").dest
args FERNFLOWER.args
input tasks.getByName("mcinject${child.name}").dest
if (jvmName.isEmpty()) {
log file(PATH_CACHED_VERSION + child.name.toLowerCase() + '.decomp.log')
dest file(PATH_CACHED_VERSION + child.name.toLowerCase() + '.decomp.jar')
} else {
log file(PATH_CACHED_VERSION + jvmName + '/' + child.name.toLowerCase() + '.decomp.log')
dest file(PATH_CACHED_VERSION + jvmName + '/' + child.name.toLowerCase() + '.decomp.jar')
}
}
if (isMainDecompile) {
fernflowerAll.dependsOn "fernflower${child.name}${jvmNameExt}"
}
if (!isMainDecompile) {
task "fernflower${child.name}${jvmNameExt}_Compare"(dependsOn:
["fernflower${child.name}", "fernflower${child.name}${jvmNameExt}"]) {
doFirst {
def expected = tasks["fernflower${child.name}"].dest
def decompiled = tasks["fernflower${child.name}${jvmNameExt}"].dest
new ZipFile(expected).withCloseable { expectedZip ->
new ZipFile(decompiled).withCloseable { decompZip ->
expectedZip.entries().each { entry ->
if (!entry.isDirectory()) {
expectedZip.getInputStream(entry).withCloseable { expectedStream ->
def decompEntry = decompZip.getEntry(entry.getName())
if (decompEntry == null) {
throw new GradleException("Decompile output with JVM " + jvmName
+ " did not contain file \"" + entry.getName() + "\" in \"" + decompiled.getAbsolutePath()
+ "\" (expected result: \"" + expected.getAbsolutePath() + "\")")
}
decompZip.getInputStream(decompEntry).withCloseable { decompStream ->
logger.debug("Verifying file " + entry.getName())
if (!Arrays.equals(expectedStream.getBytes(), decompStream.getBytes())) {
throw new GradleException("Decompile output of file \"" + entry.getName() + "\" with JVM "
+ jvmName + " in \"" + decompiled.getAbsolutePath()
+ "\" did not match expected result from \"" + expected.getAbsolutePath() + "\"");
}
}
}
}
}
}
}
}
}
tasks["testJvms${child.name}Decompile"].dependsOn("fernflower${child.name}${jvmNameExt}_Compare")
tasks["testJvms${child.name}"].dependsOn("fernflower${child.name}${jvmNameExt}_Compare")
}
if (isMainDecompile) {
task "fernflower${child.name}Inject"(dependsOn: ["fernflower${child.name}"]) {
if (PATH_INJECT_TEMPLATE != null) {
inputs.file PATH_INJECT_TEMPLATE
inputs.file tasks.getByName("fernflower${child.name}").dest
doFirst {
def template = PATH_INJECT_TEMPLATE.text
def visited = ['', 'net', 'net/minecraft', 'com', 'com/mojang'].toSet()
def target = new File(dir, "src/pkginfo/java")
new ZipFile(tasks.getByName("fernflower${child.name}").dest).withCloseable { zip ->
zip.entries().each { entry ->
def folder = entry.isDirectory() && !entry.name.endsWith("/") ? entry.name : entry.name.indexOf('/') == -1 ? '' : entry.name.substring(0, entry.name.lastIndexOf('/'))
if (visited.add(folder)) {
def parent = new File(target, folder)
if (!parent.exists())
parent.mkdirs()
new File(parent, 'package-info.java').text = template.replace('{PACKAGE}', folder.replaceAll('/', '.'))
}
}
}
}
}
}
fernflowerInject.dependsOn "fernflower${child.name}Inject"
if (MCPNAMES != null) {
task "mcpmap${child.name}"(dependsOn: [downloadMCPNames, "fernflower${child.name}"]) {
def out_path = PATH_CACHED_VERSION + child.name.toLowerCase() + '.mcpmaped.jar'
inputs.file downloadMCPNames.dest
inputs.file tasks.getByName("fernflower${child.name}").dest
outputs.file out_path
doFirst {
def names = [:]
new ZipFile(downloadMCPNames.dest).withCloseable { zip ->
zip.entries().findAll { !it.directory && it.name.endsWith('.csv') }
.each {
def reader = new CsvReader()
reader.containsHeader = true
def csv = reader.read(new InputStreamReader(zip.getInputStream(it)))
csv.rows.each { names[it.getField('searge') == null ? it.getField('param') : it.getField('searge')] = it.getField('name') }
}
}
new ZipFile(tasks.getByName("fernflower${child.name}").dest).withCloseable { izip ->
new ZipOutputStream(new FileOutputStream(out_path)).withCloseable { ozip ->
izip.entries().each { entry ->
def oentry = new ZipEntry(entry.name)
oentry.time = 0
ozip.putNextEntry(oentry)
if (entry.name.endsWith('.java'))
ozip << izip.getInputStream(entry).text.replaceAll(/func_[0-9]+_[a-zA-Z_]+|field_[0-9]+_[a-zA-Z_]+|p_[\w]+_\d+_\b/) { name -> names.getOrDefault(name, name) }
else
ozip << izip.getInputStream(entry)
ozip.closeEntry()
}
}
}
}
}
}
task "project${child.name}"(type: CreateProjectTemplate, dependsOn: [projectRoot, "filter${child.extra}Extra", "fernflower${child.name}"] +
(child.jsonlibs ? [downloadJson, extractNatives] : []) +
(child.assets ? [downloadAssets] : []) +
(PATH_INJECT != null ? ["fernflower${child.name}Inject"] : [])
) {
dest dir
distro child.name.toLowerCase()
template PROJECT_TEMPLATE
if (child.jsonlibs)
meta downloadJson.dest
if (CONFIG?.libraries?.get(child.name.toLowerCase()) != null)
CONFIG.libraries.get(child.name.toLowerCase()).each { library "'${it}'" }
library "files('" + tasks.getByName("filter${child.extra}Extra").archivePath.absolutePath.replace('\\', '/') + "')"
replace('{inject}', PATH_INJECT == null ? 'null' : "'${PATH_INJECT.absolutePath.replace('\\', '/')}'")
replace('{assets}', "'${file(PATH_ASSETS).absolutePath.replace('\\', '/')}'")
replace('{natives}', "'${file(PATH_NATIVES).absolutePath.replace('\\', '/')}'")
}
tasks.getByName("project${child.name}").mustRunAfter "project${child.name}Delete"
projectAll.dependsOn "project${child.name}"
task "project${child.name}Delete"(type: Delete) {
delete dir
}
projectDelete.dependsOn "project${child.name}Delete"
task "project${child.name}Reset"(type: ResetSourcesTask, dependsOn: ["project${child.name}", "fernflower${child.name}"] + (MCPNAMES == null ? [] : ["mcpmap${child.name}"])) {
if (MCPNAMES == null)
root tasks.getByName("fernflower${child.name}").dest
else
root tasks.getByName("mcpmap${child.name}").outputs.files.singleFile
target new File(dir, "src/main/java")
}
tasks.getByName("project${child.name}Reset").mustRunAfter "project${child.name}"
projectReset.dependsOn "project${child.name}Reset"
}
if (MCPNAMES == null) {
if (isMainDecompile) {
task "project${child.name}ApplyPatches"(type: ApplyPatchesTask, dependsOn: ["project${child.name}Reset"]) {
target new File(dir, "src/main/java")
patches dir_patches
}
projectApplyPatches.dependsOn "project${child.name}ApplyPatches"
task "project${child.name}MakePatches"(type: MakePatchesTask, dependsOn: ["fernflower${child.name}"]) {
root tasks.getByName("fernflower${child.name}").dest
target new File(dir, 'src/main/java')
patches dir_patches
doLast { //TODO: Update ProPatcher to normalize line endings
dir_patches.eachFileRecurse(FileType.FILES) { if (it.name.endsWith('.patch')) it.text = it.text.replaceAll('\r?\n', '\n') }
}
}
projectMakePatches.dependsOn "project${child.name}MakePatches"
//Adapted from the mcpmap task
task "mojmap${child.name}Rename"(dependsOn: [generateMojMap, "project${child.name}ApplyPatches"]) {
def out_path = PATH_MOJMAP + child.name.toLowerCase() + '/'
def input_path = tasks.getByName("project${child.name}ApplyPatches").target.toPath()
inputs.file file(PATH_MOJMAP + "mappings.zip")
doFirst {
def names = [:]
new ZipFile(file(PATH_MOJMAP + "mappings.zip")).withCloseable { zip ->
zip.entries().findAll { !it.directory && it.name.endsWith('.csv') }
.each {
def reader = new CsvReader()
reader.containsHeader = true
def csv = reader.read(new InputStreamReader(zip.getInputStream(it)))
csv.rows.each { names[it.getField('searge') == null ? it.getField('param') : it.getField('searge')] = it.getField('name') }
}
}
Files.walk(input_path).withCloseable { stream ->
stream.each { entry ->
if(!entry.toFile().isDirectory()) {
def out = new File(out_path + entry.toString().substring(entry.toString().indexOf("src/main/java".replace("/", File.separator))))
if (!out.getParentFile().exists())
out.getParentFile().mkdirs();
def inputString
if (entry.toString().endsWith('.java'))
inputString = new FileInputStream(entry.toFile()).withCloseable { inputstream -> inputstream.text.replaceAll(/func_[0-9]+_[a-zA-Z_]+|field_[0-9]+_[a-zA-Z_]+|p_[\w]+_\d+_\b/) { name -> names.getOrDefault(name, name) } }
else
inputString = new FileInputStream(entry.toFile()).withCloseable { inputstream -> inputstream.text }
Files.newBufferedWriter(out.toPath()).withCloseable { writer ->
writer.write(inputString)
}
}
}
}
}
}
task "test${child.name}CompileMojang"(type: JavaCompile, dependsOn: "mojmap${child.name}Rename") {
destinationDir = file(PATH_MOJMAP + child.name.toLowerCase() + '/classes')
source = new File(PATH_MOJMAP + child.name.toLowerCase() + '/src/main/java/')
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
classpath = files()
doFirst {
classpath = files(java.nio.file.Files.readAllLines(tasks.getByName("fernflowerLibraries${child.name}").dest.toPath())
.collect { file(it.substring(3)) }) // skip "-e="
}
}
tasks["mojmap${child.name}Rename"].onlyIf { hasMojmap }
tasks["test${child.name}CompileMojang"].onlyIf { hasMojmap }
def mc_ver = project.name
def canDoMojmap = false
if (mc_ver.contains("-"))
mc_ver = mc_ver.substring(0, mc_ver.indexOf("-"))
if (mc_ver.contains(".")) {
def split = mc_ver.split("\\.")
def major = Integer.parseInt(split[1])
def len = split.length
canDoMojmap = major > 14 || (major == 14 && !project.name.contains("-") && len > 2 && Integer.parseInt(split[2]) == 4)
}
else {
def snap = mc_ver.split("w")
def y = Integer.parseInt(snap[0])
canDoMojmap = y > 19 || (y == 19 && Integer.parseInt(w) >= 36)
}
if (canDoMojmap && dir_patches.exists() && dir_patches.directorySize())
testCompileMojang.dependsOn("test${child.name}CompileMojang")
}
if (!isMainDecompile) {
def testJvmsTaskName = "testJvms${child.name}${jvmNameExt}_Compile"
task "${testJvmsTaskName}"(type: JavaCompile) {
dependsOn(
"project${child.name}ApplyPatches",
"testJvms${child.name}${jvmNameExt}_Clean"
)
options.warnings = false
options.fork = true
options.forkOptions.with {
executable = new File(jvmHome, "bin/javac")
}
destinationDir = file(PATH_CACHED_VERSION + jvmName + '/classes')
source = new File(dir, 'src/main/java')
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
// JavaCompile task type requires classpath to be specified before the task begins execution
// but the data isn't generated yet, so instead - inject the classpath as the first thing done when it begins
classpath = files()
doFirst {
classpath = files(java.nio.file.Files.readAllLines(tasks.getByName("fernflowerLibraries${child.name}").dest.toPath())
.collect { file(it.substring(3)) }) // skip "-e="
}
}
task "testJvms${child.name}${jvmNameExt}_Clean"(type: Delete) {
delete tasks[testJvmsTaskName].destinationDir
}
tasks["testJvms${child.name}Compile"].dependsOn(testJvmsTaskName)
tasks["testJvms${child.name}"].dependsOn(testJvmsTaskName)
def testJvmsApiTaskName = "testJvms${child.name}${jvmNameExt}_Api"
task "${testJvmsApiTaskName}"(type: CheckAPI, dependsOn: [testJvmsTaskName, rootProject.extractRuntimeAPI]) {
input = tasks[testJvmsTaskName].destinationDir
apis.add(rootProject.extractRuntimeAPI.dest)
dest file(PATH_CACHED_VERSION + jvmName + '/api_errors.json')
}
tasks["testJvms${child.name}Api"].dependsOn(testJvmsApiTaskName)
tasks["testJvms${child.name}"].dependsOn(testJvmsApiTaskName)
}
}
}
}
}
}
task generateConfiguration(type: SingleFileOutput) {
inputs.property('config', CONFIG)
dest file(PATH_CACHED_VERSION_DATA + 'config.json')
doLast {
def json = new JsonBuilder()
def steps_def = [
joined: [
[type: 'downloadManifest'],
[type: 'downloadJson'],
[type: 'downloadClient'],
[type: 'downloadServer'],
[type: 'strip', name: 'stripClient', input: '{downloadClientOutput}'],
[type: 'strip', name: 'stripServer', input: '{downloadServerOutput}'],
[type: 'merge', client: '{stripClientOutput}', server: '{stripServerOutput}', version: project.version],
[type: 'rename', input: '{mergeOutput}'],
[type: 'mcinject', input: '{renameOutput}'],
[type: 'listLibraries'],
[type: 'decompile', libraries: '{listLibrariesOutput}', input: '{mcinjectOutput}'],
[type: 'inject', input: '{decompileOutput}'],
[type: 'patch', input: '{injectOutput}']
],
client: [
[type: 'downloadManifest'],
[type: 'downloadJson'],
[type: 'downloadClient'],
[type: 'strip', input: '{downloadClientOutput}'],
[type: 'rename', input: '{stripOutput}'],
[type: 'mcinject', input: '{renameOutput}'],
[type: 'listLibraries'],
[type: 'decompile', libraries: '{listLibrariesOutput}', input: '{mcinjectOutput}'],
[type: 'inject', input: '{decompileOutput}'],
[type: 'patch', input: '{injectOutput}']
],
server: [