Skip to content

Commit d4f5376

Browse files
GlobalBuildInfo plugin should search packed references for commit IDs (#47464) (#47938)
* GlobalBuildInfo plugin searches packed references In recent versions of Git, references may be packed in a packed-refs file. If this happens, Gradle will need to look in that file to find build information.
1 parent 1571527 commit d4f5376

File tree

1 file changed

+27
-4
lines changed

1 file changed

+27
-4
lines changed

buildSrc/src/main/java/org/elasticsearch/gradle/info/GlobalBuildInfoPlugin.java

+27-4
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@
2626
import java.util.HashMap;
2727
import java.util.List;
2828
import java.util.Map;
29+
import java.util.regex.Matcher;
30+
import java.util.regex.Pattern;
2931
import java.util.stream.Collectors;
32+
import java.util.stream.Stream;
3033

3134
public class GlobalBuildInfoPlugin implements Plugin<Project> {
3235
private static final String GLOBAL_INFO_EXTENSION_NAME = "globalInfo";
@@ -247,7 +250,23 @@ public static String gitRevision(File rootDir) {
247250
}
248251
final String ref = readFirstLine(head);
249252
if (ref.startsWith("ref:")) {
250-
revision = readFirstLine(gitDir.resolve(ref.substring("ref:".length()).trim()));
253+
String refName = ref.substring("ref:".length()).trim();
254+
Path refFile = gitDir.resolve(refName);
255+
if (Files.exists(refFile)) {
256+
revision = readFirstLine(refFile);
257+
} else if (Files.exists(dotGit.resolve("packed-refs"))) {
258+
// Check packed references for commit ID
259+
Pattern p = Pattern.compile("^([a-f0-9]{40}) " + refName + "$");
260+
try (Stream<String> lines = Files.lines(dotGit.resolve("packed-refs"))) {
261+
revision = lines.map(p::matcher)
262+
.filter(Matcher::matches)
263+
.map(m -> m.group(1))
264+
.findFirst()
265+
.orElseThrow(() -> new IOException("Packed reference not found for refName " + refName));
266+
}
267+
} else {
268+
throw new GradleException("Can't find revision for refName " + refName);
269+
}
251270
} else {
252271
// we are in detached HEAD state
253272
revision = ref;
@@ -260,9 +279,13 @@ public static String gitRevision(File rootDir) {
260279
}
261280

262281
private static String readFirstLine(final Path path) throws IOException {
263-
return Files.lines(path, StandardCharsets.UTF_8)
264-
.findFirst()
265-
.orElseThrow(() -> new IOException("file [" + path + "] is empty"));
282+
String firstLine;
283+
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
284+
firstLine = lines
285+
.findFirst()
286+
.orElseThrow(() -> new IOException("file [" + path + "] is empty"));
287+
}
288+
return firstLine;
266289
}
267290

268291
}

0 commit comments

Comments
 (0)