Avoid panicking on cannot-be-a-base URLs (#2461)

`path_segments_mut` returns an `Err` for cannot-be-a-base URLs. These
won't be valid when we try to fetch them anyway, but we need to avoid a
panic.

Closes https://github.com/astral-sh/uv/issues/2460.
This commit is contained in:
Charlie Marsh 2024-03-14 10:47:16 -07:00 committed by GitHub
parent b50cb3e79e
commit 2fb8df3769
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -21,6 +21,11 @@ impl CanonicalUrl {
pub fn new(url: &Url) -> Self {
let mut url = url.clone();
// If the URL cannot be a base, then it's not a valid URL anyway.
if url.cannot_be_a_base() {
return Self(url);
}
// Strip a trailing slash.
if url.path().ends_with('/') {
url.path_segments_mut().unwrap().pop_if_empty();
@ -194,6 +199,12 @@ mod tests {
)?,
);
// Two URLs that cannot be a base should be considered equal.
assert_eq!(
CanonicalUrl::parse("git+https:://github.com/pypa/sample-namespace-packages.git")?,
CanonicalUrl::parse("git+https:://github.com/pypa/sample-namespace-packages.git")?,
);
Ok(())
}