5

I would like to restrict the number of files to include in my build src to a select few. Directly passing the list of files to src or srcs isn't allowed as an archive or a directory is expected. I couldn't find a function to do this and builtins.filterSource does not seem to work for me (no idea why -- the intermediate derivation containing the filtered files ends up empty):

    files = [
        ./Cargo.toml
        ./Cargo.lock
        ./cpu.rs
    ];
    src = builtins.filterSource (p: t: builtins.elem p files) ./.;

Note: I'm using the rustPlatform builder but I don't think it matters.

Bruno Bieth
  • 2,317
  • 20
  • 31

1 Answers1

4

filterSource passes the full path as a string. in order to compare the paths of your list with it you need to convert the string to a path:

$ cd /Users/fghibellini/code/nix
$ nix-instantiate --eval -E './a == "/Users/fghibellini/code/nix/a"'
false
$ nix-instantiate --eval -E './a == (/. + "/Users/fghibellini/code/nix/a")'
true

i.e. the following code should work fine:

files = [
    ./Cargo.toml
    ./Cargo.lock
    ./cpu.rs
];
src = builtins.filterSource (p: t: builtins.elem (/. + p) files) ./.;

You can use builtins.typeOf and builtins.trace to debug such issues.

fghibellini
  • 636
  • 4
  • 15
  • Damn! I've been the victim of universal equality, once more! I traced it and didn't think of the type... Thanks! Don't you think such a function should be part of the lib? – Bruno Bieth May 27 '19 at 13:17
  • I don't understand what you mean by such function, but I think in this case I would blame the JavaScript-like conversion behaviour of strings/paths - it's quite a mess to work with. even in the solution: Want to convert a string to a path? ...well obviously you just concatenate the root path with the string :/ – fghibellini May 27 '19 at 19:49
  • I meant `builtins.filterSource (p: t: builtins.elem(/. + p) files) ./.`. But ideally `src` should accept a list of files in addition to directories and archives. – Bruno Bieth May 29 '19 at 19:18
  • This is an underrated answer to an underrated question. Thank you for the `/. +` tip, and for the idea to take your include/exclude list as full paths as well, instead of trying to transform the paths passed to the filter function as relative. – hraban Jan 08 '23 at 08:44