-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.gradle
589 lines (531 loc) · 20.3 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
buildscript {
repositories {
mavenLocal()
maven { url = 'http://files.minecraftforge.net/maven' }
jcenter()
mavenCentral()
//maven {url 'http://plugins.gradle.org/m2/'} // For debug purposes
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:3.0.23'
classpath 'com.github.abrarsyed.jastyle:jAstyle:1.3'
classpath 'com.google.code.gson:gson:2.8.0' // because groovy JsonGenerator doesn't exist wtf
classpath 'commons-io:commons-io:2.6'
classpath 'org.ow2.asm:asm-debug-all:5.2'
//classpath "gradle.plugin.com.dorongold.plugins:task-tree:1.3" // For debug purposes
}
}
import com.github.abrarsyed.jastyle.ASFormatter;
import com.github.abrarsyed.jastyle.OptParser
import com.google.common.collect.Maps;
import com.google.gson.GsonBuilder
import groovy.json.JsonSlurper
import java.util.zip.*
import net.minecraftforge.gradle.patcher.task.TaskExtractMCPData
import org.apache.commons.io.IOUtils
import org.apache.commons.io.input.NullInputStream
import org.objectweb.asm.*
import org.objectweb.asm.tree.*
// ===== MAIN BUILDSCRIPT ===== //
// configuration
def settings = new JsonSlurper().parseText(file('conf/settings.json').text)
apply plugin: 'eclipse'
//apply plugin: "com.dorongold.task-tree" // For debug purposes
group = 'com.example'
version = settings.modversion
// subprojects
project(':mcp') {
apply plugin: 'net.minecraftforge.gradle.forgedev.mcp'
mcp {
config = 'de.oceanlabs.mcp:mcp_config:' + settings.mcpconfig + '@zip'
pipeline = settings.pipeline
}
}
project(':clean') {
evaluationDependsOn(':mcp')
apply plugin: 'eclipse'
apply plugin: 'net.minecraftforge.gradle.forgedev.patcher'
repositories {
mavenCentral()
maven { url = 'http://files.minecraftforge.net/maven' }
}
dependencies {
compileOnly('net.minecraftforge:forgespi:0.13.0') { transitive = false }
}
patcher {
parent = project(':mcp')
patchedSrc = file('src/main/java')
mappings channel: 'snapshot', version: settings.mappings
mcVersion = settings.mcversion
}
task runclient(type: JavaExec) {
doFirst {
mkdir 'runclient'
}
classpath sourceSets.main.runtimeClasspath
args = ['--accessToken', '0', '--version', '1.13']
main 'net.minecraft.client.main.Main'
workingDir 'runclient'
}
}
project(':' + settings.modname) {
evaluationDependsOn(':clean')
apply plugin: 'eclipse'
apply plugin: 'net.minecraftforge.gradle.forgedev.patcher'
sourceSets {
main {
java {
srcDir "$rootDir/src/main/java"
}
resources {
srcDir "$rootDir/src/main/resources"
}
}
}
repositories {
//mavenLocal()
mavenCentral()
maven { url = 'http://files.minecraftforge.net/maven' }
}
patcher {
parent = project(':clean')
patches = file("$rootDir/patches")
patchedSrc = file('src/main/java')
srgPatches = false
clientRun {
main = settings.clientmain
properties = [
assetDirectory: downloadAssets.output
]
}
serverRun {
main = settings.servermain
}
}
applyPatches {
canonicalizeAccess true
canonicalizeWhitespace true
maxFuzz 3
}
dependencies {
compileOnly('net.minecraftforge:forgespi:0.13.0') { transitive = false }
// Add extra dependencies here
}
task runclient(type: JavaExec, dependsOn: [":" + settings.modname + ":downloadAssets", ":" + settings.modname + ":extractNatives"]) {
doFirst {
mkdir "$rootDir/runclient"
}
doFirst {
copy {
from sourceSets.main.resources
into "$buildDir/classes/java/main"
}
}
classpath sourceSets.main.runtimeClasspath
main settings.clientmain
systemProperties = [
"org.lwjgl.util.Debug": "true",
"org.lwjgl.util.DebugLoader": "true"
]
environment += [
assetDirectory: file("${gradle.getGradleUserHomeDir()}/caches/forge_gradle/assets/"),
nativesDirectory: extractNatives.output
]
workingDir "$rootDir/runclient"
}
task runserver(type: JavaExec) {
doFirst {
mkdir "$rootDir/runserver"
}
classpath sourceSets.main.runtimeClasspath
main settings.servermain
args 'nogui'
workingDir "$rootDir/runserver"
}
}
// Main setup task
task setup() {
dependsOn ':clean:extractMapped'
dependsOn ':' + settings.modname + ':extractMapped' //These must be strings so that we can do lazy resolution. Else we need evaluationDependsOnChildren above
}
// ===== UTILITY ===== //
class JarFilter {
String filename
final InputStream istream
final boolean newFile
JarFilter(String filename, InputStream istream, boolean newFile) {
this.filename = filename
this.istream = istream
this.newFile = newFile
}
static def filterJar(File jarIn, File jarOut, Closure transformer, Map<File, String> additionalDirs = [:]) {
def existing = [] as HashSet
def zipOut = new ZipOutputStream(new FileOutputStream(jarOut))
additionalDirs.each { additionalDir, prefix ->
additionalDir.eachFileRecurse { file ->
def filter = new JarFilter(prefix + additionalDir.toPath().relativize(file.toPath()).toString().replace(File.separator, '/'), file.isDirectory() ? new NullInputStream(0) : file.newInputStream(), true)
transformer.delegate = filter
def content = transformer.call()
if (content != null && !existing.contains(filter.filename)) {
def entryOut = new ZipEntry(filter.filename)
existing << filter.filename
zipOut.putNextEntry(entryOut)
zipOut << content
zipOut.closeEntry()
}
}
}
def zipIn = new ZipFile(jarIn)
zipIn.entries().each { entryIn ->
def filter = new JarFilter(entryIn.getName(), zipIn.getInputStream(entryIn), false)
transformer.delegate = filter
def content = transformer.call()
if (content != null && !existing.contains(filter.filename)) {
def entryOut = new ZipEntry(filter.filename)
existing << filter.filename
zipOut.putNextEntry(entryOut)
zipOut << content
zipOut.closeEntry()
}
}
zipIn.close()
zipOut.close()
}
}
class CheckModifiedHelper {
Map<String, Boolean> changedMap = Maps.<String, Boolean>newTreeMap()
String modname
String inputTaskName
String inputArchiveName
String getCleanFilepath()
{
return 'projects/clean/build/' + inputTaskName + '/' + inputArchiveName
}
String getModdedFilepath()
{
return 'projects/' + modname + '/build/' + inputTaskName + '/' + inputArchiveName
}
CheckModifiedHelper(String modname, String taskname, String archivname)
{
this.modname = modname
this.inputTaskName = taskname
this.inputArchiveName = archivname
}
def filterUnchanged() {
def cleanFilename = getCleanFilepath()
def moddedFilename = getModdedFilepath()
def zipIn = new ZipFile(moddedFilename)
zipIn.entries().each { moddedFile ->
def entryName = moddedFile.toString()
def vanillaJar = new ZipFile(cleanFilename)
def vanillaEntry = vanillaJar.getEntry entryName
if (vanillaEntry != null) {
def moddedJar = new ZipFile(moddedFilename)
def moddedEntry = moddedJar.getEntry entryName
boolean modded = !IOUtils.contentEquals(vanillaJar.getInputStream(vanillaEntry), moddedJar.getInputStream(moddedEntry))
changedMap.put(entryName, modded)
}
}
zipIn.close()
}
boolean isModified(String entryName) {
if (changedMap.containsKey(entryName)) {
boolean changed = changedMap.get(entryName)
if (changed)
return true
if (entryName.contains('$')) { // Check if outer Class has changed, if yes we need this too
String parentEntry = entryName.substring(0, entryName.lastIndexOf('$')) + '.class'
return changedMap.containsKey(parentEntry) && isModified(parentEntry)
}
return false
}
return true // Propably a new file so include it
}
}
// ===== FIXES ===== //
// Fix recompilation requiring extractSrg output
setup.dependsOn ':clean:extractSrg'
// Generic fixMcpConfig task for anything that needs to modify the mcpconfig
class FixMcpConfigTask extends DefaultTask {
List<Closure> configActions = []
List<Closure> filterActions = []
Map<File, String> additionalDirs = [:]
void configAction(Closure action) {
configActions.add(action)
}
void filterAction(Closure action) {
filterActions.add(action)
}
void additionalDir(Object dir, String prefix) {
additionalDirs.put(project.file(dir), prefix)
}
@TaskAction
void filterMcpConfig() {
JarFilter.filterJar(project.file(project.downloadConfig.output), project.file('build/mcp_config.zip'), {
if (filename == 'config.json') {
def cfg = new JsonSlurper().parse(istream)
for (def action : configActions) {
action.call(cfg)
}
return new GsonBuilder().setPrettyPrinting().create().toJson(cfg)
} else {
for (def action : filterActions) {
action.delegate = delegate
def newistream = action.call()
if (!istream.is(newistream))
return newistream
}
return istream
}
}, additionalDirs)
}
static def register(def proj) {
if (!proj.ext.properties.containsKey('registered')) {
proj.ext.registered = true
proj.downloadConfig.output = proj.file('build/mcp_config_broken.zip')
proj.task('fixMcpConfig', type: FixMcpConfigTask) {
dependsOn proj.downloadConfig
inputs.file proj.downloadConfig.output
outputs.file 'build/mcp_config.zip'
}
proj.loadConfig.dependsOn proj.fixMcpConfig
}
}
}
// Fix https://github.com/MinecraftForge/ForgeGradle/issues/517 - FG3 server pipeline missing download version JSON
// Also fix recompile error on server due to mcp.client.Start being present
if (settings.pipeline == 'server') {
project(':mcp') {
FixMcpConfigTask.register(project)
fixMcpConfig.configAction {cfg -> cfg.steps.server.add(1, [type: 'downloadJson'])}
fixMcpConfig.filterAction {return filename.startsWith('config/inject/mcp/client/') ? null : istream}
}
}
// Custom SRG
if (settings.customsrg != null) {
project(':mcp') {
FixMcpConfigTask.register(project)
fixMcpConfig.configAction { cfg ->
cfg.version = settings.mcversion
cfg.data.mappings = 'config/' + settings.customsrg
}
fixMcpConfig.filterAction {
if (filename == 'config/joined.tsrg') {
filename = 'config/' + settings.customsrg
return new FileInputStream(rootProject.file('conf/' + settings.customsrg))
} else if (filename.startsWith('patches/') && !newFile) {
return null
} else {
return istream
}
}
}
}
// Custom patches
if (rootProject.file('conf/patches/').exists()) {
project(':mcp') {
FixMcpConfigTask.register(project)
fixMcpConfig.additionalDir(rootProject.file('conf/patches/'), 'patches/' + settings.pipeline + '/')
}
}
if (rootProject.file('conf/inject/').exists()) {
project(':mcp') {
FixMcpConfigTask.register(project)
fixMcpConfig.additionalDir(rootProject.file('conf/inject/'), 'config/inject/')
}
}
// Fix formatting, optionally
if (settings.reformat) {
project(':mcp') {
task reformat {
dependsOn setupMCP
inputs.file setupMCP.output
outputs.file 'build/reformat/output.zip'
doLast {
def formatter = new ASFormatter()
formatter.setUseProperInnerClassIndenting(false)
def parser = new OptParser(formatter)
parser.parseOptionFile(rootProject.file('conf/astyle.cfg'))
JarFilter.filterJar(file(setupMCP.output), file('build/reformat/output.zip')) {
if (filename.endsWith('.java') && !filename.endsWith('package-info.java')) {
def sw = new StringWriter()
try {
formatter.format(new InputStreamReader(istream), sw)
return sw.toString()
} catch (RuntimeException e) {
println('Failed to reformat ' + filename)
return istream
}
} else {
return istream
}
}
}
}
}
project(':clean') {
applyPatches.dependsOn project(':mcp').reformat
applyPatches.setClean(project(':mcp').file('build/reformat/output.zip'))
}
}
// Fix reobf error due to local variable signatures (with lambdas?). Apply to both clean and modded to keep the classes the same
for (def projname : [':clean', ':' + settings.modname]) {
project(projname) {
def reobfArgs = []
reobfJar.args.each {reobfArgs << it}
reobfArgs << '--kill-lvt'
reobfJar.args = reobfArgs.toArray([] as String[])
}
}
// ===== RELEASE TASKS ===== //
// Utility class for dealing with @OnlyIn(Dist.XXX) using ASM
class DistUtils {
static def containsUnwanted(List<AnnotationNode> anns, String unwanted) {
if (anns == null)
return false
def annItr = anns.iterator()
while (annItr.hasNext()) {
def ann = annItr.next()
if (ann.desc == 'Lnet/minecraftforge/api/distmarker/OnlyIn;') {
annItr.remove()
def value = ann.values[1]
value = value[1]
return value == unwanted
}
}
return false
}
static def classUnwanted(InputStream istream, String unwanted) {
ClassReader reader = new ClassReader(istream)
ClassNode clazz = new ClassNode()
reader.accept(clazz, ClassReader.SKIP_CODE)
return containsUnwanted(clazz.visibleAnnotations, unwanted)
}
static def stripDist(InputStream istream, String unwanted, Closure classProvider) {
ClassReader reader = new ClassReader(istream)
ClassNode clazz = new ClassNode()
reader.accept(clazz, 0)
if (containsUnwanted(clazz.visibleAnnotations, unwanted))
return null
if (clazz.interfaces != null) {
def itfItr = clazz.interfaces.iterator()
while (itfItr.hasNext()) {
def itf = classProvider.call(itfItr.next())
if (itf != null && classUnwanted(itf, unwanted))
itfItr.remove()
}
}
if (clazz.fields != null) {
def fieldItr = clazz.fields.iterator()
while (fieldItr.hasNext())
if (containsUnwanted(fieldItr.next().visibleAnnotations, unwanted))
fieldItr.remove()
}
if (clazz.methods != null) {
def methodItr = clazz.methods.iterator()
while (methodItr.hasNext())
if (containsUnwanted(methodItr.next().visibleAnnotations, unwanted))
methodItr.remove()
}
if (clazz.innerClasses != null) {
def innerClassItr = clazz.innerClasses.iterator()
while (innerClassItr.hasNext()) {
def innerClass = innerClassItr.next()
if (innerClass.outerName == clazz.name && classUnwanted(classProvider.call(innerClass.name), unwanted))
innerClassItr.remove()
}
}
ClassWriter writer = new ClassWriter(0)
clazz.accept(writer)
return writer.toByteArray()
}
}
// Tasks to split joined jars into client and server jars
if (settings.pipeline == 'joined') {
for (def projname : [':clean', ':' + settings.modname]) {
project(projname) {
def dists = ['Client', 'Server']
def unwantedDists = ['DEDICATED_SERVER', 'CLIENT']
for (def i = 0; i < 2; i++) {
def idx = i
task('filterDist' + dists[idx]) {
dependsOn reobfJar
inputs.file reobfJar.output
outputs.file 'build/filterDist' + dists[idx] + '/output.zip'
doLast {
JarFilter.filterJar(file(reobfJar.output), file('build/filterDist' + dists[idx] + '/output.zip')) {
if (filename.endsWith('.class')) {
return DistUtils.stripDist(istream, unwantedDists[idx]) { classname ->
def zip = new ZipFile(file(reobfJar.output))
def entry = zip.getEntry(classname + '.class')
if (entry == null)
return null
return zip.getInputStream(entry)
}
} else {
return istream
}
}
}
}
}
}
}
}
// Tasks to produce zip files containing only the changed classes, making the final release zip
for (def dist : ['Client', 'Server']) {
task('createRelease' + dist, type: Zip) {
def inputTaskName = settings.pipeline == 'joined' ? 'filterDist' + dist : 'reobfJar'
def inputArchiveName = settings.pipeline == 'joined' ? 'output.zip' : 'output.jar'
dependsOn ':clean:' + inputTaskName, ':' + settings.modname + ':' + inputTaskName
CheckModifiedHelper check = new CheckModifiedHelper(settings.modname, inputTaskName, inputArchiveName)
doFirst {
check.filterUnchanged()
}
from(zipTree(check.getModdedFilepath())) {
eachFile { moddedFile ->
def entryName = moddedFile.getRelativePath().toString()
if (!check.isModified(entryName))
moddedFile.exclude()
}
}
archiveName = "${settings.modname}_${project.version}_${dist}.zip"
destinationDir = file('build/distributions')
includeEmptyDirs = false
}
}
// Master task to invoke all createRelease tasks
task createRelease {
if (settings.pipeline != 'server')
dependsOn createReleaseClient
if (settings.pipeline != 'client')
dependsOn createReleaseServer
}
//Adds idea tools tab
project(':tools') {
task setupProject {
group = 'tools ' + settings.modname
description = 'Sets project up from patches, or clean project running it the first time'
dependsOn setup
}
task generatePatches {
group = 'tools ' + settings.modname
description = 'Convert project to patches for public distribution'
dependsOn project(':' + settings.modname).genPatches
}
task releaseProject {
group = 'tools ' + settings.modname
description = 'Creates a release from the current project'
dependsOn createRelease
}
task runServer {
group = 'tools ' + settings.modname
description = 'Runs server'
dependsOn project(':' + settings.modname).runserver
}
task runClient {
group = 'tools ' + settings.modname
description = 'Runs client'
dependsOn project(':' + settings.modname).runclient
}
}