From f0869ea9405cf87964394358a1215209e907e092 Mon Sep 17 00:00:00 2001 From: IThundxr Date: Fri, 6 Sep 2024 17:23:40 -0400 Subject: [PATCH] Embed version & git commit into code at build time --- build.gradle.kts | 51 ++++++++++++------- common/build.gradle.kts | 12 ++--- .../railways/BuildParameters.java.peb | 6 +++ .../com/railwayteam/railways/Railways.java | 12 ++--- .../railwayteam/railways/multiloader/Env.java | 3 +- .../railways/multiloader/Loader.java | 8 ++- .../util/packet/ModVersionPacket.java | 2 +- .../railways/fabric/RailwaysImpl.java | 9 ---- .../railways/forge/RailwaysImpl.java | 16 ------ 9 files changed, 56 insertions(+), 63 deletions(-) create mode 100644 common/src/main/java-templates/com/railwayteam/railways/BuildParameters.java.peb diff --git a/build.gradle.kts b/build.gradle.kts index f71406038..6f3ca14fa 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -25,7 +25,6 @@ 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.Type import org.objectweb.asm.tree.AnnotationNode import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.MethodNode @@ -44,6 +43,8 @@ plugins { id("me.modmuss50.mod-publish-plugin") version "0.3.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" } println("Steam 'n' Rails v${"mod_version"()}") @@ -58,6 +59,8 @@ 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 + tasks.jar { enabled = false } @@ -87,6 +90,7 @@ allprojects { subprojects { apply(plugin = "dev.architectury.loom") + apply(plugin = "net.kyori.blossom") setupRepositories() @@ -339,11 +343,6 @@ tasks.create("railwaysPublish") { } } -operator fun String.invoke(): String { - return rootProject.ext[this] as? String - ?: throw IllegalStateException("Property $this is not defined") -} - fun Project.setupRepositories() { repositories { mavenCentral() @@ -380,24 +379,32 @@ fun Project.setupRepositories() { } fun calculateGitHash(): String { - val stdout = ByteArrayOutputStream() - exec { - commandLine("git", "rev-parse", "HEAD") - standardOutput = stdout + try { + val stdout = ByteArrayOutputStream() + exec { + commandLine("git", "rev-parse", "HEAD") + standardOutput = stdout + } + return stdout.toString().trim() + } catch(ignored: Throwable) { + return "unknown" } - return stdout.toString().trim() } fun hasUnstaged(): Boolean { - val stdout = ByteArrayOutputStream() - exec { - commandLine("git", "status", "--porcelain") - standardOutput = stdout + 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 } - val result = stdout.toString().replace(Regex("M gradlew(\\.bat)?"), "").trimEnd() - if (result.isNotEmpty()) - println("Found stageable results:\n${result}\n") - return result.isNotEmpty() } fun Project.architectury(action: Action) { @@ -414,3 +421,9 @@ fun RepositoryHandler.exclusiveMaven(url: String, vararg groups: String) { } } } + +operator fun String.invoke(): String { + return rootProject.ext[this] as? String + ?: throw IllegalStateException("Property $this is not defined") +} + diff --git a/common/build.gradle.kts b/common/build.gradle.kts index 2f0112f89..3a324d806 100644 --- a/common/build.gradle.kts +++ b/common/build.gradle.kts @@ -49,14 +49,6 @@ dependencies { modCompileOnly("de.maxhenkel.voicechat:voicechat-api:${"voicechat_api_version"()}") modCompileOnly("maven.modrinth:simple-voice-chat:fabric-${"voicechat_version"()}") - modCompileOnly("maven.modrinth:sodium:${"sodium_version"()}") - - // mod compat for tracks - - // Hex Casting -/* modCompileOnly("at.petra-k.paucal:paucal-common-${minecraft_version}:${paucal_version}") - modCompileOnly("at.petra-k.hexcasting:hexcasting-common-${minecraft_version}:${hexcasting_version}") - modCompileOnly("vazkii.patchouli:Patchouli-xplat:${minecraft_version}-${patchouli_version}")*/ annotationProcessor(implementation("io.github.llamalad7:mixinextras-common:${"mixin_extras_version"()}")!!) } @@ -75,6 +67,10 @@ sourceSets.main { exclude(".cache/**") exclude("assets/create/**") } + blossom.javaSources { + property("version", "mod_version"()) + property("gitCommit", rootProject.extra["gitHash"].toString()) + } } operator fun String.invoke(): String { diff --git a/common/src/main/java-templates/com/railwayteam/railways/BuildParameters.java.peb b/common/src/main/java-templates/com/railwayteam/railways/BuildParameters.java.peb new file mode 100644 index 000000000..6780a7009 --- /dev/null +++ b/common/src/main/java-templates/com/railwayteam/railways/BuildParameters.java.peb @@ -0,0 +1,6 @@ +package com.railwayteam.railways; + +public class BuildParameters { + public static final String VERSION = "{{ version }}"; + public static final String GIT_COMMIT = {{ gitCommit | default("unknown") }}; +} \ No newline at end of file diff --git a/common/src/main/java/com/railwayteam/railways/Railways.java b/common/src/main/java/com/railwayteam/railways/Railways.java index 440f93016..049a29cb1 100644 --- a/common/src/main/java/com/railwayteam/railways/Railways.java +++ b/common/src/main/java/com/railwayteam/railways/Railways.java @@ -29,6 +29,7 @@ import com.railwayteam.railways.base.data.recipe.RailwaysStandardRecipeGen; import com.railwayteam.railways.compat.Mods; import com.railwayteam.railways.config.CRConfigs; +import com.railwayteam.railways.multiloader.Loader; import com.railwayteam.railways.registry.CRCommands; import com.railwayteam.railways.registry.CRPackets; import com.railwayteam.railways.util.Utils; @@ -59,7 +60,7 @@ public class Railways { public static final String ID_NAME = "Railways"; public static final String NAME = "Steam 'n' Rails"; public static final Logger LOGGER = LoggerFactory.getLogger(ID_NAME); - public static final String VERSION = findVersion(); + public static final String VERSION = BuildParameters.VERSION; // Only used for datafixers, bump whenever a block changes id etc. (should not be bumped multiple times within a release) public static final int DATA_FIXER_VERSION = 2; @@ -89,13 +90,15 @@ private static void migrateConfig(Path path, Function converter) } public static void init() { + LOGGER.info("Steam 'n' Rails {} v{} built from commit hash: {}, is initializing", Loader.getFormatted(), VERSION, BuildParameters.GIT_COMMIT); + Path configDir = Utils.configDir(); Path clientConfigDir = configDir.resolve(MODID + "-client.toml"); migrateConfig(clientConfigDir, CRConfigs::migrateClient); Path commonConfigDir = configDir.resolve(MODID + "-common.toml"); migrateConfig(commonConfigDir, CRConfigs::migrateCommon); - + ModSetup.register(); finalizeRegistrate(); @@ -127,11 +130,6 @@ public static CreateRegistrate registrate() { return REGISTRATE; } - @ExpectPlatform - public static String findVersion() { - throw new AssertionError(); - } - @ExpectPlatform public static void finalizeRegistrate() { throw new AssertionError(); diff --git a/common/src/main/java/com/railwayteam/railways/multiloader/Env.java b/common/src/main/java/com/railwayteam/railways/multiloader/Env.java index 5270bbdc9..11c90bf9c 100644 --- a/common/src/main/java/com/railwayteam/railways/multiloader/Env.java +++ b/common/src/main/java/com/railwayteam/railways/multiloader/Env.java @@ -19,7 +19,6 @@ package com.railwayteam.railways.multiloader; import dev.architectury.injectables.annotations.ExpectPlatform; -import net.fabricmc.loader.api.FabricLoader; import org.jetbrains.annotations.ApiStatus.Internal; import java.util.function.Supplier; @@ -47,7 +46,7 @@ public static T unsafeRunForDist(Supplier> clientTarget, Supplie @Internal @ExpectPlatform - public static Env getCurrent() { + private static Env getCurrent() { throw new AssertionError(); } } diff --git a/common/src/main/java/com/railwayteam/railways/multiloader/Loader.java b/common/src/main/java/com/railwayteam/railways/multiloader/Loader.java index 64baf0598..04e5de3c0 100644 --- a/common/src/main/java/com/railwayteam/railways/multiloader/Loader.java +++ b/common/src/main/java/com/railwayteam/railways/multiloader/Loader.java @@ -18,9 +18,11 @@ package com.railwayteam.railways.multiloader; +import com.railwayteam.railways.util.TextUtils; import dev.architectury.injectables.annotations.ExpectPlatform; import org.jetbrains.annotations.ApiStatus.Internal; +import java.util.Locale; import java.util.function.Supplier; public enum Loader { @@ -36,10 +38,14 @@ public void runIfCurrent(Supplier run) { if (isCurrent()) run.get().run(); } + + public static String getFormatted() { + return TextUtils.titleCaseConversion(Loader.CURRENT.name().toLowerCase(Locale.ROOT)); + } @Internal @ExpectPlatform - public static Loader getCurrent() { + private static Loader getCurrent() { throw new AssertionError(); } } diff --git a/common/src/main/java/com/railwayteam/railways/util/packet/ModVersionPacket.java b/common/src/main/java/com/railwayteam/railways/util/packet/ModVersionPacket.java index 2dc06ed3c..674c75dc1 100644 --- a/common/src/main/java/com/railwayteam/railways/util/packet/ModVersionPacket.java +++ b/common/src/main/java/com/railwayteam/railways/util/packet/ModVersionPacket.java @@ -47,7 +47,7 @@ public void write(FriendlyByteBuf buffer) { public void handle(Minecraft mc) { LocalPlayer player = mc.player; if (!Railways.VERSION.equals(version) && player != null) { - String msg = "Steam 'n' Rails version mismatch: Server is using version "+version+", you are using version "+Railways.VERSION+". This may cause problems."; + String msg = "Steam 'n' Rails version mismatch: Server is using version " + version + ", you are using version " + Railways.VERSION + ". This may cause problems."; Railways.LOGGER.warn(msg); player.displayClientMessage( Components.literal(msg).withStyle(ChatFormatting.DARK_RED), diff --git a/fabric/src/main/java/com/railwayteam/railways/fabric/RailwaysImpl.java b/fabric/src/main/java/com/railwayteam/railways/fabric/RailwaysImpl.java index 218b10449..839582026 100644 --- a/fabric/src/main/java/com/railwayteam/railways/fabric/RailwaysImpl.java +++ b/fabric/src/main/java/com/railwayteam/railways/fabric/RailwaysImpl.java @@ -39,15 +39,6 @@ public void onInitialize() { CommonEventsFabric.init(); } - public static String findVersion() { - return FabricLoader.getInstance() - .getModContainer(Railways.MODID) - .orElseThrow() - .getMetadata() - .getVersion() - .getFriendlyString(); - } - public static void finalizeRegistrate() { Railways.registrate().register(); } diff --git a/forge/src/main/java/com/railwayteam/railways/forge/RailwaysImpl.java b/forge/src/main/java/com/railwayteam/railways/forge/RailwaysImpl.java index 4d8d401e7..9eb610891 100644 --- a/forge/src/main/java/com/railwayteam/railways/forge/RailwaysImpl.java +++ b/forge/src/main/java/com/railwayteam/railways/forge/RailwaysImpl.java @@ -56,22 +56,6 @@ public RailwaysImpl() { Env.CLIENT.runIfCurrent(() -> () -> RailwaysClientImpl.init()); } - public static String findVersion() { - String versionString = "UNKNOWN"; - - List infoList = ModList.get().getModFileById(Railways.MODID).getMods(); - if (infoList.size() > 1) { - Railways.LOGGER.error("Multiple mods for MOD_ID: " + Railways.MODID); - } - for (IModInfo info : infoList) { - if (info.getModId().equals(Railways.MODID)) { - versionString = MavenVersionStringHelper.artifactVersionToString(info.getVersion()); - break; - } - } - return versionString; - } - public static void finalizeRegistrate() { Railways.registrate().registerEventListeners(bus); }