From 2cef1b682c03d1a986c11d7ba2f29e412a9c8c20 Mon Sep 17 00:00:00 2001 From: xeals Date: Thu, 30 Nov 2023 12:35:17 +1100 Subject: [PATCH] Extract Zig package builder Consider moving to NUR or upstream? --- flake.nix | 42 ++++++----------------------- nix/build-zig-package.nix | 57 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 34 deletions(-) create mode 100644 nix/build-zig-package.nix diff --git a/flake.nix b/flake.nix index 4d7923d..549405c 100644 --- a/flake.nix +++ b/flake.nix @@ -12,6 +12,10 @@ inherit (nixpkgs) lib; pkgs = import nixpkgs { inherit system; }; zig = pkgs.zig_0_11; + buildZigPackage = import ./nix/build-zig-package.nix { + inherit (pkgs) stdenv; + inherit zig; + }; in { devShells = { @@ -23,39 +27,9 @@ }; }; - packages.default = - let - optimize = "ReleaseSafe"; - in - pkgs.stdenv.mkDerivation { - name = "aoc23"; - src = lib.cleanSource ./.; - - buildInputs = [ zig ]; - - # https://github.com/ziglang/zig/issues/6810 - XDG_CACHE_HOME = "xdg_cache"; - - zigFlags = [ "-Doptimize=${optimize}" ]; - - buildPhase = '' - runHook preBuild - zig build $zigFlags - runHook postBuild - ''; - - doCheck = true; - checkPhase = '' - runHook preCheck - zig build test $zigFlags - runHook postCheck - ''; - - installPhase = '' - runHook preInstall - zig build install --prefix $out $zigFlags - runHook postInstall - ''; - }; + packages.default = buildZigPackage { + name = "aoc23"; + src = lib.cleanSource ./.; + }; }); } diff --git a/nix/build-zig-package.nix b/nix/build-zig-package.nix new file mode 100644 index 0000000..c6707f2 --- /dev/null +++ b/nix/build-zig-package.nix @@ -0,0 +1,57 @@ +{ stdenv +, zig +}: + +{ buildInputs ? [ ] +, nativeBuildInputs ? [ ] +, optimize ? "ReleaseSafe" +, meta ? { } +, ... +}@args: + +stdenv.mkDerivation (args // { + nativeBuildInputs = nativeBuildInputs ++ [ + zig + ]; + + buildInputs = buildInputs; + + strictDeps = true; + + configurePhase = args.configurePhase or '' + runHook preConfigure + runHook postConfigure + ''; + + ZIGFLAGS = args.ZIGFLAGS or [ + "-Doptimize=${optimize}" + ]; + + # https://github.com/ziglang/zig/issues/6810 requires setting XDG_CACHE_HOME + # in all zig build phases. --cache-dir and --global-cache-dir do not prevent + # the builder from attempting to create the XDG cache. + + buildPhase = args.buildPhase or '' + runHook preBuild + XDG_CACHE_HOME=_cache zig build $ZIGFLAGS + runHook postBuild + ''; + + doCheck = args.doCheck or true; + checkPhase = args.checkPhase or '' + runHook preCheck + XDG_CACHE_HOME=_cache zig build test $ZIGFLAGS + runHook postCheck + ''; + + installPhase = args.installPhase or '' + runHook preInstall + XDG_CACHE_HOME=_cache zig build install --prefix $out $ZIGFLAGS + runHook postInstall + ''; + + meta = { + # default to Zig's platforms + platforms = zig.meta.platforms; + } // meta; +})