[Solved] How to apply a patch in a flake

Hello, I have a flake that includes a derivation

...
baz = pkgs.stdenv.mkDerivation {
	name = "baz";
    version = "0.0.1";
    src = builtins.fetchGit {
      url = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
	  rev = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    };	
...

I would like to apply a patch to the src.
What is a good way to do this?
Thanks!

You can apply the patch like how you normally would without flakes, by adding it as an argument to mkDerivation

pkgs.stdenv.mkDerivation {
  # ...
  patches = [ ./path/to/patch ];
}

you can also use fetchpatch

pkgs.stdenv.mkDerivation {
  # ...
  patches = [
    (pkgs.fetchpatch {
      url = "https://example.org/foo.patch";
      hash = "";
    })
  ];
}
1 Like

Thanks, that what I thought. I must be doing something pretty stupid. I have created a MWE:

{
  inputs = {
    flake-utils.url = "github:numtide/flake-utils";
    nixpkgs.url = "nixpkgs/nixpkgs-unstable";
  };
  
  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system:
      let
        pkgs = import nixpkgs { inherit system; };

        hello = pkgs.stdenv.mkDerivation {
		      name = "hello";
		      version = "0.0.1";
          src = builtins.fetchGit {
			      url = "git@github.com:jademackay/hello.git";
			      rev = "60210f2dbe9acd49197f1fe505d5ee7de79650e4";
          };
          patches = [ ./p1.patch ];
          phases = [ "unpackPhase" "patchPhase" "buildPhase" ];
          buildPhase = ''
          mkdir -p $out/bin
          cp $src/hello.sh $out/bin/hello.sh
          '';
          };
        
      in rec {
        packages.hello = hello;
      }
    );
}

where the src repo contains a shell script:

#!/usr/bin/env sh

echo Hello!

and where p1.patch is

diff --git a/hello.sh b/hello.sh
index bab30a6..ae60f80 100755
--- a/hello.sh
+++ b/hello.sh
@@ -1,3 +1,3 @@
 #!/usr/bin/env sh

-echo Hello!
+echo Bye!

I build using

nix build .#hello

and the contents of result/bin/hello.sh are

#!/usr/bin/env sh

echo Hello!

… not as desired.

$src refers to the original unpatched source, you can omit that to use the patched one from the current directory

-cp $src/hello.sh $out/bin/hello.sh
+cp hello.sh $out/bin/hello.sh
1 Like

There it is, many thanks!