Skip to content

Commit 4d11371

Browse files
committed
Helpful error for confused cargo add arguments
1 parent dd0815e commit 4d11371

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/cargo/ops/cargo_add/mod.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use std::str::FromStr;
1212
use anyhow::Context as _;
1313
use cargo_util::paths;
1414
use cargo_util_schemas::core::PartialVersion;
15+
use cargo_util_schemas::manifest::NameValidationError;
1516
use cargo_util_schemas::manifest::PathBaseName;
1617
use cargo_util_schemas::manifest::RustVersion;
1718
use indexmap::IndexSet;
@@ -104,6 +105,14 @@ pub fn add(workspace: &Workspace<'_>, options: &AddOptions<'_>) -> CargoResult<(
104105
options.gctx,
105106
&mut registry,
106107
)
108+
.map_err(|err| {
109+
if err.is::<NameValidationError>() {
110+
if let Some(note) = spec_fix_suggestion(raw) {
111+
return anyhow::format_err!("{err}\nnote: {note}");
112+
}
113+
}
114+
err
115+
})
107116
})
108117
.collect::<CargoResult<Vec<_>>>()?
109118
};
@@ -329,6 +338,26 @@ pub struct DepOp {
329338
pub tag: Option<String>,
330339
}
331340

341+
fn spec_fix_suggestion(arg: &DepOp) -> Option<&'static str> {
342+
let spec = arg.crate_spec.as_deref()?;
343+
344+
if arg.git.is_none()
345+
&& (spec.starts_with("git@") || spec.starts_with("ssh:") || spec.ends_with(".git"))
346+
{
347+
Some("git URLs must be specified with --git")
348+
} else if arg.registry.is_none()
349+
&& (spec.starts_with("registry+") || spec.starts_with("sparse+"))
350+
{
351+
Some("registy can be specified with --registry")
352+
} else if spec.contains("://") {
353+
Some("`cargo add` expects crates specified as 'name' or 'name@version', not URLs")
354+
} else if arg.path.is_none() && spec.contains('/') {
355+
Some("local crates can be added with --path")
356+
} else {
357+
None
358+
}
359+
}
360+
332361
fn resolve_dependency(
333362
manifest: &LocalManifest,
334363
arg: &DepOp,

0 commit comments

Comments
 (0)