2023-01-05 06:06:37 +03:00
|
|
|
## Source filtering
|
|
|
|
|
|
|
|
Nix considers that a derivation must be rebuilt whenever any of its inputs
|
|
|
|
change, including all source files passed into the build. Unfortunately, this
|
|
|
|
means that changes to any "irrelevant" files (such as the project README) would
|
|
|
|
end up rebuilding the project even if the final outputs don't actually care
|
|
|
|
about their contents!
|
|
|
|
|
|
|
|
Source filtering is a technique Nix employs that allows for better caching by
|
|
|
|
programmatically filtering out files which are known to not apply to the build
|
|
|
|
_before_ the inputs are hashed.
|
|
|
|
|
2023-11-29 04:08:21 +03:00
|
|
|
A default source cleaner is available via `craneLib.cleanCargoSource`: it cleans
|
2023-01-05 06:06:37 +03:00
|
|
|
a source tree to omit things like version control directories as well omit any
|
|
|
|
non-Rust/non-cargo related files. It can be used like so:
|
|
|
|
|
|
|
|
```nix
|
|
|
|
craneLib.buildPackage {
|
|
|
|
# other attributes omitted
|
2024-06-11 06:53:46 +03:00
|
|
|
src = craneLib.cleanCargoSource ./.;
|
2023-01-05 06:06:37 +03:00
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
It is possible to customize the filter to use when cleaning the source by
|
|
|
|
leveraging `craneLib.filterCargoSources`. By default this filter will only keep
|
|
|
|
files whose names end with `.rs` or `.toml`. Though it is possible to compose it
|
|
|
|
with other filters, especially if it is necessary to include additional files
|
|
|
|
which it might otherwise omit:
|
|
|
|
|
|
|
|
```nix
|
|
|
|
let
|
|
|
|
# Only keeps markdown files
|
|
|
|
markdownFilter = path: _type: builtins.match ".*md$" path != null;
|
|
|
|
markdownOrCargo = path: type:
|
2023-05-19 06:57:50 +03:00
|
|
|
(markdownFilter path type) || (craneLib.filterCargoSources path type);
|
2023-01-05 06:06:37 +03:00
|
|
|
in
|
|
|
|
craneLib.buildPackage {
|
|
|
|
# other attributes omitted
|
|
|
|
src = lib.cleanSourceWith {
|
2024-06-11 06:53:46 +03:00
|
|
|
src = ./.; # The original, unfiltered source
|
2023-01-05 06:06:37 +03:00
|
|
|
filter = markdownOrCargo;
|
2024-06-11 06:53:46 +03:00
|
|
|
name = "source"; # Be reproducible, regardless of the directory name
|
2023-01-05 06:06:37 +03:00
|
|
|
};
|
|
|
|
}
|
|
|
|
```
|