Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pull a dependency with different features under Cargo.toml "dependencies" and "dev-dependencies"?

Suppose you have a dependency called "dep" which has two features called f1 and f2. I want to use "dep" with the f1 feature when I'm building my crate normally, but use it with f2 when building it for tests. I know dev-dependencies are those we need for tests and thought the following structure for Cargo.toml should work:

    [dev-dependencies]
    dep = { version = "1.0.0", features = ["f2"] }
    
    [dependencies]
    dep = { version = "1.0.0", features = ["f1"] }
    

However, it looks like once I have pulled in "dep" with "f1", the compiler would disregard the mention of the same dependency under the dev-dependencies section. On the other hand, making the dependency "optional" will not solve the issue because then "dep" will not be pulled in for the tests at all. Any ideas on how to resolve this issue or circumvent it nicely?

PS: I noticed the issue is being tracked here: https://github.com/rust-lang/cargo/issues/7916. So at the moment, I could only expect good workarounds from the respondents.

like image 261
Alex Sed Avatar asked Oct 20 '20 03:10

Alex Sed


People also ask

What is features in cargo toml?

Cargo "features" provide a mechanism to express conditional compilation and optional dependencies. A package defines a set of named features in the [features] table of Cargo. toml , and each feature can either be enabled or disabled.

Does updating dependencies using cargo guarantee that you use the latest version of the dependency?

This means that only the dependency specified by SPEC will be updated. Its transitive dependencies will be updated only if SPEC cannot be updated without updating dependencies. All other dependencies will remain locked at their currently recorded versions.

Where is cargo toml located?

Cargo. toml and Cargo. lock are stored in the root of your project (package root). Source code goes in the src directory.

What is cargo toml?

toml. Cargo. toml is the manifest file for Rust's package manager, cargo . This file contains metadata such as name, version, and dependencies for packages, which are call "crates" in Rust.


1 Answers

This is possible with rust 2021 using resolver version 2. as documented here. Specifically it says this:

Features enabled on dev-dependencies will not be unified when those same dependencies are used as a normal dependency, unless those dev-dependencies are currently being built

In order to do this you will need your root package to have edition = "2021", then you can use resolver = "2" in your crate manifest to enable the desired behaviour.

like image 97
Alex jg Avatar answered Sep 20 '22 23:09

Alex jg