From 54219f219196fea55871728a55b5324bb30774de Mon Sep 17 00:00:00 2001 From: AxelSilverdew <4kuchibh@gmail.com> Date: Sat, 28 Oct 2023 02:09:00 +0530 Subject: [PATCH] chore: formatted everything with alejandra --- build.nix | 364 ++++++++-------- builtins/default.nix | 114 +++-- builtins/to-toml.nix | 207 ++++----- config.nix | 268 ++++++------ default.nix | 136 +++--- docparse/shell.nix | 5 +- examples/checks/flake.nix | 14 +- examples/cross-windows/flake.nix | 13 +- examples/hello-world/flake.nix | 14 +- examples/multi-target/flake.nix | 65 +-- examples/multiple-binaries/flake.nix | 19 +- examples/static-musl/flake.nix | 11 +- flake.nix | 75 ++-- lib.nix | 403 +++++++++--------- nix/default.nix | 12 +- nix/sources.nix | 323 ++++++++------ readme.nix | 46 +- test.nix | 7 +- test/default.nix | 37 +- test/fast/cargo-config/default.nix | 19 +- test/fast/cargo-wildcard/default.nix | 3 +- test/fast/default-run/default.nix | 3 +- test/fast/dummyfication/default.nix | 14 +- .../duplicated-cargo-lock-items/default.nix | 3 +- .../git-dep-by-branch-with-slash/default.nix | 65 +-- test/fast/git-dep-by-branch/default.nix | 5 +- test/fast/git-dep-by-tag/default.nix | 5 +- test/fast/git-dep-dup/default.nix | 5 +- test/fast/git-dep/default.nix | 3 +- .../default.nix | 66 +-- test/fast/git-symlink/default.nix | 66 +-- test/fast/post-install-hook/default.nix | 28 +- test/fast/readme/default.nix | 2 +- test/fast/simple-dep-patched/default.nix | 3 +- test/fast/simple-dep/default.nix | 20 +- test/fast/symlinks/default.nix | 8 +- test/fast/unused-patch/default.nix | 24 +- test/fast/workspace-build-rs/default.nix | 3 +- test/fast/workspace-patched/default.nix | 3 +- test/fast/workspace/default.nix | 2 +- test/slow/agent-rs/default.nix | 28 +- test/slow/lorri/default.nix | 15 +- test/slow/nushell/default.nix | 25 +- test/slow/probe-rs/default.nix | 63 +-- test/slow/ripgrep-all/default.nix | 15 +- test/slow/rustlings/default.nix | 7 +- test/slow/talent-plan/default.nix | 7 +- 47 files changed, 1416 insertions(+), 1227 deletions(-) diff --git a/build.nix b/build.nix index aeff784..5d31c7b 100644 --- a/build.nix +++ b/build.nix @@ -1,27 +1,28 @@ -{ src +{ + src, #| From where the crates should be downloaded -, cratesDownloadUrl + cratesDownloadUrl, #| What command to run during the build phase -, cargoCommand -, cargoBuildOptions -, remapPathPrefix -, #| What command to run during the test phase - cargoTestCommands -, cargoTestOptions -, copyTarget + cargoCommand, + cargoBuildOptions, + remapPathPrefix, + #| What command to run during the test phase + cargoTestCommands, + cargoTestOptions, + copyTarget, #| Whether or not to compress the target when copying it -, compressTarget + compressTarget, #| Whether or not to copy binaries to $out/bin -, copyBins -, copyBinsFilter + copyBins, + copyBinsFilter, #| Whether or not to copy libraries to $out/bin -, copyLibs -, copyLibsFilter -, doDoc -, doDocFail -, cargoDocCommands -, cargoDocOptions -, copyDocsToSeparateOutput + copyLibs, + copyLibsFilter, + doDoc, + doDocFail, + cargoDocCommands, + cargoDocOptions, + copyDocsToSeparateOutput, #| Whether to remove references to source code from the generated cargo docs # to reduce Nix closure size. By default cargo doc includes snippets like the # following in the generated highlighted source code in files like: src/rand/lib.rs.html: @@ -37,43 +38,42 @@ # # Which drops the run-time dependency on the crates-io source thereby # significantly reducing the Nix closure size. -, removeReferencesToSrcFromDocs -, cargoClippyOptions -, cargoFmtOptions -, mode ? "build" # `build`, `check`, `test` or `clippy` -, gitDependencies -, pname -, version -, rustc -, cargo -, clippy -, override -, nativeBuildInputs -, buildInputs -, builtDependencies -, postInstall -, release -, cargoOptions -, stdenv -, lib -, rsync -, jq -, darwin -, writeText -, runCommandLocal -, remarshal -, formats -, cratesIoDependencies -, zstd -, fetchurl -, lndir -, userAttrs -}: - -let + removeReferencesToSrcFromDocs, + cargoClippyOptions, + cargoFmtOptions, + mode ? "build", # `build`, `check`, `test` or `clippy` + gitDependencies, + pname, + version, + rustc, + cargo, + clippy, + override, + nativeBuildInputs, + buildInputs, + builtDependencies, + postInstall, + release, + cargoOptions, + stdenv, + lib, + rsync, + jq, + darwin, + writeText, + runCommandLocal, + remarshal, + formats, + cratesIoDependencies, + zstd, + fetchurl, + lndir, + userAttrs, +}: let builtinz = - builtins // import ./builtins - { inherit lib writeText remarshal runCommandLocal formats; }; + builtins + // import ./builtins + {inherit lib writeText remarshal runCommandLocal formats;}; drvAttrs = { name = "${pname}-${version}"; @@ -90,54 +90,64 @@ let # The cargo config with source replacement. Replaces both crates.io crates # and git dependencies. cargoconfig = builtinz.writeTOML "config" { - source = { - crates-io = { - directory = unpackedCratesIoDependencies; - }; - git = { - directory = unpackedGitDependencies; - }; - } // lib.listToAttrs ( - map + source = + { + crates-io = { + directory = unpackedCratesIoDependencies; + }; + git = { + directory = unpackedGitDependencies; + }; + } + // lib.listToAttrs ( + map ( - e: - let - key = if e ? rev then "?rev=${e.rev}" else - if e ? tag then "?tag=${e.tag}" else - if e ? branch then "?branch=${e.branch}" else - ""; - in - { - name = "${e.url}${key}"; - value = lib.filterAttrs (n: _: n == "rev" || n == "tag" || n == "branch") e // { + e: let + key = + if e ? rev + then "?rev=${e.rev}" + else if e ? tag + then "?tag=${e.tag}" + else if e ? branch + then "?branch=${e.branch}" + else ""; + in { + name = "${e.url}${key}"; + value = + lib.filterAttrs (n: _: n == "rev" || n == "tag" || n == "branch") e + // { git = e.url; replace-with = "git"; }; - } + } ) gitDependencies - ); + ); }; - outputs = [ "out" ] ++ lib.optional (doDoc && copyDocsToSeparateOutput) "doc"; - preInstallPhases = lib.optional doDoc [ "docPhase" ]; + outputs = ["out"] ++ lib.optional (doDoc && copyDocsToSeparateOutput) "doc"; + preInstallPhases = lib.optional doDoc ["docPhase"]; # Otherwise specifying CMake as a dep breaks the build dontUseCmakeConfigure = true; - nativeBuildInputs = [ - cargo - jq - rsync - ] ++ nativeBuildInputs + nativeBuildInputs = + [ + cargo + jq + rsync + ] + ++ nativeBuildInputs ++ lib.optionals (mode == "clippy") [clippy]; - buildInputs = lib.optionals stdenv.isDarwin [ - darwin.Security - darwin.apple_sdk.frameworks.CoreServices - darwin.cf-private - darwin.libiconv - ] ++ buildInputs; + buildInputs = + lib.optionals stdenv.isDarwin [ + darwin.Security + darwin.apple_sdk.frameworks.CoreServices + darwin.cf-private + darwin.libiconv + ] + ++ buildInputs; inherit builtDependencies; @@ -196,22 +206,22 @@ let ${lib.optionalString remapPathPrefix '' - # Remove the source path(s) in Rust - if [ -n "$RUSTFLAGS" ]; then - RUSTFLAGS="$RUSTFLAGS --remap-path-prefix $cratesio_sources=/sources" - RUSTFLAGS="$RUSTFLAGS --remap-path-prefix $git_sources=/sources" + # Remove the source path(s) in Rust + if [ -n "$RUSTFLAGS" ]; then + RUSTFLAGS="$RUSTFLAGS --remap-path-prefix $cratesio_sources=/sources" + RUSTFLAGS="$RUSTFLAGS --remap-path-prefix $git_sources=/sources" - log "RUSTFLAGS (updated): $RUSTFLAGS" - else - if [ -z "$CARGO_BUILD_RUSTFLAGS" ]; then - export CARGO_BUILD_RUSTFLAGS="" - fi + log "RUSTFLAGS (updated): $RUSTFLAGS" + else + if [ -z "$CARGO_BUILD_RUSTFLAGS" ]; then + export CARGO_BUILD_RUSTFLAGS="" + fi - CARGO_BUILD_RUSTFLAGS="$CARGO_BUILD_RUSTFLAGS --remap-path-prefix $cratesio_sources=/sources" - CARGO_BUILD_RUSTFLAGS="$CARGO_BUILD_RUSTFLAGS --remap-path-prefix $git_sources=/sources" + CARGO_BUILD_RUSTFLAGS="$CARGO_BUILD_RUSTFLAGS --remap-path-prefix $cratesio_sources=/sources" + CARGO_BUILD_RUSTFLAGS="$CARGO_BUILD_RUSTFLAGS --remap-path-prefix $git_sources=/sources" - log "CARGO_BUILD_RUSTFLAGS (updated): $CARGO_BUILD_RUSTFLAGS" - fi + log "CARGO_BUILD_RUSTFLAGS (updated): $CARGO_BUILD_RUSTFLAGS" + fi ''} @@ -277,24 +287,28 @@ let runHook preDoc export SOURCE_DATE_EPOCH=1 - ${lib.concatMapStringsSep "\n" (cmd: "logRun ${cmd} || ${if doDocFail then "false" else "true" }") cargoDocCommands} + ${lib.concatMapStringsSep "\n" (cmd: "logRun ${cmd} || ${ + if doDocFail + then "false" + else "true" + }") + cargoDocCommands} ${lib.optionalString removeReferencesToSrcFromDocs '' - # Remove references to the source derivation to reduce closure size - match='' - replacement='' - find target/doc ''${CARGO_BUILD_TARGET:+target/$CARGO_BUILD_TARGET/doc} -name "*\.rs\.html" -exec sed -i "s|$match|$replacement|" {} + - ''} + # Remove references to the source derivation to reduce closure size + match='' + replacement='' + find target/doc ''${CARGO_BUILD_TARGET:+target/$CARGO_BUILD_TARGET/doc} -name "*\.rs\.html" -exec sed -i "s|$match|$replacement|" {} + + ''} runHook postDoc ''; - installPhase = - '' - runHook preInstall - export SOURCE_DATE_EPOCH=1 + installPhase = '' + runHook preInstall + export SOURCE_DATE_EPOCH=1 - ${lib.optionalString copyBins '' + ${lib.optionalString copyBins '' export SOURCE_DATE_EPOCH=1 mkdir -p $out/bin @@ -313,8 +327,8 @@ let -not -name '*.so' -a -not -name '*.dylib' \ -exec cp {} $out/bin \; fi - ''} - ${lib.optionalString copyLibs '' + ''} + ${lib.optionalString copyLibs '' export SOURCE_DATE_EPOCH=1 mkdir -p $out/lib @@ -334,27 +348,29 @@ let -name '*.so' -or -name '*.dylib' -or -name '*.a' \ -exec cp {} $out/lib \; fi - ''} + ''} - ${lib.optionalString copyTarget '' + ${lib.optionalString copyTarget '' export SOURCE_DATE_EPOCH=1 mkdir -p $out - ${if compressTarget then - '' - # See: https://reproducible-builds.org/docs/archives/ - tar --sort=name \ - --mtime="@''${SOURCE_DATE_EPOCH}" \ - --owner=0 --group=0 --numeric-owner \ - --pax-option=exthdr.name=%d/PaxHeaders/%f,delete=atime,delete=ctime \ - -c target | ${zstd}/bin/zstd -o $out/target.tar.zst - '' else - '' - cp -r target $out - ''} + ${ + if compressTarget + then '' + # See: https://reproducible-builds.org/docs/archives/ + tar --sort=name \ + --mtime="@''${SOURCE_DATE_EPOCH}" \ + --owner=0 --group=0 --numeric-owner \ + --pax-option=exthdr.name=%d/PaxHeaders/%f,delete=atime,delete=ctime \ + -c target | ${zstd}/bin/zstd -o $out/target.tar.zst + '' + else '' + cp -r target $out + '' + } ''} - ${lib.optionalString (doDoc && copyDocsToSeparateOutput) '' + ${lib.optionalString (doDoc && copyDocsToSeparateOutput) '' export SOURCE_DATE_EPOCH=1 cp -r target/doc $doc @@ -363,8 +379,8 @@ let fi ''} - runHook postInstall - ''; + runHook postInstall + ''; passthru = { # Handy for debugging @@ -389,27 +405,29 @@ let # ``` unpackedCratesIoDependencies = symlinkJoinPassViaFile { name = "crates-io-dependencies"; - paths = (map unpackCratesIoDependency cratesIoDependencies); + paths = map unpackCratesIoDependency cratesIoDependencies; }; # Git dependencies required to compile user's crate; follows same format as # the crates.io dependencies above. unpackedGitDependencies = symlinkJoinPassViaFile { name = "git-dependencies"; - paths = (map unpackGitDependency gitDependencies); + paths = map unpackGitDependency gitDependencies; }; - unpackCratesIoDependency = { name, version, sha256 }: - let - crate = fetchurl { - inherit sha256; - - url = "${cratesDownloadUrl}/api/v1/crates/${name}/${version}/download"; - name = "download-${name}-${version}"; - }; + unpackCratesIoDependency = { + name, + version, + sha256, + }: let + crate = fetchurl { + inherit sha256; - in - runCommandLocal "unpack-${name}-${version}" { } + url = "${cratesDownloadUrl}/api/v1/crates/${name}/${version}/download"; + name = "download-${name}-${version}"; + }; + in + runCommandLocal "unpack-${name}-${version}" {} '' mkdir -p $out tar -xzf ${crate} -C $out @@ -446,10 +464,16 @@ let echo '{"package":"${sha256}","files":{}}' > "$dest/.cargo-checksum.json" ''; - unpackGitDependency = { checkout, key, name, url, ... }: + unpackGitDependency = { + checkout, + key, + name, + url, + ... + }: runCommandLocal "unpack-${name}-${version}" { inherit checkout key name url; - nativeBuildInputs = [ jq cargo ]; + nativeBuildInputs = [jq cargo]; } '' log() { @@ -548,29 +572,31 @@ let * { symlinkJoin, hello }: * symlinkJoin { name = "myhello"; paths = [ hello ]; postBuild = "echo links added"; } */ - symlinkJoinPassViaFile = - args_@{ name - , paths - , preferLocalBuild ? true - , allowSubstitutes ? false - , postBuild ? "" - , ... - }: - let - args = removeAttrs args_ [ "name" "postBuild" ] - // { inherit preferLocalBuild allowSubstitutes; - passAsFile = [ "paths" ]; - nativeBuildInputs = [ lndir ]; - }; # pass the defaults - in runCommandLocal name args - '' - mkdir -p $out + symlinkJoinPassViaFile = args_ @ { + name, + paths, + preferLocalBuild ? true, + allowSubstitutes ? false, + postBuild ? "", + ... + }: let + args = + removeAttrs args_ ["name" "postBuild"] + // { + inherit preferLocalBuild allowSubstitutes; + passAsFile = ["paths"]; + nativeBuildInputs = [lndir]; + }; # pass the defaults + in + runCommandLocal name args + '' + mkdir -p $out - for i in $(cat $pathsPath); do - lndir -silent $i $out - done - ${postBuild} - ''; + for i in $(cat $pathsPath); do + lndir -silent $i $out + done + ${postBuild} + ''; drv = stdenv.mkDerivation (drvAttrs // userAttrs); in -drv.overrideAttrs override + drv.overrideAttrs override diff --git a/builtins/default.nix b/builtins/default.nix index 7bcf40e..6ffb193 100644 --- a/builtins/default.nix +++ b/builtins/default.nix @@ -1,12 +1,11 @@ # some extra "builtins" -{ lib -, writeText -, runCommandLocal -, remarshal -, formats -}: - -rec +{ + lib, + writeText, + runCommandLocal, + remarshal, + formats, +}: rec { # Serializes given attrset into a TOML file. # @@ -24,34 +23,30 @@ rec # # ¹ e.g. cases like `[targets."cfg(\"something\")"]` are translated badly # ² https://github.com/nix-community/naersk/issues/263 - writeTOML = - let - our-impl = - let - to-toml = import ./to-toml.nix { - inherit lib; - }; - - in - name: value: - runCommandLocal name { - value = to-toml value; - passAsFile = [ "value" ]; - } '' - cp "$valuePath" "$out" - cat "$out" - ''; - - nixpkgs-impl = (formats.toml { }).generate; - + writeTOML = let + our-impl = let + to-toml = import ./to-toml.nix { + inherit lib; + }; in - if builtins.compareVersions lib.version "22.11" <= 0 then - our-impl - else - nixpkgs-impl; + name: value: + runCommandLocal name { + value = to-toml value; + passAsFile = ["value"]; + } '' + cp "$valuePath" "$out" + cat "$out" + ''; + + nixpkgs-impl = (formats.toml {}).generate; + in + if builtins.compareVersions lib.version "22.11" <= 0 + then our-impl + else nixpkgs-impl; readTOML = usePure: f: - if usePure then + if usePure + then builtins.fromTOML ( # Safety: We invoke `unsafeDiscardStringContext` _after_ reading the # file, so the derivation either had been already realized or `readFile` @@ -76,16 +71,16 @@ rec builtins.fromJSON ( builtins.readFile ( runCommandLocal "from-toml" { - buildInputs = [ remarshal ]; + buildInputs = [remarshal]; } - '' - echo "$from_toml_in" > in.toml - remarshal \ - -if toml \ - -i ${f} \ - -of json \ - -o $out - '' + '' + echo "$from_toml_in" > in.toml + remarshal \ + -if toml \ + -i ${f} \ + -of json \ + -o $out + '' ) ); @@ -95,24 +90,25 @@ rec # TODO: use `builtins.pathExists` once # https://github.com/NixOS/nix/pull/3012 has landed and is generally # available - pathExists = if lib.versionAtLeast builtins.nixVersion "2.3" then builtins.pathExists else path: - let + pathExists = + if lib.versionAtLeast builtins.nixVersion "2.3" + then builtins.pathExists + else path: let all = lib.all (x: x); - isOk = part: - let - dir = builtins.dirOf part; - basename = builtins.unsafeDiscardStringContext (builtins.baseNameOf part); - dirContent = builtins.readDir dir; - in - builtins.hasAttr basename dirContent && # XXX: this may not work if the directory is a symlink - (part == path || dirContent.${basename} == "directory"); - parts = - let - # [ "" "nix" "store" "123123" "foo" "bar" ] - parts = lib.splitString "/" path; - len = lib.length parts; - in - map (n: lib.concatStringsSep "/" (lib.take n parts)) (lib.range 3 len); + isOk = part: let + dir = builtins.dirOf part; + basename = builtins.unsafeDiscardStringContext (builtins.baseNameOf part); + dirContent = builtins.readDir dir; + in + builtins.hasAttr basename dirContent + && # XXX: this may not work if the directory is a symlink + (part == path || dirContent.${basename} == "directory"); + parts = let + # [ "" "nix" "store" "123123" "foo" "bar" ] + parts = lib.splitString "/" path; + len = lib.length parts; + in + map (n: lib.concatStringsSep "/" (lib.take n parts)) (lib.range 3 len); in all (map isOk parts); } diff --git a/builtins/to-toml.nix b/builtins/to-toml.nix index 407569e..6f83f03 100644 --- a/builtins/to-toml.nix +++ b/builtins/to-toml.nix @@ -1,6 +1,6 @@ -{ lib }: -let - inherit (lib) +{lib}: let + inherit + (lib) length elemAt concatMap @@ -11,7 +11,8 @@ let mapAttrsToList ; - inherit (builtins) + inherit + (builtins) abort match toJSON @@ -25,115 +26,115 @@ let quoteString = builtins.toJSON; - outputValInner = v: - let - ty = tomlTy v; - in - if ty == "set" then - let - vals = mapAttrsToList - (k': v': "${quoteKey k'} = ${outputValInner v'}") v; - valsStr = concatStringsSep ", " vals; - in - "{ ${valsStr} }" else - outputVal v; + outputValInner = v: let + ty = tomlTy v; + in + if ty == "set" + then let + vals = + mapAttrsToList + (k': v': "${quoteKey k'} = ${outputValInner v'}") + v; + valsStr = concatStringsSep ", " vals; + in "{ ${valsStr} }" + else outputVal v; - outputVal = v: - let - ty = tomlTy v; - in - if (ty == "bool" || ty == "int") then - builtins.toJSON v - else - if ty == "string" then - quoteString v - else - if ty == "list" || ty == "list_of_attrs" then - let - vals = map quoteString v; - valsStr = concatStringsSep ", " vals; - in - "[ ${valsStr} ]" - else - if ty == "set" then - abort "unsupported set for not-inner value" - else abort "Not implemented: type ${ty}"; + outputVal = v: let + ty = tomlTy v; + in + if (ty == "bool" || ty == "int") + then builtins.toJSON v + else if ty == "string" + then quoteString v + else if ty == "list" || ty == "list_of_attrs" + then let + vals = map quoteString v; + valsStr = concatStringsSep ", " vals; + in "[ ${valsStr} ]" + else if ty == "set" + then abort "unsupported set for not-inner value" + else abort "Not implemented: type ${ty}"; - outputKeyValInner = k: v: - let - ty = tomlTy v; - in - if ty == "set" then - let - vals = mapAttrsToList - (k': v': "${quoteKey k'} = ${outputValInner v'}") v; - valsStr = concatStringsSep ", " vals; - in - [ "${quoteKey k} = { ${valsStr} }" ] else - outputKeyVal k v; + outputKeyValInner = k: v: let + ty = tomlTy v; + in + if ty == "set" + then let + vals = + mapAttrsToList + (k': v': "${quoteKey k'} = ${outputValInner v'}") + v; + valsStr = concatStringsSep ", " vals; + in ["${quoteKey k} = { ${valsStr} }"] + else outputKeyVal k v; # Returns a list of strings; one string per line - outputKeyVal = k: v: - let - ty = tomlTy v; - in - if ty == "bool" || ty == "int" then - [ "${quoteKey k} = ${outputValInner v}" ] - else - if ty == "string" then - [ "${quoteKey k} = ${quoteString v}" ] - else - if ty == "list_of_attrs" then - concatMap ( - inner: - [ "[[${k}]]" ] ++ (concatLists (mapAttrsToList outputKeyValInner inner)) - ) v - else - if ty == "list" then - let - vals = map quoteString v; - valsStr = concatStringsSep ", " vals; - in - [ "${quoteKey k} = [ ${valsStr} ]" ] else - if ty == "set" then - [ "[${k}]" ] ++ (concatLists (mapAttrsToList outputKeyValInner v)) - else abort "Not implemented: type ${ty} for key ${k}"; + outputKeyVal = k: v: let + ty = tomlTy v; + in + if ty == "bool" || ty == "int" + then ["${quoteKey k} = ${outputValInner v}"] + else if ty == "string" + then ["${quoteKey k} = ${quoteString v}"] + else if ty == "list_of_attrs" + then + concatMap ( + inner: + ["[[${k}]]"] ++ (concatLists (mapAttrsToList outputKeyValInner inner)) + ) + v + else if ty == "list" + then let + vals = map quoteString v; + valsStr = concatStringsSep ", " vals; + in ["${quoteKey k} = [ ${valsStr} ]"] + else if ty == "set" + then ["[${k}]"] ++ (concatLists (mapAttrsToList outputKeyValInner v)) + else abort "Not implemented: type ${ty} for key ${k}"; tomlTy = x: - if typeOf x == "string" then "string" else - if typeOf x == "bool" then "bool" else - if typeOf x == "int" then "int" else - if typeOf x == "float" then "float" else - if typeOf x == "set" then - if lib.isDerivation x then "string" else "set" else - if typeOf x == "list" then - if length x == 0 then "list" - else - let - ty = typeOf (elemAt x 0); - in - #assert (all (v: typeOf v == ty) x); - if ty == "set" then "list_of_attrs" else "list" - else abort "Not implemented: toml type for ${typeOf x}"; + if typeOf x == "string" + then "string" + else if typeOf x == "bool" + then "bool" + else if typeOf x == "int" + then "int" + else if typeOf x == "float" + then "float" + else if typeOf x == "set" + then + if lib.isDerivation x + then "string" + else "set" + else if typeOf x == "list" + then + if length x == 0 + then "list" + else let + ty = typeOf (elemAt x 0); + in + #assert (all (v: typeOf v == ty) x); + if ty == "set" + then "list_of_attrs" + else "list" + else abort "Not implemented: toml type for ${typeOf x}"; toTOML = attrs: - assert (typeOf attrs == "set"); - let - byTy = lib.foldl + assert (typeOf attrs == "set"); let + byTy = + lib.foldl ( - acc: x: - let - ty = tomlTy x.v; - in - acc // { "${ty}" = (acc.${ty} or []) ++ [ x ]; } + acc: x: let + ty = tomlTy x.v; + in + acc // {"${ty}" = (acc.${ty} or []) ++ [x];} ) - {} (mapAttrsToList (k: v: { inherit k v; }) attrs); + {} (mapAttrsToList (k: v: {inherit k v;}) attrs); in concatMapStringsSep "\n" - (kv: concatStringsSep "\n" (outputKeyVal kv.k kv.v)) - ( - (byTy.string or []) ++ (byTy.int or []) ++ (byTy.float or []) ++ (byTy.list or []) ++ (byTy.list_of_attrs or []) ++ (byTy.set or []) - ) - ; + (kv: concatStringsSep "\n" (outputKeyVal kv.k kv.v)) + ( + (byTy.string or []) ++ (byTy.int or []) ++ (byTy.float or []) ++ (byTy.list or []) ++ (byTy.list_of_attrs or []) ++ (byTy.set or []) + ); in -toTOML + toTOML diff --git a/config.nix b/config.nix index 730018b..b884d2c 100644 --- a/config.nix +++ b/config.nix @@ -1,15 +1,19 @@ -{ lib, libb, builtinz, arg }: -let +{ + lib, + libb, + builtinz, + arg, +}: let allowFun = attrs0: attrName: default: - if builtins.hasAttr attrName attrs0 then - if lib.isFunction attrs0.${attrName} then - attrs0.${attrName} default - else - let - finalTy = builtins.typeOf default; - actualTy = builtins.typeOf attrs0.${attrName}; - in - throw "${attrName} should be a function from ${finalTy} to ${finalTy}, but is a ${actualTy}" + if builtins.hasAttr attrName attrs0 + then + if lib.isFunction attrs0.${attrName} + then attrs0.${attrName} default + else let + finalTy = builtins.typeOf default; + actualTy = builtins.typeOf attrs0.${attrName}; + in + throw "${attrName} should be a function from ${finalTy} to ${finalTy}, but is a ${actualTy}" else default; mkAttrs = attrs0: rec @@ -43,7 +47,7 @@ let # The command to use for the build. cargoBuild = allowFun attrs0 "cargoBuild" - ''cargo $cargo_options build $cargo_build_options >> $cargo_build_output_json''; + ''cargo $cargo_options build $cargo_build_options >> $cargo_build_output_json''; # Options passed to cargo build, i.e. `cargo build `. These options # can be accessed during the build through the environment variable @@ -55,7 +59,7 @@ let # Note: these values are not (shell) escaped, meaning that you can use # environment variables but must be careful when introducing e.g. spaces.
cargoBuildOptions = - allowFun attrs0 "cargoBuildOptions" [ "$cargo_release" ''-j "$NIX_BUILD_CORES"'' "--message-format=$cargo_message_format" ]; + allowFun attrs0 "cargoBuildOptions" ["$cargo_release" ''-j "$NIX_BUILD_CORES"'' "--message-format=$cargo_message_format"]; # When `true`, rustc remaps the (`/nix/store`) source paths to `/sources` # to reduce the number of dependencies in the closure. @@ -64,7 +68,7 @@ let # The commands to run in the `checkPhase`. Do not forget to set # [`doCheck`](https://nixos.org/nixpkgs/manual/#ssec-check-phase). cargoTestCommands = - allowFun attrs0 "cargoTestCommands" [ ''cargo $cargo_options test $cargo_test_options'' ]; + allowFun attrs0 "cargoTestCommands" [''cargo $cargo_options test $cargo_test_options'']; # Options passed to cargo test, i.e. `cargo test `. These options # can be accessed during the build through the environment variable @@ -72,7 +76,7 @@ let # Note: these values are not (shell) escaped, meaning that you can use # environment variables but must be careful when introducing e.g. spaces.
cargoTestOptions = - allowFun attrs0 "cargoTestOptions" [ "$cargo_release" ''-j "$NIX_BUILD_CORES"'' ]; + allowFun attrs0 "cargoTestOptions" ["$cargo_release" ''-j "$NIX_BUILD_CORES"'']; # Options passed to cargo clippy, i.e. `cargo clippy -- `. These options # can be accessed during the build through the environment variable @@ -80,7 +84,7 @@ let # Note: these values are not (shell) escaped, meaning that you can use # environment variables but must be careful when introducing e.g. spaces.
cargoClippyOptions = - allowFun attrs0 "cargoClippyOptions" [ "-D warnings" ]; + allowFun attrs0 "cargoClippyOptions" ["-D warnings"]; # Options passed to cargo fmt, i.e. `cargo fmt -- `. These options # can be accessed during the build through the environment variable @@ -88,7 +92,7 @@ let # Note: these values are not (shell) escaped, meaning that you can use # environment variables but must be careful when introducing e.g. spaces.
cargoFmtOptions = - allowFun attrs0 "cargoFmtOptions" [ "--check" ]; + allowFun attrs0 "cargoFmtOptions" ["--check"]; # Extra `nativeBuildInputs` to all derivations. nativeBuildInputs = attrs0.nativeBuildInputs or []; @@ -102,14 +106,14 @@ let # Note: these values are not (shell) escaped, meaning that you can use # environment variables but must be careful when introducing e.g. spaces.
cargoOptions = - allowFun attrs0 "cargoOptions" [ ]; + allowFun attrs0 "cargoOptions" []; # When true, `cargo doc` is run and a new output `doc` is generated. doDoc = attrs0.doDoc or false; # The commands to run in the `docPhase`. Do not forget to set `doDoc`. cargoDocCommands = - allowFun attrs0 "cargoDocCommands" [ ''cargo $cargo_options doc $cargo_doc_options'' ]; + allowFun attrs0 "cargoDocCommands" [''cargo $cargo_options doc $cargo_doc_options'']; # Options passed to cargo doc, i.e. `cargo doc `. These options # can be accessed during the build through the environment variable @@ -117,7 +121,7 @@ let # Note: these values are not (shell) escaped, meaning that you can use # environment variables but must be careful when introducing e.g. spaces.
cargoDocOptions = - allowFun attrs0 "cargoDocOptions" [ "--offline" "$cargo_release" ''-j "$NIX_BUILD_CORES"'' ]; + allowFun attrs0 "cargoDocOptions" ["--offline" "$cargo_release" ''-j "$NIX_BUILD_CORES"'']; # When true, all cargo builds are run with `--release`. The environment # variable `cargo_release` is set to `--release` iff this option is set. @@ -150,8 +154,9 @@ let # [`--message-format`](https://doc.rust-lang.org/cargo/reference/external-tools.html#json-messages) # JSON output.
# The value is written to the `cargo_bins_jq_filter` variable. - copyBinsFilter = attrs0.copyBinsFilter or - ''select(.reason == "compiler-artifact" and .executable != null and .profile.test == false)''; + copyBinsFilter = + attrs0.copyBinsFilter + or ''select(.reason == "compiler-artifact" and .executable != null and .profile.test == false)''; # A [`jq`](https://stedolan.github.io/jq) filter for selecting which build # artifacts to release. This is run on cargo's @@ -161,8 +166,9 @@ let # ((.target.kind | contains(["staticlib"])) or (.target.kind | # contains(["cdylib"]))) and .filenames != null and .profile.test == # false)''` - copyLibsFilter = attrs0.copyLibsFilter or - ''select(.reason == "compiler-artifact" and ((.target.kind | contains(["staticlib"])) or (.target.kind | contains(["cdylib"]))) and .filenames != null and .profile.test == false)''; + copyLibsFilter = + attrs0.copyLibsFilter + or ''select(.reason == "compiler-artifact" and ((.target.kind | contains(["staticlib"])) or (.target.kind | contains(["cdylib"]))) and .filenames != null and .profile.test == false)''; # When true, the documentation is generated in a different output, `doc`. copyDocsToSeparateOutput = attrs0.copyDocsToSeparateOutput or true; @@ -203,10 +209,14 @@ let }; argIsAttrs = - if lib.isDerivation arg then false - else if lib.isString arg then false - else if builtins.typeOf arg == "path" then false - else if builtins.hasAttr "outPath" arg then false + if lib.isDerivation arg + then false + else if lib.isString arg + then false + else if builtins.typeOf arg == "path" + then false + else if builtins.hasAttr "outPath" arg + then false else true; # if the argument is not an attribute set, then assume it's the 'root'. @@ -214,7 +224,7 @@ let attrs = if argIsAttrs then mkAttrs arg - else mkAttrs { root = arg; }; + else mkAttrs {root = arg;}; userAttrs = if argIsAttrs @@ -226,53 +236,66 @@ let # should be a "path" to avoid reading values from the nix-store. # Below we try to come up with some good values for src and root if they're # not defined. - sr = - let - hasRoot = ! isNull attrs.root; - hasSrc = ! isNull attrs.src; - isPath = x: builtins.typeOf x == "path"; - root = attrs.root; - src = attrs.src; - in - # src: yes, root: no - if hasSrc && ! hasRoot then - if isPath src then - { src = lib.cleanSource src; root = src; } - else { inherit src; root = src; } - # src: yes, root: yes - else if hasRoot && hasSrc then - { inherit src root; } - # src: no, root: yes - else if hasRoot && ! hasSrc then - if isPath root then - { inherit root; src = lib.cleanSource root; } - else - { inherit root; src = root; } - # src: no, root: yes - else throw "please specify either 'src' or 'root'"; + sr = let + hasRoot = ! isNull attrs.root; + hasSrc = ! isNull attrs.src; + isPath = x: builtins.typeOf x == "path"; + root = attrs.root; + src = attrs.src; + in + # src: yes, root: no + if hasSrc && ! hasRoot + then + if isPath src + then { + src = lib.cleanSource src; + root = src; + } + else { + inherit src; + root = src; + } + # src: yes, root: yes + else if hasRoot && hasSrc + then {inherit src root;} + # src: no, root: yes + else if hasRoot && ! hasSrc + then + if isPath root + then { + inherit root; + src = lib.cleanSource root; + } + else { + inherit root; + src = root; + } + # src: no, root: yes + else throw "please specify either 'src' or 'root'"; usePureFromTOML = attrs.usePureFromTOML; readTOML = builtinz.readTOML usePureFromTOML; cargoCommand = let - mode = attrs.mode; - in - if (mode == "build") then - attrs.cargoBuild - else if (mode == "check") then - ''cargo $cargo_options check $cargo_build_options >> $cargo_build_output_json'' - else if (mode == "test") then - ''cargo $cargo_options test $cargo_test_options >> $cargo_build_output_json'' - else if (mode == "clippy") then - ''cargo $cargo_options clippy $cargo_build_options -- $cargo_clippy_options >> $cargo_build_output_json'' - else if (mode == "fmt") then - ''cargo $cargo_options fmt -- $cargo_fmt_options'' - else throw "Unknown mode ${mode}, allowed modes: build, check, test, clippy"; + mode = attrs.mode; + in + if (mode == "build") + then attrs.cargoBuild + else if (mode == "check") + then ''cargo $cargo_options check $cargo_build_options >> $cargo_build_output_json'' + else if (mode == "test") + then ''cargo $cargo_options test $cargo_test_options >> $cargo_build_output_json'' + else if (mode == "clippy") + then ''cargo $cargo_options clippy $cargo_build_options -- $cargo_clippy_options >> $cargo_build_output_json'' + else if (mode == "fmt") + then ''cargo $cargo_options fmt -- $cargo_fmt_options'' + else throw "Unknown mode ${mode}, allowed modes: build, check, test, clippy"; # config used during build the prebuild and the final build buildConfig = { inherit cargoCommand; - inherit (attrs) + inherit + (attrs) nativeBuildInputs buildInputs release @@ -281,7 +304,6 @@ let compressTarget mode cratesDownloadUrl - cargoBuildOptions remapPathPrefix copyBins @@ -289,20 +311,16 @@ let copyLibs copyLibsFilter copyTarget - cargoTestCommands cargoTestOptions - cargoClippyOptions cargoFmtOptions - doDoc doDocFail cargoDocCommands cargoDocOptions copyDocsToSeparateOutput removeReferencesToSrcFromDocs - postInstall ; @@ -340,48 +358,50 @@ let # ... which Cargo allows and so should we. # # ¹ such as Nushell - cargotomls = - let - findCargoTomls = dir: - lib.mapAttrsToList - (name: type: - let - path = "${root}/${dir}/${name}"; - - in - if name == "Cargo.toml" then - [{ name = dir; toml = readTOML path; }] - else if type == "directory" then - findCargoTomls "${dir}/${name}" - else - []) - (builtins.readDir "${root}/${dir}"); - - in - lib.flatten (findCargoTomls "."); + cargotomls = let + findCargoTomls = dir: + lib.mapAttrsToList + (name: type: let + path = "${root}/${dir}/${name}"; + in + if name == "Cargo.toml" + then [ + { + name = dir; + toml = readTOML path; + } + ] + else if type == "directory" + then findCargoTomls "${dir}/${name}" + else []) + (builtins.readDir "${root}/${dir}"); + in + lib.flatten (findCargoTomls "."); # If `copySourcesFrom` is set, then it looks like the benefits brought by # two-step caching break, for unclear reasons as of now. As such, do not set # `copySourcesFrom` if there is no source to actually copy from. - copySourcesFrom = if copySources != [] then src else null; - - copySources = - let - mkRelative = po: - if lib.hasPrefix "/" po.path - then throw "'${toString src}/Cargo.toml' contains the absolute path '${toString po.path}' which is not allowed under a [patch] section by naersk. Please make it relative to '${toString src}'" - else po.path; - in - arg.copySources or [] - ++ - lib.optionals (builtins.hasAttr "patch" toplevelCargotoml) - ( - map mkRelative - ( - lib.collect (as: lib.isAttrs as && builtins.hasAttr "path" as) - toplevelCargotoml.patch - ) - ); + copySourcesFrom = + if copySources != [] + then src + else null; + + copySources = let + mkRelative = po: + if lib.hasPrefix "/" po.path + then throw "'${toString src}/Cargo.toml' contains the absolute path '${toString po.path}' which is not allowed under a [patch] section by naersk. Please make it relative to '${toString src}'" + else po.path; + in + arg.copySources + or [] + ++ lib.optionals (builtins.hasAttr "patch" toplevelCargotoml) + ( + map mkRelative + ( + lib.collect (as: lib.isAttrs as && builtins.hasAttr "path" as) + toplevelCargotoml.patch + ) + ); # Are we building a workspace (or is this a simple crate) ? isWorkspace = builtins.hasAttr "workspace" toplevelCargotoml; @@ -390,27 +410,31 @@ let toplevelCargotoml = readTOML (root + "/Cargo.toml"); # The cargo lock - cargolock = - let - cargolock-file = root + "/Cargo.lock"; - in - if builtins.pathExists cargolock-file then - readTOML (cargolock-file) - else - throw "Naersk requires Cargo.lock to be available in root. Check that it is not in .gitignore and stage it when using git to filter sources (which flakes does)"; + cargolock = let + cargolock-file = root + "/Cargo.lock"; + in + if builtins.pathExists cargolock-file + then readTOML cargolock-file + else throw "Naersk requires Cargo.lock to be available in root. Check that it is not in .gitignore and stage it when using git to filter sources (which flakes does)"; packageName = if ! isNull attrs.name then attrs.name - else toplevelCargotoml.package.name or - (if isWorkspace then "rust-workspace" else "rust-package"); + else + toplevelCargotoml.package.name + or ( + if isWorkspace + then "rust-workspace" + else "rust-package" + ); packageVersion = if ! isNull attrs.version then attrs.version - else toplevelCargotoml.package.version + else + toplevelCargotoml.package.version or toplevelCargotoml."workspace.package".version or "unknown"; }; in -buildPlanConfig // { inherit buildConfig; } + buildPlanConfig // {inherit buildConfig;} diff --git a/default.nix b/default.nix index a377938..b0c5aa8 100644 --- a/default.nix +++ b/default.nix @@ -1,78 +1,80 @@ -{ cargo -, darwin -, fetchurl -, jq -, lib -, lndir -, remarshal -, formats -, rsync -, runCommandLocal -, rustc -, stdenv -, writeText -, zstd -, clippy -}@defaultBuildAttrs: +{ + cargo, + darwin, + fetchurl, + jq, + lib, + lndir, + remarshal, + formats, + rsync, + runCommandLocal, + rustc, + stdenv, + writeText, + zstd, + clippy, +} @ defaultBuildAttrs: let + libb = import ./lib.nix {inherit lib writeText runCommandLocal remarshal formats;}; -let - libb = import ./lib.nix { inherit lib writeText runCommandLocal remarshal formats; }; - - builtinz = builtins // import ./builtins - { inherit lib writeText remarshal runCommandLocal formats; }; + builtinz = + builtins + // import ./builtins + {inherit lib writeText remarshal runCommandLocal formats;}; mkConfig = arg: - import ./config.nix { inherit lib arg libb builtinz; }; + import ./config.nix {inherit lib arg libb builtinz;}; - buildPackage = arg: - let - config = mkConfig arg; - gitDependencies = - libb.findGitDependencies { inherit (config) cargolock gitAllRefs gitSubmodules; }; - cargoconfig = - if builtinz.pathExists (toString config.root + "/.cargo/config") - then (config.root + "/.cargo/config") - else null; - build = args: import ./build.nix ( + buildPackage = arg: let + config = mkConfig arg; + gitDependencies = + libb.findGitDependencies {inherit (config) cargolock gitAllRefs gitSubmodules;}; + cargoconfig = + if builtinz.pathExists (toString config.root + "/.cargo/config") + then (config.root + "/.cargo/config") + else null; + build = args: + import ./build.nix ( { inherit gitDependencies; version = config.packageVersion; - } // config.buildConfig // defaultBuildAttrs // args + } + // config.buildConfig + // defaultBuildAttrs + // args ); - # the dependencies from crates.io - buildDeps = - build - { - pname = "${config.packageName}-deps"; - src = libb.dummySrc { - inherit cargoconfig; - inherit (config) cargolock cargotomls copySources copySourcesFrom; - }; - inherit (config) userAttrs; - # TODO: custom cargoTestCommands should not be needed here - cargoTestCommands = map (cmd: "${cmd} || true") config.buildConfig.cargoTestCommands; - copyTarget = true; - copyBins = false; - copyBinsFilter = "."; - copyDocsToSeparateOutput = false; - postInstall = false; - builtDependencies = []; - }; + # the dependencies from crates.io + buildDeps = + build + { + pname = "${config.packageName}-deps"; + src = libb.dummySrc { + inherit cargoconfig; + inherit (config) cargolock cargotomls copySources copySourcesFrom; + }; + inherit (config) userAttrs; + # TODO: custom cargoTestCommands should not be needed here + cargoTestCommands = map (cmd: "${cmd} || true") config.buildConfig.cargoTestCommands; + copyTarget = true; + copyBins = false; + copyBinsFilter = "."; + copyDocsToSeparateOutput = false; + postInstall = false; + builtDependencies = []; + }; - # the top-level build - buildTopLevel = - let - drv = - build - { - pname = config.packageName; - inherit (config) userAttrs src; - builtDependencies = lib.optional (! config.isSingleStep) buildDeps; - }; - in - drv.overrideAttrs config.overrideMain; + # the top-level build + buildTopLevel = let + drv = + build + { + pname = config.packageName; + inherit (config) userAttrs src; + builtDependencies = lib.optional (! config.isSingleStep) buildDeps; + }; in - buildTopLevel; -in -{ inherit buildPackage; } + drv.overrideAttrs config.overrideMain; + in + buildTopLevel; +in {inherit buildPackage;} diff --git a/docparse/shell.nix b/docparse/shell.nix index 6ac28ec..c8ebf2b 100644 --- a/docparse/shell.nix +++ b/docparse/shell.nix @@ -1,4 +1,5 @@ let pkgs = import ../nix {}; -in pkgs.mkShell - { nativeBuildInputs = [ pkgs.cargo pkgs.rustfmt ]; } +in + pkgs.mkShell + {nativeBuildInputs = [pkgs.cargo pkgs.rustfmt];} diff --git a/examples/checks/flake.nix b/examples/checks/flake.nix index 24a5fa9..d66b605 100644 --- a/examples/checks/flake.nix +++ b/examples/checks/flake.nix @@ -5,15 +5,19 @@ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; }; - outputs = { self, flake-utils, naersk, nixpkgs }: - flake-utils.lib.eachDefaultSystem (system: - let + outputs = { + self, + flake-utils, + naersk, + nixpkgs, + }: + flake-utils.lib.eachDefaultSystem ( + system: let pkgs = (import nixpkgs) { inherit system; }; naersk' = pkgs.callPackage naersk {}; - in rec { packages = { # For `nix build` & `nix run`: @@ -39,7 +43,7 @@ # For `nix develop`: devShell = pkgs.mkShell { - nativeBuildInputs = with pkgs; [ rustc cargo ]; + nativeBuildInputs = with pkgs; [rustc cargo]; }; } ); diff --git a/examples/cross-windows/flake.nix b/examples/cross-windows/flake.nix index 0398bba..30f3c5c 100644 --- a/examples/cross-windows/flake.nix +++ b/examples/cross-windows/flake.nix @@ -6,9 +6,15 @@ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; }; - outputs = { self, fenix, flake-utils, naersk, nixpkgs }: - flake-utils.lib.eachDefaultSystem (system: - let + outputs = { + self, + fenix, + flake-utils, + naersk, + nixpkgs, + }: + flake-utils.lib.eachDefaultSystem ( + system: let pkgs = (import nixpkgs) { inherit system; }; @@ -24,7 +30,6 @@ cargo = toolchain; rustc = toolchain; }; - in rec { defaultPackage = packages.x86_64-pc-windows-gnu; diff --git a/examples/hello-world/flake.nix b/examples/hello-world/flake.nix index 42145c2..6e76e7c 100644 --- a/examples/hello-world/flake.nix +++ b/examples/hello-world/flake.nix @@ -5,15 +5,19 @@ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; }; - outputs = { self, flake-utils, naersk, nixpkgs }: - flake-utils.lib.eachDefaultSystem (system: - let + outputs = { + self, + flake-utils, + naersk, + nixpkgs, + }: + flake-utils.lib.eachDefaultSystem ( + system: let pkgs = (import nixpkgs) { inherit system; }; naersk' = pkgs.callPackage naersk {}; - in rec { # For `nix build` & `nix run`: defaultPackage = naersk'.buildPackage { @@ -22,7 +26,7 @@ # For `nix develop`: devShell = pkgs.mkShell { - nativeBuildInputs = with pkgs; [ rustc cargo ]; + nativeBuildInputs = with pkgs; [rustc cargo]; }; } ); diff --git a/examples/multi-target/flake.nix b/examples/multi-target/flake.nix index f4c0a53..33cc739 100644 --- a/examples/multi-target/flake.nix +++ b/examples/multi-target/flake.nix @@ -6,9 +6,15 @@ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; }; - outputs = { self, fenix, flake-utils, naersk, nixpkgs }: - flake-utils.lib.eachDefaultSystem (system: - let + outputs = { + self, + fenix, + flake-utils, + naersk, + nixpkgs, + }: + flake-utils.lib.eachDefaultSystem ( + system: let pkgs = (import nixpkgs) { inherit system; }; @@ -30,8 +36,8 @@ naerskBuildPackage = target: args: naersk'.buildPackage ( args - // { CARGO_BUILD_TARGET = target; } - // cargoConfig + // {CARGO_BUILD_TARGET = target;} + // cargoConfig ); # All of the CARGO_* configurations which should be used for all @@ -58,7 +64,6 @@ exec wine64 $@ ''; }; - in rec { defaultPackage = packages.x86_64-unknown-linux-musl; @@ -66,7 +71,7 @@ packages.x86_64-unknown-linux-musl = naerskBuildPackage "x86_64-unknown-linux-musl" { src = ./.; doCheck = true; - nativeBuildInputs = with pkgs; [ pkgsStatic.stdenv.cc ]; + nativeBuildInputs = with pkgs; [pkgsStatic.stdenv.cc]; }; # For `nix build .#x86_64-pc-windows-gnu`: @@ -87,34 +92,35 @@ }; # For `nix build .#i686-pc-windows-gnu`: - packages.i686-pc-windows-gnu = - let - # GCC supports 2 types of exception handling: SJLJ and DWARF-2 - # (https://gcc.gnu.org/wiki/WindowsGCCImprovements) - # - # Rust uses libgcc_eh for exception handling and it does not support SJLJ - # (https://github.com/rust-lang/rust/pull/55444#issuecomment-434044002) - # - # Solution for this are either: - # 1. Rebuilding MinGW32 with DWARF-2 enabled instead of SJLJ (Which is provided in this example) - # 2. Using "panic = abort" for i686-pc-windows-gnu target and rebuilding rust-std to exclude any linking to libgcc_eh - cc' = pkgs.pkgsCross.mingw32.buildPackages.wrapCC ( - pkgs.pkgsCross.mingw32.buildPackages.gcc.cc.overrideAttrs (oldAttr: rec{ - configureFlags = oldAttr.configureFlags ++ [ + packages.i686-pc-windows-gnu = let + # GCC supports 2 types of exception handling: SJLJ and DWARF-2 + # (https://gcc.gnu.org/wiki/WindowsGCCImprovements) + # + # Rust uses libgcc_eh for exception handling and it does not support SJLJ + # (https://github.com/rust-lang/rust/pull/55444#issuecomment-434044002) + # + # Solution for this are either: + # 1. Rebuilding MinGW32 with DWARF-2 enabled instead of SJLJ (Which is provided in this example) + # 2. Using "panic = abort" for i686-pc-windows-gnu target and rebuilding rust-std to exclude any linking to libgcc_eh + cc' = pkgs.pkgsCross.mingw32.buildPackages.wrapCC ( + pkgs.pkgsCross.mingw32.buildPackages.gcc.cc.overrideAttrs (oldAttr: rec { + configureFlags = + oldAttr.configureFlags + ++ [ # Taken from Fedora mingw32 rpm spec # (https://src.fedoraproject.org/rpms/mingw-gcc/blob/rawhide/f/mingw-gcc.spec) "--disable-sjlj-exceptions --with-dwarf2" ]; - }) - ); - - in naerskBuildPackage "i686-pc-windows-gnu" { + }) + ); + in + naerskBuildPackage "i686-pc-windows-gnu" { src = ./.; doCheck = true; strictDeps = true; # libgcc_eh implicitly requires libmcfgthread to be linked. - depsBuildBuild = [cc'] ++ (with pkgs.pkgsCross.mingw32.windows; [ pthreads mcfgthreads ]); + depsBuildBuild = [cc'] ++ (with pkgs.pkgsCross.mingw32.windows; [pthreads mcfgthreads]); # It's currently not possible to statically link mcfgtread, so instead just add a symlink so it's easier to transfer to target machine postInstall = '' ln -s ${pkgs.pkgsCross.mingw32.windows.mcfgthreads}/bin/mcfgthread-12.dll $out/bin/mcfgthread-12.dll @@ -136,10 +142,11 @@ devShell = pkgs.mkShell ( { - inputsFrom = with packages; [ x86_64-unknown-linux-musl x86_64-pc-windows-gnu ]; + inputsFrom = with packages; [x86_64-unknown-linux-musl x86_64-pc-windows-gnu]; CARGO_BUILD_TARGET = "x86_64-unknown-linux-musl"; - } // cargoConfig + } + // cargoConfig ); } - ); + ); } diff --git a/examples/multiple-binaries/flake.nix b/examples/multiple-binaries/flake.nix index 40d348a..67a1cab 100644 --- a/examples/multiple-binaries/flake.nix +++ b/examples/multiple-binaries/flake.nix @@ -5,17 +5,20 @@ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; }; - outputs = { self, flake-utils, naersk, nixpkgs }: - flake-utils.lib.eachDefaultSystem (system: - let + outputs = { + self, + flake-utils, + naersk, + nixpkgs, + }: + flake-utils.lib.eachDefaultSystem ( + system: let pkgs = (import nixpkgs) { inherit system; }; - naersk' = pkgs.callPackage naersk { }; - - in - { + naersk' = pkgs.callPackage naersk {}; + in { # For `nix build .#bar` and `nix run .#bar`: packages.bar = naersk'.buildPackage { pname = "bar"; @@ -30,7 +33,7 @@ # For `nix develop`: devShell = pkgs.mkShell { - nativeBuildInputs = with pkgs; [ rustc cargo ]; + nativeBuildInputs = with pkgs; [rustc cargo]; }; } ); diff --git a/examples/static-musl/flake.nix b/examples/static-musl/flake.nix index 4fb97bd..1232bd2 100644 --- a/examples/static-musl/flake.nix +++ b/examples/static-musl/flake.nix @@ -6,7 +6,13 @@ nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; }; - outputs = { self, fenix, flake-utils, naersk, nixpkgs }: + outputs = { + self, + fenix, + flake-utils, + naersk, + nixpkgs, + }: flake-utils.lib.eachDefaultSystem ( system: let pkgs = (import nixpkgs) { @@ -24,12 +30,11 @@ cargo = toolchain; rustc = toolchain; }; - in rec { defaultPackage = naersk'.buildPackage { src = ./.; doCheck = true; - nativeBuildInputs = with pkgs; [ pkgsStatic.stdenv.cc ]; + nativeBuildInputs = with pkgs; [pkgsStatic.stdenv.cc]; # Tells Cargo that we're building for musl. # (https://doc.rust-lang.org/cargo/reference/config.html#buildtarget) diff --git a/flake.nix b/flake.nix index a3de435..97d204e 100644 --- a/flake.nix +++ b/flake.nix @@ -1,46 +1,47 @@ { description = "Build Rust projects with ease. No configuration, no code generation; IFD and sandbox friendly."; - outputs = { self, nixpkgs }: - let - forAllSystems = nixpkgs.lib.genAttrs [ "x86_64-linux" "x86_64-darwin" "i686-linux" "aarch64-linux" "aarch64-darwin" ]; - - in rec { - lib = forAllSystems (system: nixpkgs.legacyPackages."${system}".callPackage ./default.nix { }); - - # Useful when composing with other flakes: - overlay = import ./overlay.nix; - - defaultTemplate = templates.hello-world; - - templates = { - hello-world = { - description = "A simple and straight-forward 'hello world' Rust program."; - path = - builtins.filterSource (path: type: baseNameOf path == "flake.nix") - ./examples/hello-world; - }; + outputs = { + self, + nixpkgs, + }: let + forAllSystems = nixpkgs.lib.genAttrs ["x86_64-linux" "x86_64-darwin" "i686-linux" "aarch64-linux" "aarch64-darwin"]; + in rec { + lib = forAllSystems (system: nixpkgs.legacyPackages."${system}".callPackage ./default.nix {}); + + # Useful when composing with other flakes: + overlay = import ./overlay.nix; + + defaultTemplate = templates.hello-world; + + templates = { + hello-world = { + description = "A simple and straight-forward 'hello world' Rust program."; + path = + builtins.filterSource (path: type: baseNameOf path == "flake.nix") + ./examples/hello-world; + }; - cross-windows = { - description = "Pre-configured for cross-compiling to Windows."; - path = - builtins.filterSource (path: type: baseNameOf path == "flake.nix") - ./examples/cross-windows; - }; + cross-windows = { + description = "Pre-configured for cross-compiling to Windows."; + path = + builtins.filterSource (path: type: baseNameOf path == "flake.nix") + ./examples/cross-windows; + }; - static-musl = { - description = "Pre-configured for statically linked binaries for Linux with musl."; - path = - builtins.filterSource (path: type: baseNameOf path == "flake.nix") - ./examples/static-musl; - }; + static-musl = { + description = "Pre-configured for statically linked binaries for Linux with musl."; + path = + builtins.filterSource (path: type: baseNameOf path == "flake.nix") + ./examples/static-musl; + }; - multi-target = { - description = "A Rust project with multiple crates and build targets."; - path = - builtins.filterSource (path: type: baseNameOf path == "flake.nix") - ./examples/multi-target; - }; + multi-target = { + description = "A Rust project with multiple crates and build targets."; + path = + builtins.filterSource (path: type: baseNameOf path == "flake.nix") + ./examples/multi-target; }; }; + }; } diff --git a/lib.nix b/lib.nix index 1e71da3..70c45bd 100644 --- a/lib.nix +++ b/lib.nix @@ -1,68 +1,68 @@ -{ lib, writeText, runCommandLocal, remarshal, formats }: -let +{ + lib, + writeText, + runCommandLocal, + remarshal, + formats, +}: let builtinz = - builtins // import ./builtins - { inherit lib writeText remarshal runCommandLocal formats; }; -in -rec + builtins + // import ./builtins + {inherit lib writeText remarshal runCommandLocal formats;}; +in rec { # The list of _all_ crates (incl. transitive dependencies) with name, # version and sha256 of the crate # Example: # [ { name = "wabt", version = "2.0.6", sha256 = "..." } ] mkVersions = cargolock: - if builtins.hasAttr "metadata" cargolock then - + if builtins.hasAttr "metadata" cargolock + then # TODO: this should nub by - ( lib.concatMap ( - x: - let - mdk = mkMetadataKey x.name x.version; - in - ( - lib.optional (builtins.hasAttr mdk cargolock.metadata) - { - inherit (x) version name; - sha256 = cargolock.metadata.${mkMetadataKey x.name x.version}; - } - ) ++ (lib.concatMap (parseDependency cargolock) (x.dependencies or [])) - + x: let + mdk = mkMetadataKey x.name x.version; + in + ( + lib.optional (builtins.hasAttr mdk cargolock.metadata) + { + inherit (x) version name; + sha256 = cargolock.metadata.${mkMetadataKey x.name x.version}; + } + ) + ++ (lib.concatMap (parseDependency cargolock) (x.dependencies or [])) ) - cargolock.package + cargolock.package ) - else if builtins.hasAttr "package" cargolock then + else if builtins.hasAttr "package" cargolock + then map ( - p: - { - inherit (p) name version; - sha256 = p.checksum; - } + p: { + inherit (p) name version; + sha256 = p.checksum; + } ) (builtins.filter (builtins.hasAttr "checksum") cargolock.package) else []; # Turns "lib-name lib-ver (registry+...)" to [ { name = "lib-name", etc } ] # iff the package is present in the Cargo.lock (otherwise returns []) - parseDependency = cargolock: str: - let - components = lib.splitString " " str; - name = lib.elemAt components 0; - version = lib.elemAt components 1; - mdk = mkMetadataKey name version; - in - lib.optional (builtins.hasAttr mdk cargolock.metadata) - ( - let - sha256 = cargolock.metadata.${mkMetadataKey name version}; - in - { inherit name version sha256; } - ); - + parseDependency = cargolock: str: let + components = lib.splitString " " str; + name = lib.elemAt components 0; + version = lib.elemAt components 1; + mdk = mkMetadataKey name version; + in + lib.optional (builtins.hasAttr mdk cargolock.metadata) + ( + let + sha256 = cargolock.metadata.${mkMetadataKey name version}; + in {inherit name version sha256;} + ); # crafts the key used to look up the sha256 in the cargo lock; no # robustness guarantee - mkMetadataKey = name: version: - "checksum ${name} ${version} (registry+https://github.com/rust-lang/crates.io-index)"; + mkMetadataKey = name: version: "checksum ${name} ${version} (registry+https://github.com/rust-lang/crates.io-index)"; # Gets all git dependencies in Cargo.lock as a list. # [ @@ -72,174 +72,187 @@ rec # checkout = "/nix/store/checkout" # } # ] - findGitDependencies = - { cargolock, gitAllRefs, gitSubmodules }: - let - query = p: (lib.substring 0 4 (p.source or "")) == "git+"; - - extractRevision = source: lib.last (lib.splitString "#" source); - extractPart = part: source: if lib.hasInfix part source then lib.last (lib.splitString part (lib.head (lib.splitString "#" source))) else null; - extractRepoUrl = source: - let - splitted = lib.head (lib.splitString "?" source); - split = lib.substring 4 (lib.stringLength splitted) splitted; - in lib.head (lib.splitString "#" split); - - parseLock = lock: - let - source = lock.source; - rev = extractPart "?rev=" source; - tag = extractPart "?tag=" source; - branch = extractPart "?branch=" source; - in + findGitDependencies = { + cargolock, + gitAllRefs, + gitSubmodules, + }: let + query = p: (lib.substring 0 4 (p.source or "")) == "git+"; + + extractRevision = source: lib.last (lib.splitString "#" source); + extractPart = part: source: + if lib.hasInfix part source + then lib.last (lib.splitString part (lib.head (lib.splitString "#" source))) + else null; + extractRepoUrl = source: let + splitted = lib.head (lib.splitString "?" source); + split = lib.substring 4 (lib.stringLength splitted) splitted; + in + lib.head (lib.splitString "#" split); + + parseLock = lock: let + source = lock.source; + rev = extractPart "?rev=" source; + tag = extractPart "?tag=" source; + branch = extractPart "?branch=" source; + in { inherit (lock) name; revision = extractRevision source; url = extractRepoUrl source; - } // (lib.optionalAttrs (! isNull branch) { inherit branch; }) - // (lib.optionalAttrs (! isNull tag) { inherit tag; }) - // (lib.optionalAttrs (! isNull rev) { inherit rev; }); + } + // (lib.optionalAttrs (! isNull branch) {inherit branch;}) + // (lib.optionalAttrs (! isNull tag) {inherit tag;}) + // (lib.optionalAttrs (! isNull rev) {inherit rev;}); - usedPackageLocks = - builtins.map parseLock (lib.filter query cargolock.package); + usedPackageLocks = + builtins.map parseLock (lib.filter query cargolock.package); - unusedPackageLocks = - builtins.map parseLock (lib.filter query ((cargolock.patch or []).unused or [])); + unusedPackageLocks = + builtins.map parseLock (lib.filter query ((cargolock.patch or []).unused or [])); - packageLocks = usedPackageLocks ++ unusedPackageLocks; + packageLocks = usedPackageLocks ++ unusedPackageLocks; - mkFetch = lock: { - key = lock.rev or lock.tag or lock.branch or lock.revision + mkFetch = lock: + { + key = + lock.rev + or lock.tag + or lock.branch + or lock.revision or (throw "No 'rev', 'tag' or 'branch' available to specify key, nor a git revision was found in Cargo.lock"); checkout = builtins.fetchGit ({ - url = lock.url; - rev = lock.revision; - } // lib.optionalAttrs (lock ? branch) { - ref = "refs/heads/${lock.branch}"; - } // lib.optionalAttrs (lock ? tag) { - ref = "refs/tags/${lock.tag}"; - } // lib.optionalAttrs ((lib.versionAtLeast builtins.nixVersion "2.4") && (gitAllRefs || lock ? rev)) { - allRefs = true; - } // lib.optionalAttrs gitSubmodules { - submodules = true; - }); - } // lock; - in builtins.map mkFetch packageLocks; + url = lock.url; + rev = lock.revision; + } + // lib.optionalAttrs (lock ? branch) { + ref = "refs/heads/${lock.branch}"; + } + // lib.optionalAttrs (lock ? tag) { + ref = "refs/tags/${lock.tag}"; + } + // lib.optionalAttrs ((lib.versionAtLeast builtins.nixVersion "2.4") && (gitAllRefs || lock ? rev)) { + allRefs = true; + } + // lib.optionalAttrs gitSubmodules { + submodules = true; + }); + } + // lock; + in + builtins.map mkFetch packageLocks; # A very minimal 'src' which makes cargo happy nonetheless - dummySrc = - { cargoconfig # path - , cargotomls # list - , cargolock # attrset - , copySources # list of paths that should be copied to the output - , copySourcesFrom # path from which to copy ${copySources} - }: - let - cargolock' = builtinz.writeTOML "Cargo.lock" cargolock; - - fixupCargoToml = cargotoml: - let - attrs = - # Since we pretend everything is a lib, we remove any mentions - # of binaries - removeAttrs cargotoml [ "bin" "example" "lib" "test" "bench" "default-run" ] - // lib.optionalAttrs (builtins.hasAttr "package" cargotoml) ({ package = removeAttrs cargotoml.package [ "default-run" ] ; }) - ; - in - attrs // lib.optionalAttrs (lib.hasAttr "package" attrs) { - package = removeAttrs attrs.package [ "build" ]; - }; - - cargotomlss = map - ({ name, toml }: - "${name}:${builtinz.writeTOML "Cargo.toml" (fixupCargoToml toml)}") - cargotomls; - - in - runCommandLocal "dummy-src" - { inherit copySources copySourcesFrom cargotomlss; } - '' - mkdir -p $out/.cargo - ${lib.optionalString (! isNull cargoconfig) "cp ${cargoconfig} $out/.cargo/config"} - cp ${cargolock'} $out/Cargo.lock - - for tuple in $cargotomlss; do - member="''${tuple%%:*}" - cargotoml="''${tuple##*:}" - - final_dir="$out/$member" - mkdir -p "$final_dir" - final_path="$final_dir/Cargo.toml" - cp $cargotoml "$final_path" - - pushd $out/$member > /dev/null - mkdir -p src - - # Avoid accidentally pulling `std` for no-std crates. - echo '#![no_std]' >src/lib.rs - - # pretend there's a `build.rs`, otherwise cargo doesn't build - # the `[build-dependencies]`. Custom locations of build scripts - # aren't an issue because we strip the `build` field in - # `fixupCargoToml`; so cargo always thinks there's a build - # script which is `./build.rs`. - echo 'fn main() {}' > build.rs - popd > /dev/null - done - - # Copy all the "patched" sources which are used by dependencies. - # This needs to be done after the creation of the dummy to make - # sure the dummy source files do not tramp on the patch - # dependencies. - for p in $copySources; do - echo "Copying patched source $p to $out..." - mkdir -p "$out/$p" - - chmod -R +w "$out/$p" - echo copying "$copySourcesFrom/$p"/ to "$out/$p" - - cp --no-preserve=mode -R "$copySourcesFrom/$p"/* "$out/$p" - done - ''; + dummySrc = { + cargoconfig, # path + cargotomls, # list + cargolock, # attrset + copySources, # list of paths that should be copied to the output + copySourcesFrom, # path from which to copy ${copySources} + }: let + cargolock' = builtinz.writeTOML "Cargo.lock" cargolock; + + fixupCargoToml = cargotoml: let + attrs = + # Since we pretend everything is a lib, we remove any mentions + # of binaries + removeAttrs cargotoml ["bin" "example" "lib" "test" "bench" "default-run"] + // lib.optionalAttrs (builtins.hasAttr "package" cargotoml) {package = removeAttrs cargotoml.package ["default-run"];}; + in + attrs + // lib.optionalAttrs (lib.hasAttr "package" attrs) { + package = removeAttrs attrs.package ["build"]; + }; + + cargotomlss = + map + ({ + name, + toml, + }: "${name}:${builtinz.writeTOML "Cargo.toml" (fixupCargoToml toml)}") + cargotomls; + in + runCommandLocal "dummy-src" + {inherit copySources copySourcesFrom cargotomlss;} + '' + mkdir -p $out/.cargo + ${lib.optionalString (! isNull cargoconfig) "cp ${cargoconfig} $out/.cargo/config"} + cp ${cargolock'} $out/Cargo.lock + + for tuple in $cargotomlss; do + member="''${tuple%%:*}" + cargotoml="''${tuple##*:}" + + final_dir="$out/$member" + mkdir -p "$final_dir" + final_path="$final_dir/Cargo.toml" + cp $cargotoml "$final_path" + + pushd $out/$member > /dev/null + mkdir -p src + + # Avoid accidentally pulling `std` for no-std crates. + echo '#![no_std]' >src/lib.rs + + # pretend there's a `build.rs`, otherwise cargo doesn't build + # the `[build-dependencies]`. Custom locations of build scripts + # aren't an issue because we strip the `build` field in + # `fixupCargoToml`; so cargo always thinks there's a build + # script which is `./build.rs`. + echo 'fn main() {}' > build.rs + popd > /dev/null + done + + # Copy all the "patched" sources which are used by dependencies. + # This needs to be done after the creation of the dummy to make + # sure the dummy source files do not tramp on the patch + # dependencies. + for p in $copySources; do + echo "Copying patched source $p to $out..." + mkdir -p "$out/$p" + + chmod -R +w "$out/$p" + echo copying "$copySourcesFrom/$p"/ to "$out/$p" + + cp --no-preserve=mode -R "$copySourcesFrom/$p"/* "$out/$p" + done + ''; mkPackages = cargolock: lib.foldl' lib.recursiveUpdate {} ( - map (p: { ${p.name} = { ${p.version} = p; }; }) - cargolock.package + map (p: {${p.name} = {${p.version} = p;};}) + cargolock.package ); - directDependencies = cargolock: name: version: - let - packages = mkPackages cargolock; - package = packages.${name}.${version}; - in - lib.optionals (builtins.hasAttr "dependencies" package) - (map parseDependency' package.dependencies); - - transitiveDeps = cargolock: name: version: - let - wrap = p: - { - key = "${p.name}-${p.version}"; - package = p; - }; - packages = mkPackages cargolock; - in - builtins.genericClosure - { - startSet = [ (wrap packages.${name}.${version}) ]; - operator = p: map (dep: wrap (packages.${dep.name}.${dep.version})) ( - ( - lib.optionals (builtins.hasAttr "dependencies" p.package) - (map parseDependency' p.package.dependencies) - ) - ); - }; + directDependencies = cargolock: name: version: let + packages = mkPackages cargolock; + package = packages.${name}.${version}; + in + lib.optionals (builtins.hasAttr "dependencies" package) + (map parseDependency' package.dependencies); + + transitiveDeps = cargolock: name: version: let + wrap = p: { + key = "${p.name}-${p.version}"; + package = p; + }; + packages = mkPackages cargolock; + in + builtins.genericClosure + { + startSet = [(wrap packages.${name}.${version})]; + operator = p: + map (dep: wrap (packages.${dep.name}.${dep.version})) ( + lib.optionals (builtins.hasAttr "dependencies" p.package) + (map parseDependency' p.package.dependencies) + ); + }; # turns " ..." into { name = , version = ; } - parseDependency' = str: - let - components = lib.splitString " " str; - in - { name = lib.elemAt components 0; version = lib.elemAt components 1; }; + parseDependency' = str: let + components = lib.splitString " " str; + in { + name = lib.elemAt components 0; + version = lib.elemAt components 1; + }; } diff --git a/nix/default.nix b/nix/default.nix index 0941de5..63914b1 100644 --- a/nix/default.nix +++ b/nix/default.nix @@ -1,12 +1,12 @@ -{ system ? builtins.currentSystem -, nixpkgs ? "nixpkgs" -, inNixShell ? null -}: -let +{ + system ? builtins.currentSystem, + nixpkgs ? "nixpkgs", + inNixShell ? null, +}: let sources = import ./sources.nix; sources_nixpkgs = if builtins.hasAttr nixpkgs sources then sources."${nixpkgs}" else abort "No entry ${nixpkgs} in sources.json"; in -import sources_nixpkgs { inherit system; } + import sources_nixpkgs {inherit system;} diff --git a/nix/sources.nix b/nix/sources.nix index fe3dadf..50e4dea 100644 --- a/nix/sources.nix +++ b/nix/sources.nix @@ -1,139 +1,177 @@ # This file has been generated by Niv. - let - # # The fetchers. fetch_ fetches specs of type . # - - fetch_file = pkgs: name: spec: - let - name' = sanitizeName name + "-src"; - in - if spec.builtin or true then - builtins_fetchurl { inherit (spec) url sha256; name = name'; } + fetch_file = pkgs: name: spec: let + name' = sanitizeName name + "-src"; + in + if spec.builtin or true + then + builtins_fetchurl { + inherit (spec) url sha256; + name = name'; + } else - pkgs.fetchurl { inherit (spec) url sha256; name = name'; }; - - fetch_tarball = pkgs: name: spec: - let - name' = sanitizeName name + "-src"; - in - if spec.builtin or true then - builtins_fetchTarball { name = name'; inherit (spec) url sha256; } + pkgs.fetchurl { + inherit (spec) url sha256; + name = name'; + }; + + fetch_tarball = pkgs: name: spec: let + name' = sanitizeName name + "-src"; + in + if spec.builtin or true + then + builtins_fetchTarball { + name = name'; + inherit (spec) url sha256; + } else - pkgs.fetchzip { name = name'; inherit (spec) url sha256; }; - - fetch_git = name: spec: - let - ref = - spec.ref or ( - if spec ? branch then "refs/heads/${spec.branch}" else - if spec ? tag then "refs/tags/${spec.tag}" else - abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!" - ); - submodules = spec.submodules or false; - submoduleArg = - let - nixSupportsSubmodules = builtins.compareVersions builtins.nixVersion "2.4" >= 0; - emptyArgWithWarning = - if submodules - then - builtins.trace - ( - "The niv input \"${name}\" uses submodules " - + "but your nix's (${builtins.nixVersion}) builtins.fetchGit " - + "does not support them" - ) - { } - else { }; - in - if nixSupportsSubmodules - then { inherit submodules; } - else emptyArgWithWarning; + pkgs.fetchzip { + name = name'; + inherit (spec) url sha256; + }; + + fetch_git = name: spec: let + ref = + spec.ref + or ( + if spec ? branch + then "refs/heads/${spec.branch}" + else if spec ? tag + then "refs/tags/${spec.tag}" + else abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!" + ); + submodules = spec.submodules or false; + submoduleArg = let + nixSupportsSubmodules = builtins.compareVersions builtins.nixVersion "2.4" >= 0; + emptyArgWithWarning = + if submodules + then + builtins.trace + ( + "The niv input \"${name}\" uses submodules " + + "but your nix's (${builtins.nixVersion}) builtins.fetchGit " + + "does not support them" + ) + {} + else {}; in + if nixSupportsSubmodules + then {inherit submodules;} + else emptyArgWithWarning; + in builtins.fetchGit - ({ url = spec.repo; inherit (spec) rev; inherit ref; } // submoduleArg); + ({ + url = spec.repo; + inherit (spec) rev; + inherit ref; + } + // submoduleArg); fetch_local = spec: spec.path; - fetch_builtin-tarball = name: throw - ''[${name}] The niv type "builtin-tarball" is deprecated. You should instead use `builtin = true`. - $ niv modify ${name} -a type=tarball -a builtin=true''; + fetch_builtin-tarball = name: + throw + '' [${name}] The niv type "builtin-tarball" is deprecated. You should instead use `builtin = true`. + $ niv modify ${name} -a type=tarball -a builtin=true''; - fetch_builtin-url = name: throw - ''[${name}] The niv type "builtin-url" will soon be deprecated. You should instead use `builtin = true`. - $ niv modify ${name} -a type=file -a builtin=true''; + fetch_builtin-url = name: + throw + '' [${name}] The niv type "builtin-url" will soon be deprecated. You should instead use `builtin = true`. + $ niv modify ${name} -a type=file -a builtin=true''; # # Various helpers # # https://github.com/NixOS/nixpkgs/pull/83241/files#diff-c6f540a4f3bfa4b0e8b6bafd4cd54e8bR695 - sanitizeName = name: + sanitizeName = name: ( + concatMapStrings (s: + if builtins.isList s + then "-" + else s) ( - concatMapStrings (s: if builtins.isList s then "-" else s) - ( - builtins.split "[^[:alnum:]+._?=-]+" - ((x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) name) - ) - ); + builtins.split "[^[:alnum:]+._?=-]+" + ((x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) name) + ) + ); # The set of packages used when specs are fetched using non-builtins. - mkPkgs = sources: system: - let - sourcesNixpkgs = - import (builtins_fetchTarball { inherit (sources.nixpkgs) url sha256; }) { inherit system; }; - hasNixpkgsPath = builtins.any (x: x.prefix == "nixpkgs") builtins.nixPath; - hasThisAsNixpkgsPath = == ./.; - in + mkPkgs = sources: system: let + sourcesNixpkgs = + import (builtins_fetchTarball {inherit (sources.nixpkgs) url sha256;}) {inherit system;}; + hasNixpkgsPath = builtins.any (x: x.prefix == "nixpkgs") builtins.nixPath; + hasThisAsNixpkgsPath = == ./.; + in if builtins.hasAttr "nixpkgs" sources then sourcesNixpkgs - else if hasNixpkgsPath && ! hasThisAsNixpkgsPath then - import { } + else if hasNixpkgsPath && ! hasThisAsNixpkgsPath + then import {} else abort - '' - Please specify either (through -I or NIX_PATH=nixpkgs=...) or - add a package called "nixpkgs" to your sources.json. - ''; + '' + Please specify either (through -I or NIX_PATH=nixpkgs=...) or + add a package called "nixpkgs" to your sources.json. + ''; # The actual fetching function. fetch = pkgs: name: spec: - - if ! builtins.hasAttr "type" spec then - abort "ERROR: niv spec ${name} does not have a 'type' attribute" - else if spec.type == "file" then fetch_file pkgs name spec - else if spec.type == "tarball" then fetch_tarball pkgs name spec - else if spec.type == "git" then fetch_git name spec - else if spec.type == "local" then fetch_local spec - else if spec.type == "builtin-tarball" then fetch_builtin-tarball name - else if spec.type == "builtin-url" then fetch_builtin-url name - else - abort "ERROR: niv spec ${name} has unknown type ${builtins.toJSON spec.type}"; + if ! builtins.hasAttr "type" spec + then abort "ERROR: niv spec ${name} does not have a 'type' attribute" + else if spec.type == "file" + then fetch_file pkgs name spec + else if spec.type == "tarball" + then fetch_tarball pkgs name spec + else if spec.type == "git" + then fetch_git name spec + else if spec.type == "local" + then fetch_local spec + else if spec.type == "builtin-tarball" + then fetch_builtin-tarball name + else if spec.type == "builtin-url" + then fetch_builtin-url name + else abort "ERROR: niv spec ${name} has unknown type ${builtins.toJSON spec.type}"; # If the environment variable NIV_OVERRIDE_${name} is set, then use # the path directly as opposed to the fetched source. - replace = name: drv: - let - saneName = stringAsChars (c: if (builtins.match "[a-zA-Z0-9]" c) == null then "_" else c) name; - ersatz = builtins.getEnv "NIV_OVERRIDE_${saneName}"; - in - if ersatz == "" then drv else + replace = name: drv: let + saneName = stringAsChars (c: + if (builtins.match "[a-zA-Z0-9]" c) == null + then "_" + else c) + name; + ersatz = builtins.getEnv "NIV_OVERRIDE_${saneName}"; + in + if ersatz == "" + then drv + else # this turns the string into an actual Nix path (for both absolute and # relative paths) - if builtins.substring 0 1 ersatz == "/" then /. + ersatz else /. + builtins.getEnv "PWD" + "/${ersatz}"; + if builtins.substring 0 1 ersatz == "/" + then /. + ersatz + else /. + builtins.getEnv "PWD" + "/${ersatz}"; # Ports of functions for older nix versions # a Nix version of mapAttrs if the built-in doesn't exist - mapAttrs = builtins.mapAttrs or ( - f: set: with builtins; - listToAttrs (map (attr: { name = attr; value = f attr set.${attr}; }) (attrNames set)) - ); + mapAttrs = + builtins.mapAttrs + or ( + f: set: + with builtins; + listToAttrs (map (attr: { + name = attr; + value = f attr set.${attr}; + }) (attrNames set)) + ); # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295 - range = first: last: if first > last then [ ] else builtins.genList (n: first + n) (last - first + 1); + range = first: last: + if first > last + then [] + else builtins.genList (n: first + n) (last - first + 1); # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L257 stringToCharacters = s: map (p: builtins.substring p 1 s) (range 0 (builtins.stringLength s - 1)); @@ -144,55 +182,66 @@ let concatStrings = builtins.concatStringsSep ""; # https://github.com/NixOS/nixpkgs/blob/8a9f58a375c401b96da862d969f66429def1d118/lib/attrsets.nix#L331 - optionalAttrs = cond: as: if cond then as else { }; + optionalAttrs = cond: as: + if cond + then as + else {}; # fetchTarball version that is compatible between all the versions of Nix - builtins_fetchTarball = { url, name ? null, sha256 }@attrs: - let - inherit (builtins) lessThan nixVersion fetchTarball; - in - if lessThan nixVersion "1.12" then - fetchTarball ({ inherit url; } // (optionalAttrs (name != null) { inherit name; })) - else - fetchTarball attrs; + builtins_fetchTarball = { + url, + name ? null, + sha256, + } @ attrs: let + inherit (builtins) lessThan nixVersion fetchTarball; + in + if lessThan nixVersion "1.12" + then fetchTarball ({inherit url;} // (optionalAttrs (name != null) {inherit name;})) + else fetchTarball attrs; # fetchurl version that is compatible between all the versions of Nix - builtins_fetchurl = { url, name ? null, sha256 }@attrs: - let - inherit (builtins) lessThan nixVersion fetchurl; - in - if lessThan nixVersion "1.12" then - fetchurl ({ inherit url; } // (optionalAttrs (name != null) { inherit name; })) - else - fetchurl attrs; + builtins_fetchurl = { + url, + name ? null, + sha256, + } @ attrs: let + inherit (builtins) lessThan nixVersion fetchurl; + in + if lessThan nixVersion "1.12" + then fetchurl ({inherit url;} // (optionalAttrs (name != null) {inherit name;})) + else fetchurl attrs; # Create the final "sources" from the config mkSources = config: mapAttrs - ( - name: spec: - if builtins.hasAttr "outPath" spec - then - abort - "The values in sources.json should not have an 'outPath' attribute" - else - spec // { outPath = replace name (fetch config.pkgs name spec); } - ) - config.sources; + ( + name: spec: + if builtins.hasAttr "outPath" spec + then + abort + "The values in sources.json should not have an 'outPath' attribute" + else spec // {outPath = replace name (fetch config.pkgs name spec);} + ) + config.sources; # The "config" used by the fetchers - mkConfig = - { sourcesFile ? if builtins.pathExists ./sources.json then ./sources.json else null - , sources ? if sourcesFile == null then { } else builtins.fromJSON (builtins.readFile sourcesFile) - , system ? builtins.currentSystem - , pkgs ? mkPkgs sources system - }: rec { - # The sources, i.e. the attribute set of spec name to spec - inherit sources; - - # The "pkgs" (evaluated nixpkgs) to use for e.g. non-builtin fetchers - inherit pkgs; - }; - + mkConfig = { + sourcesFile ? + if builtins.pathExists ./sources.json + then ./sources.json + else null, + sources ? + if sourcesFile == null + then {} + else builtins.fromJSON (builtins.readFile sourcesFile), + system ? builtins.currentSystem, + pkgs ? mkPkgs sources system, + }: rec { + # The sources, i.e. the attribute set of spec name to spec + inherit sources; + + # The "pkgs" (evaluated nixpkgs) to use for e.g. non-builtin fetchers + inherit pkgs; + }; in -mkSources (mkConfig { }) // { __functor = _: settings: mkSources (mkConfig settings); } + mkSources (mkConfig {}) // {__functor = _: settings: mkSources (mkConfig settings);} diff --git a/readme.nix b/readme.nix index 4268bdd..a4f13b6 100644 --- a/readme.nix +++ b/readme.nix @@ -1,5 +1,4 @@ # This script is used to test & generate `README.md`. - let sources = import ./nix/sources.nix; @@ -15,37 +14,34 @@ let docparse = naersk.buildPackage { root = ./docparse; - src = builtins.filterSource + src = + builtins.filterSource ( - p: t: - let - p' = pkgs.lib.removePrefix (toString ./docparse + "/") p; - in + p: t: let + p' = pkgs.lib.removePrefix (toString ./docparse + "/") p; + in p' == "Cargo.lock" || p' == "Cargo.toml" || p' == "src" || p' == "src/main.rs" - ) ./docparse; + ) + ./docparse; }; - -in -rec { - body = - let - readme = builtins.readFile ./README.tpl.md; - - params = builtins.readFile ( - pkgs.runCommand "docparse" - { buildInputs = [ docparse ]; } - "docparse ${./config.nix} > $out" - ); - - in +in rec { + body = let + readme = builtins.readFile ./README.tpl.md; + + params = builtins.readFile ( + pkgs.runCommand "docparse" + {buildInputs = [docparse];} + "docparse ${./config.nix} > $out" + ); + in pkgs.writeText "readme" ( builtins.replaceStrings - [ "{{ params }}" ] - [ params ] - readme + ["{{ params }}"] + [params] + readme ); - test = pkgs.runCommand "readme-test" { } '' + test = pkgs.runCommand "readme-test" {} '' diff ${./README.md} ${body} touch $out ''; diff --git a/test.nix b/test.nix index fcb795b..58c3b36 100644 --- a/test.nix +++ b/test.nix @@ -1,5 +1,8 @@ -{ system ? builtins.currentSystem, fast ? false, nixpkgs ? "nixpkgs" }: - +{ + system ? builtins.currentSystem, + fast ? false, + nixpkgs ? "nixpkgs", +}: import ./test { inherit system fast nixpkgs; } diff --git a/test/default.nix b/test/default.nix index ede5b1c..183c4f4 100644 --- a/test/default.nix +++ b/test/default.nix @@ -1,21 +1,23 @@ -{ system, fast, nixpkgs }: -let +{ + system, + fast, + nixpkgs, +}: let sources = import ../nix/sources.nix; - pkgs = - let - pkgs' = import ../nix { - inherit system nixpkgs; - }; - - older-pkgs = import ../nix { - inherit system; + pkgs = let + pkgs' = import ../nix { + inherit system nixpkgs; + }; - nixpkgs = "nixpkgs-21.05"; - }; + older-pkgs = import ../nix { + inherit system; - in - pkgs' // { + nixpkgs = "nixpkgs-21.05"; + }; + in + pkgs' + // { # Some of our tests use dynamically-built Git repositories that fail extra # security checks introduced in newer Git versions - so for the time being # let's pin our test-Git to an older version. @@ -40,8 +42,7 @@ let # `nix-build` then evaluates in its entirety. runTests = tests: pkgs.lib.collect pkgs.lib.isDerivation tests; - in -runTests ( - fastTests // pkgs.lib.optionalAttrs (!fast) slowTests -) + runTests ( + fastTests // pkgs.lib.optionalAttrs (!fast) slowTests + ) diff --git a/test/fast/cargo-config/default.nix b/test/fast/cargo-config/default.nix index 51fffbf..9aef0bb 100644 --- a/test/fast/cargo-config/default.nix +++ b/test/fast/cargo-config/default.nix @@ -1,7 +1,9 @@ -{ sources, pkgs, ... }: - -let - fenix = import sources.fenix { }; +{ + sources, + pkgs, + ... +}: let + fenix = import sources.fenix {}; # Support for custom environmental variables was introduced in Cargo 1.56 and # our tests use nixpkgs-21.05 which contains an older version of Cargo, making @@ -12,9 +14,8 @@ let cargo = toolchain.cargo; rustc = toolchain.rustc; }; - in -naersk.buildPackage { - src = ./fixtures; - doCheck = true; -} + naersk.buildPackage { + src = ./fixtures; + doCheck = true; + } diff --git a/test/fast/cargo-wildcard/default.nix b/test/fast/cargo-wildcard/default.nix index d34c380..2587241 100644 --- a/test/fast/cargo-wildcard/default.nix +++ b/test/fast/cargo-wildcard/default.nix @@ -1,5 +1,4 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; diff --git a/test/fast/default-run/default.nix b/test/fast/default-run/default.nix index d34c380..2587241 100644 --- a/test/fast/default-run/default.nix +++ b/test/fast/default-run/default.nix @@ -1,5 +1,4 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; diff --git a/test/fast/dummyfication/default.nix b/test/fast/dummyfication/default.nix index 2ddad90..0aeeba4 100644 --- a/test/fast/dummyfication/default.nix +++ b/test/fast/dummyfication/default.nix @@ -1,11 +1,13 @@ -{ naersk, pkgs, ... }: -let +{ + naersk, + pkgs, + ... +}: let app = naersk.buildPackage { src = ./fixtures; doCheck = true; }; - in -pkgs.runCommand "dummyfication-test" { - buildInputs = [ app ]; -} "my-bin > $out" + pkgs.runCommand "dummyfication-test" { + buildInputs = [app]; + } "my-bin > $out" diff --git a/test/fast/duplicated-cargo-lock-items/default.nix b/test/fast/duplicated-cargo-lock-items/default.nix index d34c380..2587241 100644 --- a/test/fast/duplicated-cargo-lock-items/default.nix +++ b/test/fast/duplicated-cargo-lock-items/default.nix @@ -1,5 +1,4 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; diff --git a/test/fast/git-dep-by-branch-with-slash/default.nix b/test/fast/git-dep-by-branch-with-slash/default.nix index 04604ab..3ffcff9 100644 --- a/test/fast/git-dep-by-branch-with-slash/default.nix +++ b/test/fast/git-dep-by-branch-with-slash/default.nix @@ -1,35 +1,40 @@ -{ naersk, pkgs, ... }: -let - dep = pkgs.runCommand "dep" { - buildInputs = [ pkgs.git ]; - } '' - mkdir $out - cd $out - cp -ar ${./fixtures/dep}/* . +{ + naersk, + pkgs, + ... +}: let + dep = + pkgs.runCommand "dep" { + buildInputs = [pkgs.git]; + } '' + mkdir $out + cd $out + cp -ar ${./fixtures/dep}/* . - git init --initial-branch=with/slash - git add . - git config user.email 'someone' - git config user.name 'someone' - git commit -am 'Initial commit' - ''; + git init --initial-branch=with/slash + git add . + git config user.email 'someone' + git config user.name 'someone' + git commit -am 'Initial commit' + ''; - app = pkgs.runCommand "app" { - buildInputs = [ pkgs.git ]; - } '' - mkdir $out - cd $out - cp -ar ${./fixtures/app}/* . + app = + pkgs.runCommand "app" { + buildInputs = [pkgs.git]; + } '' + mkdir $out + cd $out + cp -ar ${./fixtures/app}/* . - depPath="${dep}" - depRev=$(cd ${dep} && git rev-parse HEAD) + depPath="${dep}" + depRev=$(cd ${dep} && git rev-parse HEAD) - sed "s:\$depPath:$depPath:" -is Cargo.* - sed "s:\$depRev:$depRev:" -is Cargo.* - ''; + sed "s:\$depPath:$depPath:" -is Cargo.* + sed "s:\$depRev:$depRev:" -is Cargo.* + ''; in -naersk.buildPackage { - src = app; - doCheck = true; - cargoOptions = (opts: opts ++ [ "--locked" ]); -} + naersk.buildPackage { + src = app; + doCheck = true; + cargoOptions = opts: opts ++ ["--locked"]; + } diff --git a/test/fast/git-dep-by-branch/default.nix b/test/fast/git-dep-by-branch/default.nix index b5ef420..55e572f 100644 --- a/test/fast/git-dep-by-branch/default.nix +++ b/test/fast/git-dep-by-branch/default.nix @@ -1,7 +1,6 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; - cargoOptions = (opts: opts ++ [ "--locked" ]); + cargoOptions = opts: opts ++ ["--locked"]; } diff --git a/test/fast/git-dep-by-tag/default.nix b/test/fast/git-dep-by-tag/default.nix index b5ef420..55e572f 100644 --- a/test/fast/git-dep-by-tag/default.nix +++ b/test/fast/git-dep-by-tag/default.nix @@ -1,7 +1,6 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; - cargoOptions = (opts: opts ++ [ "--locked" ]); + cargoOptions = opts: opts ++ ["--locked"]; } diff --git a/test/fast/git-dep-dup/default.nix b/test/fast/git-dep-dup/default.nix index b5ef420..55e572f 100644 --- a/test/fast/git-dep-dup/default.nix +++ b/test/fast/git-dep-dup/default.nix @@ -1,7 +1,6 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; - cargoOptions = (opts: opts ++ [ "--locked" ]); + cargoOptions = opts: opts ++ ["--locked"]; } diff --git a/test/fast/git-dep/default.nix b/test/fast/git-dep/default.nix index d34c380..2587241 100644 --- a/test/fast/git-dep/default.nix +++ b/test/fast/git-dep/default.nix @@ -1,5 +1,4 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; diff --git a/test/fast/git-single-repository-with-multiple-crates/default.nix b/test/fast/git-single-repository-with-multiple-crates/default.nix index cb16610..b0e8937 100644 --- a/test/fast/git-single-repository-with-multiple-crates/default.nix +++ b/test/fast/git-single-repository-with-multiple-crates/default.nix @@ -1,36 +1,40 @@ -{ naersk, pkgs, ... }: -let - dep = pkgs.runCommand "dep" { - buildInputs = [ pkgs.git ]; - } '' - mkdir $out - cd $out - cp -ar ${./fixtures/dep}/* . +{ + naersk, + pkgs, + ... +}: let + dep = + pkgs.runCommand "dep" { + buildInputs = [pkgs.git]; + } '' + mkdir $out + cd $out + cp -ar ${./fixtures/dep}/* . - git init - git add . - git config user.email 'someone' - git config user.name 'someone' - git commit -am 'Initial commit' - ''; + git init + git add . + git config user.email 'someone' + git config user.name 'someone' + git commit -am 'Initial commit' + ''; - app = pkgs.runCommand "app" { - buildInputs = [ pkgs.git ]; - } '' - mkdir $out - cd $out - cp -ar ${./fixtures/app}/* . + app = + pkgs.runCommand "app" { + buildInputs = [pkgs.git]; + } '' + mkdir $out + cd $out + cp -ar ${./fixtures/app}/* . - depPath="${dep}" - depRev=$(cd ${dep} && git rev-parse HEAD) - - sed "s:\$depPath:$depPath:" -is Cargo.* - sed "s:\$depRev:$depRev:" -is Cargo.* - ''; + depPath="${dep}" + depRev=$(cd ${dep} && git rev-parse HEAD) + sed "s:\$depPath:$depPath:" -is Cargo.* + sed "s:\$depRev:$depRev:" -is Cargo.* + ''; in -naersk.buildPackage { - src = app; - doCheck = true; - cargoOptions = (opts: opts ++ [ "--locked" ]); -} + naersk.buildPackage { + src = app; + doCheck = true; + cargoOptions = opts: opts ++ ["--locked"]; + } diff --git a/test/fast/git-symlink/default.nix b/test/fast/git-symlink/default.nix index 981e058..ec3c156 100644 --- a/test/fast/git-symlink/default.nix +++ b/test/fast/git-symlink/default.nix @@ -1,36 +1,40 @@ -{ naersk, pkgs, ... }: -let - dep = pkgs.runCommand "dep" { - buildInputs = [ pkgs.git ]; - } '' - mkdir $out - cd $out - cp -ar ${./fixtures/dep-workspace}/* . +{ + naersk, + pkgs, + ... +}: let + dep = + pkgs.runCommand "dep" { + buildInputs = [pkgs.git]; + } '' + mkdir $out + cd $out + cp -ar ${./fixtures/dep-workspace}/* . - git init - git add . - git config user.email 'someone' - git config user.name 'someone' - git commit -am 'Initial commit' - ''; + git init + git add . + git config user.email 'someone' + git config user.name 'someone' + git commit -am 'Initial commit' + ''; - app = pkgs.runCommand "app" { - buildInputs = [ pkgs.git ]; - } '' - mkdir $out - cd $out - cp -ar ${./fixtures/app}/* . + app = + pkgs.runCommand "app" { + buildInputs = [pkgs.git]; + } '' + mkdir $out + cd $out + cp -ar ${./fixtures/app}/* . - depPath="${dep}" - depRev=$(cd ${dep} && git rev-parse HEAD) - - sed "s:\$depPath:$depPath:" -is Cargo.* - sed "s:\$depRev:$depRev:" -is Cargo.* - ''; + depPath="${dep}" + depRev=$(cd ${dep} && git rev-parse HEAD) + sed "s:\$depPath:$depPath:" -is Cargo.* + sed "s:\$depRev:$depRev:" -is Cargo.* + ''; in -naersk.buildPackage { - src = app; - doCheck = true; - cargoOptions = (opts: opts ++ [ "--locked" ]); -} + naersk.buildPackage { + src = app; + doCheck = true; + cargoOptions = opts: opts ++ ["--locked"]; + } diff --git a/test/fast/post-install-hook/default.nix b/test/fast/post-install-hook/default.nix index 2acc640..e9431db 100644 --- a/test/fast/post-install-hook/default.nix +++ b/test/fast/post-install-hook/default.nix @@ -1,16 +1,18 @@ -{ naersk, pkgs, ... }: { - postInstall = - let - app = naersk.buildPackage { - src = ./fixtures; - nativeBuildInputs = with pkgs; [ makeWrapper ]; - postInstall = '' - wrapProgram $out/bin/app --set FAVORITE_SHOW 'The Office' - ''; - }; - - in +{ + naersk, + pkgs, + ... +}: { + postInstall = let + app = naersk.buildPackage { + src = ./fixtures; + nativeBuildInputs = with pkgs; [makeWrapper]; + postInstall = '' + wrapProgram $out/bin/app --set FAVORITE_SHOW 'The Office' + ''; + }; + in pkgs.runCommand "post-install-hook-test" { - buildInputs = [ app ]; + buildInputs = [app]; } "app && touch $out"; } diff --git a/test/fast/readme/default.nix b/test/fast/readme/default.nix index 863c09b..30b8c9b 100644 --- a/test/fast/readme/default.nix +++ b/test/fast/readme/default.nix @@ -1,2 +1,2 @@ -{ ... }: +{...}: (import ../../../readme.nix).test diff --git a/test/fast/simple-dep-patched/default.nix b/test/fast/simple-dep-patched/default.nix index d34c380..2587241 100644 --- a/test/fast/simple-dep-patched/default.nix +++ b/test/fast/simple-dep-patched/default.nix @@ -1,5 +1,4 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; diff --git a/test/fast/simple-dep/default.nix b/test/fast/simple-dep/default.nix index d1ae771..a0727f8 100644 --- a/test/fast/simple-dep/default.nix +++ b/test/fast/simple-dep/default.nix @@ -1,4 +1,8 @@ -{ naersk, pkgs, ... }: rec { +{ + naersk, + pkgs, + ... +}: rec { default = naersk.buildPackage { src = ./fixtures; doCheck = true; @@ -36,9 +40,10 @@ # which is wasteful. # # See: https://github.com/nix-community/naersk/issues/202. - depsTargetNotEmptyWhenCompressed = pkgs.runCommand "test" { - inherit (withCompressTarget) builtDependencies; - } '' + depsTargetNotEmptyWhenCompressed = + pkgs.runCommand "test" { + inherit (withCompressTarget) builtDependencies; + } '' for dep in $builtDependencies; do mkdir dst ${pkgs.zstd}/bin/zstd -d "$dep/target.tar.zst" --stdout | tar -x -C ./dst @@ -56,9 +61,10 @@ ''; # Same as the one above, just for `withoutCompressTarget` - depsTargetNotEmptyWhenNotCompressed = pkgs.runCommand "test" { - inherit (withoutCompressTarget) builtDependencies; - } '' + depsTargetNotEmptyWhenNotCompressed = + pkgs.runCommand "test" { + inherit (withoutCompressTarget) builtDependencies; + } '' for dep in $builtDependencies; do if [ -z "$(ls -A "$dep"/target)" ]; then echo target directory is empty: "$dep" diff --git a/test/fast/symlinks/default.nix b/test/fast/symlinks/default.nix index 0e99baa..7f9eb9f 100644 --- a/test/fast/symlinks/default.nix +++ b/test/fast/symlinks/default.nix @@ -1,8 +1,12 @@ -{ naersk, pkgs, ... }: { +{ + naersk, + pkgs, + ... +}: { default = naersk.buildPackage { src = pkgs.symlinkJoin { name = "src"; - paths = [ ./fixtures ]; + paths = [./fixtures]; }; }; } diff --git a/test/fast/unused-patch/default.nix b/test/fast/unused-patch/default.nix index 2f6ea43..7e62483 100644 --- a/test/fast/unused-patch/default.nix +++ b/test/fast/unused-patch/default.nix @@ -1,15 +1,17 @@ -{ naersk, pkgs, ... }: -let +{ + naersk, + pkgs, + ... +}: let app = naersk.buildPackage { src = ./fixtures; }; - in -if builtins.compareVersions pkgs.lib.version "22.11" <= 0 then - # Executing this test requires nixpkgs > 22.11 due to changes to the TOML - # serialization function. - # - # See `writeTOML` in this repository for more details. - true -else - app + if builtins.compareVersions pkgs.lib.version "22.11" <= 0 + then + # Executing this test requires nixpkgs > 22.11 due to changes to the TOML + # serialization function. + # + # See `writeTOML` in this repository for more details. + true + else app diff --git a/test/fast/workspace-build-rs/default.nix b/test/fast/workspace-build-rs/default.nix index d34c380..2587241 100644 --- a/test/fast/workspace-build-rs/default.nix +++ b/test/fast/workspace-build-rs/default.nix @@ -1,5 +1,4 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; diff --git a/test/fast/workspace-patched/default.nix b/test/fast/workspace-patched/default.nix index d34c380..2587241 100644 --- a/test/fast/workspace-patched/default.nix +++ b/test/fast/workspace-patched/default.nix @@ -1,5 +1,4 @@ -{ naersk, ... }: - +{naersk, ...}: naersk.buildPackage { src = ./fixtures; doCheck = true; diff --git a/test/fast/workspace/default.nix b/test/fast/workspace/default.nix index d455bb5..2565fc1 100644 --- a/test/fast/workspace/default.nix +++ b/test/fast/workspace/default.nix @@ -1,4 +1,4 @@ -{ naersk, ... }: { +{naersk, ...}: { default = naersk.buildPackage { src = ./fixtures; doCheck = true; diff --git a/test/slow/agent-rs/default.nix b/test/slow/agent-rs/default.nix index 5a56ee7..6968716 100644 --- a/test/slow/agent-rs/default.nix +++ b/test/slow/agent-rs/default.nix @@ -1,6 +1,9 @@ -{ sources, pkgs, ... }: -let - fenix = import sources.fenix { }; +{ + sources, + pkgs, + ... +}: let + fenix = import sources.fenix {}; toolchain = fenix.fromToolchainFile { file = "${sources.agent-rs}/rust-toolchain.toml"; @@ -11,14 +14,15 @@ let cargo = toolchain; rustc = toolchain; }; - in -naersk.buildPackage { - src = sources.agent-rs; + naersk.buildPackage { + src = sources.agent-rs; - buildInputs = [ - pkgs.openssl - pkgs.pkg-config - pkgs.perl - ] ++ pkgs.lib.optional pkgs.stdenv.isDarwin pkgs.libiconv; -} + buildInputs = + [ + pkgs.openssl + pkgs.pkg-config + pkgs.perl + ] + ++ pkgs.lib.optional pkgs.stdenv.isDarwin pkgs.libiconv; + } diff --git a/test/slow/lorri/default.nix b/test/slow/lorri/default.nix index 114a084..31aed0f 100644 --- a/test/slow/lorri/default.nix +++ b/test/slow/lorri/default.nix @@ -1,12 +1,15 @@ -{ sources, naersk, pkgs, ... }: -let +{ + sources, + naersk, + pkgs, + ... +}: let app = naersk.buildPackage { src = sources.lorri; BUILD_REV_COUNT = 1; RUN_TIME_CLOSURE = "${sources.lorri}/nix/runtime.nix"; }; - in -pkgs.runCommand "lorri-test" { - buildInputs = [ app ]; -} "lorri --help && touch $out" + pkgs.runCommand "lorri-test" { + buildInputs = [app]; + } "lorri --help && touch $out" diff --git a/test/slow/nushell/default.nix b/test/slow/nushell/default.nix index 526dce0..c5ca7a8 100644 --- a/test/slow/nushell/default.nix +++ b/test/slow/nushell/default.nix @@ -1,6 +1,9 @@ -{ sources, pkgs, ... }: -let - fenix = import sources.fenix { }; +{ + sources, + pkgs, + ... +}: let + fenix = import sources.fenix {}; toolchain = fenix.fromToolchainFile { file = "${sources.nushell}/rust-toolchain.toml"; @@ -15,16 +18,16 @@ let app = naersk.buildPackage { src = sources.nushell; - nativeBuildInputs = with pkgs; [ pkg-config ]; + nativeBuildInputs = with pkgs; [pkg-config]; - buildInputs = with pkgs; [ openssl ] - ++ lib.optionals stdenv.isDarwin [ zlib libiconv darwin.Libsystem darwin.Security darwin.apple_sdk.frameworks.Foundation ]; + buildInputs = with pkgs; + [openssl] + ++ lib.optionals stdenv.isDarwin [zlib libiconv darwin.Libsystem darwin.Security darwin.apple_sdk.frameworks.Foundation]; LIBCLANG_PATH = "${pkgs.clang.cc.lib}/lib"; }; - in -pkgs.runCommand "nushell-test" -{ - buildInputs = [ app ]; -} "nu -c 'echo yes!' && touch $out" + pkgs.runCommand "nushell-test" + { + buildInputs = [app]; + } "nu -c 'echo yes!' && touch $out" diff --git a/test/slow/probe-rs/default.nix b/test/slow/probe-rs/default.nix index 62b4677..661eb96 100644 --- a/test/slow/probe-rs/default.nix +++ b/test/slow/probe-rs/default.nix @@ -1,12 +1,17 @@ -{ sources, pkgs, ... }: -let - fenix = import sources.fenix { }; +{ + sources, + pkgs, + ... +}: let + fenix = import sources.fenix {}; - toolchain = (fenix.toolchainOf { - channel = "nightly"; - date = "2023-07-01"; - sha256 = "sha256-pWd4tAHP4QWGC3CKWZzDjzYANxATC6CGRmKuP2ZZv5k="; - }).toolchain; + toolchain = + (fenix.toolchainOf { + channel = "nightly"; + date = "2023-07-01"; + sha256 = "sha256-pWd4tAHP4QWGC3CKWZzDjzYANxATC6CGRmKuP2ZZv5k="; + }) + .toolchain; naersk = pkgs.callPackage ../../../default.nix { cargo = toolchain; @@ -16,25 +21,27 @@ let app = naersk.buildPackage { src = sources.probe-rs; - buildInputs = with pkgs; [ - pkg-config - libusb1 - openssl - ] ++ lib.optionals stdenv.isDarwin [ - darwin.DarwinTools - darwin.apple_sdk.frameworks.AppKit - ]; + buildInputs = with pkgs; + [ + pkg-config + libusb1 + openssl + ] + ++ lib.optionals stdenv.isDarwin [ + darwin.DarwinTools + darwin.apple_sdk.frameworks.AppKit + ]; }; - in -if builtins.compareVersions pkgs.lib.version "22.11" <= 0 then - # Executing this test requires nixpkgs > 22.11 due to changes to the TOML - # serialization function. - # - # See `writeTOML` in this repository for more details. - true -else - pkgs.runCommand "probe-rs-test" - { - buildInputs = [ app ]; - } "rtthost --help && touch $out" + if builtins.compareVersions pkgs.lib.version "22.11" <= 0 + then + # Executing this test requires nixpkgs > 22.11 due to changes to the TOML + # serialization function. + # + # See `writeTOML` in this repository for more details. + true + else + pkgs.runCommand "probe-rs-test" + { + buildInputs = [app]; + } "rtthost --help && touch $out" diff --git a/test/slow/ripgrep-all/default.nix b/test/slow/ripgrep-all/default.nix index 4f09e40..072ba0c 100644 --- a/test/slow/ripgrep-all/default.nix +++ b/test/slow/ripgrep-all/default.nix @@ -1,11 +1,14 @@ -{ sources, naersk, pkgs, ... }: -let +{ + sources, + naersk, + pkgs, + ... +}: let app = naersk.buildPackage { src = sources.ripgrep-all; doCheck = true; }; - in -pkgs.runCommand "ripgrep-all-test" { - buildInputs = [ app ]; -} "rga --help && touch $out" + pkgs.runCommand "ripgrep-all-test" { + buildInputs = [app]; + } "rga --help && touch $out" diff --git a/test/slow/rustlings/default.nix b/test/slow/rustlings/default.nix index b6b4a1a..6f89bde 100644 --- a/test/slow/rustlings/default.nix +++ b/test/slow/rustlings/default.nix @@ -1,3 +1,6 @@ -{ sources, naersk, ... }: - +{ + sources, + naersk, + ... +}: naersk.buildPackage sources.rustlings diff --git a/test/slow/talent-plan/default.nix b/test/slow/talent-plan/default.nix index 72fef41..cd76ce3 100644 --- a/test/slow/talent-plan/default.nix +++ b/test/slow/talent-plan/default.nix @@ -1,4 +1,9 @@ -{ sources, naersk, pkgs, ... }: { +{ + sources, + naersk, + pkgs, + ... +}: { talent-plan-1 = naersk.buildPackage { src = "${sources.talent-plan}/rust/projects/project-1"; doCheck = true;