26
26
import java .util .HashMap ;
27
27
import java .util .List ;
28
28
import java .util .Map ;
29
+ import java .util .regex .Matcher ;
30
+ import java .util .regex .Pattern ;
29
31
import java .util .stream .Collectors ;
32
+ import java .util .stream .Stream ;
30
33
31
34
public class GlobalBuildInfoPlugin implements Plugin <Project > {
32
35
private static final String GLOBAL_INFO_EXTENSION_NAME = "globalInfo" ;
@@ -247,7 +250,23 @@ public static String gitRevision(File rootDir) {
247
250
}
248
251
final String ref = readFirstLine (head );
249
252
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
+ }
251
270
} else {
252
271
// we are in detached HEAD state
253
272
revision = ref ;
@@ -260,9 +279,13 @@ public static String gitRevision(File rootDir) {
260
279
}
261
280
262
281
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 ;
266
289
}
267
290
268
291
}
0 commit comments