Detecting whether dependency package enabled its feature

Hello, when a dependency has its own optional features, and it is used by multiple crates, chances are it has some of its features enabled by other crates in the dependencies. Is there any current stable approach to detect whether its certain feature has been required and enabled by another crate in the dep graph?

I know the unstable cfg(accessible) might help here. Is there any stable approach?

Does cargo tree -e features help?

i want to do conditional compilation based on this information. (Sorry if i didn't make it totally clear)

I don't think there's any stable non-hacky way to do this.

Usually you're expected to make your feature flag in your crate, and then explicitly enable feature in a dependency. This information doesn't travel the other way.

The hacky way would be to have that uses cargo_metadata to read your dependency tree and see which features are enabled there, and set cfg for your crate. I'm not even sure if that'd work if your crate is a dependency.

1 Like

You could use cargo metadata --format-version 1 to generate the full metadata json file and analyze it:

  • packages field contains each package info with all the features listed including the dep names: this can produce the possible dependency graphs, which seems you're looking for
  • resolve field provides the final dependency graph that you can double check

Finally i come up with a solution: Luckily i have access to the dependency repo, so i defined a macro there that expands to input when the feature is enabled and nothing when the feature is not set. This way, i can put all conditional handling within the macro input. It will handle the logic properly.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.