-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbuild.gradle
More file actions
548 lines (462 loc) · 18.7 KB
/
build.gradle
File metadata and controls
548 lines (462 loc) · 18.7 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
/*
* Copyright 2018-2022 Ki11er_wolf
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.security.DigestInputStream
import java.security.MessageDigest
//#########################//
// Resynth 1.16.4 //
//#########################//
apply plugin: 'net.minecraftforge.gradle'
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'eclipse'
//####################################//
// Properties //
//####################################//
/*
* Constant Properties
*/
/** The unique String ID that identifies this mod. */
final String MODID = "resynth"
/** The URL to the website of the mod. */
final String MOD_URL = "https://resynth-minecraft-mod.github.io"
/** The full English title of the mod. */
final String MOD_TITLE = "Resynth-Minecraft-Mod"
/** The mod authors pen name. */
final String MOD_AUTHOR = "Ki11er_wolf"
/*
* Build Versions
*/
/** The version to give this build of the mod. */
final String MOD_VERSION = ext.getProperty('version.mod')
/** The (minimum) version of MinecraftForge to build and run the mod against. */
final String FORGE_VERSION = ext.getProperty('version.forge')
/** The version of Minecraft the mod is built for. */
final String MINECRAFT_VERSION = ext.getProperty('version.minecraft')
//######################//
// Dependencies //
//######################//
/*
* Dependency Config
*/
boolean enableTop = Boolean.valueOf(ext.getProperty('dependency.enabled.theoneprobe'))
boolean enableHwyla = Boolean.valueOf(ext.getProperty('dependency.enabled.hwyla'))
String hwylaGroup = "${ext.getProperty('dependency.group.hwyla')}:${ext.getProperty('dependency.version.hwyla')}"
String topGroup = "${ext.getProperty('dependency.group.theoneprobe')}:${ext.getProperty('dependency.version.theoneprobe')}"
/**
* Version dependencies on other mods. Handles compiling specific
* versions of required dependencies.
*/
dependencies {
//Forge
minecraft "net.minecraftforge:forge:${MINECRAFT_VERSION}-${FORGE_VERSION}"
//The One Probe
if (enableTop) {
compileOnly fg.deobf("${topGroup}:api")
runtimeOnly fg.deobf(topGroup)
}
//Hwyla
if (enableHwyla) {
compileOnly fg.deobf("${hwylaGroup}:api")
runtimeOnly fg.deobf(hwylaGroup)
}
}
/**
* Specifies the URL's to the maven repositories that host the
* required dependencies.
*/
repositories {
// Forge
maven { name 'Forge'; url = 'https://maven.minecraftforge.net' }
//The One Probe
if (enableTop) maven {
name 'TOP'
url "https://maven.tterrag.com/"
}
//Hwyla
if (enableHwyla) maven {
name 'Waila'
url = "https://maven.tehnut.info/"
}
// Other
jcenter()
mavenCentral()
}
//######################//
// Jar Manifest //
//######################//
/**
* Mod Jar Archive manifest attribute specification.
* Adds additional custom manifest attributes.
*/
jar {
manifest {
attributes([
// Generic - for resynth in general
"Specification-Title": MODID,
"Specification-Vendor": MOD_AUTHOR,
"Specification-Version": "${MOD_VERSION}-[${MINECRAFT_VERSION}]",
// Specific - for single resynth release
"Implementation-Title": MOD_TITLE,
"Implementation-Version": "Resynth-${MOD_VERSION}-[Minecraft-Forge-${MINECRAFT_VERSION}-${FORGE_VERSION}]",
"Implementation-Vendor": MOD_AUTHOR,
"Implementation-Vendor-Id": "com.ki11erwolf",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"),
"Implementation-URL": new URL(MOD_URL),
// Java
"Signature-Version": MOD_VERSION,
"Created-By": (System.getProperty("java.vendor") == "Oracle Corporation" ? "Java(TM)" : "Java-OpenJDK") +
"-${System.getProperty("java.version")}" + " (${System.getProperty("java.vendor")})",
// Custom (Resynth/Forge/Minecraft)
"Mod-License": "Apache License, Version 2.0",
])
}
}
//######################//
// Custom Tasks //
//######################//
boolean enableJarsigner = Boolean.valueOf(ext.getProperty('task.enabled.jarsigner'))
String jarsignerProperties = ext.getProperty('task.properties.jarsigner')
/**
* Always called after the build task has completed.
*
* Handles renaming the recently created mod jar, created by the most
* recent build task, to the more informative mod title specified. It
* is also simultaneously moved to a specified directory, preferably
* one more visibly accessible.
*
* Mod jar title and output directory is specified using `jarTitle`
* and `jarOutputDir` at top of this file.
*/
task distribution() {
//The directory where forge builds and saves the mod jar
def lookIn = new File("${project.file("build")}/libs/")
// The directory to put the mod jar in when it's built.
def outputDirectory = project.file("jar")
//Defines the specific mod jar name to be looked for.
//Later reassigned the value of the mod jar path before move.
def modjar = "${MODID}-${MOD_VERSION}.jar"
//The final name & title of the output mod jar, expect when signed.
def outputModJar = "Resynth-${MOD_VERSION}-[Minecraft-Forge-${MINECRAFT_VERSION}].jar"
/**
* Called and executed last as part of the task,
* which itself is called after the build process
* is completed.
*
* The Closure that actually handles and coordinates
* the attempt made to Move & Rename the most recent
* mod jar build.
*/
doLast {
def result = null
if(tryFindBuiltJar(lookIn, modjar)){
//If Jar Found
def finalModJarDest = new File("${outputDirectory}/${outputModJar}")
cleanAndCreate(outputDirectory)
//Store results from the attempted Rename & Move operation
result = tryRenameAndMove(modjar, finalModJarDest)
//Check results for success and verify results if successful .
if(result != true || !finalModJarDest.exists()) {
//Will default to FAILURE! Could not verify results as successful
println("[WARNING] Results '${result}' indicate a failure.")
} else {
//If Move & Rename results are successful and verified!
//Also ensure control returns from the task on success, before failing by default.
//Checksum the original
printMD5Checksum(finalModJarDest)
//Create a signed copy
if(signArchive(finalModJarDest)) {
println("\n[SUCCESS] Move, Rename, and Sign operation completed with no known errors!")
println("\n* * * * ${finalModJarDest} * * * *")
} else {
println("\n[FAIL] Could not sign jar!")
}
return
}
}
//Always defaults to FAILURE unless task is
//cancelled on SUCCESS with a `return` statement.
failByDefault(result)
}
/// functions ///
/**
* Looks for the latest mod jar build in the given directory scope
* under the given mod jar name.
*
* Returns {@code true} if and only if the mod jar was found and the operation
* can proceed with certainty. Returns {@code false} in all other situations.
*/
ext.tryFindBuiltJar = { scope, jar ->
//Begin search for existence of mod jar
println("\nMod jar build completed by Forge! Looking for mod to rename and move...")
println("Looking in: \"${scope}\" for \"${jar}\".")
//Check for mod jar existence, but first
//Assign full path of jar back into 'modjar' for use later
def found = (modjar = new File("${scope}/${jar}")).exists()
//Print and return the search results
if (!found) {
println("\n[WARNING] Missing expected mod jar from build! Skipping naming and placement.")
return false //FAIL
} else {
println("\nFound expected mod jar from build! Renaming & moving jar to...")
println("${outputDirectory} as ${outputModJar}")
return true //PASS
}
}
/**
* Ensures that, the given output directory destination
* is cleaned of all files, and, that the directory
* actually exists on the filesystem, creating the
* directory if needed.
*
* Cleaning and Creating takes place at the beginning
* of the task, directly and only after the recently
* built mod jar is confirmed to exist.
*/
ext.cleanAndCreate = { dest ->
println("Cleaning output first...")
//If final output destination exists, clean with delete
if(dest.exists())
dest.delete()
//before (re)creating destination
dest.mkdirs()
}
/**
* Called when ready to attempt the actual renaming and
* moving of the built mod jar.
*
* When called, the function delegates the job to
* 'java.nio.Files#move(src, dest)' and monitors
* the function call until it returns or an
* exception is thrown.
*
* Function returns {@code true} if and only if both
* the call returns without an exception, and if the
* path to the renamed and moved mod jar points to
* an existing file.
*
* If any exception is thrown during the call, it's
* returned so that it may be rethrown after the task
* fails gracefully and completely.
*/
ext.tryRenameAndMove = { modStartDest, modEndDest ->
try{
//Attempt Move & Rename operation
//noinspection UnnecessaryQualifiedReference
def finalPath = Files.move(modStartDest.toPath(), modEndDest.toPath(), StandardCopyOption.REPLACE_EXISTING)
//Verify mod jar exists at destination path
return finalPath.toFile().exists()
} catch (Exception e){
//Recovery impossible - just catch, log, and return all errors that needs to be dealt with.
print("\n[WARNING] Move & Rename operation failed with exception: ${e.getClass().getCanonicalName()}")
return e //Do not throw
}
}
/**
* Attempts to sign and verify the jar archive using the keystore
* certificate credentials in the provided properties file.
*/
ext.signArchive = { File archive ->
if(!enableJarsigner) {
println("\n[DISABLED] Skipping signing mod jar archive!")
return true
}
println("\nAttempting to sign mod jar archive...")
// Check properties file
Properties certificateProperties = new Properties()
File propertiesFile = jarsignerProperties.startsWith("/")
? new File(projectDir.getAbsolutePath() + jarsignerProperties)
: new File(jarsignerProperties)
try {
certificateProperties.load(new FileReader(propertiesFile))
} catch (Exception e) {
println("[WARNING] Could not load certificate properties from file: " + e.getMessage())
createTemplate(certificateProperties, propertiesFile)
return false
}
// Private data
String signedArchive = archive == null ? null : archive.getAbsolutePath().replace(".jar", "-Signed.jar")
String keystorePath = certificateProperties.getProperty("keystore.path", null)
String keystorePassword = certificateProperties.getProperty("keystore.password", null)
String keyAlias = certificateProperties.getProperty("key.alias", null)
println("Creating signed archive '${signedArchive}'...")
Files.copy(archive.toPath(), new File(signedArchive).toPath(), StandardCopyOption.REPLACE_EXISTING)
// Sign
def exec_line = "jarsigner " + "-keystore \"${keystorePath}\" " + "-storepass ${keystorePassword} " +
"-tsa http://sha256timestamp.ws.symantec.com/sha256/timestamp " + "\"${signedArchive}\" \"${keyAlias}\""
println("Signing jar with '${exec_line.replace(keystorePassword, "******")}'")
Process signer = exec_line.execute()
def exitCode = signer.waitFor()
if(exitCode != 0) {
println("Jarsigner returned failure: ${exitCode}!")
new File(signedArchive).delete()
return false
} else println("Jar signer returned success!")
//Checksum
printMD5Checksum(new File(signedArchive))
// Verify
return verifySignedJar(signedArchive)
}
/**
* Verifies the the given signed jar archive has a
* valid certificate.
*/
ext.verifySignedJar = { signedArchive ->
def exec_line_2 = "jarsigner -verify \"${signedArchive}\""
println("\nChecking jar signature with '${exec_line_2}'...")
Process verifier = exec_line_2.execute()
verifier.consumeProcessOutput(System.out, System.err)
def verifierExitCode = verifier.waitFor()
if(verifierExitCode != 0) {
println("Jar verifier returned failure: ${exitCode}!")
new File(signedArchive).delete()
return false
}
println("Jar verifier returned success!")
return true
}
/**
* Creates a new properties file for keystore certificate credentials
* with placeholders for credentials.
*/
ext.createTemplate = { Properties properties, File propertiesFile ->
// Template
properties.setProperty("keystore.path", "/path/to/keystore.p12")
properties.setProperty("keystore.password", "password")
properties.setProperty("key.alias", "alias")
try {
// Write
FileOutputStream propertiesOut = new FileOutputStream(propertiesFile)
properties.store(propertiesOut, " Private certificate & keystore credentials for jar archive signing!")
propertiesOut.flush()
propertiesOut.close()
println("Created new template certificate properties file.")
} catch (Exception ex) {
println("[WARNING] Could not save new certificate properties file template: " + ex.getMessage())
}
}
/**
* Calculates the MD5 Checksum of any given file, and prints
* it to the console as a hexadecimal String, along with the filename.
*/
ext.printMD5Checksum = { File archive ->
//noinspection GrUnnecessarySemicolon
try {
MessageDigest md = MessageDigest.getInstance("MD5")
InputStream is = Files.newInputStream(Paths.get(archive.getAbsolutePath()))
DigestInputStream dis = new DigestInputStream(is, md)
while(dis.read() != -1);
println("\nChecksum:\t${archive.getName()} ${bytesToHex(md.digest())}")
} catch (Exception ex) {
println("\nChecksum failed! Reason: ${ex.getMessage()}")
}
}
/**
* Converts an array of bytes to a hexadecimal String.
*/
ext.bytesToHex = { byte[] bytes ->
final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray()
char[] hexChars = new char[bytes.length * 2]
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF
hexChars[j * 2] = HEX_ARRAY[v >>> 4]
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]
}
return new String(hexChars)
}
/**
* Called as soon as, and never before the task is completely declared a failure,
* when unable to guarantee success - at which point the whole task comes to an
* end and deems itself a failure by default, prompting the call to this function.
* The task releases control back directly after this function returns.
*
* The result that probably lead to the failure is passed along with the
* call, typically to pass on any Exceptions and stacktrace
*/
ext.failByDefault = { result ->
print("\n[FAILURE] Could not Move & Rename the built mod jar!")
//Lastly, rethrow the first exception if any only after failure is complete.
if(result instanceof Exception) { println(); throw result }
else println(" Result was determined to be '${result}' before failure.")
}
}
build.finalizedBy(distribution)
//########################//
// Miscellaneous //
//########################//
/*
* General Properties
*/
archivesBaseName = MODID
version = MOD_VERSION
group = "com.ki11erwolf.${archivesBaseName}"
String mappingsVersion = ext.getProperty("version.minecraft-mappings")
//noinspection GroovyUnusedAssignment
sourceCompatibility = targetCompatibility = compileJava.sourceCompatibility = compileJava.targetCompatibility = '1.8'
/**
* Sets up the version dependencies for the Forge buildscript.
*/
buildscript {
repositories {
maven { url = 'https://files.minecraftforge.net/maven' }
jcenter()
mavenCentral()
}
dependencies {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true
}
}
/**
* Configures the version of the deobfuscation map used to deobfuscate the names
* of fields and methods, as well as various other Minecraft properties.
*/
minecraft {
mappings channel: 'official', version: mappingsVersion
runs {
client {
workingDirectory project.file('run')
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
property 'forge.logging.console.level', 'debug'
mods {
resynth {
source sourceSets.main
}
}
}
server {
workingDirectory project.file('run')
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
property 'forge.logging.console.level', 'debug'
mods {
resynth {
source sourceSets.main
}
}
}
data {
workingDirectory project.file('run')
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'
property 'forge.logging.console.level', 'debug'
mods {
resynth {
source sourceSets.main
}
}
}
}
}