@@ -29,4 +29,30 @@ rec {
2929 in type == "directory" || lib.any (ext: lib.hasSuffix ext base) exts;
3030 in builtins.filterSource filter path;
3131
32+ # Get the commit id of a git repo
33+ # Example: commitIdFromGitRepo <nixpkgs/.git>
34+ commitIdFromGitRepo =
35+ let readCommitFromFile = path: file:
36+ with builtins;
37+ let fileName = toString path + "/" + file;
38+ packedRefsName = toString path + "/packed-refs";
39+ in if lib.pathExists fileName
40+ then
41+ let fileContent = readFile fileName;
42+ # Sometimes git stores the commitId directly in the file but
43+ # sometimes it stores something like: «ref: refs/heads/branch-name»
44+ matchRef = match "^ref: (.*)\n$" fileContent;
45+ in if isNull matchRef
46+ then lib.removeSuffix "\n" fileContent
47+ else readCommitFromFile path (lib.head matchRef)
48+ # Sometimes, the file isn't there at all and has been packed away in the
49+ # packed-refs file, so we have to grep through it:
50+ else if lib.pathExists packedRefsName
51+ then
52+ let packedRefs = lib.splitString "\n" (readFile packedRefsName);
53+ matchRule = match ("^(.*) " + file + "$");
54+ matchedRefs = lib.flatten (lib.filter (m: ! (isNull m)) (map matchRule packedRefs));
55+ in lib.head matchedRefs
56+ else throw ("Not a .git directory: " + path);
57+ in lib.flip readCommitFromFile "HEAD";
3258}