modules/misc/version.nix: populate nixosRevision based on <nixpkgs/.git> when possible (#15624)

Example:

$ nixos-option system.nixosLabel
Value:
"16.09.git.4643ca1"

obadz 47950b53 c726773f

+32 -2
+26
lib/sources.nix
··· 29 29 in type == "directory" || lib.any (ext: lib.hasSuffix ext base) exts; 30 30 in builtins.filterSource filter path; 31 31 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"; 32 58 }
+6 -2
nixos/modules/misc/version.nix
··· 5 5 let 6 6 cfg = config.system; 7 7 8 - releaseFile = "${toString pkgs.path}/.version"; 9 - suffixFile = "${toString pkgs.path}/.version-suffix"; 8 + releaseFile = "${toString pkgs.path}/.version"; 9 + suffixFile = "${toString pkgs.path}/.version-suffix"; 10 10 revisionFile = "${toString pkgs.path}/.git-revision"; 11 + gitRepo = "${toString pkgs.path}/.git"; 12 + gitCommitId = lib.substring 0 7 (commitIdFromGitRepo gitRepo); 11 13 in 12 14 13 15 { ··· 102 104 # changing them would not rebuild the manual 103 105 nixosLabel = mkDefault (maybeEnv "NIXOS_LABEL" cfg.nixosVersion); 104 106 nixosVersion = mkDefault (maybeEnv "NIXOS_VERSION" (cfg.nixosRelease + cfg.nixosVersionSuffix)); 107 + nixosRevision = mkIf (pathExists gitRepo) (mkDefault gitCommitId); 108 + nixosVersionSuffix = mkIf (pathExists gitRepo) (mkDefault (".git." + gitCommitId)); 105 109 106 110 # Note: code names must only increase in alphabetical order. 107 111 nixosCodeName = "Flounder";