TimonPost / cargo-unused-features

Find potential unused enabled feature flags and prune them.
MIT License
230 stars 10 forks source link

Does not work properly with Cargo's sparse index protocol #16

Open jyoung15 opened 10 months ago

jyoung15 commented 10 months ago

When the Cargo registry sparse protocol is enabled as described here, unused-features generates an empty report.

The debug logs indicate:

Failed to compile without feature flag. error: Failed to compile toml document: failed to get `[dependency]` as a dependency of package `[package]`

A common fix for this issue is to delete ~/.cargo/registry/index and retry, however this did not fix my issue.

In order to see more details of the problem, I patched the Anyhow error message to display the backtrace.

diff --git a/src/cargo_project.rs b/src/cargo_project.rs
index 67390f3..4c2aff1 100644
--- a/src/cargo_project.rs
+++ b/src/cargo_project.rs
@@ -204,7 +204,7 @@ impl CargoProject {
         let workspace = Workspace::new(&self.toml_path(), &config)?;

         cargo::ops::compile(&workspace, &compile_options)
-            .map_err(|e| anyhow::anyhow!("Failed to compile toml document: {}", e))?;
+            .map_err(|e| anyhow::anyhow!("Failed to compile toml document: {e:?}"))?;

         Ok(())
     }

This indicated the source of the problem.

    Caused by:
        0: failed to load source for dependency `[dependency]`
        1: Unable to update registry `crates-io`
        2: usage of sparse registries requires `-Z sparse-registry`

Once the root cause was known, the workaround is to disable the sparse protocol in ~/.cargo/config.toml.

I'm just opening this issue in case others run into the same problem. I don't see any way to pass cargo flags (-Z) to unused-features analyze. I would also suggest updating Anyhow errors to include the backtrace to make identifying issues like this easier.