forked from GregTechCEu/Buildscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.gradle
1535 lines (1337 loc) · 55.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
//version: 1726584787
/*
* DO NOT CHANGE THIS FILE!
* Also, you may replace this file at any time if there is an update available.
* Please check https://github.com/GTModpackTeam/Buildscripts/blob/master/build.gradle for updates.
* You can also run ./gradlew updateBuildScript to update your buildscript.
*/
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import com.gtnewhorizons.retrofuturagradle.MinecraftExtension
import com.gtnewhorizons.retrofuturagradle.mcp.MCPTasks
import com.gtnewhorizons.retrofuturagradle.minecraft.MinecraftTasks
import com.gtnewhorizons.retrofuturagradle.mcp.ReobfuscatedJar
import com.gtnewhorizons.retrofuturagradle.minecraft.RunMinecraftTask
import com.gtnewhorizons.retrofuturagradle.util.Distribution
import com.modrinth.minotaur.dependencies.ModDependency
import com.modrinth.minotaur.dependencies.VersionDependency
import de.undercouch.gradle.tasks.download.DownloadExtension
import org.apache.commons.io.FileUtils
import org.gradle.api.internal.artifacts.configurations.DefaultUnlockedConfiguration
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent
import org.gradle.internal.logging.text.StyledTextOutputFactory
import org.jetbrains.gradle.ext.Gradle
import javax.inject.Inject
import static org.gradle.internal.logging.text.StyledTextOutput.Style
plugins {
id 'java'
id 'java-library'
id 'base'
id 'eclipse'
id 'maven-publish'
id 'org.jetbrains.gradle.plugin.idea-ext' version '1.1.8'
id 'com.gtnewhorizons.retrofuturagradle' version '1.4.0'
id 'net.darkhax.curseforgegradle' version '1.1.24' apply false
id 'com.modrinth.minotaur' version '2.8.7' apply false
id 'com.diffplug.spotless' version '6.13.0' apply false
id 'com.palantir.git-version' version '3.0.0' apply false
id 'com.github.johnrengelman.shadow' version '8.1.1' apply false
id 'org.jetbrains.kotlin.jvm' version '1.8.0' apply false
id 'org.jetbrains.kotlin.kapt' version '1.8.0' apply false
id 'com.google.devtools.ksp' version '1.8.0-1.0.9' apply false
id 'de.undercouch.download' version '5.6.0' apply false
}
def out = services.get(StyledTextOutputFactory).create('an-output')
// Project properties
// Required properties: we don't know how to handle these being missing gracefully
checkPropertyExists("modName")
checkPropertyExists("modId")
checkPropertyExists("modGroup")
checkPropertyExists("minecraftVersion") // hard-coding this makes it harder to immediately tell what version a mod is in (even though this only really supports 1.12.2)
checkPropertyExists("apiPackage")
checkPropertyExists("accessTransformersFile")
checkPropertyExists("usesMixins")
checkPropertyExists("mixinsPackage")
checkPropertyExists("coreModClass")
checkPropertyExists("containsMixinsAndOrCoreModOnly")
// Optional properties: we can assume some default behavior if these are missing
propertyDefaultIfUnset("modVersion", "")
propertyDefaultIfUnset("includeMCVersionJar", false)
propertyDefaultIfUnset("autoUpdateBuildScript", false)
propertyDefaultIfUnset("modArchivesBaseName", project.modId)
propertyDefaultIfUnsetWithEnvVar("developmentEnvironmentUserName", "Developer", "DEV_USERNAME")
propertyDefaultIfUnset("additionalJavaArguments", "")
propertyDefaultIfUnset("enableJava17RunTasks", false)
propertyDefaultIfUnset("generateGradleTokenClass", "")
propertyDefaultIfUnset("gradleTokenModId", "")
propertyDefaultIfUnset("gradleTokenModName", "")
propertyDefaultIfUnset("gradleTokenVersion", "")
propertyDefaultIfUnset("useSrcApiPath", false)
propertyDefaultIfUnset("includeWellKnownRepositories", true)
propertyDefaultIfUnset("includeCommonDevEnvMods", true)
propertyDefaultIfUnset("stripForgeRequirements", false)
propertyDefaultIfUnset("noPublishedSources", false)
propertyDefaultIfUnset("forceEnableMixins", false)
propertyDefaultIfUnset("mixinConfigRefmap", "mixins.${project.modId}.refmap.json")
propertyDefaultIfUnsetWithEnvVar("enableCoreModDebug", false, "CORE_MOD_DEBUG")
propertyDefaultIfUnset("generateMixinConfig", true)
propertyDefaultIfUnset("usesShadowedDependencies", false)
propertyDefaultIfUnset("minimizeShadowedDependencies", true)
propertyDefaultIfUnset("relocateShadowedDependencies", true)
propertyDefaultIfUnset("separateRunDirectories", false)
propertyDefaultIfUnset("versionDisplayFormat", '$MOD_NAME \u2212 $VERSION')
propertyDefaultIfUnsetWithEnvVar("modrinthProjectId", "", "MODRINTH_PROJECT_ID")
propertyDefaultIfUnset("modrinthRelations", "")
propertyDefaultIfUnsetWithEnvVar("curseForgeProjectId", "", "CURSEFORGE_PROJECT_ID")
propertyDefaultIfUnset("curseForgeRelations", "")
propertyDefaultIfUnsetWithEnvVar("releaseType", "release", "RELEASE_TYPE")
propertyDefaultIfUnset("generateDefaultChangelog", false)
propertyDefaultIfUnset("customMavenPublishUrl", "")
propertyDefaultIfUnset("mavenArtifactGroup", getDefaultArtifactGroup())
propertyDefaultIfUnset("enableModernJavaSyntax", false)
propertyDefaultIfUnset("enableSpotless", false)
propertyDefaultIfUnset("enableJUnit", false)
propertyDefaultIfUnsetWithEnvVar("deploymentDebug", false, "DEPLOYMENT_DEBUG")
// Project property assertions
final String javaSourceDir = 'src/main/java/'
final String scalaSourceDir = 'src/main/scala/'
final String kotlinSourceDir = 'src/main/kotlin/'
final String modGroupPath = modGroup.toString().replace('.' as char, '/' as char)
final String apiPackagePath = apiPackage.toString().replace('.' as char, '/' as char)
String targetPackageJava = javaSourceDir + modGroupPath
String targetPackageScala = scalaSourceDir + modGroupPath
String targetPackageKotlin = kotlinSourceDir + modGroupPath
if (!getFile(targetPackageJava).exists() && !getFile(targetPackageScala).exists() && !getFile(targetPackageKotlin).exists()) {
throw new GradleException("Could not resolve \"modGroup\"! Could not find ${targetPackageJava} or ${targetPackageScala} or ${targetPackageKotlin}")
}
if (apiPackage) {
final String endApiPath = modGroupPath + '/' + apiPackagePath
if (useSrcApiPath.toBoolean()) {
targetPackageJava = 'src/api/java/' + endApiPath
targetPackageScala = 'src/api/scala/' + endApiPath
targetPackageKotlin = 'src/api/kotlin/' + endApiPath
} else {
targetPackageJava = javaSourceDir + endApiPath
targetPackageScala = scalaSourceDir + endApiPath
targetPackageKotlin = kotlinSourceDir + endApiPath
}
if (!getFile(targetPackageJava).exists() && !getFile(targetPackageScala).exists() && !getFile(targetPackageKotlin).exists()) {
throw new GradleException("Could not resolve \"apiPackage\"! Could not find ${targetPackageJava} or ${targetPackageScala} or ${targetPackageKotlin}")
}
}
if (accessTransformersFile) {
for (atFile in accessTransformersFile.split(",")) {
String targetFile = 'src/main/resources/' + atFile.trim()
if (!getFile(targetFile).exists()) {
throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile)
}
tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(targetFile)
tasks.srgifyBinpatchedJar.accessTransformerFiles.from(targetFile)
}
}
if (usesMixins.toBoolean()) {
if (mixinsPackage.isEmpty()) {
throw new GradleException("\"usesMixins\" requires \"mixinsPackage\" to be set!")
}
final String mixinPackagePath = mixinsPackage.toString().replaceAll('\\.', '/')
targetPackageJava = javaSourceDir + modGroupPath + '/' + mixinPackagePath
targetPackageScala = scalaSourceDir + modGroupPath + '/' + mixinPackagePath
targetPackageKotlin = kotlinSourceDir + modGroupPath + '/' + mixinPackagePath
if (!getFile(targetPackageJava).exists() && !getFile(targetPackageScala).exists() && !getFile(targetPackageKotlin).exists()) {
throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find ${targetPackageJava} or ${targetPackageScala} or ${targetPackageKotlin}")
}
}
if (coreModClass) {
final String coreModPath = coreModClass.toString().replaceAll('\\.', '/')
String targetFileJava = javaSourceDir + modGroupPath + '/' + coreModPath + '.java'
String targetFileScala = scalaSourceDir + modGroupPath + '/' + coreModPath + '.scala'
String targetFileScalaJava = scalaSourceDir + modGroupPath + '/' + coreModPath + '.java'
String targetFileKotlin = kotlinSourceDir + modGroupPath + '/' + coreModPath + '.kt'
if (!getFile(targetFileJava).exists() && !getFile(targetFileScala).exists() && !getFile(targetFileScalaJava).exists() && !getFile(targetFileKotlin).exists()) {
throw new GradleException("Could not resolve \"coreModClass\"! Could not find ${targetFileJava} or ${targetFileScala} or ${targetFileScalaJava} or ${targetFileKotlin}")
}
}
// Plugin application
// Scala
if (getFile('src/main/scala').exists()) {
apply plugin: 'scala'
}
if (getFile('src/main/kotlin').exists()) {
apply plugin: 'org.jetbrains.kotlin.jvm'
}
// Kotlin
pluginManager.withPlugin('org.jetbrains.kotlin.jvm') {
kotlin {
jvmToolchain(8)
}
def disabledKotlinTaskList = [
"kaptGenerateStubsMcLauncherKotlin",
"kaptGenerateStubsPatchedMcKotlin",
"kaptGenerateStubsInjectedTagsKotlin",
"compileMcLauncherKotlin",
"compilePatchedMcKotlin",
"compileInjectedTagsKotlin",
"kaptMcLauncherKotlin",
"kaptPatchedMcKotlin",
"kaptInjectedTagsKotlin",
"kspMcLauncherKotlin",
"kspPatchedMcKotlin",
"kspInjectedTagsKotlin",
]
tasks.configureEach { task ->
if (task.name in disabledKotlinTaskList) {
task.enabled = false
}
}
}
// Spotless
//noinspection GroovyAssignabilityCheck
project.extensions.add(com.diffplug.blowdryer.Blowdryer, 'Blowdryer', com.diffplug.blowdryer.Blowdryer) // make Blowdryer available in plugin application
if (enableSpotless.toBoolean()) {
apply plugin: 'com.diffplug.spotless'
// Spotless auto-formatter
// See https://github.com/diffplug/spotless/tree/main/plugin-gradle
// Can be locally toggled via spotless:off/spotless:on comments
spotless {
encoding 'UTF-8'
format 'misc', {
target '.gitignore'
trimTrailingWhitespace()
indentWithSpaces(4)
endWithNewline()
}
java {
target 'src/main/java/**/*.java', 'src/test/java/**/*.java' // exclude api as they are not our files
def orderFile = project.file('spotless.importorder')
if (!orderFile.exists()) {
orderFile = Blowdryer.file('spotless.importorder')
}
def formatFile = project.file('spotless.eclipseformat.xml')
if (!formatFile.exists()) {
formatFile = Blowdryer.file('spotless.eclipseformat.xml')
}
toggleOffOn()
importOrderFile(orderFile)
removeUnusedImports()
endWithNewline()
//noinspection GroovyAssignabilityCheck
eclipse('4.19.0').configFile(formatFile)
}
kotlin {
target 'src/*/kotlin/**/*.kt'
toggleOffOn()
ktfmt('0.39')
trimTrailingWhitespace()
indentWithSpaces(4)
endWithNewline()
}
scala {
target 'src/*/scala/**/*.scala'
scalafmt('3.7.1')
}
}
}
// Git version checking, also checking for if this is a submodule
if (project.file('.git/HEAD').isFile() || project.file('.git').isFile()) {
apply plugin: 'com.palantir.git-version'
}
// Shadowing
if (usesShadowedDependencies.toBoolean()) {
apply plugin: 'com.github.johnrengelman.shadow'
}
// Configure Java
java {
toolchain {
if (enableModernJavaSyntax.toBoolean()) {
languageVersion.set(JavaLanguageVersion.of(17))
} else {
languageVersion.set(JavaLanguageVersion.of(8))
}
// Azul covers the most platforms for Java 8+ toolchains, crucially including MacOS arm64
vendor.set(JvmVendorSpec.AZUL)
}
if (!noPublishedSources.toBoolean()) {
withSourcesJar()
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
if (enableModernJavaSyntax.toBoolean()) {
if (it.name in ['compileMcLauncherJava', 'compilePatchedMcJava']) {
return
}
sourceCompatibility = 17
options.release.set(8)
javaCompiler.set(javaToolchains.compilerFor {
languageVersion.set(JavaLanguageVersion.of(17))
vendor.set(JvmVendorSpec.AZUL)
})
}
}
tasks.withType(ScalaCompile).configureEach {
options.encoding = 'UTF-8'
}
// Allow others using this buildscript to have custom gradle code run
if (getFile('addon.gradle').exists()) {
apply from: 'addon.gradle'
} else if (getFile('addon.gradle.kts').exists()) {
apply from: 'addon.gradle.kts'
}
// Configure Minecraft
// Try to gather mod version from git tags if version is not manually specified
if (!modVersion) {
try {
modVersion = gitVersion()
} catch (Exception ignored) {
out.style(Style.Failure).text(
"Mod version could not be determined! Property 'modVersion' is not set, and either git is not installed or no git tags exist.\n" +
"Either specify a mod version in 'gradle.properties', or create at least one tag in git for this project."
)
modVersion = 'NO-GIT-TAG-SET'
}
}
if (includeMCVersionJar.toBoolean()){
version = "${minecraftVersion}-${modVersion}"
}
else {
version = modVersion
}
group = modGroup
base {
archivesName = modArchivesBaseName
}
minecraft {
mcVersion = minecraftVersion
username = developmentEnvironmentUserName.toString()
useDependencyAccessTransformers = true
// Automatic token injection with RetroFuturaGradle
if (gradleTokenModId) {
injectedTags.put gradleTokenModId, modId
}
if (gradleTokenModName) {
injectedTags.put gradleTokenModName, modName
}
if (gradleTokenVersion) {
injectedTags.put gradleTokenVersion, modVersion
}
// JVM arguments
extraRunJvmArguments.add("-ea:${modGroup}")
if (usesMixins.toBoolean()) {
extraRunJvmArguments.addAll([
'-Dmixin.hotSwap=true',
'-Dmixin.checks.interfaces=true',
'-Dmixin.debug.export=true'
])
}
if (enableCoreModDebug.toBoolean()) {
extraRunJvmArguments.addAll([
'-Dlegacy.debugClassLoading=true',
'-Dlegacy.debugClassLoadingFiner=true',
'-Dlegacy.debugClassLoadingSave=true'
])
}
if (additionalJavaArguments.size() != 0) {
extraRunJvmArguments.addAll(additionalJavaArguments.split(';'))
}
if (enableJava17RunTasks.toBoolean()) {
lwjgl3Version = "3.3.2"
}
}
if (coreModClass) {
for (runTask in ['runClient', 'runServer']) {
tasks.named(runTask).configure {
extraJvmArgs.add("-Dfml.coreMods.load=${modGroup}.${coreModClass}")
}
}
}
if (generateGradleTokenClass) {
tasks.injectTags.outputClassName.set(generateGradleTokenClass)
}
tasks.named('processIdeaSettings').configure {
dependsOn('injectTags')
}
// Repositories
// Allow unsafe repos but warn
repositories.configureEach { repo ->
if (repo instanceof UrlArtifactRepository) {
if (repo.getUrl() != null && repo.getUrl().getScheme() == "http" && !repo.allowInsecureProtocol) {
logger.warn("Deprecated: Allowing insecure connections for repo '${repo.name}' - add 'allowInsecureProtocol = true'")
repo.allowInsecureProtocol = true
}
}
}
// Allow adding custom repositories to the buildscript
if (getFile('repositories.gradle').exists()) {
apply from: 'repositories.gradle'
} else if (getFile('repositories.gradle.kts').exists()) {
apply from: 'repositories.gradle.kts'
}
repositories {
if (includeWellKnownRepositories.toBoolean() || includeCommonDevEnvMods.toBoolean()) {
exclusiveContent {
forRepository {
//noinspection ForeignDelegate
maven {
name = 'Curse Maven'
url = 'https://www.cursemaven.com'
// url = 'https://beta.cursemaven.com'
}
}
filter {
includeGroup 'curse.maven'
}
}
exclusiveContent {
forRepository {
//noinspection ForeignDelegate
maven {
name = 'Modrinth'
url = 'https://api.modrinth.com/maven'
}
}
filter {
includeGroup 'maven.modrinth'
}
}
maven {
name 'Cleanroom Maven'
url 'https://maven.cleanroommc.com'
}
maven {
name 'BlameJared Maven'
url 'https://maven.blamejared.com'
}
maven {
name 'GTNH Maven'
url 'https://nexus.gtnewhorizons.com/repository/public/'
}
maven {
name 'GTCEu Maven'
url 'https://maven.gtceu.com'
}
}
if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) {
// need to add this here even if we did not above
if (!includeWellKnownRepositories.toBoolean()) {
maven {
name 'Cleanroom Maven'
url 'https://maven.cleanroommc.com'
}
}
}
mavenLocal() // Must be last for caching to work
}
// Dependencies
// Configure dependency configurations
configurations {
embed
implementation.extendsFrom(embed)
if (usesShadowedDependencies.toBoolean()) {
for (config in [compileClasspath, runtimeClasspath, testCompileClasspath, testRuntimeClasspath]) {
config.extendsFrom(shadowImplementation)
config.extendsFrom(shadowCompile)
}
}
create("runtimeOnlyNonPublishable") {
description = "Runtime only dependencies that are not published alongside the jar"
canBeConsumed = false
canBeResolved = false
}
create("devOnlyNonPublishable") {
description = "Runtime and compiletime dependencies that are not published alongside the jar (compileOnly + runtimeOnlyNonPublishable)"
canBeConsumed = false
canBeResolved = false
}
compileOnly.extendsFrom(devOnlyNonPublishable)
runtimeOnlyNonPublishable.extendsFrom(devOnlyNonPublishable)
runtimeClasspath.extendsFrom(runtimeOnlyNonPublishable)
testRuntimeClasspath.extendsFrom(runtimeOnlyNonPublishable)
}
String mixinProviderSpec = 'zone.rong:mixinbooter:9.1'
dependencies {
if (usesMixins.toBoolean()) {
annotationProcessor 'org.ow2.asm:asm-debug-all:5.2'
// should use 24.1.1 but 30.0+ has a vulnerability fix
annotationProcessor 'com.google.guava:guava:30.0-jre'
// should use 2.8.6 but 2.8.9+ has a vulnerability fix
annotationProcessor 'com.google.code.gson:gson:2.8.9'
mixinProviderSpec = modUtils.enableMixins(mixinProviderSpec, mixinConfigRefmap)
api (mixinProviderSpec) {
transitive = false
}
annotationProcessor(mixinProviderSpec) {
transitive = false
}
} else if (forceEnableMixins.toBoolean()) {
runtimeOnlyNonPublishable(mixinProviderSpec)
}
if (enableJUnit.toBoolean()) {
testImplementation 'org.hamcrest:hamcrest:2.2'
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
if (enableModernJavaSyntax.toBoolean()) {
annotationProcessor 'com.github.bsideup.jabel:jabel-javac-plugin:1.0.1'
compileOnly('com.github.bsideup.jabel:jabel-javac-plugin:1.0.1') {
transitive = false
}
// workaround for https://github.com/bsideup/jabel/issues/174
annotationProcessor 'net.java.dev.jna:jna-platform:5.13.0'
// Allow jdk.unsupported classes like sun.misc.Unsafe, workaround for JDK-8206937 and fixes Forge crashes in tests.
patchedMinecraft 'me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0'
// allow Jabel to work in tests
testAnnotationProcessor "com.github.bsideup.jabel:jabel-javac-plugin:1.0.1"
testCompileOnly("com.github.bsideup.jabel:jabel-javac-plugin:1.0.1") {
transitive = false // We only care about the 1 annotation class
}
testCompileOnly "me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0"
}
compileOnlyApi 'org.jetbrains:annotations:24.1.0'
annotationProcessor 'org.jetbrains:annotations:24.1.0'
patchedMinecraft('net.minecraft:launchwrapper:1.17.2') {
transitive = false
}
if ((usesMixins.toBoolean() || forceEnableMixins.toBoolean()) && stripForgeRequirements.toBoolean()) {
runtimeOnlyNonPublishable 'com.cleanroommc:strip-latest-forge-requirements:1.0'
}
if (includeCommonDevEnvMods.toBoolean()) {
if (!(modId.equals('jei'))) {
implementation 'mezz.jei:jei_1.12.2:4.16.1.302'
}
if (!(modId.equals('theoneprobe'))) {
//noinspection DependencyNotationArgument
implementation rfg.deobf('curse.maven:top-245211:2667280') // TOP 1.4.28
}
}
}
pluginManager.withPlugin('org.jetbrains.kotlin.kapt') {
if (usesMixins.toBoolean()) {
dependencies {
kapt(mixinProviderSpec)
}
}
}
configurations.configureEach {
resolutionStrategy.dependencySubstitution {
substitute module('org.scala-lang:scala-library:2.11.1') using module('org.scala-lang:scala-library:2.11.5') because('To allow mixing with Java 8 targets')
}
}
if (getFile('dependencies.gradle').exists()) {
apply from: 'dependencies.gradle'
} else if (getFile('dependencies.gradle.kts').exists()) {
apply from: 'dependencies.gradle.kts'
}
// Test configuration
// Ensure tests have access to minecraft classes
sourceSets {
test {
java {
compileClasspath += patchedMc.output + mcLauncher.output
runtimeClasspath += patchedMc.output + mcLauncher.output
}
}
}
test {
// ensure tests are run with java8
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(8)
}.get()
testLogging {
events TestLogEvent.STARTED, TestLogEvent.PASSED, TestLogEvent.FAILED
exceptionFormat TestExceptionFormat.FULL
showExceptions true
showStackTraces true
showCauses true
showStandardStreams true
}
if (enableJUnit.toBoolean()) {
useJUnitPlatform()
}
}
// Resource processing and jar building
processResources {
// this will ensure that this task is redone when the versions change.
inputs.property 'version', modVersion
inputs.property 'mcversion', minecraftVersion
// Blowdryer puts these files into the resource directory, so
// exclude them from builds (doesn't hurt to exclude even if not present)
exclude('spotless.importorder')
exclude('spotless.eclipseformat.xml')
// replace stuff in mcmod.info, nothing else
filesMatching('mcmod.info') { fcd ->
fcd.expand(
'version': modVersion,
'mcversion': minecraftVersion,
'modid': modId,
'modname': modName
)
}
if (accessTransformersFile) {
String[] ats = accessTransformersFile.split(',')
ats.each { at ->
rename "(${at})", 'META-INF/$1'
}
}
}
// Automatically generate a mixin json file if it does not already exist
tasks.register('generateAssets') {
group = 'GT Buildscript'
description = 'Generates a pack.mcmeta, mcmod.info, or mixins.{modid}.json if needed'
doLast {
// pack.mcmeta
def packMcmetaFile = getFile('src/main/resources/pack.mcmeta')
if (!packMcmetaFile.exists()) {
packMcmetaFile.text = """{
"pack": {
"pack_format": 3,
"description": "${modName} Resource Pack"
}
}
"""
}
// mcmod.info
def mcmodInfoFile = getFile('src/main/resources/mcmod.info')
if (!mcmodInfoFile.exists()) {
mcmodInfoFile.text = """[{
"modid": "\${modid}",
"name": "\${modname}",
"description": "An example mod for Minecraft 1.12.2 with Forge",
"version": "\${version}",
"mcversion": "\${mcversion}",
"logoFile": "",
"url": "",
"authorList": [],
"credits": "",
"dependencies": []
}]
"""
}
// mixins.{modid}.json
if (usesMixins.toBoolean() && generateMixinConfig.toBoolean()) {
def mixinConfigFile = getFile("src/main/resources/mixins.${modId}.json")
if (!mixinConfigFile.exists()) {
mixinConfigFile.text = """{
"package": "${modGroup}.${mixinsPackage}",
"refmap": "${mixinConfigRefmap}",
"target": "@env(DEFAULT)",
"minVersion": "0.8",
"compatibilityLevel": "JAVA_8",
"mixins": [],
"client": [],
"server": []
}
"""
}
}
}
}
tasks.named('processResources').configure {
dependsOn('generateAssets')
}
jar {
manifest {
attributes(getManifestAttributes())
}
// Add all embedded dependencies into the jar
from provider {
configurations.embed.collect {
it.isDirectory() ? it : zipTree(it)
}
}
if (useSrcApiPath && apiPackage) {
from sourceSets.api.output
dependsOn apiClasses
include "${modGroupPath}/**"
include "assets/**"
include "mcmod.info"
include "pack.mcmeta"
if (accessTransformersFile) {
include "META-INF/${accessTransformersFile}"
}
}
}
// Configure default run tasks
if (separateRunDirectories.toBoolean()) {
runClient {
workingDir = file('run/client')
}
runServer {
workingDir = file('run/server')
}
}
// Create API library jar
tasks.register('apiJar', Jar) {
archiveClassifier.set 'api'
if (useSrcApiPath) {
from(sourceSets.api.java) {
include "${modGroupPath}/${apiPackagePath}/**"
}
from(sourceSets.api.output) {
include "${modGroupPath}/${apiPackagePath}/**"
}
} else {
from(sourceSets.main.java) {
include "${modGroupPath}/${apiPackagePath}/**"
}
from(sourceSets.main.output) {
include "${modGroupPath}/${apiPackagePath}/**"
}
}
}
// Configure shadow jar task
if (usesShadowedDependencies.toBoolean()) {
tasks.named('shadowJar', ShadowJar).configure {
manifest {
attributes(getManifestAttributes())
}
// Only shadow classes that are actually used, if enabled
if (minimizeShadowedDependencies.toBoolean()) {
minimize()
}
configurations = [
project.configurations.shadowImplementation,
project.configurations.shadowCompile
]
archiveClassifier.set('dev')
if (relocateShadowedDependencies.toBoolean()) {
relocationPrefix = modGroup + '.shadow'
enableRelocation = true
}
}
configurations.runtimeElements.outgoing.artifacts.clear()
configurations.apiElements.outgoing.artifacts.clear()
configurations.runtimeElements.outgoing.artifact(tasks.named('shadowJar', ShadowJar))
configurations.apiElements.outgoing.artifact(tasks.named('shadowJar', ShadowJar))
tasks.named('jar', Jar) {
enabled = false
finalizedBy(tasks.shadowJar)
}
tasks.named('reobfJar', ReobfuscatedJar) {
inputJar.set(tasks.named('shadowJar', ShadowJar).flatMap({it.archiveFile}))
}
AdhocComponentWithVariants javaComponent = (AdhocComponentWithVariants) project.components.findByName('java')
javaComponent.withVariantsFromConfiguration(configurations.shadowRuntimeElements) {
skip()
}
for (runTask in ['runClient', 'runServer']) {
tasks.named(runTask).configure {
dependsOn('shadowJar')
}
}
}
def getManifestAttributes() {
def attributes = [:]
if (coreModClass) {
attributes['FMLCorePlugin'] = "${modGroup}.${coreModClass}"
}
if (!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) {
attributes['FMLCorePluginContainsFMLMod'] = true
}
if (accessTransformersFile) {
attributes['FMLAT'] = accessTransformersFile.toString()
}
if (usesMixins.toBoolean()) {
attributes['ForceLoadAsMod'] = !containsMixinsAndOrCoreModOnly.toBoolean()
}
return attributes
}
// LWJGL3ify setup
if (enableJava17RunTasks.toBoolean()) {
apply plugin: 'de.undercouch.download'
ext.java17Toolchain = (JavaToolchainSpec spec) -> {
spec.languageVersion.set(JavaLanguageVersion.of(17))
spec.vendor.set(JvmVendorSpec.matching("jetbrains"))
}
ext.java21Toolchain = (JavaToolchainSpec spec) -> {
spec.languageVersion.set(JavaLanguageVersion.of(21))
spec.vendor.set(JvmVendorSpec.matching("jetbrains"))
}
ext.java17DependenciesCfg = (DefaultUnlockedConfiguration) configurations.create("java17Dependencies") {
extendsFrom(configurations.getByName("runtimeClasspath")) // Ensure consistent transitive dependency resolution
canBeConsumed = false
}
ext.java17PatchDependenciesCfg = (DefaultUnlockedConfiguration) configurations.create("java17PatchDependencies") {
canBeConsumed = false
}
dependencies {
if (modId != 'lwjgl3ify') {
java17Dependencies("io.github.twilightflower:lwjgl3ify:1.0.0")
}
java17PatchDependencies("io.github.twilightflower:lwjgl3ify:1.0.0:forgePatches") {
transitive = false
}
}
ext.java17JvmArgs = [
"-Dfile.encoding=UTF-8",
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader",
"-Djava.security.manager=allow",
"--add-opens", "java.base/jdk.internal.loader=ALL-UNNAMED",
"--add-opens", "java.base/java.net=ALL-UNNAMED",
"--add-opens", "java.base/java.nio=ALL-UNNAMED",
"--add-opens", "java.base/java.io=ALL-UNNAMED",
"--add-opens", "java.base/java.lang=ALL-UNNAMED",
"--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED",
"--add-opens", "java.base/java.text=ALL-UNNAMED",
"--add-opens", "java.base/java.util=ALL-UNNAMED",
"--add-opens", "java.base/jdk.internal.reflect=ALL-UNNAMED",
"--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED",
"--add-opens", "jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming",
"--add-opens", "java.desktop/sun.awt=ALL-UNNAMED",
"--add-opens", "java.desktop/sun.awt.image=ALL-UNNAMED",
"--add-opens", "java.desktop/com.sun.imageio.plugins.png=ALL-UNNAMED",
"--add-opens", "jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED",
"--add-opens", "java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED"
]
ext.hotswapJvmArgs = [
// DCEVM advanced hot reload
"-XX:+AllowEnhancedClassRedefinition",
"-XX:HotswapAgent=fatjar"
]
ext.setupHotswapAgent17 = tasks.register("setupHotswapAgent17", SetupHotswapAgentTask, t -> {
t.setTargetForToolchain(java17Toolchain)
})
ext.setupHotswapAgent21 = tasks.register("setupHotswapAgent21", SetupHotswapAgentTask, t -> {
t.setTargetForToolchain(java21Toolchain)
})
def runClient17Task = tasks.register("runClient17", RunHotswappableMinecraftTask, Distribution.CLIENT, "runClient")
runClient17Task.configure {
dependsOn(setupHotswapAgent17)
setup(project)
javaLauncher = project.javaToolchains.launcherFor(project.java17Toolchain)
}
def runServer17Task = tasks.register("runServer17", RunHotswappableMinecraftTask, Distribution.DEDICATED_SERVER, "runServer")
runServer17Task.configure {
dependsOn(setupHotswapAgent17)
setup(project)
javaLauncher = project.javaToolchains.launcherFor(project.java17Toolchain)
}
def runClient21Task = tasks.register("runClient21", RunHotswappableMinecraftTask, Distribution.CLIENT, "runClient")
runClient21Task.configure {
dependsOn(setupHotswapAgent21)
setup(project)
javaLauncher = project.javaToolchains.launcherFor(project.java21Toolchain)
}
def runServer21Task = tasks.register("runServer21", RunHotswappableMinecraftTask, Distribution.DEDICATED_SERVER, "runServer")
runServer21Task.configure {
dependsOn(setupHotswapAgent21)
setup(project)
javaLauncher = project.javaToolchains.launcherFor(project.java21Toolchain)
}
}
abstract class RunHotswappableMinecraftTask extends RunMinecraftTask {
// IntelliJ doesn't seem to allow pre-set commandline arguments, so we also support an env variable
private boolean enableHotswap = Boolean.valueOf(System.getenv("HOTSWAP"))
public final Distribution side
public final String superTask
@Input
boolean getEnableHotswap() {
return enableHotswap
}
@Option(option = "hotswap", description = "Enables HotSwapAgent for enhanced class reloading under a debugger")
boolean setEnableHotswap(boolean enable) {
enableHotswap = enable
}
@Inject
RunHotswappableMinecraftTask(Distribution side, String superTask, org.gradle.api.invocation.Gradle gradle) {
super(side, gradle)
this.side = side
this.superTask = superTask
setGroup("Modded Minecraft")
setDescription("Runs the modded " + side.name().toLowerCase(Locale.ROOT) + " using modern Java and lwjgl3ify")
this.getLwjglVersion().set(3)
}
void setup(Project project) {
final MinecraftExtension minecraft = project.getExtensions().getByType(MinecraftExtension.class)
final MCPTasks mcpTasks = project.getExtensions().getByType(MCPTasks.class)
final MinecraftTasks mcTasks = project.getExtensions().getByType(MinecraftTasks.class)
this.getExtraJvmArgs().addAll((List<String>) project.property("java17JvmArgs"))
if (getEnableHotswap()) {
this.getExtraJvmArgs().addAll((List<String>) project.property("hotswapJvmArgs"))
}
this.classpath(project.property("java17PatchDependenciesCfg"))
this.classpath(mcpTasks.getTaskPackageMcLauncher())
this.classpath(mcpTasks.getTaskPackagePatchedMc())
this.classpath(mcpTasks.getPatchedConfiguration())
this.classpath(project.getTasks().named("jar"))
this.classpath(project.property("java17DependenciesCfg"))
super.setup(project)
dependsOn(
mcpTasks.getLauncherSources().getClassesTaskName(),
mcTasks.getTaskDownloadVanillaAssets(),
mcpTasks.getTaskPackagePatchedMc(),
"jar"
)
getMainClass().set((side == Distribution.CLIENT) ? "GradleStart" : "GradleStartServer")