Description
Problem
Adding a new required dependency is usually as simple as cargo add pkgname
, then use cratename
in your code.
However, if you try to do this with a package that is already an optional dependency, it will result in rustc telling you to cargo add cratename
, which can be quite confusing.
Proposed Solution
If a cargo add
command is run, and all of the following are true:
- All listed crates already are in Cargo.toml
- No new features were enabled by this command
- The
--optional
flag was not passed - One of the listed crates has
optional = true
already set
A warning should be printed:
Warning: `pkgname` is already added as an optional dependency, use `cargo add pkgname --no-optional` to make it required
Notes
In my case this happened when I revisited a project that I abandoned for several months.
I originally added a dep thinking I would provide optional integration with it, but just now decided it would make more sense as part of the core API.
This lead to a moment of confusion when cargo add
seemingly refused to add the dep, only realizing what was happening when I looked at Cargo.toml
, but in projects with more deps this might not be as obvious.
Another reason this may be confusing is because a similar situation does not happen when doing cargo add --dev pkgname
followed by cargo add pkgname
. I understand this is because dev deps are a separate table and not just a flag, but it can still be a bit unintuitive.