|
| 1 | +import org.gradle.api.file.DirectoryProperty |
| 2 | +import org.gradle.api.provider.Property |
| 3 | +import org.gradle.api.provider.ValueSource |
| 4 | +import org.gradle.api.provider.ValueSourceParameters |
| 5 | +import org.gradle.process.ExecOperations |
| 6 | +import java.io.ByteArrayOutputStream |
| 7 | +import java.io.File |
| 8 | +import javax.inject.Inject |
| 9 | + |
| 10 | +abstract class GitVersionSource : ValueSource<String, GitVersionSource.Parameters> { |
| 11 | + |
| 12 | + interface Parameters : ValueSourceParameters { |
| 13 | + val minecraftVersion: Property<String> |
| 14 | + val projectDir: DirectoryProperty |
| 15 | + } |
| 16 | + |
| 17 | + @get:Inject |
| 18 | + abstract val execOperations: ExecOperations |
| 19 | + |
| 20 | + override fun obtain(): String { |
| 21 | + val minecraftVersion = parameters.minecraftVersion.get() |
| 22 | + val workDir = parameters.projectDir.get().asFile |
| 23 | + |
| 24 | + val releaseLine = workDir.resolve("release_line.txt").readText().trim() |
| 25 | + |
| 26 | + val patch = try { |
| 27 | + // Find the most recent first-parent commit that touched release_line.txt |
| 28 | + val lineStartCommit = git(workDir, |
| 29 | + "log", "--first-parent", |
| 30 | + "-n", "1", |
| 31 | + "--format=%H", |
| 32 | + "--", |
| 33 | + "release_line.txt" |
| 34 | + ).trim() |
| 35 | + |
| 36 | + if (lineStartCommit.isEmpty()) { |
| 37 | + // count all first-parent commits as a safe fallback |
| 38 | + git(workDir, "rev-list", "--count", "--first-parent", "HEAD") |
| 39 | + .trim().toIntOrNull() ?: 0 |
| 40 | + } else { |
| 41 | + git(workDir, "rev-list", "--count", "--first-parent", "$lineStartCommit..HEAD") |
| 42 | + .trim().toIntOrNull() ?: 0 |
| 43 | + } |
| 44 | + } catch (_: Exception) { |
| 45 | + // Git is unavailable or this is not a git repository |
| 46 | + 999 |
| 47 | + } |
| 48 | + |
| 49 | + return "$releaseLine.$patch+mc$minecraftVersion" |
| 50 | + } |
| 51 | + |
| 52 | + private fun git(workDir: File, vararg args: String): String { |
| 53 | + val output = ByteArrayOutputStream() |
| 54 | + execOperations.exec { |
| 55 | + commandLine("git", *args) |
| 56 | + standardOutput = output |
| 57 | + workingDir(workDir) |
| 58 | + } |
| 59 | + return output.toString(Charsets.UTF_8) |
| 60 | + } |
| 61 | +} |
0 commit comments