gitnix

How inject git revision into Nix derivation?


There are libraries such as gitrev, which allows to compile in git revision into executable file, but in case of using nix-build http://../master git meta data are missing in the source tree.

How to reference derivation revision in such situation to have it at least inside shellHook?


Solution

  • You can inject git revision of the current Nix flake into derivation by using self.rev.

    flake.nix:

    {
      inputs.nixpkgs.url = "github:NixOS/nixpkgs";
      outputs = { self, nixpkgs }:
        let
          system = "x86_64-linux";
          pkgs = nixpkgs.legacyPackages.${system};
        in
        {
          devShells.${system}.default = pkgs.mkShell {
            shellHook = ''
              echo "Nix flake revision is ${self.rev or self.dirtyRev or "dirty"}"
              echo "nixpkgs revision is ${nixpkgs.rev}"
            '';
          };
        };
      nixConfig.bash-prompt-suffix = "[devshell] ";
    }
    
    $ git init
    $ git add flake.nix
    $ git commit -m initial
    $ nix develop
    Nix flake revision is 32074a3b6583d7677f3aeb3679f75c190ab62c78
    nixpkgs revision is bd1cde45c77891214131cbbea5b1203e485a9d51
    

    Revisions of other flake inputs can be used as well. Starting from Nix v2.17 dirtyRev and dirtyShortRev are also provided (thus you can remove the or "dirty" part) in case the git working directory is in a modified state.


    As of 2023, Nix flake is the de-facto standard of developing, building and packaging software projects.