Repository navigation
Expand file tree
/
Copy pathbuild.gradle
More file actions
1036 lines (981 loc) · 48.8 KB
/
Copy pathbuild.gradle
File metadata and controls
1036 lines (981 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
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
import groovy.json.JsonSlurper
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.jar.Manifest
import java.util.zip.ZipFile
import org.apache.tools.ant.filters.FixCrLfFilter
plugins {
id 'java'
id 'eclipse'
id 'idea'
id 'maven-publish'
id 'net.minecraftforge.renamer' version '1.1.5'
id 'net.minecraftforge.gradle' version '7.0.34'
}
// The native GUI adapter is a test mod, not a production or published source set.
sourceSets {
guiProbe {
java.srcDir 'test-rig/client-resources/java'
resources.srcDir 'test-rig/client-resources/resources'
compileClasspath += sourceSets.main.compileClasspath + sourceSets.main.output
}
}
tasks.register('clientResourceProbeJar', Jar) {
group = 'verification'
description = 'Builds the isolated native GUI capture mod, outside release artifacts.'
dependsOn tasks.named('guiProbeClasses')
from sourceSets.guiProbe.output
archiveFileName = 'advantageclientresources-deobf.jar'
destinationDirectory = layout.buildDirectory.dir('client-resource-probe')
}
group = project.mod_group
version = project.mod_version
base.archivesName = 'basePower'
def versionParts = project.mod_version.toString().tokenize('.')
if (versionParts.size() != 4 || !versionParts.every { it ==~ /\d+/ }) {
throw new GradleException("mod_version must use Major.Minor.Bug.Target numeric form: ${project.mod_version}")
}
def minecraftVersionParts = project.minecraft_version.toString().tokenize('.')
if (minecraftVersionParts.size() < 2 || minecraftVersionParts.size() > 3
|| !minecraftVersionParts.every { it ==~ /\d+/ }) {
throw new GradleException("minecraft_version must use major.minor or major.minor.patch numeric form: "
+ project.minecraft_version)
}
def minecraftPatch = minecraftVersionParts.size() == 3 ? minecraftVersionParts[2] : '0'
def expectedTargetVersion = "${minecraftVersionParts[0]}" \
+ "${minecraftVersionParts[1].padLeft(2, '0')}" \
+ "${minecraftPatch.padLeft(2, '0')}" \
+ project.loader_code
if (versionParts[3] != expectedTargetVersion) {
throw new GradleException("mod_version target ${versionParts[3]} does not match "
+ "Minecraft ${project.minecraft_version} ${project.loader_name} target ${expectedTargetVersion}")
}
ext.functional_version = versionParts[0..2].join('.')
ext.display_version = project.mod_version
ext.release_tag = project.mod_version
java {
toolchain.languageVersion = JavaLanguageVersion.of(8)
withSourcesJar()
withJavadocJar()
}
tasks.withType(JavaCompile).configureEach {
javaCompiler = javaToolchains.compilerFor {
languageVersion = JavaLanguageVersion.of(8)
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
options.encoding = 'UTF-8'
options.compilerArgs.addAll(['-Xmaxerrs', '1000'])
}
tasks.withType(Javadoc).configureEach {
failOnError = false
options.encoding = 'UTF-8'
options.addStringOption('Xdoclint:none', '-quiet')
options.addBooleanOption('notimestamp', true)
}
tasks.withType(AbstractArchiveTask).configureEach {
preserveFileTimestamps = false
reproducibleFileOrder = true
}
def archiveTextSuffixes = [
'.cfg', '.css', '.html', '.info', '.java', '.js', '.json', '.lang',
'.mcmeta', '.md', '.properties', '.txt', '.xml'
]
def archiveTextPatterns = archiveTextSuffixes.collect { "**/*${it}".toString() }
archiveTextPatterns.addAll(['**/element-list', '**/package-list'])
def normalizeArchiveLineEndings = { details ->
details.filter(FixCrLfFilter,
eol: FixCrLfFilter.CrLf.newInstance('lf'),
eof: FixCrLfFilter.AddAsisRemove.newInstance('asis'))
}
minecraft {
mappings channel: project.mapping_channel, version: project.mapping_version
String configuredRunDirectory = providers.gradleProperty('powerAdvantageRunDirectory')
.getOrElse('run')
runs {
configureEach {
workingDir.convention layout.projectDirectory.dir(configuredRunDirectory)
systemProperty 'forge.logging.console.level', 'debug'
}
register('client')
register('server') {
args '--nogui'
}
}
}
// Forge 1.10 requires a single development-mod classpath root. ForgeGradle 7
// splits classes and resources, so merge only the launch output.
def forge10DevelopmentOutput = layout.buildDirectory.dir('forge10-development/main')
def syncForge10DevelopmentResources = tasks.register('syncForge10DevelopmentResources', Sync) {
group = 'ide'
description = 'Merges classes and processed resources for Forge 1.10 Gradle launches.'
dependsOn tasks.named('classes')
from tasks.named('compileJava', JavaCompile).flatMap { it.destinationDirectory }
from sourceSets.main.output.resourcesDir
into forge10DevelopmentOutput
}
tasks.configureEach {
if (name == 'runClient' || name == 'runServer') {
dependsOn syncForge10DevelopmentResources
doFirst {
Set<File> splitMainOutputs = [
tasks.named('compileJava', JavaCompile).get().destinationDirectory.get().asFile,
sourceSets.main.output.resourcesDir
] as Set<File>
classpath = files(forge10DevelopmentOutput, classpath.filter {
!splitMainOutputs.contains(it)
})
}
}
}
repositories {
minecraft.mavenizer(it)
maven fg.forgeMaven
maven fg.minecraftLibsMaven
if (providers.gradleProperty('rebornCoreVerificationRepository').isPresent()) {
maven {
name = 'RebornCoreReleaseVerificationMirror'
url = uri(providers.gradleProperty('rebornCoreVerificationRepository').get())
metadataSources { artifact() }
content { includeGroup('curse.maven') }
}
}
exclusiveContent {
forRepository {
maven {
name = 'Sponge'
url = 'https://repo.spongepowered.org/repository/maven-public'
}
}
filter { includeGroupAndSubgroups('org.spongepowered') }
}
mavenCentral()
maven {
name = 'MinecraftLibraries'
url = 'https://libraries.minecraft.net/'
}
if (!providers.gradleProperty('rebornCoreVerificationRepository').isPresent()) {
maven {
name = 'CurseMaven'
url = 'https://www.cursemaven.com'
metadataSources { artifact() }
content { includeGroup('curse.maven') }
}
}
}
def rfApiJar = file('libs/RF-API.jar')
def rebornCoreCoordinate = "curse.maven:reborncore-${project.reborncore_curse_project_id}:" \
+ project.reborncore_curse_file_id
// OreSpawn is a required runtime mod, but its API is supplied as a local deobf jar
// so development and CI do not depend on a historical Maven repository.
def defaultOreSpawnDeobfJar = file("../../../MinecraftMineralogy/OS110/OreSpawn/build/libs-dev/" \
+ "OreSpawn-${project.orespawn_version}-deobf.jar")
def oreSpawnDeobfJar = providers.gradleProperty('oreSpawnDeobfJar')
.map { file(it) }
.getOrElse(defaultOreSpawnDeobfJar)
if (!oreSpawnDeobfJar.isFile()) {
throw new GradleException("Missing OreSpawn deobf jar: ${oreSpawnDeobfJar}. "
+ "Build pinned OreSpawn commit ${project.orespawn_source_commit} first, or pass "
+ "-PoreSpawnDeobfJar=<path>.")
}
dependencies {
implementation minecraft.dependency(
"net.minecraftforge:forge:${project.minecraft_version}-${project.forge_version}")
// Mavenizer's legacy metadata omits this compile-time Minecraft library.
compileOnly 'org.lwjgl.lwjgl:lwjgl_util:2.9.4-nightly-20150209'
// These integrations are optional at runtime. Compile against their APIs,
// but do not package or launch PowerAdvantage with the provider mods.
compileOnly files(rfApiJar)
compileOnly rebornCoreCoordinate
compileOnly files(oreSpawnDeobfJar)
runtimeOnly files(oreSpawnDeobfJar)
testImplementation files(oreSpawnDeobfJar)
testImplementation 'junit:junit:4.13.2'
}
tasks.named('processResources', ProcessResources) {
filteringCharset = 'UTF-8'
inputs.property('version', project.version)
inputs.property('mcversion', project.minecraft_version)
filesMatching('mcmod.info') {
expand version: project.version, mcversion: project.minecraft_version
}
filesMatching(archiveTextPatterns, normalizeArchiveLineEndings)
}
def prepareEclipseResources = tasks.register('prepareEclipseResources') {
group = 'ide'
description = 'Copies Gradle-processed resources into Eclipse production output.'
dependsOn tasks.named('processResources')
doLast {
project.copy {
from(layout.buildDirectory.dir('resources/main'))
into(layout.projectDirectory.dir('bin/main'))
}
}
}
tasks.named('jar', Jar) {
archiveClassifier = 'deobf'
destinationDirectory = layout.buildDirectory.dir('libs-dev')
manifest {
attributes([
'Maven-Artifact' : "${project.group}:${base.archivesName.get()}:${project.version}",
'Specification-Title' : project.mod_id,
'Specification-Vendor' : project.mod_authors,
'Specification-Version' : '1',
'Implementation-Title' : base.archivesName.get(),
'Implementation-Version': project.version,
'Implementation-Vendor' : project.mod_authors,
'Built-On-Java' : project.java_version,
'Built-On' : "${project.minecraft_version}-${project.forge_version}"
])
}
}
def releaseJar = renamer.classes(tasks.named('jar', Jar)) {
map.from minecraft.dependency.toSrgFile
archiveClassifier = null
}
tasks.register('deobfJar') {
group = 'build'
description = 'Builds the deobfuscated development jar under build/libs-dev.'
dependsOn tasks.named('jar')
}
tasks.named('sourcesJar', Jar) {
filteringCharset = 'UTF-8'
includeEmptyDirs = false
archiveClassifier = 'sources'
filesMatching(archiveTextPatterns, normalizeArchiveLineEndings)
manifest {
attributes([
'Maven-Artifact' : "${project.group}:${base.archivesName.get()}:${project.version}:sources",
'Implementation-Title' : "${base.archivesName.get()}-sources",
'Implementation-Version': project.version
])
}
}
tasks.named('javadocJar', Jar) {
filteringCharset = 'UTF-8'
archiveClassifier = 'javadoc'
filesMatching(archiveTextPatterns, normalizeArchiveLineEndings)
manifest {
attributes([
'Maven-Artifact' : "${project.group}:${base.archivesName.get()}:${project.version}:javadoc",
'Implementation-Title' : "${base.archivesName.get()}-javadoc",
'Implementation-Version': project.version
])
}
}
['apiElements', 'runtimeElements'].each { configurationName ->
configurations.named(configurationName) { artifacts.clear() }
artifacts { add(configurationName, releaseJar) }
}
tasks.named('assemble') {
dependsOn releaseJar
dependsOn tasks.named('sourcesJar')
dependsOn tasks.named('javadocJar')
}
def expectedReleaseFiles = providers.provider {
def prefix = "${base.archivesName.get()}-${project.version}"
["${prefix}.jar", "${prefix}-sources.jar", "${prefix}-javadoc.jar"]
}
def preparedReleaseDir = providers.gradleProperty('preparedReleaseDir')
tasks.register('verifyReleaseConfiguration') {
group = 'verification'
description = 'Validates release identity, target metadata, and optional integration policy.'
doLast {
if (project.mod_version != '2.4.4.110021') {
throw new GradleException("Unexpected PowerAdvantage release version: ${project.mod_version}")
}
if (project.minecraft_version != '1.10.2'
|| project.forge_version != '12.18.3.2511'
|| project.mapping_channel != 'stable'
|| project.mapping_version != '29-1.10.2') {
throw new GradleException('Unexpected Minecraft, Forge, or mappings target')
}
if (project.loader_name != 'forge' || project.loader_code != '1'
|| project.java_version != '8'
|| project.java_toolchain_version != '8.0.502+7'
|| project.gradle_java_version != '17') {
throw new GradleException('Unexpected release dispatcher target metadata')
}
if (project.mod_id != 'basepower'
|| project.group.toString() != 'zone.moddev.mc.basepower'
|| base.archivesName.get() != 'basePower'
|| project.curseforge_project_id != '1780140') {
throw new GradleException('Unexpected Forge, Maven, archive, or CurseForge identity')
}
if (project.cf_requirements != 'base-metals,mmd-orespawn'
|| project.cf_optionals != 'additional-loot-tables'
|| project.cf_versions != '1.10.2') {
throw new GradleException('Unexpected CurseForge dependency or game-version metadata')
}
if (project.reborncore_curse_project_id != '237903'
|| project.reborncore_curse_file_id != '2425028'
|| project.reborncore_version != '2.13.6.142'
|| project.reborncore_sha256 != 'C7C0D57FFC65B056D3795EBF60912EF5C6333009F33FAEEDA804BE4C22626C99') {
throw new GradleException('Unexpected RebornCore compile API identity')
}
if (project.orespawn_version != '4.0.8.110021'
|| project.orespawn_source_repository != 'MinecraftModDevelopmentMods/OreSpawn'
|| project.orespawn_source_commit != '5a50df1158e948c8db55814e819090b34c12d765'
|| project.orespawn_deobf_sha256 != '33BFB8C9D626D071147A0952A74B633F0BCC6A27E0408B4524370F4833B003C2') {
throw new GradleException('Unexpected OreSpawn API dependency identity')
}
['.github/workflows/ci.yml', '.github/workflows/codeql-analysis.yml'].each { workflowPath ->
String workflow = file(workflowPath).getText('UTF-8')
if (!workflow.contains('repository: ' + project.orespawn_source_repository)
|| !workflow.contains('ref: ' + project.orespawn_source_commit)) {
throw new GradleException("${workflowPath} does not build the pinned OreSpawn source")
}
}
String mainSource = file(
'src/main/java/zone/moddev/mc/basepower/PowerAdvantage.java').getText('UTF-8')
if (!mainSource.contains('MODID = "basepower"')
|| !mainSource.contains('VERSION = "2.4.4.110021"')
|| !mainSource.contains('required-before:orespawn@[4.0.6,5.0.0)')) {
throw new GradleException('PowerAdvantage source identity or dependency policy changed')
}
if (!file('src/main/java/cyano/poweradvantage/api/PoweredEntity.java').isFile()) {
throw new GradleException('Legacy cyano.poweradvantage.api compatibility surface is missing')
}
def metadata = new JsonSlurper().parse(file('src/main/resources/mcmod.info'))
def mod = metadata instanceof List ? metadata.first() : metadata
if (mod.modid != 'basepower') {
throw new GradleException('Source mcmod.info does not use the stable poweradvantage mod id')
}
}
}
def publicationTargetAllowed = { String projectId ->
(projectId ==~ /[1-9][0-9]*/) && projectId != '240982'
}
tasks.register('verifyPublicationTarget') {
group = 'verification'
description = 'Validates the assigned basePower CurseForge publication target.'
doLast {
if (!publicationTargetAllowed(project.curseforge_project_id.toString())) {
throw new GradleException('Use basePower CurseForge project 1780140; never reuse Power Advantage 240982.')
}
}
}
tasks.register('verifyReleaseDependencies') {
group = 'verification'
description = 'Resolves and audits Forge plus the exact optional compile APIs.'
dependsOn tasks.named('verifyReleaseConfiguration')
doLast {
if (!rfApiJar.isFile()) {
throw new GradleException("Missing tracked RF API jar: ${rfApiJar}")
}
String actualRfHash = MessageDigest.getInstance('SHA-256')
.digest(rfApiJar.bytes).encodeHex().toString().toUpperCase()
if (actualRfHash != project.rf_api_sha256) {
throw new GradleException("RF API SHA-256 is ${actualRfHash}, expected ${project.rf_api_sha256}")
}
String actualOreSpawnHash = MessageDigest.getInstance('SHA-256')
.digest(oreSpawnDeobfJar.bytes).encodeHex().toString().toUpperCase()
if (actualOreSpawnHash != project.orespawn_deobf_sha256) {
throw new GradleException("OreSpawn SHA-256 is ${actualOreSpawnHash}, expected "
+ project.orespawn_deobf_sha256)
}
new ZipFile(oreSpawnDeobfJar).withCloseable { zip ->
['zone/moddev/mc/orespawn/api/OreSpawnApi.class',
'zone/moddev/mc/orespawn/api/WorldgenProvider.class'].each { required ->
if (zip.getEntry(required) == null) {
throw new GradleException("OreSpawn API jar is missing ${required}")
}
}
}
def compileArtifacts = configurations.compileClasspath.resolvedConfiguration.resolvedArtifacts
def rebornCoreArtifacts = compileArtifacts.findAll { artifact ->
def id = artifact.moduleVersion.id
id.group == 'curse.maven' && id.name == "reborncore-${project.reborncore_curse_project_id}"
}
String expectedRebornCore = rebornCoreCoordinate.toString()
if (rebornCoreArtifacts.size() != 1
|| "${rebornCoreArtifacts.first().moduleVersion.id.group}:"
+ "${rebornCoreArtifacts.first().moduleVersion.id.name}:"
+ "${rebornCoreArtifacts.first().moduleVersion.id.version}" != expectedRebornCore) {
throw new GradleException("Expected exactly ${expectedRebornCore}, found "
+ rebornCoreArtifacts.collect { it.moduleVersion.id })
}
File rebornCoreJar = rebornCoreArtifacts.first().file
String actualRebornCoreHash = MessageDigest.getInstance('SHA-256')
.digest(rebornCoreJar.bytes).encodeHex().toString().toUpperCase()
if (actualRebornCoreHash != project.reborncore_sha256) {
throw new GradleException("RebornCore SHA-256 is ${actualRebornCoreHash}, expected "
+ project.reborncore_sha256)
}
new ZipFile(rebornCoreJar).withCloseable { zip ->
['reborncore/api/power/IEnergyInterfaceTile.class',
'reborncore/api/power/EnumPowerTier.class'].each { required ->
if (zip.getEntry(required) == null) {
throw new GradleException("RebornCore compile API is missing ${required}")
}
}
}
Set<File> compileFiles = configurations.compileClasspath.files.collect { it.canonicalFile } as Set<File>
if (!compileFiles.contains(rfApiJar.canonicalFile)
|| !compileFiles.contains(rebornCoreJar.canonicalFile)
|| !compileFiles.contains(oreSpawnDeobfJar.canonicalFile)) {
throw new GradleException('A required compile API is missing from compileClasspath')
}
Set<File> runtimeFiles = configurations.runtimeClasspath.files.collect { it.canonicalFile } as Set<File>
if (runtimeFiles.contains(rfApiJar.canonicalFile)
|| runtimeFiles.contains(rebornCoreJar.canonicalFile)) {
throw new GradleException('Optional RF or RebornCore API leaked onto runtimeClasspath')
}
if (!runtimeFiles.contains(oreSpawnDeobfJar.canonicalFile)) {
throw new GradleException('Required OreSpawn mod is missing from development runtimeClasspath')
}
List<String> forbiddenRuntimeMods = runtimeFiles.collect { it.name.toLowerCase(Locale.ROOT) }
.findAll { name ->
name.contains('basemetals') || name.contains('tesla') || name.contains('reborncore')
}
if (!forbiddenRuntimeMods.isEmpty()) {
throw new GradleException("Optional mods leaked onto runtimeClasspath: ${forbiddenRuntimeMods}")
}
}
}
tasks.register('verifyReleaseArtifacts') {
group = 'verification'
description = 'Audits the exact three distributable jars and release-critical contents.'
dependsOn tasks.named('verifyReleaseDependencies')
dependsOn tasks.named('assemble')
doLast {
File libs = layout.buildDirectory.dir('libs').get().asFile
List<File> jars = (libs.listFiles() ?: [] as File[])
.findAll { it.name.endsWith('.jar') }.sort { it.name }
List<String> expected = expectedReleaseFiles.get().sort()
if (jars.collect { it.name } != expected) {
throw new GradleException("Expected exactly ${expected}, found ${jars.collect { it.name }}")
}
jars.each { candidate ->
if (candidate.length() == 0L) {
throw new GradleException("Empty release artifact: ${candidate.name}")
}
new ZipFile(candidate).withCloseable { candidateZip ->
candidateZip.entries().findAll { entry ->
!entry.isDirectory()
&& (archiveTextSuffixes.any { entry.name.endsWith(it) }
|| entry.name.endsWith('/element-list')
|| entry.name.endsWith('/package-list'))
}.each { entry ->
boolean containsCarriageReturn = candidateZip.getInputStream(entry).withCloseable { input ->
input.bytes.any { value -> value == 13 }
}
if (containsCarriageReturn) {
throw new GradleException(
"${candidate.name}!/${entry.name} does not use canonical LF line endings")
}
}
}
}
File mainJar = new File(libs, expectedReleaseFiles.get()[0])
new ZipFile(mainJar).withCloseable { zip ->
List<String> names = zip.entries().collect { it.name }
['mcmod.info', 'pack.mcmeta',
'zone/moddev/mc/basepower/PowerAdvantage.class',
'cyano/poweradvantage/api/PoweredEntity.class',
'cyano/poweradvantage/api/fluid/FluidNetworkApi.class',
'com/mcmoddev/poweradvantage/math/Integer2D.class',
'com/mcmoddev/poweradvantage/registry/ITileEntityGUI.class',
'com/mcmoddev/poweradvantage/conduitnetwork/ConduitRegistry.class',
'com/mcmoddev/poweradvantage/init/Fluids.class',
'assets/basepower/lang/en_US.lang'].each { required ->
if (!names.contains(required)) {
throw new GradleException("Release jar is missing ${required}")
}
}
def allowedLegacyClasses = [
'com/mcmoddev/poweradvantage/math/Integer2D.class',
'com/mcmoddev/poweradvantage/registry/ITileEntityGUI.class',
'com/mcmoddev/poweradvantage/conduitnetwork/ConduitRegistry.class',
'com/mcmoddev/poweradvantage/init/Fluids.class'
] as Set
def legacyImplementationClasses = names.findAll {
it.startsWith('com/mcmoddev/poweradvantage/') && it.endsWith('.class')
} as Set
if (legacyImplementationClasses != allowedLegacyClasses) {
throw new GradleException("Unexpected legacy implementation classes: "
+ "${legacyImplementationClasses - allowedLegacyClasses}; missing: "
+ "${allowedLegacyClasses - legacyImplementationClasses}")
}
['agent-notes/', '.codex/', 'src/test/', 'com/mcmoddev/advantageworks/',
'zone/moddev/mc/advantageworks/',
'assets/advantageworkstest/', 'cofh/api/', 'reborncore/api/',
'zone/moddev/mc/orespawn/', 'com/mcmoddev/orespawn/',
'net/minecraft/', 'net/minecraftforge/'].each { forbidden ->
if (names.any { it.contains(forbidden) }) {
throw new GradleException("Release jar contains forbidden entry matching ${forbidden}")
}
}
def metadata = new JsonSlurper().parseText(zip.getInputStream(zip.getEntry('mcmod.info'))
.getText(StandardCharsets.UTF_8.name()))
def mod = metadata instanceof List ? metadata.first() : metadata
if (mod.modid != project.mod_id || mod.version != project.mod_version
|| mod.mcversion != project.minecraft_version) {
throw new GradleException('Packaged mcmod.info identity, version, or target is incorrect')
}
def manifest = new Manifest(zip.getInputStream(zip.getEntry('META-INF/MANIFEST.MF'))).mainAttributes
if (manifest.getValue('Implementation-Version') != project.mod_version
|| manifest.getValue('Built-On-Java') != project.java_version
|| manifest.getValue('Implementation-Timestamp') != null
|| manifest.getValue('Timestamp') != null) {
throw new GradleException('Release manifest identity is incorrect or volatile')
}
zip.entries().findAll { it.name.endsWith('.class') }.each { entry ->
byte[] header = new byte[8]
zip.getInputStream(entry).withCloseable { input ->
if (input.read(header) != header.length) {
throw new GradleException("Cannot inspect bytecode header for ${entry.name}")
}
}
int major = ((header[6] & 0xff) << 8) | (header[7] & 0xff)
if (major != 52) {
throw new GradleException("${entry.name} uses Java class major ${major}, expected 52")
}
}
}
new ZipFile(new File(libs, expectedReleaseFiles.get()[1])).withCloseable { sourceZip ->
if (sourceZip.getEntry('zone/moddev/mc/basepower/PowerAdvantage.java') == null
|| sourceZip.getEntry('cyano/poweradvantage/api/PoweredEntity.java') == null
|| sourceZip.getEntry('cyano/poweradvantage/api/fluid/FluidNetworkApi.java') == null) {
throw new GradleException('Sources jar is missing implementation or legacy API sources')
}
}
new ZipFile(new File(libs, expectedReleaseFiles.get()[2])).withCloseable { javadocZip ->
if (javadocZip.getEntry('index.html') == null) {
throw new GradleException('Javadoc jar is missing index.html')
}
}
}
}
tasks.register('writeReleaseChecksums') {
group = 'verification'
description = 'Writes SHA-256 checksums for the audited release jars.'
dependsOn tasks.named('verifyReleaseArtifacts')
def outputFile = layout.buildDirectory.file('release/SHA256SUMS')
outputs.file(outputFile)
doLast {
File output = outputFile.get().asFile
output.parentFile.mkdirs()
File libs = layout.buildDirectory.dir('libs').get().asFile
String contents = expectedReleaseFiles.get().sort().collect { name ->
MessageDigest digest = MessageDigest.getInstance('SHA-256')
new File(libs, name).withInputStream { input ->
byte[] buffer = new byte[8192]
for (int read = input.read(buffer); read >= 0; read = input.read(buffer)) {
if (read > 0) digest.update(buffer, 0, read)
}
}
"${digest.digest().encodeHex().toString().toUpperCase()} ${name}"
}.join('\n') + '\n'
output.setText(contents, 'UTF-8')
}
}
tasks.register('verifyPreparedReleaseArtifacts') {
group = 'verification'
description = 'Audits an immutable release bundle before Maven publication.'
dependsOn tasks.named('verifyReleaseConfiguration')
doLast {
if (!preparedReleaseDir.isPresent()) {
throw new GradleException('preparedReleaseDir is required for prepared artifact publication')
}
File prepared = file(preparedReleaseDir.get())
List<String> expected = expectedReleaseFiles.get().sort()
List<File> jars = (prepared.listFiles() ?: [] as File[])
.findAll { it.name.endsWith('.jar') }.sort { it.name }
if (!prepared.isDirectory() || jars.collect { it.name } != expected
|| jars.any { it.length() == 0L }) {
throw new GradleException("Prepared release must contain exactly the non-empty jars ${expected}")
}
File checksums = new File(prepared, 'SHA256SUMS')
File changelog = new File(prepared, 'CHANGELOG.txt')
if (!checksums.isFile() || !changelog.isFile()) {
throw new GradleException('Prepared release is missing SHA256SUMS or CHANGELOG.txt')
}
List<String> actualChecksums = jars.collect { candidate ->
MessageDigest digest = MessageDigest.getInstance('SHA-256')
candidate.withInputStream { input ->
byte[] buffer = new byte[8192]
for (int read = input.read(buffer); read >= 0; read = input.read(buffer)) {
if (read > 0) digest.update(buffer, 0, read)
}
}
"${digest.digest().encodeHex().toString().toUpperCase()} ${candidate.name}"
}.sort()
List<String> declaredChecksums = checksums.readLines('UTF-8')
.findAll { !it.trim().isEmpty() }.sort()
if (actualChecksums != declaredChecksums) {
throw new GradleException('Prepared release checksums do not match the immutable jars')
}
}
}
def mavenUploadUrl = providers.environmentVariable('MAVEN_UPLOAD_URL')
.orElse('https://invalid.invalid/missing-maven-upload-url')
def mavenUploadUsername = providers.environmentVariable('MAVEN_UPLOAD_USERNAME')
def mavenUploadPassword = providers.environmentVariable('MAVEN_UPLOAD_PASSWORD')
publishing {
publications {
mavenJava(MavenPublication) {
groupId = project.group.toString()
artifactId = base.archivesName.get()
version = project.version.toString()
if (preparedReleaseDir.isPresent()) {
File prepared = file(preparedReleaseDir.get())
artifact(new File(prepared, expectedReleaseFiles.get()[0]))
artifact(new File(prepared, expectedReleaseFiles.get()[1])) { classifier = 'sources' }
artifact(new File(prepared, expectedReleaseFiles.get()[2])) { classifier = 'javadoc' }
} else {
artifact(releaseJar)
artifact(tasks.named('sourcesJar'))
artifact(tasks.named('javadocJar'))
}
pom {
name = 'basePower'
description = project.mod_description
url = 'https://github.com/MinecraftModDevelopmentMods/basePower'
licenses {
license {
name = 'GNU Lesser General Public License, Version 3'
url = 'https://www.gnu.org/licenses/lgpl-3.0.txt'
}
}
scm {
connection = 'scm:git:https://github.com/MinecraftModDevelopmentMods/basePower.git'
developerConnection = 'scm:git:ssh://git@github.com/MinecraftModDevelopmentMods/basePower.git'
url = 'https://github.com/MinecraftModDevelopmentMods/basePower'
}
}
}
}
repositories {
maven {
name = 'release'
url = uri(mavenUploadUrl.get())
credentials {
username = mavenUploadUsername.orNull ?: ''
password = mavenUploadPassword.orNull ?: ''
}
}
}
}
tasks.register('validateMavenReleaseCredentials') {
group = 'publishing'
description = 'Prevents Maven publication from using a local or incomplete destination.'
doLast {
if (!providers.environmentVariable('MAVEN_UPLOAD_URL').isPresent()
|| !mavenUploadUsername.isPresent() || !mavenUploadPassword.isPresent()) {
throw new GradleException(
'MAVEN_UPLOAD_URL, MAVEN_UPLOAD_USERNAME, and MAVEN_UPLOAD_PASSWORD are required')
}
if (providers.environmentVariable('MAVEN_UPLOAD_URL').get().startsWith('file:')) {
throw new GradleException('Maven release publication must use a remote repository')
}
}
}
tasks.withType(PublishToMavenRepository).configureEach {
dependsOn tasks.named('verifyPublicationTarget')
dependsOn tasks.named('verifyReleaseConfiguration')
dependsOn tasks.named('validateMavenReleaseCredentials')
dependsOn preparedReleaseDir.isPresent()
? tasks.named('verifyPreparedReleaseArtifacts')
: tasks.named('verifyReleaseArtifacts')
}
tasks.register('verifyPublicationGuards') {
group = 'verification'
description = 'Checks publication policy and task dependencies without executing publication.'
inputs.files('build.gradle', '.github/workflows/release-on-tag.yml')
doLast {
['', '0', '240982', '-1', 'unassigned'].each { rejectedId ->
if (publicationTargetAllowed(rejectedId)) {
throw new GradleException("Publication target must reject '${rejectedId}'")
}
}
if (!publicationTargetAllowed('999999')) {
throw new GradleException('Publication target must accept an assigned non-legacy numeric ID')
}
if (publishing.publications.named('mavenJava', MavenPublication).get().pom.name.get() != 'basePower') {
throw new GradleException('Maven POM must use the basePower name')
}
def requireDependencies = { Task candidate, List<String> required ->
Set<String> actual = candidate.taskDependencies.getDependencies(candidate).collect { it.name } as Set
if (!actual.containsAll(required)) {
throw new GradleException("${candidate.name} is missing guards: ${required - actual}")
}
}
requireDependencies(tasks.named('verifyPreparedReleaseArtifacts').get(), ['verifyReleaseConfiguration'])
def publicationTasks = tasks.withType(PublishToMavenRepository).toList()
if (publicationTasks.isEmpty()) {
throw new GradleException('No external Maven publication task was inspected')
}
publicationTasks.each { publicationTask ->
requireDependencies(publicationTask, ['verifyPublicationTarget', 'verifyReleaseConfiguration',
'validateMavenReleaseCredentials', preparedReleaseDir.isPresent()
? 'verifyPreparedReleaseArtifacts' : 'verifyReleaseArtifacts'])
}
// Inspect dependencies only; never invoke publication or its rejecting guard actions.
def pending = [tasks.named('check').get()]
Set<Task> inspected = [] as Set
while (!pending.isEmpty()) {
Task candidate = pending.remove(pending.size() - 1)
if (!inspected.add(candidate)) continue
if (candidate instanceof PublishToMavenRepository || candidate.name == 'verifyPublicationTarget') {
throw new GradleException("Normal check must not execute ${candidate.name}")
}
pending.addAll(candidate.taskDependencies.getDependencies(candidate))
}
String tagWorkflow = file('.github/workflows/release-on-tag.yml').readLines('UTF-8')
.collect { it.trim() }.join('\n')
String tagGuard = '''project_id="$(value curseforge_project_id)"
if [[ ! "$project_id" =~ ^[1-9][0-9]*$ || "$project_id" == '240982' ]]; then
echo "basePower publication requires a new assigned CurseForge project; refusing $project_id" >&2
exit 1
fi'''.replace('\r\n', '\n')
if (!tagWorkflow.contains(tagGuard)
|| tagWorkflow.indexOf(tagGuard) > tagWorkflow.indexOf('successful_ci=')) {
throw new GradleException('Release tag must reject unassigned and legacy project IDs before checking CI')
}
}
}
idea {
module {
downloadSources = true
downloadJavadoc = true
}
}
def obsoleteForgeGradle2EclipseLaunches = [
'PowerAdvantage_Client.launch': 'GradleStart',
'PowerAdvantage_Server.launch': 'GradleStartServer'
]
eclipse {
project {
buildCommand 'org.eclipse.buildship.core.gradleprojectbuilder'
natures 'org.eclipse.buildship.core.gradleprojectnature'
}
classpath {
downloadSources = true
downloadJavadoc = true
}
synchronizationTasks 'isolateEclipseProductionRuns'
}
tasks.register('configureEclipseBuildship') {
group = 'ide'
description = 'Creates Buildship preferences for ForgeGradle 7 Eclipse imports.'
doLast {
File preferencesFile = file('.settings/org.eclipse.buildship.core.prefs')
Properties preferences = new Properties()
[
'eclipse.preferences.version' : '1',
'connection.gradle.distribution': 'GRADLE_DISTRIBUTION(WRAPPER)',
'connection.gradle.user.home' : gradle.gradleUserHomeDir.canonicalPath,
'connection.project.dir' : '',
'gradle.user.home' : gradle.gradleUserHomeDir.canonicalPath,
'override.workspace.settings' : 'true'
].each { key, value -> preferences.setProperty(key, value) }
preferencesFile.parentFile.mkdirs()
preferencesFile.withOutputStream {
preferences.store(it,
'Generated by configureEclipseBuildship; keep Eclipse and command-line caches aligned.')
}
}
}
tasks.register('isolateEclipseProductionRuns') {
group = 'ide'
description = 'Normalizes ForgeGradle Eclipse launches for production-only execution.'
dependsOn tasks.named('genEclipseRuns')
dependsOn tasks.named('configureEclipseBuildship')
dependsOn prepareEclipseResources
doLast {
obsoleteForgeGradle2EclipseLaunches.each { String name, String mainClass ->
File launch = file(name)
if (launch.isFile()) {
String contents = launch.getText('UTF-8')
String obsoleteMainType =
"org.eclipse.jdt.launching.MAIN_TYPE\" value=\"${mainClass}\""
if (contents.contains(obsoleteMainType) && !launch.delete()) {
throw new GradleException("Could not remove obsolete ForgeGradle 2 launch ${name}")
}
}
}
['runClient.launch', 'runServer.launch'].each { name ->
File launch = file(name)
if (!launch.isFile()) {
throw new GradleException("ForgeGradle did not generate ${name}")
}
String contents = launch.getText('UTF-8')
if (!contents.contains('org.eclipse.jdt.launching.ATTR_EXCLUDE_TEST_CODE')) {
String marker = '</launchConfiguration>'
String attribute =
' <booleanAttribute key="org.eclipse.jdt.launching.ATTR_EXCLUDE_TEST_CODE" value="true"/>'
contents = contents.replace(marker, attribute + '\n' + marker)
}
['--cache', '--metadata', '--to-srg', '--to-obf'].each { option ->
String prefix = option + ' '
int valueStart = contents.indexOf(prefix)
if (valueStart < 0) {
throw new GradleException("${name} is missing Slime Launcher argument ${option}")
}
valueStart += prefix.length()
int valueEnd = contents.indexOf(' --', valueStart)
if (valueEnd < 0) {
throw new GradleException("${name} has malformed Slime Launcher argument ${option}")
}
String value = contents.substring(valueStart, valueEnd)
if (value.find(/\s/) != null && !value.startsWith('"')) {
contents = (contents.substring(0, valueStart)
+ '"' + value + '"' + contents.substring(valueEnd))
}
}
launch.setText(contents.replace('\r\n', '\n'), 'UTF-8')
}
}
}
tasks.register('verifyEclipseProductionClasspath') {
group = 'verification'
description = 'Verifies the generated Eclipse project and production launches.'
dependsOn tasks.named('eclipse')
dependsOn tasks.named('isolateEclipseProductionRuns')
doLast {
File preferencesFile = file('.settings/org.eclipse.buildship.core.prefs')
Properties preferences = new Properties()
preferencesFile.withInputStream { preferences.load(it) }
if (preferences.getProperty('connection.gradle.distribution') != 'GRADLE_DISTRIBUTION(WRAPPER)'
|| file(preferences.getProperty('connection.gradle.user.home', '')).canonicalFile
!= gradle.gradleUserHomeDir.canonicalFile) {
throw new GradleException('Eclipse Buildship does not use this wrapper and Gradle home')
}
String projectMetadata = file('.project').getText('UTF-8')
if (!projectMetadata.contains('org.eclipse.buildship.core.gradleprojectnature')
|| !projectMetadata.contains('org.eclipse.buildship.core.gradleprojectbuilder')) {
throw new GradleException('Eclipse project metadata is missing its Buildship nature or builder')
}
File eclipseModMetadata = file('bin/main/mcmod.info')
def eclipseMetadata = new JsonSlurper().parseText(eclipseModMetadata.getText('UTF-8'))
def eclipseMod = eclipseMetadata instanceof List ? eclipseMetadata.first() : eclipseMetadata
if (eclipseMod.modid != project.mod_id || eclipseMod.version != project.mod_version
|| eclipseMod.mcversion != project.minecraft_version) {
throw new GradleException('Eclipse output contains incorrect mod metadata')
}
['runClient.launch', 'runServer.launch'].each { name ->
String contents = file(name).getText('UTF-8').replace('\\', '/')
if (!contents.contains('org.eclipse.jdt.launching.ATTR_EXCLUDE_TEST_CODE')
|| !contents.contains('value="true"')
|| contents.contains('src/test') || contents.contains('bin/test')) {
throw new GradleException("${name} does not isolate production code")
}
if (!contents.contains('PROJECT_ATTR" value="basePower"')) {
throw new GradleException("${name} targets the wrong Eclipse project")
}
}
}
}
tasks.named('check') {
dependsOn tasks.named('verifyReleaseConfiguration')
dependsOn tasks.named('verifyPublicationGuards')
}
tasks.register('prepareGuiProbeLaunch') {
group = 'verification'
description = 'Writes a separate native GUI capture launch with an explicit runtime-only classpath.'
dependsOn tasks.named('genEclipseRuns')
inputs.file(layout.projectDirectory.file('runClient.launch'))
inputs.files(configurations.runtimeClasspath)
def bootstrapOverride = providers.gradleProperty('guiProbeBootstrapJar')
if (bootstrapOverride.isPresent()) {
inputs.file(bootstrapOverride.map { file(it) })
}
outputs.file(layout.buildDirectory.file('client-resource-probe/runClientGuiProbe.launch'))
doLast {
File template = file('runClient.launch')
def launch = new groovy.xml.XmlParser(false, false).parse(template)
def stringAttribute = { String key ->
def attributes = launch.stringAttribute.findAll { it.attribute('key') == key }
if (attributes.size() != 1) {
throw new GradleException("GUI launch needs exactly one ${key} attribute")
}
attributes.first()
}
if (stringAttribute('org.eclipse.jdt.launching.MAIN_TYPE').attribute('value')
!= 'net.minecraftforge.launcher.Main') {
throw new GradleException('GUI capture requires the native ForgeGradle Slime Launcher')
}
def environment = launch.mapAttribute.find {
it.attribute('key') == 'org.eclipse.debug.core.environmentVariables'
}
if (environment == null) {
throw new GradleException('GUI launch is missing its native Forge environment')
}
[MC_VERSION: project.minecraft_version,
FORGE_VERSION: project.forge_version,
MCP_MAPPINGS: "${project.mapping_channel}_${project.mapping_version}"].each { key, value ->
def entry = environment.mapEntry.find { it.attribute('key') == key }
if (entry == null || entry.attribute('value') != value.toString()) {
throw new GradleException("GUI launch has an unexpected ${key}")
}
}
def program = stringAttribute('org.eclipse.jdt.launching.PROGRAM_ARGUMENTS')
String arguments = program.attribute('value')
if (!arguments.contains('--main net.minecraftforge.legacydev.MainClient ')
|| arguments.find(/--(?:server|port|gameDir|world)\b/) != null) {
throw new GradleException('GUI capture requires a client launch without a world or server target')
}
['--cache', '--metadata', '--to-srg', '--to-obf'].each { String option ->
int start = arguments.indexOf(option + ' ')
int end = start < 0 ? -1 : arguments.indexOf(' --', start + option.length() + 1)
if (start < 0 || end < 0) {
throw new GradleException("GUI launch is missing a complete ${option} argument")
}
start += option.length() + 1
String value = arguments.substring(start, end)
if (value.find(/\s/) != null && !value.startsWith('"')) {
arguments = arguments.substring(0, start) + '"' + value + '"' + arguments.substring(end)
}
}
program.attributes().put('value', arguments)
def classpathLists = launch.listAttribute.findAll {
it.attribute('key') == 'org.eclipse.jdt.launching.CLASSPATH'
}
if (classpathLists.size() != 1) {
throw new GradleException('GUI launch needs exactly one generated classpath')
}
// Never use Buildship/project outputs here: the runner supplies hash-bound
// Advantage and probe jars in its disposable mods directory.
Set<File> runtime = new LinkedHashSet<>(configurations.runtimeClasspath.files.collect {
it.canonicalFile
})
classpathLists.first().listEntry.each { entry ->
def parsed = new groovy.xml.XmlParser(false, false).parseText(entry.attribute('value'))
String archive = parsed.attribute('externalArchive')