|
| 1 | +package dev.xpple.seedmapper.buildscript; |
| 2 | + |
| 3 | +import com.google.gson.Gson; |
| 4 | +import com.google.gson.JsonObject; |
| 5 | +import org.gradle.api.DefaultTask; |
| 6 | +import org.gradle.api.file.RegularFileProperty; |
| 7 | +import org.gradle.api.tasks.OutputFile; |
| 8 | +import org.gradle.api.tasks.TaskAction; |
| 9 | +import org.gradle.process.ExecOperations; |
| 10 | + |
| 11 | +import javax.inject.Inject; |
| 12 | +import java.io.BufferedWriter; |
| 13 | +import java.io.ByteArrayOutputStream; |
| 14 | +import java.io.IOException; |
| 15 | +import java.nio.charset.StandardCharsets; |
| 16 | +import java.nio.file.Files; |
| 17 | + |
| 18 | +public abstract class GenerateBuildInfoTask extends DefaultTask { |
| 19 | + |
| 20 | + private static final Gson GSON = new Gson(); |
| 21 | + |
| 22 | + @OutputFile |
| 23 | + public abstract RegularFileProperty getOutputFile(); |
| 24 | + |
| 25 | + @Inject |
| 26 | + protected abstract ExecOperations getExecOperations(); |
| 27 | + |
| 28 | + { |
| 29 | + // never reuse previous outputs |
| 30 | + this.getOutputs().upToDateWhen(_ -> false); |
| 31 | + } |
| 32 | + |
| 33 | + @TaskAction |
| 34 | + protected void run() { |
| 35 | + String version = this.getProject().getVersion().toString(); |
| 36 | + String branch = this.executeCommand("git", "branch", "--show-current"); |
| 37 | + String shortCommitHash = this.executeCommand("git", "rev-parse", "--short", "HEAD"); |
| 38 | + String commitHash = this.executeCommand("git", "rev-parse", "HEAD"); |
| 39 | + |
| 40 | + JsonObject object = new JsonObject(); |
| 41 | + object.addProperty("version", version); |
| 42 | + object.addProperty("branch", branch); |
| 43 | + object.addProperty("shortCommitHash", shortCommitHash); |
| 44 | + object.addProperty("commitHash", commitHash); |
| 45 | + |
| 46 | + try (BufferedWriter writer = Files.newBufferedWriter(this.getOutputFile().getAsFile().get().toPath())) { |
| 47 | + GSON.toJson(object, writer); |
| 48 | + } catch (IOException e) { |
| 49 | + throw new RuntimeException(e); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + private String executeCommand(Object... args) { |
| 54 | + ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(); |
| 55 | + this.getExecOperations().exec(execSpec -> { |
| 56 | + execSpec.setStandardOutput(outputBytes); |
| 57 | + execSpec.commandLine(args); |
| 58 | + }).rethrowFailure(); |
| 59 | + return outputBytes.toString(StandardCharsets.UTF_8).trim(); |
| 60 | + } |
| 61 | +} |
0 commit comments