How to access git commit sha in nix-build package

I am building a nix package (a module, if I get the naming right) for a small golang CLI application. It works, but the application developer would like to include the commit SHA in the version string. Example:

$ app -v
app v1 (11889a5af0)

My first idea was to add the commit SHA to a variable, like this:

{ lib, buildGoModule, fetchFromGitHub }:

buildGoModule rec {
  pname = "app";
  version = "v1";
  commit = "11889a5af0";

  src = fetchFromGitHub { ... };

  ldflags = [ "-X main.commit=${commit}" ];

  meta = {...};

This works, but the pull request reviewers don’t like this solution since the commit variable will not be automatically updated. Understandably so, this solution requires manual intervention at each update.

I found a better solution looking through the nixpkgs repository by storing a temporary file and using that value in the flags.

 fetchFromGitHub {
   owner = "owner";
   repo = "app";
   rev = "v1";
   hash = "sha256-hash=";
   leaveDotGit = true;
   postFetch = ''
     cd "$out"
     git rev-parse HEAD > $out/COMMIT
     find "$out" -name .git -print0 | xargs -0 rm -rf


preBuild = ''
  ldflags+=" -X main.commit=$(cat COMMIT)"

This works for the examples I find on GitHub, but my package doesn’t build. The preBuild step complains that it can’t find the COMMIT file. Or it is not created, or I am pointing it to the wrong path.

Running phase: buildPhase
cat: COMMIT: No such file or directory

Any ideas on how to assign the current git commit SHA to the ldflags when building the application?

Thank you!

Thank you for your assistance. I believe that I have found the problem.

Removing the hash="sha256-hash="; part, building the package, letting it fail and adding the new hash from the failed result seems to pick up the changes.

I guess not changing the hash caused some cached version to run, which did not include the postFetch part, since I added it later. I thought my changes were being run, but some old cached version was used.