How can I run cargo check/test individually on each feature of my Cargo.toml?

Viewed 82

Cargo features allow conditional compilation, so the final build will have just specific groups of features which can be filtered by the final user.

Now depending on the complexity of a library crate, you may end with several features forming a dependency tree, something like:

[features]
banana = []
avocado = []
pineapple = ["avocado"]
orange = ["pineapple", "banana"]

It's natural that, beyond cargo check|test --all-features, I will want to run cargo check|test --features banana on each one of the individual features, to ensure they can live on their own. Currently I'm doing this with a crude shell script, manually fed with the features. If I add a new feature and I forget to add it to the script, I'm in trouble.

FEATS=(banana avocado pineapple orange)

for FEAT in "${FEATS[@]}" ; do
    echo "$FEAT..."
    cargo check --features "$FEAT"
    #cargo test --features "$FEAT"
done

So, is there any automated way to run cargo check|test --features banana on each feature, one by one, then report the warnings/errors which have been found?

2 Answers

I recently found taiki-e/cargo-hack which claims to handle this problem. I haven't tried it myself.

cargo-hack is basically wrapper of cargo that propagates subcommand and most of the passed flags to cargo, but provides additional flags and changes the behavior of some existing flags.

--each-feature

Perform for each feature which includes default features and --no-default-features of the package.

This is useful to check that each feature is working properly.

There is the cargo-all-features crate that provides commands for using all combination of features, not only individual features:

> cargo install cargo-all-features --locked

With it installed, you can run the following cargo commands to check, test, and build:

> cargo check-all-features
> cargo test-all-features
> cargo build-all-features

Further customizations (like skipping features or combinations) can be set by configuring the [package.metadata.cargo-all-features] section in your Cargo.toml.

Related