-
Notifications
You must be signed in to change notification settings - Fork 15
/
build.gradle
1176 lines (1022 loc) · 40.2 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: 1701739812
/*
* 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/GregTechCEu/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.mcp.ReobfuscatedJar
import com.modrinth.minotaur.dependencies.ModDependency
import com.modrinth.minotaur.dependencies.VersionDependency
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 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.7'
id 'com.gtnewhorizons.retrofuturagradle' version '1.3.25'
id 'net.darkhax.curseforgegradle' version '1.1.17' apply false
id 'com.modrinth.minotaur' version '2.8.6' 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
}
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("generateGradleTokenClass", "")
propertyDefaultIfUnset("gradleTokenModId", "")
propertyDefaultIfUnset("gradleTokenModName", "")
propertyDefaultIfUnset("gradleTokenVersion", "")
propertyDefaultIfUnset("includeWellKnownRepositories", true)
propertyDefaultIfUnset("includeCommonDevEnvMods", true)
propertyDefaultIfUnset("noPublishedSources", false)
propertyDefaultIfUnset("forceEnableMixins", false)
propertyDefaultIfUnsetWithEnvVar("enableCoreModDebug", false, "CORE_MOD_DEBUG")
propertyDefaultIfUnset("generateMixinConfig", true)
propertyDefaultIfUnset("usesShadowedDependencies", false)
propertyDefaultIfUnset("minimizeShadowedDependencies", true)
propertyDefaultIfUnset("relocateShadowedDependencies", true)
propertyDefaultIfUnset("separateRunDirectories", false)
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("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) {
targetPackageJava = javaSourceDir + modGroupPath + '/' + apiPackagePath
targetPackageScala = scalaSourceDir + modGroupPath + '/' + apiPackagePath
targetPackageKotlin = kotlinSourceDir + modGroupPath + '/' + apiPackagePath
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 (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 'http://jenkins.usrv.eu:8081/nexus/content/groups/public'
allowInsecureProtocol = true
}
}
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)
}
}
}
String mixinProviderSpec = 'zone.rong:mixinbooter:8.9'
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, "mixins.${modId}.refmap.json")
api (mixinProviderSpec) {
transitive = false
}
annotationProcessor(mixinProviderSpec) {
transitive = false
}
} else if (forceEnableMixins.toBoolean()) {
runtimeOnly(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.0'
compileOnly('com.github.bsideup.jabel:jabel-javac-plugin:1.0.0') {
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.0"
testCompileOnly("com.github.bsideup.jabel:jabel-javac-plugin:1.0.0") {
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 (includeCommonDevEnvMods.toBoolean()) {
implementation 'mezz.jei:jei_1.12.2:4.16.1.302'
//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)
}
}
}
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()) {
def mixinConfigRefmap = "mixins.${modId}.refmap.json"
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)
}
}
}
// 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'
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
}
// IDE Configuration
eclipse {
classpath {
downloadSources = true
downloadJavadoc = true
}
}
idea {
module {
inheritOutputDirs true
downloadJavadoc true
downloadSources true
}
project {
settings {
runConfigurations {
'1. Setup Workspace'(Gradle) {
taskNames = ['setupDecompWorkspace']
}
'2. Run Client'(Gradle) {
taskNames = ['runClient']
}
'3. Run Server'(Gradle) {
taskNames = ['runServer']
}
'4. Run Obfuscated Client'(Gradle) {
taskNames = ['runObfClient']
}
'5. Run Obfuscated Server'(Gradle) {
taskNames = ['runObfServer']
}
if (enableSpotless.toBoolean()) {
'6. Apply Spotless'(Gradle) {
taskNames = ["spotlessApply"]
}
'7. Build Jars'(Gradle) {
taskNames = ['build']
}
} else {
'6. Build Jars'(Gradle) {
taskNames = ['build']
}
}
'Update Buildscript'(Gradle) {
taskNames = ['updateBuildScript']
}
'FAQ'(Gradle) {
taskNames = ['faq']
}
}
compiler.javac {
afterEvaluate {
javacAdditionalOptions = '-encoding utf8'
moduleJavacAdditionalOptions = [
(project.name + '.main'): tasks.compileJava.options.compilerArgs.collect {
'"' + it + '"'
}.join(' ')
]
}
}
}
}
}
// Deployment
def final modrinthApiKey = providers.environmentVariable('MODRINTH_API_KEY')
def final cfApiKey = providers.environmentVariable('CURSEFORGE_API_KEY')
final boolean isCIEnv = providers.environmentVariable('CI').getOrElse('false').toBoolean()
if (isCIEnv || deploymentDebug.toBoolean()) {
artifacts {
if (!noPublishedSources.toBoolean()) {
archives sourcesJar
}
if (apiPackage) {
archives apiJar
}
}
}
// Changelog generation
tasks.register('generateChangelog') {
group = 'GT Buildscript'
description = 'Generate a default changelog of all commits since the last tagged git commit'
onlyIf {
generateDefaultChangelog.toBoolean()
}
doLast {
def lastTag = getLastTag()
def changelog = runShell(([
"git",
"log",
"--date=format:%d %b %Y",
"--pretty=%s - **%an** (%ad)",
"${lastTag}..HEAD"
] + (sourceSets.main.java.srcDirs + sourceSets.main.resources.srcDirs)
.collect { ['--', it] }).flatten())
if (changelog) {
changelog = "Changes since ${lastTag}:\n${{("\n" + changelog).replaceAll("\n", "\n* ")}}"
}
def f = getFile('build/changelog.md')
changelog = changelog ?: 'There have been no changes.'
f.write(changelog, 'UTF-8')
// Set changelog for Modrinth
if (modrinthApiKey.isPresent() || deploymentDebug.toBoolean()) {
modrinth.changelog.set(changelog)
}
}
}
if (cfApiKey.isPresent() || deploymentDebug.toBoolean()) {
apply plugin: 'net.darkhax.curseforgegradle'
//noinspection UnnecessaryQualifiedReference
tasks.register('curseforge', net.darkhax.curseforgegradle.TaskPublishCurseForge) {
disableVersionDetection()
debugMode = deploymentDebug.toBoolean()
apiToken = cfApiKey.getOrElse('debug_token')
doFirst {
def mainFile = upload(curseForgeProjectId, reobfJar)
def changelogFile = getChangelog()
def changelogRaw = changelogFile.exists() ? changelogFile.getText('UTF-8') : ""
mainFile.displayName = "${modName}: ${modVersion}"
mainFile.releaseType = getReleaseType()
mainFile.changelog = changelogRaw
mainFile.changelogType = 'markdown'
mainFile.addModLoader 'Forge'
mainFile.addJavaVersion "Java 8"
mainFile.addGameVersion minecraftVersion
if (curseForgeRelations.size() != 0) {
String[] deps = curseForgeRelations.split(';')
deps.each { dep ->
if (dep.size() == 0) {
return
}
String[] parts = dep.split(':')
String type = parts[0], slug = parts[1]
if (!(type in ['requiredDependency', 'embeddedLibrary', 'optionalDependency', 'tool', 'incompatible'])) {
throw new Exception('Invalid Curseforge dependency type: ' + type)
}
mainFile.addRelation(slug, type)
}
}
for (artifact in getSecondaryArtifacts()) {
def additionalFile = mainFile.withAdditionalFile(artifact)
additionalFile.changelog = changelogRaw
}
}
}
tasks.curseforge.dependsOn(build)
tasks.curseforge.dependsOn('generateChangelog')
}
if (modrinthApiKey.isPresent() || deploymentDebug.toBoolean()) {
apply plugin: 'com.modrinth.minotaur'
def final changelogFile = getChangelog()
modrinth {
token = modrinthApiKey.getOrElse('debug_token')
projectId = modrinthProjectId
changelog = changelogFile.exists() ? changelogFile.getText('UTF-8') : ""
versionType = getReleaseType()
versionNumber = modVersion
gameVersions = [minecraftVersion]
loaders = ["forge"]
debugMode = deploymentDebug.toBoolean()
uploadFile = reobfJar
additionalFiles = getSecondaryArtifacts()
}
if (modrinthRelations.size() != 0) {
String[] deps = modrinthRelations.split(';')
deps.each { dep ->
if (dep.size() == 0) {
return
}
String[] parts = dep.split(':')
String[] qual = parts[0].split('-')
addModrinthDep(qual[0], qual[1], parts[1])
}
}
tasks.modrinth.dependsOn(build)
tasks.modrinth.dependsOn('generateChangelog')
}
def addModrinthDep(String scope, String type, String name) {
com.modrinth.minotaur.dependencies.Dependency dep
if (!(scope in ['required', 'optional', 'incompatible', 'embedded'])) {
throw new Exception('Invalid modrinth dependency scope: ' + scope)
}
switch (type) {
case 'project':
dep = new ModDependency(name, scope)
break
case 'version':
dep = new VersionDependency(name, scope)
break
default:
throw new Exception('Invalid modrinth dependency type: ' + type)
}
project.modrinth.dependencies.add(dep)
}
if (customMavenPublishUrl) {
String publishedVersion = modVersion
publishing {
publications {
create('maven', MavenPublication) {
//noinspection GroovyAssignabilityCheck
from components.java
if (apiPackage) {
artifact apiJar
}
// providers is not available here, use System for getting env vars
groupId = System.getenv('ARTIFACT_GROUP_ID') ?: project.group
artifactId = System.getenv('ARTIFACT_ID') ?: project.name
version = System.getenv('RELEASE_VERSION') ?: publishedVersion
}
}
repositories {
maven {
url = customMavenPublishUrl
allowInsecureProtocol = !customMavenPublishUrl.startsWith('https')
credentials {
username = providers.environmentVariable('MAVEN_USER').getOrElse('NONE')
password = providers.environmentVariable('MAVEN_PASSWORD').getOrElse('NONE')
}