From 3223e4860ee0f313c374209e872f9b5e2868220a Mon Sep 17 00:00:00 2001 From: Ivan Petkov Date: Thu, 30 Dec 2021 13:22:05 -0800 Subject: [PATCH] Add mkDummySrc --- lib/default.nix | 1 + lib/mkDummySrc.nix | 78 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 lib/mkDummySrc.nix diff --git a/lib/default.nix b/lib/default.nix index baa3ee7..85889b8 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -15,6 +15,7 @@ lib.makeScope newScope (self: buildWithCargo = callPackage ./buildWithCargo.nix { }; cleanCargoToml = callPackage ./cleanCargoToml.nix { }; downloadCargoPackage = callPackage ./downloadCargoPackage.nix { }; + mkDummySrc = callPackage ./mkDummySrc.nix { }; urlForCargoPackage = callPackage ./urlForCargoPackage.nix { }; vendorCargoDeps = callPackage ./vendorCargoDeps.nix { }; writeTOML = callPackage ./writeTOML.nix { }; diff --git a/lib/mkDummySrc.nix b/lib/mkDummySrc.nix new file mode 100644 index 0000000..b9bae05 --- /dev/null +++ b/lib/mkDummySrc.nix @@ -0,0 +1,78 @@ +{ cleanCargoToml +, lib +, runCommand +, writeText +, writeTOML +}: + +{ src ? null +, cargoToml ? src + /Cargo.toml +, cargoLock ? src + /Cargo.lock +, cargoConfig ? src + /.cargo/config +, cargoConfigToml ? src + /.cargo/config.toml +}: +let + inherit (builtins) + dirOf + concatStringsSep + hasAttr + pathExists; + + dummyrs = writeText "dummy.rs" '' + #![allow(dead_code)] + pub fn main() {} + ''; + + trimmedCargoToml = cleanCargoToml { + inherit cargoToml; + }; + + p = trimmedCargoToml.package; + name = "${p.name}-${p.version}-dummy-src"; + + copyCargoConfig = + # the .toml extension is preferred, but the extension-less path takes precedence + # https://doc.rust-lang.org/cargo/reference/config.html + if pathExists cargoConfig + then "cp ${cargoConfig} $out/.cargo" + else if pathExists cargoConfigToml + then "cp ${cargoConfigToml} $out/.cargo" + else ""; + + cpDummy = path: '' + mkdir -p $out/${dirOf path} + cp -f ${dummyrs} $out/${path} + ''; + + safeStubLib = + if hasAttr "lib" trimmedCargoToml + then cpDummy (trimmedCargoToml.lib.path or "src/lib.rs") + else ""; + + safeStubList = attr: defaultPath: + let + targetList = trimmedCargoToml.${attr} or [ ]; + paths = map (t: t.path or "${defaultPath}/${t.name}") targetList; + commands = map cpDummy paths; + in + concatStringsSep "\n" commands; +in +runCommand name { } '' + # Base configuration + mkdir -p $out/.cargo + ${copyCargoConfig} + cp ${writeTOML "Cargo.toml" trimmedCargoToml} $out/Cargo.toml + cp ${cargoLock} $out/Cargo.lock + + # To build build-dependencies + ${cpDummy "build.rs"} + # To build regular and dev dependencies (cargo build + cargo test) + ${cpDummy "src/main.rs"} + + # Stub all other targets in case they have particular feature combinations + ${safeStubLib} + ${safeStubList "bench" "benches"} + ${safeStubList "bin" "bin"} + ${safeStubList "example" "examples"} + ${safeStubList "test" "tests"} +''