Repository navigation
Expand file tree
/
Copy pathbuild.gradle
More file actions
583 lines (498 loc) · 22.9 KB
/
Copy pathbuild.gradle
File metadata and controls
583 lines (498 loc) · 22.9 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
plugins {
id 'java'
id 'com.github.johnrengelman.shadow' version '8.1.1'
id 'maven-publish'
id 'signing'
}
group = 'me.tamkungz.nilkit'
version = '4.1.0'
java {
// Gradle runs on an automatically selected modern JDK while NilKit bytecode
// remains Java 8 compatible. A separate JDK 8 installation is not required.
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
withSourcesJar()
withJavadocJar()
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
options.release.set(8)
}
tasks.withType(Javadoc).configureEach {
options.encoding = 'UTF-8'
options.charSet = 'UTF-8'
if (options.hasProperty('addStringOption')) {
options.addStringOption('Xdoclint:none', '-quiet')
}
failOnError = false
}
// Reproducible archives make CI/release checksums stable for identical inputs.
tasks.withType(AbstractArchiveTask).configureEach {
preserveFileTimestamps = false
reproducibleFileOrder = true
}
configurations {
nilLoaderArtifact
cfr
shadowBundle
// Optional developer-tooling libraries are available at compile/test time but are
// not published as transitive dependencies of the normal artifact. They are
// physically bundled only in the all-in-one shadow JAR.
compileOnly.extendsFrom shadowBundle
testImplementation.extendsFrom shadowBundle
}
repositories {
mavenCentral()
maven { url 'https://repo.sleeping.town' }
}
dependencies {
cfr 'org.benf:cfr:0.152'
// No Minecraft game JAR is required to compile the core library. Minecraft-facing
// helpers are resolved lazily so the published JAR has no hard game-version link.
compileOnly 'com.unascribed:nilloader:1.4.0'
nilLoaderArtifact 'com.unascribed:nilloader:1.4.0'
// Optional developer toolbox bundled only in NilKit-*-all.jar.
// NilKit core does not require these libraries to start. They are included so
// nilmod developers can use common instrumentation/config/scanning APIs without
// maintaining a second dependency list when they choose the all-in-one artifact.
// High-level runtime bytecode generation/instrumentation. Byte Buddy repackages
// its own ASM dependency, avoiding a public org.objectweb.asm collision.
shadowBundle 'net.bytebuddy:byte-buddy:1.17.6'
// Optional access to java.lang.instrument.Instrumentation/self-attach helpers.
// NilKit does not self-attach during startup; this is developer tooling only.
shadowBundle 'net.bytebuddy:byte-buddy-agent:1.17.6'
// Alternative compile-time generated event bus. NilKit keeps its own EventBus;
// GEB is bundled only as an optional high-performance choice for downstream mods.
shadowBundle 'foo.zaaarf.geb:core:0.5.4'
// GEB's processor generates dispatchers at compile time. It must NOT be put in the
// runtime shadow JAR; Gradle users that author @Listen handlers need it on the
// annotation-processor path. Keeping it here also lets NilKit examples/tests compile
// generated GEB code without shipping the processor or JavaPoet at runtime.
annotationProcessor 'foo.zaaarf.geb:processor:0.4.9'
// Classpath/module scanner used by optional discovery helpers.
shadowBundle 'io.github.classgraph:classgraph:4.8.184'
// YAML 1.1 parser/emitter for mods that prefer YAML alongside the built-in KDL API.
shadowBundle 'org.yaml:snakeyaml:2.6'
testImplementation 'junit:junit:4.13.2'
}
// Guard the legacy-runtime promise of the all-in-one artifact. Multi-release
// entries are allowed to target newer JVMs, but every root class in the bundled
// libraries must remain loadable on Java 8 (class-file major <= 52).
tasks.register('verifyShadowBundleJava8') {
group = 'verification'
description = 'Fails if a root class in a shadowBundle dependency requires newer than Java 8.'
inputs.files(configurations.shadowBundle)
doLast {
def incompatible = []
configurations.shadowBundle.resolve().findAll { it.name.endsWith('.jar') }.each { jarFile ->
def zip = new java.util.zip.ZipFile(jarFile)
try {
def entries = zip.entries()
while (entries.hasMoreElements()) {
def entry = entries.nextElement()
if (entry.directory || !entry.name.endsWith('.class') || entry.name.startsWith('META-INF/versions/')) {
continue
}
def input = zip.getInputStream(entry)
try {
byte[] header = new byte[8]
int offset = 0
while (offset < header.length) {
int count = input.read(header, offset, header.length - offset)
if (count < 0) break
offset += count
}
if (offset == header.length &&
(header[0] & 0xFF) == 0xCA && (header[1] & 0xFF) == 0xFE &&
(header[2] & 0xFF) == 0xBA && (header[3] & 0xFF) == 0xBE) {
int major = ((header[6] & 0xFF) << 8) | (header[7] & 0xFF)
if (major > 52) {
incompatible.add("${jarFile.name}!/${entry.name} (major ${major})")
}
}
} finally {
input.close()
}
}
} finally {
zip.close()
}
}
if (!incompatible.isEmpty()) {
throw new GradleException('shadowBundle contains root classes newer than Java 8:\n ' + incompatible.take(20).join('\n '))
}
}
}
tasks.named('check') {
dependsOn 'verifyShadowBundleJava8'
}
shadowJar {
configurations = [project.configurations.shadowBundle]
archiveClassifier.set('all')
// Keep service-provider metadata from bundled developer libraries intact.
mergeServiceFiles()
// Signatures from dependency JARs become invalid after files are merged. Keep the
// upstream license/notices, but never copy stale JAR signature blocks.
exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA'
// Byte Buddy uses a multi-release JAR. Preserve that behavior in the merged JAR.
manifest {
attributes(
'NilModID': 'nilkit',
'NilModName': 'NilKit API',
'Implementation-Title': 'NilKit API Developer Toolbox',
'Implementation-Version': project.version,
'Multi-Release': 'true'
)
}
// Do not minimize: these libraries are intentionally present for downstream mods
// even when NilKit itself does not reference every public API.
from('LICENSE') { into 'META-INF/nilkit' }
from('NOTICE') { into 'META-INF/nilkit' }
from('THIRD_PARTY_LICENSES.md') { into 'META-INF/nilkit' }
from('licenses') { into 'META-INF/nilkit/licenses' }
}
def nilLoaderDepsDir = layout.buildDirectory.dir('deps')
def nilLoaderDecompileDir = layout.buildDirectory.dir('decompiled')
tasks.register('fetchNilLoader', Copy) {
group = 'development'
description = 'Copies the NilLoader artifact used by optional developer tasks.'
from configurations.nilLoaderArtifact
into nilLoaderDepsDir
}
tasks.register('decompileNilLoader', JavaExec) {
group = 'development'
description = 'Decompiles NilLoader for local reference. This task is never part of a normal build.'
dependsOn 'fetchNilLoader'
classpath = configurations.cfr
mainClass = 'org.benf.cfr.reader.Main'
doFirst {
def nilJar = fileTree(nilLoaderDepsDir.get().asFile).matching {
include '*nilloader*.jar'
}.singleFile
args = [
nilJar.absolutePath,
'--outputdir', nilLoaderDecompileDir.get().asFile.absolutePath
]
}
}
// Compatibility aliases for scripts/docs that used the historical task names.
tasks.register('fetchDeps') {
group = 'development'
description = 'Deprecated alias for fetchNilLoader.'
dependsOn 'fetchNilLoader'
}
tasks.register('decompileNilloader') {
group = 'development'
description = 'Deprecated alias for decompileNilLoader.'
dependsOn 'decompileNilLoader'
}
// Generated sources used by the main compilation.
def generatedRemapJavaDir = layout.buildDirectory.dir('generated/sources/remapping/main')
def generatedBuildInfoJavaDir = layout.buildDirectory.dir('generated/sources/buildinfo/main')
tasks.register('generateModBuildInfoFallback') {
outputs.file generatedBuildInfoJavaDir.map {
it.file('me/tamkungz/nilkit/build/ModBuildInfo.java')
}
doLast {
def sourceBuildInfo = layout.projectDirectory.file('src/main/java/me/tamkungz/nilkit/build/ModBuildInfo.java').asFile
if (sourceBuildInfo.exists()) {
return
}
def out = generatedBuildInfoJavaDir.get().file('me/tamkungz/nilkit/build/ModBuildInfo.java').asFile
out.parentFile.mkdirs()
out.setText('''package me.tamkungz.nilkit.build;
public final class ModBuildInfo {
private final String buildTag;
public ModBuildInfo(String buildTag) {
this.buildTag = (buildTag == null || buildTag.trim().isEmpty()) ? "unknown-build" : buildTag.trim();
}
public String getBuildTag() {
return buildTag;
}
}
''', 'UTF-8')
}
}
tasks.register('generateSimpleRemapMappings') {
inputs.dir('tools/MinecraftRemapping').optional()
inputs.files fileTree('src/main/java') { include '**/*.java' }
outputs.file generatedRemapJavaDir.map {
it.file('me/tamkungz/nilkit/remapping/GeneratedSrgMappings.java')
}
doLast {
def fieldNeed = new LinkedHashSet<String>()
def methodNeed = new LinkedHashSet<String>()
def classNeed = new LinkedHashSet<String>()
fileTree('src/main/java').matching { include '**/*.java' }.each { f ->
String txt = f.getText('UTF-8')
def fm = (txt =~ /remap\.field\(\s*"([^"]+)"\s*,\s*"([^"]+)"\s*\)/)
fm.each { m -> fieldNeed.add("${m[1]}.${m[2]}") }
def mm = (txt =~ /remap\.method\(\s*"([^"]+)"\s*,\s*"([^"]+)"\s*\)/)
mm.each { m -> methodNeed.add("${m[1]}.${m[2]}") }
def cm = (txt =~ /remap\.cls\(\s*"([^"]+)"\s*\)/)
cm.each { m -> classNeed.add("${m[1]}") }
}
def versionData = new LinkedHashMap<String, Map<String, Map<String, String>>>()
def root = file('tools/MinecraftRemapping')
if (root.exists()) {
root.listFiles()?.findAll { it.isDirectory() }?.sort { a, b -> a.name <=> b.name }?.each { vd ->
def srg = new File(vd, 'mcp2obf.srg')
boolean reverse = false
if (!srg.exists()) {
srg = new File(vd, 'obf2mcp.srg')
reverse = true
}
if (!srg.exists()) return
def classes = new LinkedHashMap<String, String>()
def fields = new LinkedHashMap<String, String>()
def methods = new LinkedHashMap<String, String>()
srg.eachLine('UTF-8') { raw ->
String line = raw.trim()
if (line.isEmpty() || line.startsWith('#')) return
if (line.startsWith('CL: ')) {
String[] p = line.substring(4).trim().split(/\s+/)
if (p.length >= 2) {
String friendly = reverse ? p[1] : p[0]
int idx = friendly.lastIndexOf('/')
friendly = idx >= 0 ? friendly.substring(idx + 1) : friendly
if (classNeed.contains(friendly) && !classes.containsKey(friendly)) {
String obf = reverse ? p[0] : p[1]
if (obf.indexOf('/') >= 0) obf = obf.replace('/', '.')
classes.put(friendly, obf)
}
}
} else if (line.startsWith('FD: ')) {
String[] p = line.substring(4).trim().split(/\s+/)
if (p.length >= 2) {
String friendlyToken = reverse ? p[1] : p[0]
String obfToken = reverse ? p[0] : p[1]
int fi = friendlyToken.lastIndexOf('/')
int oi = obfToken.lastIndexOf('/')
if (fi > 0 && oi > 0 && fi < friendlyToken.length() - 1 && oi < obfToken.length() - 1) {
String friendlyOwner = friendlyToken.substring(0, fi)
String friendlyName = friendlyToken.substring(fi + 1)
String obfName = obfToken.substring(oi + 1)
int cidx = friendlyOwner.lastIndexOf('/')
String simpleOwner = cidx >= 0 ? friendlyOwner.substring(cidx + 1) : friendlyOwner
String key = simpleOwner + '.' + friendlyName
if (fieldNeed.contains(key) && !fields.containsKey(key)) {
fields.put(key, obfName)
}
}
}
} else if (line.startsWith('MD: ')) {
String[] p = line.substring(4).trim().split(/\s+/)
if (p.length >= 4) {
String friendlyToken = reverse ? p[2] : p[0]
String obfToken = reverse ? p[0] : p[2]
int fi = friendlyToken.lastIndexOf('/')
int oi = obfToken.lastIndexOf('/')
if (fi > 0 && oi > 0 && fi < friendlyToken.length() - 1 && oi < obfToken.length() - 1) {
String friendlyOwner = friendlyToken.substring(0, fi)
String friendlyName = friendlyToken.substring(fi + 1)
String obfName = obfToken.substring(oi + 1)
int cidx = friendlyOwner.lastIndexOf('/')
String simpleOwner = cidx >= 0 ? friendlyOwner.substring(cidx + 1) : friendlyOwner
String key = simpleOwner + '.' + friendlyName
if (methodNeed.contains(key) && !methods.containsKey(key)) {
methods.put(key, obfName)
}
}
}
}
}
if (!classes.isEmpty() || !fields.isEmpty() || !methods.isEmpty()) {
versionData.put(vd.name, [classes: classes, fields: fields, methods: methods])
}
}
}
def esc = { String s ->
s.replace('\\', '\\\\').replace('"', '\\"')
}
def legacyOut = generatedRemapJavaDir.get().file('me/tamkungz/remapping/GeneratedSrgMappings.java').asFile
if (legacyOut.exists()) {
legacyOut.delete()
}
def out = generatedRemapJavaDir.get().file('me/tamkungz/nilkit/remapping/GeneratedSrgMappings.java').asFile
out.parentFile.mkdirs()
StringBuilder sb = new StringBuilder()
sb.append('package me.tamkungz.nilkit.remapping;\n\n')
sb.append('/** Auto-generated by Gradle task generateSimpleRemapMappings. */\n')
sb.append('public final class GeneratedSrgMappings {\n')
sb.append(' private GeneratedSrgMappings() {}\n\n')
sb.append(' public static boolean apply(String version, SimpleRemap r, boolean overwriteExisting) {\n')
sb.append(' if (version == null) return false;\n')
sb.append(' switch (version) {\n')
versionData.each { ver, maps ->
sb.append(' case "').append(esc(ver)).append('":\n')
maps.classes.entrySet().sort { a, b -> a.key <=> b.key }.each { e ->
sb.append(' r.addClass("').append(esc(e.key)).append('", "').append(esc(e.value)).append('", overwriteExisting);\n')
}
maps.fields.entrySet().sort { a, b -> a.key <=> b.key }.each { e ->
int idx = e.key.indexOf('.')
String cls = e.key.substring(0, idx)
String name = e.key.substring(idx + 1)
sb.append(' r.addField("').append(esc(cls)).append('", "').append(esc(name)).append('", "').append(esc(e.value)).append('", overwriteExisting);\n')
}
maps.methods.entrySet().sort { a, b -> a.key <=> b.key }.each { e ->
int idx = e.key.indexOf('.')
String cls = e.key.substring(0, idx)
String name = e.key.substring(idx + 1)
sb.append(' r.addMethod("').append(esc(cls)).append('", "').append(esc(name)).append('", "').append(esc(e.value)).append('", overwriteExisting);\n')
}
sb.append(' return true;\n')
}
sb.append(' default:\n')
sb.append(' return false;\n')
sb.append(' }\n')
sb.append(' }\n')
sb.append('}\n')
out.setText(sb.toString(), 'UTF-8')
}
}
sourceSets {
main {
java {
srcDir generatedRemapJavaDir
srcDir generatedBuildInfoJavaDir
}
}
}
tasks.named('compileJava') {
dependsOn 'generateSimpleRemapMappings', 'generateModBuildInfoFallback'
}
tasks.named('sourcesJar') {
dependsOn 'generateSimpleRemapMappings', 'generateModBuildInfoFallback'
}
jar {
from('LICENSE') { into 'META-INF/nilkit' }
from('NOTICE') { into 'META-INF/nilkit' }
from('THIRD_PARTY_LICENSES.md') { into 'META-INF/nilkit' }
manifest {
attributes(
'NilModID': 'nilkit',
'NilModName': 'NilKit API',
'Implementation-Title': 'NilKit API',
'Implementation-Version': project.version
)
}
}
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
artifactId = 'nilkit'
pom {
name = 'NilKit API'
description = 'Independent API and tooling for NilLoader-based Minecraft mod development'
url = 'https://github.com/NilKitAPI/NilKit-API'
licenses {
license {
name = 'GNU Lesser General Public License v3.0 or later'
url = 'https://www.gnu.org/licenses/lgpl-3.0.txt'
distribution = 'repo'
}
}
developers {
developer {
id = 'TamKungZ_'
name = 'TamKungZ_'
email = 'dev@tamkungz.me'
}
}
scm {
connection = 'scm:git:https://github.com/NilKitAPI/NilKit-API.git'
developerConnection = 'scm:git:ssh://git@github.com/NilKitAPI/NilKit-API.git'
url = 'https://github.com/NilKitAPI/NilKit-API'
}
}
}
}
repositories {
// Project-local Maven repository. This intentionally does not publish to ~/.m2.
maven {
name = 'projectLocal'
url = layout.projectDirectory.dir('maven').asFile.toURI()
}
}
}
def mappingToolSources = files(
'src/main/java/me/tamkungz/nilkit/mapping/SrgMappingSet.java',
'src/main/java/me/tamkungz/nilkit/mapping/SrgMappings.java',
'src/main/java/me/tamkungz/nilkit/mapping/MappingToolMain.java'
)
def mappingToolClassesDir = layout.buildDirectory.dir('mapping-tool/classes')
tasks.register('compileMappingToolJava', JavaCompile) {
group = 'mapping'
description = 'Compiles only the standalone mapping utility (no Minecraft/NilLoader classpath required).'
source = mappingToolSources
classpath = files()
destinationDirectory.set(mappingToolClassesDir)
options.encoding = 'UTF-8'
options.release.set(8)
}
tasks.register('mappingTool', JavaExec) {
group = 'mapping'
description = 'Runs the local SRG/CSRG mapping utility. Example: ./gradlew mappingTool --args="inspect file.srg"'
dependsOn 'compileMappingToolJava'
classpath = files(mappingToolClassesDir)
mainClass = 'me.tamkungz.nilkit.mapping.MappingToolMain'
}
tasks.register('mappingToolJar', Jar) {
group = 'mapping'
description = 'Builds a standalone mapping utility JAR. It contains code only, never mapping data.'
dependsOn 'compileMappingToolJava'
archiveClassifier.set('mapping-tool')
from mappingToolClassesDir
from('LICENSE') { into 'META-INF/nilkit' }
from('NOTICE') { into 'META-INF/nilkit' }
manifest {
attributes(
'Main-Class': 'me.tamkungz.nilkit.mapping.MappingToolMain',
'Implementation-Title': 'NilKit Mapping Tool',
'Implementation-Version': project.version
)
}
}
// Add the standalone mapping tool after its task has been registered. Configure
// signing only after every classified artifact has been attached, so the local
// Maven publication signs the normal, all, mapping-tool, sources and Javadoc JARs.
publishing.publications.mavenJava.artifact(tasks.named('mappingToolJar'))
signing {
// Use the user's normal GnuPG setup / gpg-agent; no private keys are stored in the project.
// Publishing is intentionally never allowed to silently fall back to unsigned artifacts.
required = true
useGpgCmd()
sign publishing.publications.mavenJava
}
// Friendly alias for the generated publication task. Signed .asc files are emitted beside artifacts.
tasks.register('publishProjectLocal') {
group = 'publishing'
description = 'Publishes the signed Maven artifacts into ./maven.'
dependsOn 'publishMavenJavaPublicationToProjectLocalRepository'
}
tasks.named('assemble') {
dependsOn 'mappingToolJar', 'shadowJar'
}
tasks.register('inspectMinecraftRemapping') {
group = 'mapping'
description = 'Inspects a mapping file directly from tools/MinecraftRemapping; nothing is copied into the project.'
dependsOn 'compileMappingToolJava'
doLast {
String mcVersion = providers.gradleProperty('mcVersion').orNull
String mappingFile = providers.gradleProperty('mappingFile').getOrElse('mcp2obf.srg')
if (mcVersion == null || mcVersion.trim().isEmpty()) {
throw new GradleException('Missing -PmcVersion=<version>, for example -PmcVersion=1.4.7')
}
javaexec {
classpath = files(mappingToolClassesDir)
mainClass = 'me.tamkungz.nilkit.mapping.MappingToolMain'
args 'inspect-submodule', mcVersion, mappingFile
}
}
}
tasks.register('cleanProjectLocalMaven', Delete) {
group = 'publishing'
description = 'Deletes the project-local Maven repository directory.'
delete layout.projectDirectory.dir('maven')
}