Skip to content

Commit

Permalink
Fix Cargo removing the sparse+ prefix from sparse URLs in .crates.toml
Browse files Browse the repository at this point in the history
  • Loading branch information
arlosi committed Feb 22, 2023
1 parent f3de2de commit b9a3cf4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
16 changes: 15 additions & 1 deletion src/cargo/core/source/source_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ impl SourceId {
///
/// The canonical url will be calculated, but the precise field will not
fn new(kind: SourceKind, url: Url, name: Option<&str>) -> CargoResult<SourceId> {
if kind == SourceKind::SparseRegistry {
assert!(url.as_str().starts_with("sparse+"));
}
let source_id = SourceId::wrap(SourceIdInner {
kind,
canonical_url: CanonicalUrl::new(&url)?,
Expand Down Expand Up @@ -152,7 +155,7 @@ impl SourceId {
.with_precise(Some("locked".to_string())))
}
"sparse" => {
let url = url.into_url()?;
let url = string.into_url()?;
Ok(SourceId::new(SourceKind::SparseRegistry, url, None)?
.with_precise(Some("locked".to_string())))
}
Expand Down Expand Up @@ -721,6 +724,7 @@ impl<'a> fmt::Display for SourceIdAsUrl<'a> {
ref url,
..
} => {
// Sparse registry URL already includes the `sparse+` prefix
write!(f, "{url}")
}
SourceIdInner {
Expand Down Expand Up @@ -864,4 +868,14 @@ mod tests {
assert_eq!(gen_hash(source_id), 17459999773908528552);
assert_eq!(crate::util::hex::short_hash(&source_id), "6568fe2c2fab5bfe");
}

#[test]
fn serde_roundtrip() {
let url = "sparse+https://my-crates.io/".into_url().unwrap();
let source_id = SourceId::for_registry(&url).unwrap();
let formatted = format!("{}", source_id.as_url());
let deserialized = SourceId::from_url(&formatted).unwrap();
assert_eq!(formatted, "sparse+https://my-crates.io/");
assert_eq!(source_id, deserialized);
}
}
13 changes: 1 addition & 12 deletions src/cargo/util/canonical_url.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::util::{errors::CargoResult, IntoUrl};
use crate::util::errors::CargoResult;
use std::hash::{self, Hash};
use url::Url;

Expand Down Expand Up @@ -56,17 +56,6 @@ impl CanonicalUrl {
url.path_segments_mut().unwrap().pop().push(&last);
}

// Ignore the protocol specifier (if any).
if url.scheme().starts_with("sparse+") {
// NOTE: it is illegal to use set_scheme to change sparse+http(s) to http(s).
url = url
.to_string()
.strip_prefix("sparse+")
.expect("we just found that prefix")
.into_url()
.expect("a valid url without a protocol specifier should still be valid");
}

Ok(CanonicalUrl(url))
}

Expand Down

0 comments on commit b9a3cf4

Please sign in to comment.