-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathbuild.gradle.kts
More file actions
364 lines (306 loc) · 14 KB
/
build.gradle.kts
File metadata and controls
364 lines (306 loc) · 14 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
import dev.kikugie.stonecutter.build.config.ReplacementContainer
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject
import me.modmuss50.mpp.ReleaseType
plugins { // versions in gradle.properties + settings.gradle.kts
kotlin("jvm")
id("dev.isxander.modstitch.base")
id("net.fabricmc.fabric-loom") apply false
id("me.modmuss50.mod-publish-plugin")
}
val id = m("id")
val v: String = m("version")
val minecraft = stonecutter.current.version
val loader: String = name.substringAfter("-").replace("neoforge", "neo") // prepub: does this cause any issues...
val currentIsActive = minecraft == stonecutter.active?.version
var publish = providers.gradleProperty("publish").getOrElse("false").toBoolean() // prepub: abolish bc this is annoying bc the default is
// that it will publish bc the property is not set but u need that for regular publishMods to work without ugly command line parameters, but it would be best
// if we just had a `testPublishMods` task
var changes = "No changelog specified."
fun java(): Int = modstitch.javaVersion.orNull ?: error("No Java version available (per Modstitch)")
fun javaStr(): String = java().toString()
/**
* Returns the property with the given name. If it doesn't exist then returns the
* fallback, but if that's null then throws an error.
*/
fun p(name: String, fallback: String? = null): String {
val p = findProperty(name) as String?
return when {
p != null -> p
fallback != null -> fallback
else -> error("Property '$name' not found with no fallback provided")
}
}
fun prop(name: String, consumer: (prop: String) -> Unit) {
val p = p(name, "")
if(p.isNotEmpty()) p.let(consumer)
}
/**
* See the `publishMods` and `modstitch.metadata` blocks
*/
fun propList(name: String): List<String> = p(name).split(",").filter { it.isNotBlank() }
fun d(name: String, fallback: String? = null): String = p("dep.$name", fallback)
fun dep(name: String, consumer: (prop: String) -> Unit) = prop("dep.$name", consumer)
fun m(name: String, fallback: String? = null): String = p("mod.$name", fallback)
//fun mod(name: String, consumer: (prop: String) -> Unit) = prop("mod.$name", consumer)
/**
* Returns the property belonging to the current loader. For example, `l("api")`
* will return the value of `fabric.api`, `neo.api`, or `forge.api` depending on
* the current loader.
*/
/*fun l(name: String, fallback: String? = null): String = p("$loader.$name", fallback)*/
/*kotlin {
jvmToolchain(25) // can't use java() bc it's not available here - warning: commenting this out may cause issues?
}*/
dependencies {
// fabric only
modstitch.loom {
val fapi = p("fabric.api") + "+" + minecraft.substringBefore('-')
modstitchModImplementation(fabricApi.module("fabric-lifecycle-events-v1", fapi))
modstitchModImplementation(fabricApi.module("fabric-networking-api-v1", fapi))
modstitchModImplementation(fabricApi.module("fabric-screen-api-v1", fapi))
}
modstitchModImplementation(
if(minecraft == "1.20.2")
"dev.isxander.yacl:yet-another-config-lib-fabric:${d("yacl")}"
else
"dev.isxander:yet-another-config-lib:${d("yacl")}-fabric"
)
modstitchModImplementation("com.terraformersmc:modmenu:${d("modmenu")}")
implementation(kotlin("stdlib-jdk8"))
}
repositories {
mavenCentral()
maven("https://maven.isxander.dev/releases")
maven("https://maven.terraformersmc.com/releases/")
if(minecraft == "1.20.4") {
maven("https://maven.nucleoid.xyz/") // Placeholder API for Mod Menu -_-
}
}
modstitch {
minecraftVersion = minecraft
parchment {
dep("parchment") { mappingsVersion = it }
}
// applies to any files inside the templates folder
metadata {
modId = id
modVersion = v
modName = m("name")
modGroup = m("group")
modDescription = m("desc")
modAuthor = m("author")
modCredits = m("credits").split(",").map { "\"$it\"" }.toString() // transforms the invalid json into a valid list
modLicense = m("license")
//todo forge: uses mods.toml instead of neoforge.mods.toml
fun dep2StringList(list: String): String = propList(list).joinToString(separator = ",\n\t", transform = { "\"$it\": \"*\"" })
replacementProperties.putAll(mapOf(
"java" to javaStr(),
"mod_source" to m("source"),
"mod_modrinth" to m("modrinth"),
"minecraft_range" to m("range", minecraft).run {
if(contains(',')) {
// parse versions into a list and then add quotes to ensure valid JSON syntax
split(",").map { "\"$it\"" }.toString()
} else {
"\"$this\""
}
//if(!isLoom) [list.getFirst(),list.getLast()] // version ranges should all be consecutive
},
"fabric_loader_core" to p("fabric.loader").substringAfter('.').substringBefore('.'), // ex. 0.18.4 -> 18
"optional_list" to dep2StringList("optionals"),
"incompatible_list" to dep2StringList("incompatibles"),
//"embed_list" to dep2StringList("embedded"), // currently empty
))
}
// Fabric
loom {
fabricLoaderVersion = p("fabric.loader")
// Configure loom like normal here
/*configureLoom {
}*/
}
// NeoForge, Forge
moddevgradle {
// Configures client runs for MDG, it is not done by default
//defaultRuns(true, false) { "$loader $it" }
// This block configures the `neoforge` extension that MDG exposes by default,
// you can configure MDG like normal from here
/*configureNeoforge {
runs.all {
disableIdeRun()
}
//todo https://projects.neoforged.net/neoforged/moddevgradle # Runs
// + https://discord.com/channels/780023008668287017/780485575194312704/1402249054179688468
}*/
}
mixin {
addMixinsToModManifest = true // auto-gen mixins in FMJ and mods.toml
configs.register(id)
// loader specific mixin configs:
//if(is(Loom|ModDevGradleRegular|ModDevGradleLegacy))
//configs.register("$id-{}")
}
}
tasks {
modstitch.finalJarTask {
archiveBaseName.set(id)
archiveVersion.set("$v+$minecraft")
archiveClassifier.set(loader)
}
processResources {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
val changelogFile: File = rootDir.toPath().resolve("changelog.md").toFile()
if(changelogFile.exists()) {
var fileText = changelogFile.readText()
// replace issue numbers with links
fileText = fileText.replace(Regex("##(\\d+)"), "[#$1](https://www.github.com/mrbuilder1961/ChatPatches/issues/$1)")
changelogFile.writeText(fileText) // update the file
// hack-ily gets the first changelog entry
val newEntryTitle = "## Chat Patches `$v`"
val newIndex = fileText.indexOf(newEntryTitle)
val prevEntryIndex = fileText.replaceFirst(newEntryTitle, "").indexOf("## Chat Patches `") + newEntryTitle.length - 2
changes = (if(newIndex > prevEntryIndex) "" else fileText.substring(if(newIndex >= 0) newIndex else 0, prevEntryIndex))
// considered "malformed" if it doesn't end with any word characters, whitespace, or newlines - or changes were emptied bc the indices were bad
if( !changes.matches(Regex("(?s).*(\\s+|(\r?\n)+|\\w+)$")) || newIndex == -1 ) {
println("Warning: Changelog appears malformed, this is typically caused by an outdated version ($v)")
if(publish) {
publish = false
}
} else if(changes.length > 2000) {
val cutoff = "... (trimmed)"
changes = changes.substring(0, 2000 - cutoff.length) + cutoff
println("Warning: Changelog is longer than 2000 characters, trimming for publish action")
}
}
}
clean {
delete(rootProject.layout.buildDirectory)
delete(project.file("build"))
}
publishMods {
dependencies.get().dependsOn("processResources")
}
}
stonecutter { // https://stonecutter.kikugie.dev/wiki/config/params
constants {
match(loader, "fabric", "neo", "forge")
//put("forge", loader != "fabric") //prepub forgelike maybe?
}
dependencies {
put("java", javaStr())
put("config", when {
current.parsed >= "1.19" -> "yacl"
else -> "cloth"
})
}
swaps {
put("text_codec", when {
current.parsed > "1.20.2" -> "net.minecraft.network.chat.ComponentSerialization.CODEC"
else -> "net.minecraft.util.ExtraCodecs.COMPONENT"
})
val v1215 = current.parsed >= "1.21.5"
// all of these require 'new' before them, regardless of version
put("open_url", if(v1215) "ClickEvent.OpenUrl(URI.create($1))" else "ClickEvent(ClickEvent.Action.OPEN_URL, $1)") // java.net.URI is always available
put("suggest_command", if(v1215) "ClickEvent.SuggestCommand($1)" else "ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, $1)")
put("show_text", if(v1215) "HoverEvent.ShowText($1)" else "HoverEvent(HoverEvent.Action.SHOW_TEXT, $1)")
val v1216 = current.parsed >= "1.21.6"
put("push_stack", if(v1216) "graphics.pose().pushMatrix();" else "graphics.pose().pushPose();")
put("pop_stack", if(v1216) "graphics.pose().popMatrix();" else "graphics.pose().popPose();")
val v1219 = current.parsed >= "1.21.9"
put("key_event", if(v1219) "KeyEvent key" else "int keyCode, int scanCode, int modifiers")
put("key_args", if(v1219) "key" else "keyCode, scanCode, modifiers")
put("mouse_event", if(v1219) "MouseButtonEvent mouse, boolean bl" else "double mX, double mY, int button")
put("mouse_args", if(v1219) "mouse, bl" else "mX, mY, button")
}
replacements {
fun str(dir: Boolean, from: String, to: String, nameId: String? = null, defaultEnabled: Boolean = true) {
val action: ReplacementContainer.StringReplacementSpec.() -> Unit = { replace(from, to) }
val id = (if(defaultEnabled) "!" else "") + nameId
if(nameId == null) {
if(!defaultEnabled) error("Replacement cannot be nameless and disabled by default: '$from' -> '$to'")
string(dir, action)
} else {
string(dir, id, action)
}
//println("REGISTERED STRING REPLACEMENT $id: '$from' ${if(dir) "->" else "<-"} '$to' (defaultEnabled = $defaultEnabled)")
}
//prepub rename these they ugly as freak
val j21 = java() >= 21
str(j21, ".get(0)", ".getFirst()", "j21_get_first")
str(j21, ".remove(0)", ".removeFirst()", "j21_remove_first")
val v12111 = current.parsed >= "1.21.11"
str(v12111, "net.minecraft.Util", "net.minecraft.util.Util")
str(v12111, "ResourceLocation", "Identifier", "yarnification", false) // selectively enabled
val v261 = current.parsed >= "26.1"
str(v261, "net.minecraft.client.GuiMessage", "net.minecraft.client.multiplayer.chat.GuiMessage") // also conveniently covers GuiMessageTag!
str(v261, "GuiGraphics", "GuiGraphicsExtractor")
str(v261, "render(", "extractRenderState(", "extract_render_state", true) // targets plain render(..) calls
str(v261, "\"render\"", "\"extractRenderState\"", "extract_render_state_target", true) // targets plain render(..) injectors
str(v261, "render", "extract", "render_extraction", false) // targets render<component>(..) calls
}
}
publishMods {
val secrets = rootDir.toPath().resolve("secrets.json").toFile()
fun token(name: String): String {
return when {
!secrets.exists() -> {
dryRun = true
"-"
}
else -> (
Json.parseToJsonElement( secrets.readText(Charsets.UTF_8) )
.jsonObject[name]
?.toString()
?.replace("\"", "") // kotlin's json is weird
?:
"?"
)
}
}
val targets = m("range", minecraft).split(",")
val required = propList("required")
val optionals = propList("optionals")
val incompatibles = propList("incompatibles")
val embedded = propList("embedded")
//prepub prob need to store these in options... sigh
version = "$v+$name" // mod_version+minecraft-loader
displayName = "$v for $minecraft ${loader.replaceFirstChar { it.uppercase() }}"
file = modstitch.finalJarTask.flatMap { it.archiveFile } // https://modmuss50.github.io/mod-publish-plugin/getting_started/#input-file
changelog = changes
type = when {
"alpha" in v -> ReleaseType.ALPHA
"beta" in v -> ReleaseType.BETA
else -> ReleaseType.STABLE
}
modLoaders = propList("loaders") // todo: vers-specific for forge/neo version cutoffs
dryRun = !publish
curseforge {
accessToken = token("curseforge")
projectId = m("curseforge")
projectSlug = m("id")
minecraftVersions.addAll(targets)
required.forEach(::requires)
optionals.forEach(::optional)
incompatibles.forEach(::incompatible)
embedded.forEach(::embeds)
}
modrinth {
accessToken = token("modrinth")
projectId = m("modrinth")
minecraftVersions.addAll(targets)
// specify id OR slug NOT both, +OPTIONAL specific version
required.forEach(::requires)
optionals.forEach(::optional)
incompatibles.forEach(::incompatible)
embedded.forEach(::embeds)
}
if(currentIsActive) { // only announce the version once
discord {
webhookUrl = token("discord") // official
dryRunWebhookUrl = token("discord_debug") // testing
username = "Publisher Bot"
avatarUrl = "https://cdn.modrinth.com/data/MOqt4Z5n/56c954dea290ef4dd1b0d6ea92a811acac62ca85.png"
}
}
}