From cd360b329f0d077ed6d784f1ed2cd02fb2cdb243 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arma=C3=ABl=20Gu=C3=A9neau?= Date: Fri, 2 Aug 2024 11:21:31 +0200 Subject: [PATCH] flake.nix: add static cross-compiled builds The nix invocations come from the garage .nix files --- compile.nix | 44 ++++++++++++++++++++++++++++++++++++++++++++ flake.nix | 43 +++++++++++++++++++++++++++---------------- 2 files changed, 71 insertions(+), 16 deletions(-) create mode 100644 compile.nix diff --git a/compile.nix b/compile.nix new file mode 100644 index 0000000..e31cba4 --- /dev/null +++ b/compile.nix @@ -0,0 +1,44 @@ +{ system, target ? null, pkgsSrc, cargo2nixOverlay, compiler ? "rustc", + release ? false, }: + +let + pkgs = if target != null then + import pkgsSrc { + inherit system; + crossSystem = { + config = target; + isStatic = true; + }; + overlays = [ cargo2nixOverlay ]; + } + else + import pkgsSrc { + inherit system; + overlays = [ cargo2nixOverlay ]; + }; + + toolchainOptions = { + rustVersion = "1.75.0"; + }; + + packageFun = import ./Cargo.nix; + + codegenOpts = { + "armv6l-unknown-linux-musleabihf" = [ + "target-feature=+crt-static" + "link-arg=-static" + ]; # compile as dynamic with static-pie + "x86_64-unknown-linux-musl" = + [ "target-feature=+crt-static" "link-arg=-static-pie" ]; + }; + + # NixOS and Rust/Cargo triples do not match for ARM, fix it here. + rustTarget = if target == "armv6l-unknown-linux-musleabihf" then + "arm-unknown-linux-musleabihf" + else + target; + +in pkgs.rustBuilder.makePackageSet ({ + inherit release packageFun codegenOpts; + target = rustTarget; +} // toolchainOptions) diff --git a/flake.nix b/flake.nix index 59b6c38..1512e58 100644 --- a/flake.nix +++ b/flake.nix @@ -10,25 +10,36 @@ }; outputs = { self, nixpkgs, cargo2nix, flake-utils }: + let + compile = import ./compile.nix; + in flake-utils.lib.eachDefaultSystem (system: let - pkgs = import nixpkgs { - inherit system; - overlays = [cargo2nix.overlays.default]; - }; - - rustPkgs = pkgs.rustBuilder.makePackageSet { - rustVersion = "1.75.0"; - packageFun = import ./Cargo.nix; - }; - - in rec { - packages = { - restic-alarm = (rustPkgs.workspace.restic-alarm {}); - default = packages.restic-alarm; - }; + pkgs = nixpkgs.legacyPackages.${system}; + in + rec { + packages = + let + packageFor = target: (compile { + inherit system target; + pkgsSrc = nixpkgs; + cargo2nixOverlay = cargo2nix.overlays.default; + release = true; + }).workspace.restic-alarm { compileMode = "build"; }; + in + { + # default = native release build + default = packages.restic-alarm; + restic-alarm = packageFor null; + # other = cross-compiled, statically-linked builds + amd64 = packageFor "x86_64-unknown-linux-musl"; + i386 = packageFor "i686-unknown-linux-musl"; + arm64 = packageFor "aarch64-unknown-linux-musl"; + arm = packageFor "armv6l-unknown-linux-musleabihf"; + }; } - ) // rec { + ) + // rec { nixosModules.restic-alarm = { config, lib, pkgs, ... }: with lib; let