|
1 | 1 | package org.mangorage.mangobotgradle.util; |
2 | 2 |
|
3 | | -import java.io.BufferedReader; |
| 3 | +import org.eclipse.jgit.lib.Repository; |
| 4 | +import org.eclipse.jgit.revwalk.RevCommit; |
| 5 | +import org.eclipse.jgit.revwalk.RevWalk; |
| 6 | +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; |
| 7 | + |
| 8 | +import java.io.File; |
4 | 9 | import java.io.IOException; |
5 | | -import java.io.InputStreamReader; |
6 | 10 |
|
7 | 11 | public record GitVersion(String tag, String commits, String commit) { |
8 | 12 | private static final GitVersion UNKNOWN = new GitVersion("0.0", "9999", "unknown"); |
9 | 13 |
|
10 | 14 | public static GitVersion getGitVersion() { |
11 | 15 | try { |
12 | | - var process = Runtime.getRuntime().exec("git describe --long --tags"); |
13 | | - try (var isr = new InputStreamReader(process.getInputStream())) { |
14 | | - try (var br = new BufferedReader(isr)) { |
15 | | - var result = br.readLine().split("-"); |
16 | | - return new GitVersion( |
17 | | - result[0], |
18 | | - result[1], |
19 | | - result[2] |
20 | | - ); |
| 16 | + FileRepositoryBuilder builder = new FileRepositoryBuilder(); |
| 17 | + try (Repository repository = builder.setGitDir(new File(".git")).readEnvironment().findGitDir().build()) { |
| 18 | + try (RevWalk walk = new RevWalk(repository)) { |
| 19 | + RevCommit headCommit = walk.parseCommit(repository.resolve("HEAD")); |
| 20 | + String commitHash = headCommit.getName().substring(0, 7); |
| 21 | + |
| 22 | + // Find the latest tag |
| 23 | + String tag = repository.getRefDatabase().getRefsByPrefix("refs/tags/") |
| 24 | + .stream() |
| 25 | + .map(ref -> ref.getName().substring("refs/tags/".length())) |
| 26 | + .reduce((first, second) -> second) // Get the latest tag |
| 27 | + .orElse(""); |
| 28 | + |
| 29 | + if (tag.isBlank()) |
| 30 | + return UNKNOWN; |
| 31 | + |
| 32 | + // Count commits since the tag |
| 33 | + int commitCount = 0; |
| 34 | + walk.markStart(headCommit); |
| 35 | + for (RevCommit commit : walk) { |
| 36 | + commitCount++; |
| 37 | + } |
| 38 | + |
| 39 | + return new GitVersion(tag, String.valueOf(commitCount), commitHash); |
21 | 40 | } |
22 | 41 | } |
23 | 42 | } catch (IOException ignored) {} |
24 | 43 | return UNKNOWN; |
25 | 44 | } |
26 | 45 |
|
| 46 | + |
27 | 47 | public boolean isUnknown() { |
28 | 48 | return this == UNKNOWN; |
29 | 49 | } |
|
0 commit comments