forked from mekanism/Mekanism
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.gradle
894 lines (811 loc) · 41.4 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
import com.modrinth.minotaur.TaskModrinthUpload
import com.modrinth.minotaur.dependencies.ModDependency
import com.modrinth.minotaur.dependencies.VersionDependency
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import mekanism.MergeJars
import net.darkhax.curseforgegradle.TaskPublishCurseForge
import net.darkhax.curseforgegradle.UploadArtifact
import net.minecraftforge.gradle.common.util.RunConfig
import net.minecraftforge.gradle.userdev.tasks.RenameJarInPlace
import java.util.function.Consumer
plugins {
id 'org.ajoberstar.grgit.service' version '5.2.0'
id 'net.darkhax.curseforgegradle' version '1.1.16'
id "com.modrinth.minotaur" version "2.+"
id 'java'
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.neoforged.gradle' version '[6.0.18,6.2)'
id 'org.parchmentmc.librarian.forgegradle' version '1.+'
}
tasks.named('wrapper', Wrapper).configure {
//Define wrapper values here so as to not have to always do so when updating gradlew.properties
gradleVersion = '8.2.1'
distributionType = Wrapper.DistributionType.ALL
}
defaultTasks 'build'
idea {
module {
//Exclude directories from being managed
for (String excludeDirName in ["run", "runGameTests", "out", "logs", "gradle"]) {
excludeDirs.add(new File(projectDir, excludeDirName))
}
}
}
ext {
versionProperties = ["version" : mod_version, "mc_version": minecraft_version_range, "forge_version": forge_version_range,
"loader_version": loader_version_range, "crafttweaker_version": crafttweaker_version_range, "curios_version": curios_version_range,
"jei_version": jei_version_range, "json_things_version": json_things_version_range, "wthit_version": wthit_version_range]
jsonPatterns = ["**/*.json", "**/*.mcmeta"]
secondaryModules = ['additions', 'defense', 'generators', 'tools']
extraTypes = ['datagen', 'gameTest']
}
sourceSets {
api {
//The API has no resources
resources.srcDirs = []
}
main {
resources {
include '**/**'
// copy everything else, but blender and bbmodel files.
exclude '**/*.blend'
exclude '**/*.bbmodel'
//Add the generated main module resources
srcDirs += ['src/datagen/generated/mekanism']
//But exclude the cache of the generated data from what gets built
exclude '.cache'
}
compileClasspath += api.output
runtimeClasspath += api.output
}
test {
//The test module has no resources
resources.srcDirs = []
//Add the api to the output, all other ones that need to will get added via setupExtraSourceSets
compileClasspath += api.output
runtimeClasspath += api.output
}
}
configurations {
datagenNonMod
}
//Add all extra source sets that the main sourceSet should have
setupExtraSourceSets(sourceSets.main)
configurations {
//Make sure all our sub source set stuff extends the proper base methods so that
// they can see all the dependencies we have in dependencies including forge
extendConfigurations(implementation, apiImplementation, testImplementation)
extendConfigurations(compileOnly, apiCompileOnly, testCompileOnly)
extendConfigurations(runtimeOnly, apiRuntimeOnly)
}
//Create sourceSets and configurations for each of the additional modules in src/$name and adds a reference to
// the corresponding data gen's resource directory excluding the cache. It also adds the api and main mekanism
// module to the dependencies of the source set we are setting up, and sets up all extra source sets that are
// based on the primary added source set
for (String name : secondaryModules) {
def sourceSet = sourceSets.create(name)
sourceSet.resources {
//Add the generated module resources
srcDirs += ["src/datagen/generated/mekanism${name}"]
//But exclude the cache of the generated data from what gets built
exclude '.cache'
}
sourceSet.compileClasspath += sourceSets.api.output
sourceSet.compileClasspath += sourceSets.main.output
//Create all secondary sourceSets for this module
setupExtraSourceSets(sourceSet)
}
//Setup the UPDATE_SOURCESET property in case we are doing any remappings
project.ext."UPDATE_SOURCESETS" = project.sourceSets.collect { it.name }.join(';')
def setupExtraSourceSets(SourceSet base) {
//Expose the base module to junit
project.sourceSets.test.compileClasspath += base.output
project.sourceSets.test.runtimeClasspath += base.output
//Setup and extend configurations for alternate modules. First by making the implementation, compileOnly, runtimeOnly equivalents
// for those modules extend the main ones
def baseImplementation = project.configurations.maybeCreate(base.getTaskName(null, "implementation"))
def baseCompileOnly = project.configurations.maybeCreate(base.getTaskName(null, "compileOnly"))
def baseRuntimeOnly = project.configurations.maybeCreate(base.getTaskName(null, "runtimeOnly"))
if (base != project.sourceSets.main) {
// If this is a secondary module then make the base tasks extend the builtin ones
baseImplementation.extendsFrom(project.configurations.getByName("implementation"))
baseCompileOnly.extendsFrom(project.configurations.getByName("compileOnly"))
baseRuntimeOnly.extendsFrom(project.configurations.getByName("runtimeOnly"))
}
//And then setup and have all the extra sourceSets have their configurations extend the ones for the base module so that they can
// properly access the dependency
for (String extraType : extraTypes) {
//Setup a source set in extraType/$name
def extraSourceSet = setupExtraSourceSet(base, extraType)
//And then setup the configurations for it
def implExtends = [baseImplementation]
if (extraType == 'datagen'){
implExtends.add(project.configurations.getByName("datagenNonMod"))
}
project.configurations.maybeCreate(extraSourceSet.getTaskName(null, "implementation")).extendsFrom(*implExtends)
project.configurations.maybeCreate(extraSourceSet.getTaskName(null, "compileOnly")).extendsFrom(baseCompileOnly)
project.configurations.maybeCreate(extraSourceSet.getTaskName(null, "runtimeOnly")).extendsFrom(baseRuntimeOnly)
}
}
SourceSet setupExtraSourceSet(SourceSet baseSourceSet, String extra) {
def name = baseSourceSet.getName()
def extraSourceSet = sourceSets.create(baseSourceSet.getTaskName(extra, null))
extraSourceSet.java.srcDirs = ["src/${extra}/${name}/java"]
//Resources folder for if we have anything get created by our annotation processors or in the case of game tests, for any nbt presets
extraSourceSet.resources.srcDirs = ["src/${extra}/${name}/resources"]
extraSourceSet.compileClasspath += project.sourceSets.api.output
extraSourceSet.compileClasspath += project.sourceSets.main.output
if (baseSourceSet != project.sourceSets.main) {
//If the base sourceSet is main it already is the extra source set and has a reference to the base one from before this if statement
extraSourceSet.compileClasspath += getExtraSourceSet(project.sourceSets.main, extra).output
extraSourceSet.compileClasspath += baseSourceSet.output
}
return extraSourceSet
}
static void extendConfigurations(Configuration base, Configuration... configurations) {
for (def configuration : configurations) {
configuration.extendsFrom(base)
}
}
SourceSet getExtraSourceSet(String base, String name) {
return getExtraSourceSet(project.sourceSets.getByName(base), name)
}
SourceSet getExtraSourceSet(SourceSet base, String name) {
return project.sourceSets.getByName(base.getTaskName(name, null))
}
setupTasks(sourceSets.main)
for (String name : secondaryModules) {
setupTasks(sourceSets.getByName(name))
}
def setupTasks(SourceSet sourceSet) {
def output = sourceSet.name
def compileTask = tasks.named(sourceSet.getCompileJavaTaskName(), JavaCompile)
def replaceResourceTask = tasks.register(sourceSet.getTaskName("replace", "resources"), Copy, {
setGroup("replace resources")
outputs.upToDateWhen { false }
def modsToml = copySpec {
from(sourceSet.resources) {
include "META-INF/mods.toml"
expand versionProperties
}
}
//Copy it into the build dir
with(modsToml)
into "$buildDir/resources/${output}/"
//If IntelliJ's output dir exists, copy it there as well
def intellijPath = sourceSet == project.sourceSets.main ? "production" : output
if (new File("$rootDir/out/${intellijPath}/resources/").exists()) {
copy {
with(modsToml)
into "$rootDir/out/${intellijPath}/resources/"
}
}
//If Eclipse's output dir exists, copy it there as well
if (new File("$rootDir/bin/${output}/").exists()) {
copy {
with(modsToml)
into "$rootDir/bin/${output}/"
}
}
})
//Set the various variables/settings for the different process resources tasks
tasks.named(sourceSet.getProcessResourcesTaskName(), ProcessResources).configure {
setGroup("process resources")
duplicatesStrategy(DuplicatesStrategy.FAIL)
exclude('META-INF/mods.toml')
from("${projectDir}") { include 'logo.png' }
//Depend on the compile task so that we can map the computer methods as needed
dependsOn(compileTask)
finalizedBy(replaceResourceTask)
doLast {
fileTree(dir: getOutputs().getFiles().getAsPath(), includes: jsonPatterns).each {
File file -> file.setText(JsonOutput.toJson(new JsonSlurper().parse(file)))
}
}
}
tasks.named(sourceSet.getCompileJavaTaskName(), JavaCompile).configure { setGroup("compile") }
for (String extraType : extraTypes) {
def extraSourceSet = getExtraSourceSet(sourceSet, extraType)
tasks.named(extraSourceSet.getProcessResourcesTaskName(), ProcessResources).configure {
setGroup("process resources")
dependsOn(compileTask)
}
tasks.named(extraSourceSet.getCompileJavaTaskName(), JavaCompile).configure { setGroup("compile") }
}
//Make the various classes tasks depend on the corresponding replaceResources tasks in addition to the default processResources tasks they depend on
tasks.named(sourceSet.getClassesTaskName()).configure { dependsOn(replaceResourceTask) }
//Configure specific compile tasks to have the proper annotation processor info
compileTask.configure {
setGroup("compile")
options.annotationProcessorPath = configurations.annotationProcessor
options.compilerArgs.addAll([
"-AmekanismModule=mekanism${sourceSet == sourceSets.main ? "" : output}",//annotation processor param
"-parameters"
])
}
}
group = "mekanism"
def basicVersion = "${mod_version}." + (System.env.BUILD_NUMBER ?: "homebaked")
version = "${minecraft_version}-${basicVersion}"
archivesBaseName = "Mekanism"
java {
toolchain.languageVersion = JavaLanguageVersion.of("${java_version}")
withSourcesJar()
}
//nb this exists here so that IDEA can resolve `project`
def datagenExtraClasspath = {
def paths = new HashSet<String>()
project.configurations.datagenNonMod.copyRecursive().resolve()
.collect { it.absolutePath.toString() }
.findAll { (!it.contains("datafixerupper")) }//avoid adding datafixerupper twice as modlauncher will die
.each { path -> paths.add(path) }
return paths.join(File.pathSeparator)
}
minecraft {
if (mappings_channel == "parchment_previous") {
mappings channel: 'parchment', version: "${previous_minecraft_version}-${mappings_version}"
} else {
mappings channel: "${mappings_channel}", version: "${mappings_version}"
}
accessTransformers.from(file('src/main/resources/META-INF/accesstransformer.cfg'),
file('src/additions/resources/META-INF/accesstransformer.cfg'))
runs {
client {
setupRunConfig(it, true)
//The below if statements are to add args to your gradle.properties file in user home
// (DO NOT add them directly to the gradle.properties file for this project)
// Setting the below properties allows use of your normal Minecraft account in the
// dev environment including having your skin load. Each property also has a comment
// explaining what information to set the value to/format it expects
// One thing to note is because of the caching that goes on, after changing these
// variables, you need to refresh the project and rerun genIntellijRuns/genEclipseRuns
if (project.hasProperty('mc_uuid')) {
//Your uuid without any dashes in the middle
args '--uuid', project.getProperty('mc_uuid')
}
if (project.hasProperty('mc_username')) {
//Your username/display name, this is the name that shows up in chat
// Note: This is not your email, even if you have a Mojang account
args '--username', project.getProperty('mc_username')
}
if (project.hasProperty('mc_accessToken')) {
//Your access token, you can find it in your '.minecraft/launcher_accounts.json' file
args '--accessToken', project.getProperty('mc_accessToken')
}
}
server { setupRunConfig(it, true) }
gameTestServer { setupRunConfig(it, true, "runGameTests") }
data {
setupRunConfig(it, false)
environment 'target', 'fmluserdevdata'
args '--all', '--output', file('src/datagen/generated/'),
'--mod', 'mekanism', '--existing', file('src/main/resources/')
mods.named("mekanism").configure { source((SourceSet) sourceSets.datagenMain) }
for (String name : secondaryModules) {
def modName = "mekanism${name}"
def extra = getExtraSourceSet(name, 'datagen')
mods.named(modName).configure { source(extra) }
args '--mod', modName, '--existing', file("src/${name}/resources/")
}
project.afterEvaluate {
//After the project has been evaluated so our dependencies has been populated,
// add all the extra non-mod files to runData's minecraft classpath so that they can be
// access from the game module layer at runtime
lazyToken("minecraft_classpath", datagenExtraClasspath)
}
}
}
}
def setupRunConfig(RunConfig runConfig, boolean supportsGameTests, String directory = "run") {
runConfig.workingDirectory(file(directory))
//This fixes Mixin application problems from other mods because their refMaps are SRG-based, but we're in a MCP env
runConfig.property 'mixin.env.remapRefMap', 'true'
runConfig.property 'mixin.env.refMapRemappingFile', "${projectDir}/build/createSrgToMcp/output.srg"
if (supportsGameTests) {
//Specify all our mods as domains to look for game tests
runConfig.property 'forge.enabledGameTestNamespaces', 'mekanism,mekanismadditions,mekanismdefense,mekanismgenerators,mekanismtools'
}
if (project.hasProperty('forge_force_ansi')) {
//Force ansi if declared as a gradle variable, as the auto detection doesn't detect IntelliJ properly
// or eclipse's plugin that adds support for ansi escape in console
runConfig.jvmArg("-Dterminal.ansi=${project.getProperty('forge_force_ansi')}")
}
runConfig.mods.register("mekanism").configure {
sources((SourceSet[]) [sourceSets.main, sourceSets.api])
if (supportsGameTests) source((SourceSet) sourceSets.gameTestMain)
}
for (String name : secondaryModules) {
def base = sourceSets.getByName(name)
def extra = supportsGameTests ? getExtraSourceSet(base, 'gameTest') : null
runConfig.mods.register("mekanism${name}").configure {
source(base)
if (supportsGameTests) source(extra)
}
}
//if the selected toolchain is a JBR, enable DCEVM
if(project.javaToolchains.launcherFor(java.toolchain).map{it.metadata.vendor }.getOrElse("").contains("JetBrains")) {
runConfig.jvmArg("-XX:+AllowEnhancedClassRedefinition")
}
}
void exclusiveRepo(RepositoryHandler handler, String url, String... groups) {
exclusiveRepo(handler, url, filter -> {
for (def group : groups) {
filter.includeGroup(group)
}
})
}
//Note: This cannot be static so that fg.repository can be properly accessed
@SuppressWarnings('GrMethodMayBeStatic')
void exclusiveRepo(RepositoryHandler handler, String url, Consumer<InclusiveRepositoryContentDescriptor> filterSetup) {
handler.exclusiveContent {
it.forRepositories(handler.maven {
setUrl(url)
}, fg.repository)//Add FG's repo so we make sure we are able to then find the mapped deps
it.filter { f -> filterSetup.accept(f) }
}
}
repositories { RepositoryHandler handler ->
exclusiveRepo(handler, 'https://maven.blamejared.com', filter -> {
filter.includeGroupByRegex 'com\\.blamejared.*'
filter.includeGroup 'mezz.jei'
filter.includeGroup 'org.openzen.zencode'
})
exclusiveRepo(handler, 'https://maven.theillusivec4.top/', 'top.theillusivec4.curios')
exclusiveRepo(handler, 'https://maven.tterrag.com/', 'team.chisel.ctm')
exclusiveRepo(handler, 'https://squiddev.cc/maven/', 'cc.tweaked', 'org.squiddev')
exclusiveRepo(handler, 'https://dogforce-games.com/maven/', 'dev.gigaherz.jsonthings')
exclusiveRepo(handler, 'https://maven2.bai.lol', 'lol.bai', 'mcp.mobius.waila')//WTHIT
exclusiveRepo(handler, 'https://www.cursemaven.com', 'curse.maven')
exclusiveRepo(handler, 'https://modmaven.dev/', 'appeng', 'mcjty.theoneprobe')
exclusiveRepo(handler, 'https://maven.thiakil.com', 'com.thiakil')
exclusiveRepo(handler, 'https://maven.parchmentmc.org/', 'org.parchmentmc.data')
}
test {
useJUnitPlatform()
}
dependencies {
minecraft "net.neoforged:forge:${minecraft_version}-${forge_version}"
annotationProcessor project(":annotation-processor")
testImplementation "org.junit.jupiter:junit-jupiter-api:${junit_version}"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${junit_version}"
//We use https://github.com/quicktheories/QuickTheories to allow for implementing property based testing
testImplementation "org.quicktheories:quicktheories:${quicktheories_version}"
compileOnly fg.deobf("mezz.jei:jei-${minecraft_version}-common-api:${jei_version}")
compileOnly fg.deobf("mezz.jei:jei-${minecraft_version}-forge-api:${jei_version}")
runtimeOnly fg.deobf("mezz.jei:jei-${minecraft_version}-forge:${jei_version}")
//TODO - 1.19: Re-enable once https://github.com/Chisel-Team/ConnectedTexturesMod/pull/204 is merged
//runtimeOnly fg.deobf("team.chisel.ctm:CTM:${minecraft_version}-${ctm_version}")
//TODO: Remove having to specify these as non transitive once https://github.com/McJtyMods/TheOneProbe/issues/548 is fixed
compileOnly fg.deobf("mcjty.theoneprobe:theoneprobe:${top_version}:api") {
transitive = false
}
runtimeOnly fg.deobf("mcjty.theoneprobe:theoneprobe:${top_version}") {
transitive = false
}
compileOnly fg.deobf("curse.maven:jade-api-324717:${jade_api_id}")
runtimeOnly fg.deobf("curse.maven:jade-324717:${jade_id}")
compileOnly fg.deobf("mcp.mobius.waila:wthit-api:forge-${wthit_version}")
implementation fg.deobf("com.blamejared.crafttweaker:CraftTweaker-forge-${minecraft_version}:${crafttweaker_version}")
implementation fg.deobf("com.blamejared.jeitweaker:JeiTweaker-forge-${minecraft_version}:${jeitweaker_version}")
compileOnly fg.deobf("dev.gigaherz.jsonthings:JsonThings-${minecraft_version}:${json_things_version}")
//Mods we have dependencies on but don't bother loading into the dev environment
compileOnly fg.deobf("curse.maven:projecte-api-226410:${projecte_api_id}")
compileOnly fg.deobf("curse.maven:flux-networks-248020:${flux_networks_id}")
compileOnly fg.deobf("top.theillusivec4.curios:curios-forge:${curios_version}:api")
compileOnly fg.deobf("com.blamejared.recipestages:RecipeStages:${recipe_stages_version}")
compileOnly fg.deobf("curse.maven:opencomputers2-437654:${oc2_id}")
compileOnly fg.deobf("cc.tweaked:cc-tweaked-${minecraft_version}-forge-api:${cc_tweaked_version}")
compileOnly fg.deobf("cc.tweaked:cc-tweaked-${minecraft_version}-core-api:${cc_tweaked_version}")
//runtimeOnly fg.deobf("cc.tweaked:cc-tweaked-${minecraft_version}-forge:${cc_tweaked_version}")
compileOnly fg.deobf("curse.maven:female-gender-forge-481655:${wildfire_gender_mod_id}")
//Dependencies for data generators for mod compat reference
datagenMainImplementation fg.deobf("appeng:appliedenergistics2-forge:${ae2_version}")
datagenMainCompileOnly fg.deobf("curse.maven:biomes-o-plenty-api-220318:${biomesoplenty_api_id}")
datagenMainRuntimeOnly fg.deobf("curse.maven:biomes-o-plenty-220318:${biomesoplenty_id}")
datagenMainRuntimeOnly fg.deobf("curse.maven:terrablender-563928:${terrablender_id}")
//TODO - 1.20: Switch back to datagenMainImplementation
datagenMainCompileOnly fg.deobf("curse.maven:biomes-youll-go-247560:${byg_id}")
datagenMainImplementation fg.deobf("curse.maven:farmers-delight-398521:${farmers_delight_id}")
datagenMainImplementation fg.deobf("curse.maven:i-like-wood-324164:${ilikewood_id}")
//TODO - 1.20: Switch back to datagenMainImplementation
datagenMainCompileOnly fg.deobf("curse.maven:i-like-wood-biomes-o-plenty-437203:${ilikewood_bop_id}")
//TODO - 1.20: Switch back to datagenMainImplementation
datagenMainCompileOnly fg.deobf("curse.maven:i-like-wood-oh-the-biomes-youll-go-475110:${ilikewood_byg_id}")
//TODO - 1.20: Re-enable after projecte is updated
//datagenMainRuntimeOnly fg.deobf("curse.maven:projecte-226410:${projecte_id}")
datagenNonMod "com.thiakil:yaml-ops:${yamlops_version}"
}
def getManifestAttributes(String title) {
return [
"Specification-Title" : title,
"Specification-Vendor" : "Mekanism",
"Specification-Version" : "${project.mod_version}",
"Implementation-Title" : title,
"Implementation-Version" : "${project.mod_version}",
"Implementation-Vendor" : "Mekanism",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"),
"Automatic-Module-Name" : title.toLowerCase(Locale.ROOT)
]
}
tasks.named('jar', Jar).configure {
duplicatesStrategy(DuplicatesStrategy.FAIL)
from([sourceSets.api.output, sourceSets.main.output])
exclude('crafttweaker_parameter_names.json')
manifest.attributes(getManifestAttributes("Mekanism"))
}
tasks.named('sourcesJar', Jar).configure {
dependsOn(classes, apiClasses, additionsClasses, defenseClasses, generatorsClasses, toolsClasses)
duplicatesStrategy(DuplicatesStrategy.FAIL)
//Note: Already contains main source set's sources by default
from(sourceSets.api.allJava, sourceSets.additions.allJava, sourceSets.defense.allJava, sourceSets.generators.allJava, sourceSets.tools.allJava)
manifest.attributes(getManifestAttributes("Mekanism"))
}
def secondaryJar(SourceSet sourceSet, String title) {
return tasks.register(sourceSet.getJarTaskName(), Jar, {
duplicatesStrategy(DuplicatesStrategy.FAIL)
archiveClassifier.set(sourceSet.name)
from sourceSet.output
if (!title.isEmpty()) {
archiveFileName.set("${title}-${project.version}.jar")
}
manifest.attributes(getManifestAttributes(title.isEmpty() ? "Mekanism" : title))
})
}
def apiJar = secondaryJar(sourceSets.api, '')
def additionsJar = secondaryJar(sourceSets.additions, 'MekanismAdditions')
def defenseJar = secondaryJar(sourceSets.defense, 'MekanismDefense')
def generatorsJar = secondaryJar(sourceSets.generators, 'MekanismGenerators')
def toolsJar = secondaryJar(sourceSets.tools, 'MekanismTools')
def allJar = tasks.register('allJar', Jar, {
dependsOn(classes, apiClasses, additionsClasses, defenseClasses, generatorsClasses, toolsClasses)
mustRunAfter(clean)
duplicatesStrategy(DuplicatesStrategy.FAIL)
archiveClassifier.set("all")
manifest.attributes(getManifestAttributes("MekanismAll"))
def combineSets = [sourceSets.main, sourceSets.additions, sourceSets.defense, sourceSets.generators, sourceSets.tools]
doFirst {
//Start by generating the merged data
MergeJars.merge(project, combineSets)
}
//Then copy all the files except for ones we are going to include from the merged
from(sourceSets.api.output)
List<String> baseExcludeData = MergeJars.getGeneralPathsToExclude(project, combineSets)
Closure excludeFromMain = MergeJars.createExcludeClosure(baseExcludeData, 'crafttweaker_parameter_names.json')
from(sourceSets.main.output, excludeFromMain)
Closure excludeFromAll = MergeJars.createExcludeClosure(baseExcludeData, 'logo.png', 'pack.mcmeta')
for (String name : secondaryModules) {
from(sourceSets.getByName(name).output, excludeFromAll)
}
//And finally copy over the generated files
MergeJars.getGeneratedClosures(versionProperties).each { closure -> from("$buildDir/generated", closure) }
})
clean {
//TODO: Try to come up with a slightly better solution to this that deletes more,
// for example make it calculate the current hash and only leave that or only do
// this if clean build is being ran. We also ideally would have it remove some of
// the data from our generated folder, but for now this will do given jenkins runs
// a clean build because we need to make sure it doesn't fail
def filteredDelete = new HashSet<>()
for (def toDelete : getDelete()) {
for (def f : file(toDelete).listFiles()) {
if (f.getName() != "fg_cache") {
filteredDelete.add(f)
}
}
}
setDelete(filteredDelete)
}
tasks.withType(JavaCompile).configureEach({
options.encoding = 'UTF-8'
options.compilerArgs.addAll(["-Xmaxerrs", "100000"])
})
tasks.withType(Javadoc).configureEach({
options.tags = [
'apiNote:a:<em>API Note:</em>',
'implSpec:a:<em>Implementation Requirements:</em>',
'implNote:a:<em>Implementation Note:</em>'
]
})
artifacts {
archives apiJar
archives jar
archives additionsJar
archives generatorsJar
archives defenseJar
archives toolsJar
archives allJar
archives sourcesJar
}
createReobf(sourceSets.api)
for (String name : secondaryModules) {
createReobf(sourceSets.getByName(name))
}
def reobfAllJar = createReobf('allJar')
def createReobf(SourceSet sourceSet) {
def reobfTask = createReobf(sourceSet.getJarTaskName())
reobfTask.configure { libraries.from(sourceSet.compileClasspath) }
tasks.named(sourceSet.getJarTaskName()).configure(task -> task.finalizedBy(reobfTask))
return reobfTask
}
def createReobf(String name) {
def reobfExtension = (NamedDomainObjectContainer<RenameJarInPlace>) extensions.getByName("reobf")
return reobfExtension.register(name)
}
allJar.configure { finalizedBy(reobfAllJar) }
afterEvaluate {
tasks.named('jar', Jar).configure { finalizedBy(tasks.named('reobfJar', RenameJarInPlace)) }
}
//Minimize/optimize all png files, requires optipng on the PATH
// Credits: BrainStone
void minimizePNGFile(File file) {
long size = file.length()
exec {
executable "optipng"
args "-q", "-o7", "-zm1-9", "-strip", "all", file
}
long newSize = file.length()
if (newSize < size) {
System.out.format("Reduced File size of %s from %d bytes to %d bytes (reduced by %.2f%%)\n",
file, size, newSize, ((double) (size - newSize)) / ((double) size) * 100.0)
}
}
tasks.register('optimizePng').configure {
doLast {
def pngPatterns = ["**/*.png"]
//Ensure the logo is minimized (we add this file to each jar)
minimizePNGFile(file("${projectDir}/logo.png"))
//Minimize any PNGs in the source sets
def sourceSets = [sourceSets.main, sourceSets.additions, sourceSets.generators, sourceSets.defense, sourceSets.tools]
for (def sourceSet : sourceSets) {
for (dir in sourceSet.resources.srcDirs) {
fileTree(dir: dir, includes: pngPatterns).each { minimizePNGFile(it) }
}
}
}
}
tasks.withType(GenerateModuleMetadata).configureEach {
//Disable Gradle 7 module metadata generation as it does not play nicely with FG
enabled = false
}
//properties to put in $HOME/.gradle/gradle.properties
def MAVEN_PASSWORD_PROPERTY_NAME = 'mekanismMavenPassword'
def MODMAVEN_PW = System.getenv('MEK_MAVEN_PW') ?: (String)project.findProperty(MAVEN_PASSWORD_PROPERTY_NAME)
publishing {
publications { PublicationContainer publicationContainer ->
publicationContainer.register("maven", MavenPublication) { MavenPublication publication ->
publication.from((SoftwareComponent) components.java)
publication.groupId = project.group
publication.version = project.version
publication.artifactId = System.getenv("MAVEN_ARTIFACT") ?: project.archivesBaseName
publication.artifacts = [apiJar, jar, generatorsJar, additionsJar, toolsJar, allJar, sourcesJar]
publication.pom {
name.set("Mekanism")
packaging = 'jar'
description.set('Mekanism is a Minecraft add-on featuring high-tech machinery that can be used to create powerful tools, armor, and weapons.')
url.set('https://aidancbrady.com/mekanism/')
scm {
url.set('https://github.com/mekanism/Mekanism.git')
}
issueManagement {
system.set('github')
url.set('https://github.com/mekanism/Mekanism/issues')
}
licenses {
license {
name.set('MIT')
distribution.set('repo')
}
}
withXml {
NodeList dependencies = asNode().dependencies
NodeList allDeps = dependencies.'*'
// Remove forge deps
allDeps.<Node> findAll() { Node el ->
el.artifactId.text() == 'forge' && el.groupId.text() == 'net.neoforged'
}.forEach() { Node el ->
el.parent().remove(el)
}
//remove NeoGradle's mapped suffix from versions & set as optional so anyone else doesn't inherit them
allDeps.<Node> findAll() { Node el ->
el.version.text().contains('_mapped_')
}.each { Node el ->
el.version.each { Node version ->
def versionText = version.text()
version.setValue(versionText.substring(0, versionText.indexOf('_mapped_')))
}
el.appendNode('optional', true)
}
}
}
}
}
repositories {
maven {
url = 'https://modmaven.dev/artifactory/local-releases/'
if (MODMAVEN_PW != null) {
credentials {
username = "mekanism"
password = MODMAVEN_PW
}
}
}
}
}
def resolvedChangelog = null
//closure to generate the changelog once, and only when needed by CurseGradle or Modrinth
def changeLogResolver = { ->
if (resolvedChangelog != null) {
println "Using cached changelog"
return resolvedChangelog
}
def generatedChangelog = "Unable to generate changelog :("
def currentCommit = System.getenv("GIT_COMMIT")
def prevCommit = System.getenv("GIT_PREVIOUS_SUCCESSFUL_COMMIT") ?: System.getenv("GIT_PREVIOUS_COMMIT")
if (currentCommit != null && prevCommit != null) {
generatedChangelog = ""
//Use the service to avoid eagerly instantiating the grgit instance, and only do so when we actually need it
// for usage in generating the changelog for either CF or Modrinth
grgitService.service.get().grgit.log {
range(prevCommit, currentCommit)
}.reverse().each { commit ->
//Use full message rather than short message to get any new lines, and trim it so that any trailing new lines
// get removed so that we don't end up with extra spaces
String message = commit.fullMessage.trim()
if (!message.startsWith("Merge branch") && !message.startsWith("Merge pull request") && !message.contains("[no-changelog]")) {
//Ignore Merges and PR Merges
message = message.replaceAll("#(\\d+)", { match ->//turn issues/prs into links (github currently supports prs being linked as issues)
return "<a href=\"https://github.com/mekanism/Mekanism/issues/${match[1]}\">${match[0]}</a>"
}).replaceAll("\\n", "<br> ")//convert new lines that are part of a commit message into actual new lines and a tab
if (generatedChangelog != "") {
//If this isn't the first commit prepend an extra newline
generatedChangelog += "<br>"
}
generatedChangelog += "<a href=\"https://github.com/mekanism/Mekanism/commit/${commit.id}\">${commit.getAbbreviatedId()}</a> - ${message}"
}
}
println "Changelog generated"
}
def releaseNotesFile = project.file("docs/release_${mod_version}.html")
if (releaseNotesFile.exists()) {
//Add any version specific changelog stuff
def releaseNotes = releaseNotesFile.getText()
generatedChangelog = "$releaseNotes<br> $generatedChangelog"
}
if (release_type == "alpha") {
//Add a warning at the top about what an alpha build means
generatedChangelog = "Warning: Mekanism is currently in alpha, and is not recommended for widespread use in modpacks. There are likely to be game breaking bugs, " +
"and updating from one alpha to the next may cause various mekanism blocks to disappear/void their contents. While we will try to not have this happen/keep " +
"it to a minimum make sure to make backups. You can read more about the alpha state of this project <a href=\"https://github.com/mekanism/Mekanism#alpha-status\">here</a>." +
"<br> $generatedChangelog"
}
resolvedChangelog = generatedChangelog
return generatedChangelog
}
tasks.register('outputChangelog') {
doLast {
project.file("build/changelog.html").text = changeLogResolver.call()
}
}
if (System.getenv("CURSEFORGE_KEY") != null || project.hasProperty('curseforgeKey')) {
println "Enabling Curseforge config"
tasks.register("curseforge", TaskPublishCurseForge, { task ->
setGroup("publishing")
setDescription("Upload Mekanism to CurseForge")
apiToken = System.getenv("CURSEFORGE_KEY") ?: project.findProperty("curseforgeKey")
def changelog = changeLogResolver.call()
//Main Mekanism Project
task.upload(268560, jar) { main ->
setGenericCurseArtifactData(main, changelog)
//Include the API jar as a secondary file to the main file
withAdditionalFile(apiJar)
//Add optional deps
addOptional(
//Computers
'cc-tweaked', 'oc2',
//Looking at mods
'jade', 'the-one-probe', 'wthit-forge',
//Tweakers
'crafttweaker', 'jeitweaker',
//World gen
'biomes-o-plenty', 'oh-the-biomes-youll-go',
//Wood types
'i-like-wood', 'i-like-wood-biomes-o-plenty-plugin', 'i-like-wood-oh-the-biomes-youll-go-plugin',
//Misc
'applied-energistics-2', 'ctm', 'curios', 'dark-mode-everywhere', 'farmers-delight', 'female-gender-forge', 'flux-networks',
'jei', 'json-things', 'perviaminvenire', 'projecte', 'recipe-stages'
)
}
//Secondary modules/projects
uploadSecondaryCurseProject(task, 345425, changelog, additionsJar)
//uploadSecondaryCurseProject(task, 376939, changelog, defenseJar)
uploadSecondaryCurseProject(task, 268566, changelog, generatorsJar)
uploadSecondaryCurseProject(task, 268567, changelog, toolsJar)
})
}
void setGenericCurseArtifactData(UploadArtifact artifact, String changelog) {
artifact.changelog = changelog
artifact.changelogType = 'html'
artifact.releaseType = "${release_type}"
//Add that we support forge for now as we currently support both Forge and NeoForge. NeoForge is detected automatically from the gradle plugin
artifact.addModLoader("Forge")
}
void uploadSecondaryCurseProject(TaskPublishCurseForge task, long projectId, String changelog, TaskProvider<Jar> sourceSetJar) {
task.upload(projectId, sourceSetJar) { artifact ->
setGenericCurseArtifactData(artifact, changelog)
addRequirement('mekanism')
}
}
if (System.getenv("MODRINTH_TOKEN") != null || project.hasProperty('modrinthToken')) {
println "Enabling Modrinth config"
def additionsModrinth = createSecondaryModrinthUpload("additions", "a6F3uASn", additionsJar)
//def defenseModrinth = createSecondaryModrinthUpload("defense", "", defenseJar)
def generatorsModrinth = createSecondaryModrinthUpload("generators", "OFVYKsAk", generatorsJar)
def toolsModrinth = createSecondaryModrinthUpload("tools", "tqQpq1lt", toolsJar)
tasks.named('modrinth').configure {
dependsOn(jar, apiJar)
finalizedBy(additionsModrinth, /*defenseModrinth,*/ generatorsModrinth, toolsModrinth)
}
modrinth {
if (System.getenv("MODRINTH_TOKEN") == null) {
//Defaults to MODRINTH_TOKEN so we only have to check for a token via gradle properties if there isn't a system property
getToken().value((String) project.findProperty("modrinthToken"))
} else {
token = System.getenv("MODRINTH_TOKEN")
}
projectId = "Ce6I4WUE"
//Use the full "basic" version number rather than just mod version number so that if multiple releases end up happening due to bugs
// then we don't run into conflicts in uploading
//Note: The versionName is set to the versionNumber automatically
versionNumber = "${basicVersion}"
versionType = "${release_type}"
changelog = changeLogResolver.call()
uploadFile = jar
//Add that we support forge for now as we currently support both Forge and NeoForge
// Note: Once we no longer support forge we can just remove the line as NeoForge will be able to be detected automatically
// Currently we can't as Minotaur only detects loaders if none are set
loaders.addAll("forge", "neoforge")
getAdditionalFiles().value([apiJar.get()])
//Note: Can't use nested dependency configuration as we have no way to clear it for the secondary uploads
getDependencies().value([
new ModDependency("XxWD5pD3", "optional"),//AE2
new ModDependency("gu7yAYhd", "optional"),//CC: Tweaked
new ModDependency("Xg35A4rS", "optional"),//CraftTweaker
new ModDependency("vvuO3ImH", "optional"),//Curios
new ModDependency("R2OftAxM", "optional"),//Farmer's Delight
new ModDependency("nvQzSEkH", "optional"),//Jade
new ModDependency("EiEOyeoL", "optional"),//JEI Tweaker
new ModDependency("uE1WpIAk", "optional"),//Oh the Biomes You'll Go
new ModDependency("qXkLFB0L", "optional"),//Recipe Stages
new ModDependency("Eyw0UxEx", "optional"),//The One Probe
new ModDependency("bcOsQHnC", "optional"),//Wildfire's Female Gender Mod
new ModDependency("6AQIaxuO", "optional"),//WTHIT
])
}
}
def createSecondaryModrinthUpload(String output, String targetProjectId, TaskProvider<Jar> sourceSetJar) {
return tasks.register("${output}Modrinth", TaskModrinthUpload, {
setGroup("publishing")
setDescription("Upload Mekanism ${output} to Modrinth")
dependsOn(tasks.named("modrinth"), sourceSetJar)
doFirst {
//Run in do first to change the configured extension values before it starts applying
modrinth {
projectId = targetProjectId
uploadFile = sourceSetJar.get()
//Clear additional upload files as this is a modification of what things are set to from before
getAdditionalFiles().empty()
//Mark that the addon requires the build of Mekanism that we just uploaded (and override it to clear all optional dependencies)
if (tasks.modrinth.newVersion == null || tasks.modrinth.newVersion.getId() == null) {
//If we failed to find the upload version just set it to Mekanism in general
getDependencies().value([new ModDependency("Ce6I4WUE", "required")])
} else {
getDependencies().value([new VersionDependency(tasks.modrinth.newVersion.getId(), "required")])
}
}
println "Updated Modrinth extension"
}
})
}