Skip to content

Commit

Permalink
Embed version & git commit into code at build time
Browse files Browse the repository at this point in the history
  • Loading branch information
IThundxr committed Sep 6, 2024
1 parent a2cce5b commit f0869ea
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 63 deletions.
51 changes: 32 additions & 19 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"()}")
Expand All @@ -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
}
Expand Down Expand Up @@ -87,6 +90,7 @@ allprojects {

subprojects {
apply(plugin = "dev.architectury.loom")
apply(plugin = "net.kyori.blossom")

setupRepositories()

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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<ArchitectPluginExtension>) {
Expand All @@ -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")
}

12 changes: 4 additions & 8 deletions common/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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"()}")!!)
}
Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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") }};
}
12 changes: 5 additions & 7 deletions common/src/main/java/com/railwayteam/railways/Railways.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -89,13 +90,15 @@ private static void migrateConfig(Path path, Function<String, String> 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();

Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -47,7 +46,7 @@ public static <T> T unsafeRunForDist(Supplier<Supplier<T>> clientTarget, Supplie

@Internal
@ExpectPlatform
public static Env getCurrent() {
private static Env getCurrent() {
throw new AssertionError();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -36,10 +38,14 @@ public void runIfCurrent(Supplier<Runnable> 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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,22 +56,6 @@ public RailwaysImpl() {
Env.CLIENT.runIfCurrent(() -> () -> RailwaysClientImpl.init());
}

public static String findVersion() {
String versionString = "UNKNOWN";

List<IModInfo> 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);
}
Expand Down

0 comments on commit f0869ea

Please sign in to comment.