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

2

6

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?

Miterwort answered 9/8, 2022 at 12:44 Comment(2)
Not natively with cargo. I guess you'd a script that parses your Cargo.toml and collects all the features automatically. I bet you can whip that up in Python in a couple of lines.Maladapted
You may want to set up a code coverage report so that you can see what your shell script has and hasn't tested.Vaulted
E
4

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.

Efflorescence answered 9/8, 2022 at 16:34 Comment(0)
A
2

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.

Anorexia answered 21/9, 2022 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.