-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
build.gradle.kts
423 lines (361 loc) · 14.9 KB
/
build.gradle.kts
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
/*
* Steam 'n' Rails
* Copyright (c) 2022-2024 The Railways Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import dev.architectury.plugin.ArchitectPluginExtension
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import net.fabricmc.loom.api.LoomGradleExtensionAPI
import net.fabricmc.loom.task.RemapJarTask
import org.gradle.configurationcache.extensions.capitalized
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.tree.AnnotationNode
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
import java.io.ByteArrayOutputStream
import java.util.*
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.zip.Deflater
plugins {
java
`maven-publish`
id("architectury-plugin") version "3.4-SNAPSHOT"
id("dev.architectury.loom") version "1.7.+" apply false
id("me.modmuss50.mod-publish-plugin") version "0.7.4" apply false // https://github.com/modmuss50/mod-publish-plugin
id("com.github.johnrengelman.shadow") version "8.1.1" apply false
id("dev.ithundxr.silk") version "0.11.15" // https://github.com/IThundxr/silk
id("net.kyori.blossom") version "2.1.0" apply false // https://github.com/KyoriPowered/blossom
id("org.jetbrains.gradle.plugin.idea-ext") version "1.1.8" // https://github.com/JetBrains/gradle-idea-ext-plugin
}
println("Steam 'n' Rails v${"mod_version"()}")
val isRelease = System.getenv("RELEASE_BUILD")?.toBoolean() ?: false
val buildNumber = System.getenv("GITHUB_RUN_NUMBER")?.toInt()
val removeDevMixinAnyway = System.getenv("REMOVE_DEV_MIXIN_ANYWAY")?.toBoolean() ?: false
val gitHash = "\"${calculateGitHash() + (if (hasUnstaged()) "-modified" else "")}\""
extra["gitHash"] = gitHash
architectury {
minecraft = "minecraft_version"()
}
allprojects {
apply(plugin = "java")
apply(plugin = "architectury-plugin")
apply(plugin = "maven-publish")
base.archivesName.set("archives_base_name"())
group = "maven_group"()
// Formats the mod version to include the loader, Minecraft version, and build number (if present)
// example: 1.0.0+fabric-1.19.2-build.100 (or -local)
val build = buildNumber?.let { "-build.${it}" } ?: "-local"
version = "${"mod_version"()}+${project.name}-mc${"minecraft_version"() + if (isRelease) "" else build}"
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
}
java {
withSourcesJar()
}
}
subprojects {
apply(plugin = "dev.architectury.loom")
apply(plugin = "net.kyori.blossom")
setupRepositories()
val capitalizedName = project.name.capitalized()
val loom = project.extensions.getByType<LoomGradleExtensionAPI>()
loom.apply {
silentMojangMappingsLicense()
runs.configureEach {
vmArg("-XX:+AllowEnhancedClassRedefinition")
vmArg("-XX:+IgnoreUnrecognizedVMOptions")
vmArg("-Dmixin.debug.export=true")
vmArg("-Dmixin.env.remapRefMap=true")
vmArg("-Dmixin.env.refMapRemappingFile=${projectDir}/build/createSrgToMcp/output.srg")
}
}
configurations.configureEach {
resolutionStrategy {
force("net.fabricmc:fabric-loader:${"fabric_loader_version"()}")
}
}
@Suppress("UnstableApiUsage")
dependencies {
"minecraft"("com.mojang:minecraft:${"minecraft_version"()}")
// layered mappings - Mojmap names, parchment docs and parameters
"mappings"(loom.layered {
officialMojangMappings { nameSyntheticMembers = false }
parchment("org.parchmentmc.data:parchment-${"minecraft_version"()}:${"parchment_version"()}@zip")
})
// Used to decompile mixin dumps, needs to be on the classpath
// Uncomment if you want it to decompile mixin exports, beware it has very verbose logging.
//implementation("org.vineflower:vineflower:1.10.0")
}
publishing {
publications {
create<MavenPublication>("maven${capitalizedName}") {
artifactId = "${"archives_base_name"()}-${project.name}-${"minecraft_version"()}"
from(components["java"])
}
}
repositories {
val mavenToken = System.getenv("MAVEN_TOKEN")
val maven = if (isRelease) "releases" else "snapshots"
if (mavenToken != null && mavenToken.isNotEmpty()) {
maven {
url = uri("https://maven.ithundxr.dev/${maven}")
credentials {
username = "railways-github"
password = mavenToken
}
}
}
}
}
// from here down is platform configuration
if(project.path == ":common") {
return@subprojects
}
apply(plugin = "com.github.johnrengelman.shadow")
apply(plugin = "me.modmuss50.mod-publish-plugin")
architectury {
platformSetupLoomIde()
}
tasks.named<RemapJarTask>("remapJar") {
from("${rootProject.projectDir}/LICENSE")
val shadowJar = project.tasks.named<ShadowJar>("shadowJar").get()
inputFile.set(shadowJar.archiveFile)
injectAccessWidener = true
dependsOn(shadowJar)
archiveClassifier = null
doLast {
transformJar(outputs.files.singleFile)
}
}
val common: Configuration by configurations.creating
val shadowCommon: Configuration by configurations.creating
val development = configurations.maybeCreate("development${capitalizedName}")
configurations {
compileOnly.get().extendsFrom(common)
runtimeOnly.get().extendsFrom(common)
development.extendsFrom(common)
}
dependencies {
common(project(":common", "namedElements")) { isTransitive = false }
shadowCommon(project(":common", "transformProduction${capitalizedName}")) { isTransitive = false }
}
tasks.named<ShadowJar>("shadowJar") {
archiveClassifier = "dev-shadow"
configurations = listOf(shadowCommon)
exclude("architectury.common.json")
destinationDirectory = layout.buildDirectory.dir("devlibs").get()
}
tasks.processResources {
// include packs
from(project(":common").file("src/main/resources")) {
include("resourcepacks/")
}
// Trim -build.X+mcX.XX.X from version string
//val createFabricVersion: String = Regex("(\\d+\\.\\d+\\.\\d+-\\w)").find("create_fabric_version"())?.value.toString()
// set up properties for filling into metadata
val properties = mapOf(
"version" to version,
"minecraft_version" to "minecraft_version"(),
"fabric_api_version" to "fabric_api_version"(),
"fabric_loader_version" to "fabric_loader_version"(),
"voicechat_api_version" to "voicechat_api_version"(),
"forge_version" to "forge_version"().split(".")[0], // only specify major version of forge
"create_forge_version" to "create_forge_version"().split("-")[0],
"create_fabric_version" to "create_fabric_version"()
)
inputs.properties(properties)
filesMatching(listOf("fabric.mod.json", "META-INF/mods.toml")) {
expand(properties)
}
}
tasks.jar {
archiveClassifier = "dev"
manifest {
attributes(mapOf("Git-Hash" to gitHash))
}
}
tasks.named<Jar>("sourcesJar") {
val commonSources = project(":common").tasks.getByName<Jar>("sourcesJar")
dependsOn(commonSources)
from(commonSources.archiveFile.map { zipTree(it) })
manifest {
attributes(mapOf("Git-Hash" to gitHash))
}
}
components.getByName<AdhocComponentWithVariants>("java") {
withVariantsFromConfiguration(project.configurations["shadowRuntimeElements"]) {
skip()
}
}
}
fun transformJar(jar: File) {
val contents = linkedMapOf<String, ByteArray>()
JarFile(jar).use {
it.entries().asIterator().forEach { entry ->
if (!entry.isDirectory) {
contents[entry.name] = it.getInputStream(entry).readAllBytes()
}
}
}
jar.delete()
JarOutputStream(jar.outputStream()).use { out ->
out.setLevel(Deflater.BEST_COMPRESSION)
contents.forEach { var (name, data) = it
if(name.startsWith("architectury_inject_${project.name}_common"))
return@forEach
if (name.endsWith(".json") || name.endsWith(".mcmeta")) {
data = (JsonOutput.toJson(JsonSlurper().parse(data)).toByteArray())
} else if (name.endsWith(".class")) {
data = transformClass(data)
}
out.putNextEntry(JarEntry(name))
out.write(data)
out.closeEntry()
}
out.finish()
out.close()
}
}
fun transformClass(bytes: ByteArray): ByteArray {
val node = ClassNode()
ClassReader(bytes).accept(node, 0)
// Remove Methods & Field Annotated with @DevEnvMixin
node.methods.removeIf { methodNode: MethodNode -> removeIfDevMixin(node.name, methodNode.visibleAnnotations) }
// Disabled as I don't feel ok with people being able to remove these
//node.fields.removeIf { fieldNode: FieldNode -> removeIfDevMixin(fieldNode.visibleAnnotations) }
return ClassWriter(0).also { node.accept(it) }.toByteArray()
}
fun removeIfDevMixin(nodeName: String, visibleAnnotations: List<AnnotationNode>?): Boolean {
// Don't remove methods if it's not a GHA build/Release build
if (!removeDevMixinAnyway && buildNumber == null && !nodeName.lowercase(Locale.ROOT).matches(Regex(".*\\/mixin\\/.*Mixin")))
return false
if (visibleAnnotations != null) {
for (annotationNode in visibleAnnotations) {
if (annotationNode.desc == "Lcom/railwayteam/railways/annotation/mixin/DevEnvMixin;")
return true
}
}
return false
}
fun <T> getValueFromAnnotation(annotation: AnnotationNode?, key: String): T? {
var getNextValue = false
if (annotation?.values == null) {
return null
}
// Keys and value are stored in successive pairs, search for the key and if found return the following entry
for (value in annotation.values) {
if (getNextValue) {
@Suppress("UNCHECKED_CAST")
return value as T
}
if (value == key) {
getNextValue = true
}
}
return null
}
tasks.create("railwaysPublish") {
when (val platform = System.getenv("PLATFORM")) {
"both" -> {
dependsOn(tasks.build, ":fabric:publish", ":forge:publish", ":common:publish", ":fabric:publishMods", ":forge:publishMods")
}
"fabric", "forge" -> {
dependsOn("${platform}:build", "${platform}:publish", "${platform}:publishMods")
}
}
}
fun Project.setupRepositories() {
repositories {
mavenCentral()
maven("https://maven.shedaniel.me/") // Cloth Config, REI
maven("https://maven.blamejared.com/") // JEI, Hex Casting
exclusiveMaven("https://maven.parchmentmc.org", "org.parchmentmc.data") // Parchment mappings
exclusiveMaven("https://maven.quiltmc.org/repository/release", "org.quiltmc") // Quilt Mappings
maven("https://jm.gserv.me/repository/maven-public/") // JourneyMap API
exclusiveMaven("https://api.modrinth.com/maven", "maven.modrinth") // LazyDFU, JourneyMap
exclusiveMaven("https://cursemaven.com", "curse.maven")
maven("https://maven.theillusivec4.top/") // Curios
maven("https://maven.tterrag.com/") { // Flywheel, Registrate, Create
content {
includeGroup("com.simibubi.create")
includeGroup("com.tterrag.registrate")
includeGroup("com.jozufozu.flywheel")
}
}
maven("https://maven.maxhenkel.de/repository/public") // Simple Voice Chat
maven("https://maven.jamieswhiteshirt.com/libs-release") // Reach Entity Attributes
exclusiveMaven("https://thedarkcolour.github.io/KotlinForForge/", "thedarkcolour") // KFF (Hex Casting dependency)
maven("https://maven.terraformersmc.com/releases/") // Mod Menu, EMI
maven("https://mvn.devos.one/snapshots/") // Create Fabric, Porting Lib, Forge Tags, Milk Lib, Registrate Fabric
maven("https://mvn.devos.one/releases/") // Porting Lib
maven("https://maven.cafeteria.dev/releases") // Fake Player API
maven("https://raw.githubusercontent.com/Fuzss/modresources/main/maven/") // forge config api port
exclusiveMaven("https://maven.ladysnake.org/releases", "dev.onyxstudios.cardinal-components-api") // Cardinal Components (Hex Casting dependency)
maven("https://jitpack.io/") { // Mixin Extras, Fabric ASM
content {
includeGroupByRegex("com.github.*")
}
}
}
}
fun calculateGitHash(): String {
try {
val stdout = ByteArrayOutputStream()
exec {
commandLine("git", "rev-parse", "HEAD")
standardOutput = stdout
}
return stdout.toString().trim()
} catch(ignored: Throwable) {
return "unknown"
}
}
fun hasUnstaged(): Boolean {
try {
val stdout = ByteArrayOutputStream()
exec {
commandLine("git", "status", "--porcelain")
standardOutput = stdout
}
val result = stdout.toString().replace(Regex("M gradlew(\\.bat)?"), "").trimEnd()
if (result.isNotEmpty())
println("Found stageable results:\n${result}\n")
return result.isNotEmpty()
} catch(ignored: Throwable) {
return false
}
}
fun Project.architectury(action: Action<ArchitectPluginExtension>) {
action.execute(this.extensions.getByType<ArchitectPluginExtension>())
}
fun RepositoryHandler.exclusiveMaven(url: String, vararg groups: String) {
exclusiveContent {
forRepository { maven(url) }
filter {
groups.forEach {
includeGroup(it)
}
}
}
}
operator fun String.invoke(): String {
return rootProject.ext[this] as? String
?: throw IllegalStateException("Property $this is not defined")
}