From 8d721830db8ad75b8b7ef38edc0e346696c52e3d Mon Sep 17 00:00:00 2001 From: danieleades <33452915+danieleades@users.noreply.github.com> Date: Sun, 25 Feb 2024 19:04:05 +0000 Subject: [PATCH] Clippy pedantic (#1963) Address a few pedantic lints lints are separated into separate commits so they can be reviewed individually. I've not added enforcement for any of these lints, but that could be added if desirable. --- crates/cache-key/src/canonical_url.rs | 8 +- crates/distribution-filename/src/lib.rs | 12 +- .../distribution-filename/src/source_dist.rs | 4 +- crates/distribution-filename/src/wheel.rs | 2 +- crates/distribution-types/src/cached.rs | 12 +- crates/distribution-types/src/direct_url.rs | 14 +- crates/distribution-types/src/file.rs | 6 +- crates/distribution-types/src/id.rs | 16 +- crates/distribution-types/src/index_url.rs | 12 +- crates/distribution-types/src/lib.rs | 42 ++--- .../src/prioritized_distribution.rs | 8 +- crates/distribution-types/src/resolution.rs | 14 +- crates/gourgeist/src/lib.rs | 6 +- crates/install-wheel-rs/src/script.rs | 4 +- crates/pep440-rs/src/version.rs | 167 +++++++++--------- crates/pep440-rs/src/version_specifier.rs | 39 ++-- crates/pep508-rs/src/lib.rs | 24 +-- crates/pep508-rs/src/marker.rs | 60 +++---- crates/platform-host/src/lib.rs | 99 ++++++----- crates/platform-tags/src/lib.rs | 10 +- crates/pypi-types/src/direct_url.rs | 14 +- crates/pypi-types/src/metadata.rs | 4 +- crates/pypi-types/src/simple_json.rs | 4 +- crates/requirements-txt/src/lib.rs | 114 +++++------- crates/uv-auth/src/lib.rs | 4 +- crates/uv-build/src/lib.rs | 2 +- crates/uv-cache/src/cli.rs | 8 +- crates/uv-cache/src/lib.rs | 28 +-- crates/uv-cache/src/wheel.rs | 10 +- crates/uv-client/src/cached_client.rs | 47 +++-- crates/uv-client/src/error.rs | 20 +-- crates/uv-client/src/flat_index.rs | 4 +- crates/uv-client/src/html.rs | 4 +- crates/uv-client/src/httpcache/control.rs | 30 ++-- crates/uv-client/src/httpcache/mod.rs | 48 ++--- crates/uv-client/src/registry_client.rs | 8 +- crates/uv-client/src/rkyvutil.rs | 30 ++-- crates/uv-dev/src/install_many.rs | 1 - crates/uv-dev/src/resolve_cli.rs | 5 +- crates/uv-dev/src/resolve_many.rs | 2 +- crates/uv-distribution/src/download.rs | 28 ++- crates/uv-distribution/src/source/mod.rs | 6 +- crates/uv-distribution/src/unzip.rs | 6 +- crates/uv-extract/src/stream.rs | 25 ++- crates/uv-git/src/git.rs | 44 ++--- crates/uv-git/src/known_hosts.rs | 8 +- crates/uv-git/src/util/retry.rs | 4 +- crates/uv-installer/src/site_packages.rs | 22 ++- crates/uv-interpreter/src/python_query.rs | 28 +-- crates/uv-normalize/src/lib.rs | 10 +- crates/uv-normalize/src/package_name.rs | 4 +- crates/uv-resolver/src/candidate_selector.rs | 18 +- crates/uv-resolver/src/error.rs | 6 +- .../uv-resolver/src/pubgrub/dependencies.rs | 12 +- crates/uv-resolver/src/pubgrub/package.rs | 8 +- crates/uv-resolver/src/pubgrub/report.rs | 10 +- crates/uv-resolver/src/python_requirement.rs | 16 +- crates/uv-resolver/src/resolver/mod.rs | 6 +- crates/uv-resolver/src/version_map.rs | 4 +- crates/uv-resolver/src/yanks.rs | 3 +- crates/uv-traits/src/lib.rs | 4 +- crates/uv/src/commands/mod.rs | 6 +- crates/uv/src/commands/pip_sync.rs | 8 +- crates/uv/src/main.rs | 6 +- crates/uv/src/requirements.rs | 48 +++-- crates/uv/tests/common/mod.rs | 2 +- crates/uv/tests/pip_install.rs | 2 +- crates/uv/tests/venv.rs | 18 +- 68 files changed, 635 insertions(+), 673 deletions(-) diff --git a/crates/cache-key/src/canonical_url.rs b/crates/cache-key/src/canonical_url.rs index 86db6af2d..36c15dae4 100644 --- a/crates/cache-key/src/canonical_url.rs +++ b/crates/cache-key/src/canonical_url.rs @@ -18,7 +18,7 @@ use crate::cache_key::{CacheKey, CacheKeyHasher}; pub struct CanonicalUrl(Url); impl CanonicalUrl { - pub fn new(url: &Url) -> CanonicalUrl { + pub fn new(url: &Url) -> Self { let mut url = url.clone(); // Strip a trailing slash. @@ -62,7 +62,7 @@ impl CanonicalUrl { } } - CanonicalUrl(url) + Self(url) } pub fn parse(url: &str) -> Result { @@ -104,7 +104,7 @@ impl std::fmt::Display for CanonicalUrl { pub struct RepositoryUrl(Url); impl RepositoryUrl { - pub fn new(url: &Url) -> RepositoryUrl { + pub fn new(url: &Url) -> Self { let mut url = CanonicalUrl::new(url).0; // If a Git URL ends in a reference (like a branch, tag, or commit), remove it. @@ -122,7 +122,7 @@ impl RepositoryUrl { url.set_fragment(None); url.set_query(None); - RepositoryUrl(url) + Self(url) } pub fn parse(url: &str) -> Result { diff --git a/crates/distribution-filename/src/lib.rs b/crates/distribution-filename/src/lib.rs index 36f7931be..174f78043 100644 --- a/crates/distribution-filename/src/lib.rs +++ b/crates/distribution-filename/src/lib.rs @@ -43,15 +43,15 @@ impl DistFilename { pub fn name(&self) -> &PackageName { match self { - DistFilename::SourceDistFilename(filename) => &filename.name, - DistFilename::WheelFilename(filename) => &filename.name, + Self::SourceDistFilename(filename) => &filename.name, + Self::WheelFilename(filename) => &filename.name, } } pub fn version(&self) -> &Version { match self { - DistFilename::SourceDistFilename(filename) => &filename.version, - DistFilename::WheelFilename(filename) => &filename.version, + Self::SourceDistFilename(filename) => &filename.version, + Self::WheelFilename(filename) => &filename.version, } } } @@ -59,8 +59,8 @@ impl DistFilename { impl Display for DistFilename { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - DistFilename::SourceDistFilename(filename) => Display::fmt(filename, f), - DistFilename::WheelFilename(filename) => Display::fmt(filename, f), + Self::SourceDistFilename(filename) => Display::fmt(filename, f), + Self::WheelFilename(filename) => Display::fmt(filename, f), } } } diff --git a/crates/distribution-filename/src/source_dist.rs b/crates/distribution-filename/src/source_dist.rs index b923cf1df..b9447272d 100644 --- a/crates/distribution-filename/src/source_dist.rs +++ b/crates/distribution-filename/src/source_dist.rs @@ -36,8 +36,8 @@ impl FromStr for SourceDistExtension { impl Display for SourceDistExtension { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - SourceDistExtension::Zip => f.write_str("zip"), - SourceDistExtension::TarGz => f.write_str("tar.gz"), + Self::Zip => f.write_str("zip"), + Self::TarGz => f.write_str("tar.gz"), } } } diff --git a/crates/distribution-filename/src/wheel.rs b/crates/distribution-filename/src/wheel.rs index 97abe0945..7e5dcfe5f 100644 --- a/crates/distribution-filename/src/wheel.rs +++ b/crates/distribution-filename/src/wheel.rs @@ -163,7 +163,7 @@ impl WheelFilename { .map_err(|err| WheelFilenameError::InvalidPackageName(filename.to_string(), err))?; let version = Version::from_str(version) .map_err(|err| WheelFilenameError::InvalidVersion(filename.to_string(), err))?; - Ok(WheelFilename { + Ok(Self { name, version, python_tag: python_tag.split('.').map(String::from).collect(), diff --git a/crates/distribution-types/src/cached.rs b/crates/distribution-types/src/cached.rs index bf55bef95..2a0da761d 100644 --- a/crates/distribution-types/src/cached.rs +++ b/crates/distribution-types/src/cached.rs @@ -89,8 +89,8 @@ impl CachedDist { /// Return the [`DirectUrl`] of the distribution, if it exists. pub fn direct_url(&self) -> Result> { match self { - CachedDist::Registry(_) => Ok(None), - CachedDist::Url(dist) => { + Self::Registry(_) => Ok(None), + Self::Url(dist) => { if dist.editable { assert_eq!(dist.url.scheme(), "file", "{}", dist.url); Ok(Some(DirectUrl::LocalFile(LocalFileUrl { @@ -106,15 +106,15 @@ impl CachedDist { pub fn editable(&self) -> bool { match self { - CachedDist::Registry(_) => false, - CachedDist::Url(dist) => dist.editable, + Self::Registry(_) => false, + Self::Url(dist) => dist.editable, } } pub fn filename(&self) -> &WheelFilename { match self { - CachedDist::Registry(dist) => &dist.filename, - CachedDist::Url(dist) => &dist.filename, + Self::Registry(dist) => &dist.filename, + Self::Url(dist) => &dist.filename, } } } diff --git a/crates/distribution-types/src/direct_url.rs b/crates/distribution-types/src/direct_url.rs index c05144b63..ac7a6060f 100644 --- a/crates/distribution-types/src/direct_url.rs +++ b/crates/distribution-types/src/direct_url.rs @@ -120,9 +120,9 @@ impl TryFrom<&DirectUrl> for pypi_types::DirectUrl { fn try_from(value: &DirectUrl) -> std::result::Result { match value { - DirectUrl::LocalFile(value) => pypi_types::DirectUrl::try_from(value), - DirectUrl::Git(value) => pypi_types::DirectUrl::try_from(value), - DirectUrl::Archive(value) => pypi_types::DirectUrl::try_from(value), + DirectUrl::LocalFile(value) => Self::try_from(value), + DirectUrl::Git(value) => Self::try_from(value), + DirectUrl::Archive(value) => Self::try_from(value), } } } @@ -131,7 +131,7 @@ impl TryFrom<&LocalFileUrl> for pypi_types::DirectUrl { type Error = Error; fn try_from(value: &LocalFileUrl) -> Result { - Ok(pypi_types::DirectUrl::LocalDirectory { + Ok(Self::LocalDirectory { url: value.url.to_string(), dir_info: pypi_types::DirInfo { editable: value.editable.then_some(true), @@ -144,7 +144,7 @@ impl TryFrom<&DirectArchiveUrl> for pypi_types::DirectUrl { type Error = Error; fn try_from(value: &DirectArchiveUrl) -> Result { - Ok(pypi_types::DirectUrl::ArchiveUrl { + Ok(Self::ArchiveUrl { url: value.url.to_string(), archive_info: pypi_types::ArchiveInfo { hash: None, @@ -159,7 +159,7 @@ impl TryFrom<&DirectGitUrl> for pypi_types::DirectUrl { type Error = Error; fn try_from(value: &DirectGitUrl) -> Result { - Ok(pypi_types::DirectUrl::VcsUrl { + Ok(Self::VcsUrl { url: value.url.repository().to_string(), vcs_info: pypi_types::VcsInfo { vcs: pypi_types::VcsKind::Git, @@ -199,7 +199,7 @@ impl From for Url { impl From for Url { fn from(value: DirectGitUrl) -> Self { - let mut url = Url::parse(&format!("{}{}", "git+", Url::from(value.url).as_str())) + let mut url = Self::parse(&format!("{}{}", "git+", Self::from(value.url).as_str())) .expect("Git URL is invalid"); if let Some(subdirectory) = value.subdirectory { url.set_fragment(Some(&format!("subdirectory={}", subdirectory.display()))); diff --git a/crates/distribution-types/src/file.rs b/crates/distribution-types/src/file.rs index 920d144fe..d43f101ee 100644 --- a/crates/distribution-types/src/file.rs +++ b/crates/distribution-types/src/file.rs @@ -85,9 +85,9 @@ pub enum FileLocation { impl Display for FileLocation { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - FileLocation::RelativeUrl(_base, url) => Display::fmt(&url, f), - FileLocation::AbsoluteUrl(url) => Display::fmt(&url, f), - FileLocation::Path(path) => Display::fmt(&path.display(), f), + Self::RelativeUrl(_base, url) => Display::fmt(&url, f), + Self::AbsoluteUrl(url) => Display::fmt(&url, f), + Self::Path(path) => Display::fmt(&path.display(), f), } } } diff --git a/crates/distribution-types/src/id.rs b/crates/distribution-types/src/id.rs index 1fb83ab7e..c6e2a2a8b 100644 --- a/crates/distribution-types/src/id.rs +++ b/crates/distribution-types/src/id.rs @@ -27,8 +27,8 @@ impl PackageId { impl Display for PackageId { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - PackageId::NameVersion(name, version) => write!(f, "{name}-{version}"), - PackageId::Url(url) => write!(f, "{url}"), + Self::NameVersion(name, version) => write!(f, "{name}-{version}"), + Self::Url(url) => write!(f, "{url}"), } } } @@ -59,23 +59,23 @@ impl ResourceId { } } -impl From<&PackageId> for PackageId { +impl From<&Self> for PackageId { /// Required for `WaitMap::wait`. - fn from(value: &PackageId) -> Self { + fn from(value: &Self) -> Self { value.clone() } } -impl From<&DistributionId> for DistributionId { +impl From<&Self> for DistributionId { /// Required for `WaitMap::wait`. - fn from(value: &DistributionId) -> Self { + fn from(value: &Self) -> Self { value.clone() } } -impl From<&ResourceId> for ResourceId { +impl From<&Self> for ResourceId { /// Required for `WaitMap::wait`. - fn from(value: &ResourceId) -> Self { + fn from(value: &Self) -> Self { value.clone() } } diff --git a/crates/distribution-types/src/index_url.rs b/crates/distribution-types/src/index_url.rs index e884a3531..d6de0829a 100644 --- a/crates/distribution-types/src/index_url.rs +++ b/crates/distribution-types/src/index_url.rs @@ -23,8 +23,8 @@ pub enum IndexUrl { impl Display for IndexUrl { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - IndexUrl::Pypi => Display::fmt(&*PYPI_URL, f), - IndexUrl::Url(url) => Display::fmt(url, f), + Self::Pypi => Display::fmt(&*PYPI_URL, f), + Self::Url(url) => Display::fmt(url, f), } } } @@ -61,8 +61,8 @@ impl Deref for IndexUrl { fn deref(&self) -> &Self::Target { match &self { - IndexUrl::Pypi => &PYPI_URL, - IndexUrl::Url(url) => url, + Self::Pypi => &PYPI_URL, + Self::Url(url) => url, } } } @@ -123,8 +123,8 @@ impl FromStr for FlatIndexLocation { impl Display for FlatIndexLocation { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - FlatIndexLocation::Path(path) => Display::fmt(&path.display(), f), - FlatIndexLocation::Url(url) => Display::fmt(url, f), + Self::Path(path) => Display::fmt(&path.display(), f), + Self::Url(url) => Display::fmt(url, f), } } } diff --git a/crates/distribution-types/src/lib.rs b/crates/distribution-types/src/lib.rs index 931f7cc36..06c4e9abd 100644 --- a/crates/distribution-types/src/lib.rs +++ b/crates/distribution-types/src/lib.rs @@ -342,15 +342,15 @@ impl Dist { /// Returns the [`File`] instance, if this dist is from a registry with simple json api support pub fn file(&self) -> Option<&File> { match self { - Dist::Built(built) => built.file(), - Dist::Source(source) => source.file(), + Self::Built(built) => built.file(), + Self::Source(source) => source.file(), } } pub fn version(&self) -> Option<&Version> { match self { - Dist::Built(wheel) => Some(wheel.version()), - Dist::Source(source_dist) => source_dist.version(), + Self::Built(wheel) => Some(wheel.version()), + Self::Source(source_dist) => source_dist.version(), } } } @@ -359,16 +359,16 @@ impl BuiltDist { /// Returns the [`File`] instance, if this dist is from a registry with simple json api support pub fn file(&self) -> Option<&File> { match self { - BuiltDist::Registry(registry) => Some(®istry.file), - BuiltDist::DirectUrl(_) | BuiltDist::Path(_) => None, + Self::Registry(registry) => Some(®istry.file), + Self::DirectUrl(_) | Self::Path(_) => None, } } pub fn version(&self) -> &Version { match self { - BuiltDist::Registry(wheel) => &wheel.filename.version, - BuiltDist::DirectUrl(wheel) => &wheel.filename.version, - BuiltDist::Path(wheel) => &wheel.filename.version, + Self::Registry(wheel) => &wheel.filename.version, + Self::DirectUrl(wheel) => &wheel.filename.version, + Self::Path(wheel) => &wheel.filename.version, } } } @@ -377,26 +377,26 @@ impl SourceDist { /// Returns the [`File`] instance, if this dist is from a registry with simple json api support pub fn file(&self) -> Option<&File> { match self { - SourceDist::Registry(registry) => Some(®istry.file), - SourceDist::DirectUrl(_) | SourceDist::Git(_) | SourceDist::Path(_) => None, + Self::Registry(registry) => Some(®istry.file), + Self::DirectUrl(_) | Self::Git(_) | Self::Path(_) => None, } } pub fn version(&self) -> Option<&Version> { match self { - SourceDist::Registry(source_dist) => Some(&source_dist.filename.version), - SourceDist::DirectUrl(_) | SourceDist::Git(_) | SourceDist::Path(_) => None, + Self::Registry(source_dist) => Some(&source_dist.filename.version), + Self::DirectUrl(_) | Self::Git(_) | Self::Path(_) => None, } } #[must_use] pub fn with_url(self, url: Url) -> Self { match self { - SourceDist::DirectUrl(dist) => SourceDist::DirectUrl(DirectUrlSourceDist { + Self::DirectUrl(dist) => Self::DirectUrl(DirectUrlSourceDist { url: VerbatimUrl::unknown(url), ..dist }), - SourceDist::Git(dist) => SourceDist::Git(GitSourceDist { + Self::Git(dist) => Self::Git(GitSourceDist { url: VerbatimUrl::unknown(url), ..dist }), @@ -799,17 +799,17 @@ impl Identifier for (&Url, &str) { impl Identifier for FileLocation { fn distribution_id(&self) -> DistributionId { match self { - FileLocation::RelativeUrl(base, url) => (base.as_str(), url.as_str()).distribution_id(), - FileLocation::AbsoluteUrl(url) => url.distribution_id(), - FileLocation::Path(path) => path.distribution_id(), + Self::RelativeUrl(base, url) => (base.as_str(), url.as_str()).distribution_id(), + Self::AbsoluteUrl(url) => url.distribution_id(), + Self::Path(path) => path.distribution_id(), } } fn resource_id(&self) -> ResourceId { match self { - FileLocation::RelativeUrl(base, url) => (base.as_str(), url.as_str()).resource_id(), - FileLocation::AbsoluteUrl(url) => url.resource_id(), - FileLocation::Path(path) => path.resource_id(), + Self::RelativeUrl(base, url) => (base.as_str(), url.as_str()).resource_id(), + Self::AbsoluteUrl(url) => url.resource_id(), + Self::Path(path) => path.resource_id(), } } } diff --git a/crates/distribution-types/src/prioritized_distribution.rs b/crates/distribution-types/src/prioritized_distribution.rs index fff9ea2de..9569c710b 100644 --- a/crates/distribution-types/src/prioritized_distribution.rs +++ b/crates/distribution-types/src/prioritized_distribution.rs @@ -326,7 +326,7 @@ impl Ord for WheelCompatibility { impl PartialOrd for WheelCompatibility { fn partial_cmp(&self, other: &Self) -> Option { - Some(WheelCompatibility::cmp(self, other)) + Some(Self::cmp(self, other)) } } @@ -339,10 +339,8 @@ impl WheelCompatibility { impl From for WheelCompatibility { fn from(value: TagCompatibility) -> Self { match value { - TagCompatibility::Compatible(priority) => WheelCompatibility::Compatible(priority), - TagCompatibility::Incompatible(tag) => { - WheelCompatibility::Incompatible(IncompatibleWheel::Tag(tag)) - } + TagCompatibility::Compatible(priority) => Self::Compatible(priority), + TagCompatibility::Incompatible(tag) => Self::Incompatible(IncompatibleWheel::Tag(tag)), } } } diff --git a/crates/distribution-types/src/resolution.rs b/crates/distribution-types/src/resolution.rs index b9ed2baed..94efd5efc 100644 --- a/crates/distribution-types/src/resolution.rs +++ b/crates/distribution-types/src/resolution.rs @@ -64,7 +64,7 @@ impl Resolution { impl From for Requirement { fn from(dist: Dist) -> Self { match dist { - Dist::Built(BuiltDist::Registry(wheel)) => Requirement { + Dist::Built(BuiltDist::Registry(wheel)) => Self { name: wheel.filename.name, extras: vec![], version_or_url: Some(pep508_rs::VersionOrUrl::VersionSpecifier( @@ -74,19 +74,19 @@ impl From for Requirement { )), marker: None, }, - Dist::Built(BuiltDist::DirectUrl(wheel)) => Requirement { + Dist::Built(BuiltDist::DirectUrl(wheel)) => Self { name: wheel.filename.name, extras: vec![], version_or_url: Some(pep508_rs::VersionOrUrl::Url(wheel.url)), marker: None, }, - Dist::Built(BuiltDist::Path(wheel)) => Requirement { + Dist::Built(BuiltDist::Path(wheel)) => Self { name: wheel.filename.name, extras: vec![], version_or_url: Some(pep508_rs::VersionOrUrl::Url(wheel.url)), marker: None, }, - Dist::Source(SourceDist::Registry(sdist)) => Requirement { + Dist::Source(SourceDist::Registry(sdist)) => Self { name: sdist.filename.name, extras: vec![], version_or_url: Some(pep508_rs::VersionOrUrl::VersionSpecifier( @@ -96,19 +96,19 @@ impl From for Requirement { )), marker: None, }, - Dist::Source(SourceDist::DirectUrl(sdist)) => Requirement { + Dist::Source(SourceDist::DirectUrl(sdist)) => Self { name: sdist.name, extras: vec![], version_or_url: Some(pep508_rs::VersionOrUrl::Url(sdist.url)), marker: None, }, - Dist::Source(SourceDist::Git(sdist)) => Requirement { + Dist::Source(SourceDist::Git(sdist)) => Self { name: sdist.name, extras: vec![], version_or_url: Some(pep508_rs::VersionOrUrl::Url(sdist.url)), marker: None, }, - Dist::Source(SourceDist::Path(sdist)) => Requirement { + Dist::Source(SourceDist::Path(sdist)) => Self { name: sdist.name, extras: vec![], version_or_url: Some(pep508_rs::VersionOrUrl::Url(sdist.url)), diff --git a/crates/gourgeist/src/lib.rs b/crates/gourgeist/src/lib.rs index 49e140f8c..9ba067bda 100644 --- a/crates/gourgeist/src/lib.rs +++ b/crates/gourgeist/src/lib.rs @@ -39,9 +39,9 @@ impl Prompt { /// Determine the prompt value to be used from the command line arguments. pub fn from_args(prompt: Option) -> Self { match prompt { - Some(prompt) if prompt == "." => Prompt::CurrentDirectoryName, - Some(prompt) => Prompt::Static(prompt), - None => Prompt::None, + Some(prompt) if prompt == "." => Self::CurrentDirectoryName, + Some(prompt) => Self::Static(prompt), + None => Self::None, } } } diff --git a/crates/install-wheel-rs/src/script.rs b/crates/install-wheel-rs/src/script.rs index 99df8c8ce..be4cb0a8d 100644 --- a/crates/install-wheel-rs/src/script.rs +++ b/crates/install-wheel-rs/src/script.rs @@ -40,7 +40,7 @@ impl Script { script_name: &str, value: &str, extras: Option<&[String]>, - ) -> Result, Error> { + ) -> Result, Error> { // "Within a value, readers must accept and ignore spaces (including multiple consecutive spaces) before or after the colon, // between the object reference and the left square bracket, between the extra names and the square brackets and colons delimiting them, // and after the right square bracket." @@ -65,7 +65,7 @@ impl Script { } } - Ok(Some(Script { + Ok(Some(Self { script_name: script_name.to_string(), module: captures.name("module").unwrap().as_str().to_string(), function: captures.name("function").unwrap().as_str().to_string(), diff --git a/crates/pep440-rs/src/version.rs b/crates/pep440-rs/src/version.rs index 2cc80b190..35dc47162 100644 --- a/crates/pep440-rs/src/version.rs +++ b/crates/pep440-rs/src/version.rs @@ -66,13 +66,13 @@ impl Operator { pub(crate) fn is_local_compatible(&self) -> bool { !matches!( *self, - Operator::GreaterThan - | Operator::GreaterThanEqual - | Operator::LessThan - | Operator::LessThanEqual - | Operator::TildeEqual - | Operator::EqualStar - | Operator::NotEqualStar + Self::GreaterThan + | Self::GreaterThanEqual + | Self::LessThan + | Self::LessThanEqual + | Self::TildeEqual + | Self::EqualStar + | Self::NotEqualStar ) } @@ -80,10 +80,10 @@ impl Operator { /// /// This returns `None` when this operator doesn't have an analogous /// wildcard operator. - pub(crate) fn to_star(self) -> Option { + pub(crate) fn to_star(self) -> Option { match self { - Operator::Equal => Some(Operator::EqualStar), - Operator::NotEqual => Some(Operator::NotEqualStar), + Self::Equal => Some(Self::EqualStar), + Self::NotEqual => Some(Self::NotEqualStar), _ => None, } } @@ -124,18 +124,18 @@ impl std::fmt::Display for Operator { /// Note the `EqualStar` is also `==`. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let operator = match self { - Operator::Equal => "==", + Self::Equal => "==", // Beware, this doesn't print the star - Operator::EqualStar => "==", + Self::EqualStar => "==", #[allow(deprecated)] - Operator::ExactEqual => "===", - Operator::NotEqual => "!=", - Operator::NotEqualStar => "!=", - Operator::TildeEqual => "~=", - Operator::LessThan => "<", - Operator::LessThanEqual => "<=", - Operator::GreaterThan => ">", - Operator::GreaterThanEqual => ">=", + Self::ExactEqual => "===", + Self::NotEqual => "!=", + Self::NotEqualStar => "!=", + Self::TildeEqual => "~=", + Self::LessThan => "<", + Self::LessThanEqual => "<=", + Self::GreaterThan => ">", + Self::GreaterThanEqual => ">=", }; write!(f, "{operator}") @@ -285,12 +285,12 @@ impl Version { /// /// When the iterator yields no elements. #[inline] - pub fn new(release_numbers: I) -> Version + pub fn new(release_numbers: I) -> Self where I: IntoIterator, R: Borrow, { - Version { + Self { inner: Arc::new(VersionInner::Small { small: VersionSmall::new(), }), @@ -409,7 +409,7 @@ impl Version { /// /// When the iterator yields no elements. #[inline] - pub fn with_release(mut self, release_numbers: I) -> Version + pub fn with_release(mut self, release_numbers: I) -> Self where I: IntoIterator, R: Borrow, @@ -453,7 +453,7 @@ impl Version { /// Set the epoch and return the updated version. #[inline] - pub fn with_epoch(mut self, value: u64) -> Version { + pub fn with_epoch(mut self, value: u64) -> Self { if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) { if small.set_epoch(value) { return self; @@ -465,7 +465,7 @@ impl Version { /// Set the pre-release component and return the updated version. #[inline] - pub fn with_pre(mut self, value: Option) -> Version { + pub fn with_pre(mut self, value: Option) -> Self { if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) { if small.set_pre(value) { return self; @@ -477,7 +477,7 @@ impl Version { /// Set the post-release component and return the updated version. #[inline] - pub fn with_post(mut self, value: Option) -> Version { + pub fn with_post(mut self, value: Option) -> Self { if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) { if small.set_post(value) { return self; @@ -489,7 +489,7 @@ impl Version { /// Set the dev-release component and return the updated version. #[inline] - pub fn with_dev(mut self, value: Option) -> Version { + pub fn with_dev(mut self, value: Option) -> Self { if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) { if small.set_dev(value) { return self; @@ -501,7 +501,7 @@ impl Version { /// Set the local segments and return the updated version. #[inline] - pub fn with_local(mut self, value: Vec) -> Version { + pub fn with_local(mut self, value: Vec) -> Self { if value.is_empty() { self.without_local() } else { @@ -515,7 +515,7 @@ impl Version { /// and local version labels MUST be ignored entirely when checking if /// candidate versions match a given version specifier." #[inline] - pub fn without_local(mut self) -> Version { + pub fn without_local(mut self) -> Self { // A "small" version is already guaranteed not to have a local // component, so we only need to do anything if we have a "full" // version. @@ -531,7 +531,7 @@ impl Version { /// The version `1.0min0` is smaller than all other `1.0` versions, /// like `1.0a1`, `1.0dev0`, etc. #[inline] - pub fn with_min(mut self, value: Option) -> Version { + pub fn with_min(mut self, value: Option) -> Self { if let VersionInner::Small { ref mut small } = Arc::make_mut(&mut self.inner) { if small.set_min(value) { return self; @@ -554,7 +554,7 @@ impl Version { dev: small.dev(), local: vec![], }; - *self = Version { + *self = Self { inner: Arc::new(VersionInner::Full { full }), }; } @@ -572,7 +572,7 @@ impl Version { /// representation. #[cold] #[inline(never)] - fn cmp_slow(&self, other: &Version) -> Ordering { + fn cmp_slow(&self, other: &Self) -> Ordering { match self.epoch().cmp(&other.epoch()) { Ordering::Less => { return Ordering::Less; @@ -666,7 +666,7 @@ impl std::fmt::Display for Version { impl std::fmt::Debug for Version { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "\"{}\"", self) + write!(f, "\"{self}\"") } } @@ -853,8 +853,8 @@ impl VersionSmall { const SUFFIX_MAX_VERSION: u64 = 0x1FFFFF; #[inline] - fn new() -> VersionSmall { - VersionSmall { + fn new() -> Self { + Self { repr: 0x00000000_00A00000, release: [0, 0, 0, 0], len: 0, @@ -913,7 +913,7 @@ impl VersionSmall { #[inline] fn post(&self) -> Option { - if self.suffix_kind() == VersionSmall::SUFFIX_POST { + if self.suffix_kind() == Self::SUFFIX_POST { Some(self.suffix_version()) } else { None @@ -927,13 +927,13 @@ impl VersionSmall { } match value { None => { - self.set_suffix_kind(VersionSmall::SUFFIX_NONE); + self.set_suffix_kind(Self::SUFFIX_NONE); } Some(number) => { - if number > VersionSmall::SUFFIX_MAX_VERSION { + if number > Self::SUFFIX_MAX_VERSION { return false; } - self.set_suffix_kind(VersionSmall::SUFFIX_POST); + self.set_suffix_kind(Self::SUFFIX_POST); self.set_suffix_version(number); } } @@ -943,17 +943,17 @@ impl VersionSmall { #[inline] fn pre(&self) -> Option { let (kind, number) = (self.suffix_kind(), self.suffix_version()); - if kind == VersionSmall::SUFFIX_PRE_ALPHA { + if kind == Self::SUFFIX_PRE_ALPHA { Some(PreRelease { kind: PreReleaseKind::Alpha, number, }) - } else if kind == VersionSmall::SUFFIX_PRE_BETA { + } else if kind == Self::SUFFIX_PRE_BETA { Some(PreRelease { kind: PreReleaseKind::Beta, number, }) - } else if kind == VersionSmall::SUFFIX_PRE_RC { + } else if kind == Self::SUFFIX_PRE_RC { Some(PreRelease { kind: PreReleaseKind::Rc, number, @@ -970,21 +970,21 @@ impl VersionSmall { } match value { None => { - self.set_suffix_kind(VersionSmall::SUFFIX_NONE); + self.set_suffix_kind(Self::SUFFIX_NONE); } Some(PreRelease { kind, number }) => { - if number > VersionSmall::SUFFIX_MAX_VERSION { + if number > Self::SUFFIX_MAX_VERSION { return false; } match kind { PreReleaseKind::Alpha => { - self.set_suffix_kind(VersionSmall::SUFFIX_PRE_ALPHA); + self.set_suffix_kind(Self::SUFFIX_PRE_ALPHA); } PreReleaseKind::Beta => { - self.set_suffix_kind(VersionSmall::SUFFIX_PRE_BETA); + self.set_suffix_kind(Self::SUFFIX_PRE_BETA); } PreReleaseKind::Rc => { - self.set_suffix_kind(VersionSmall::SUFFIX_PRE_RC); + self.set_suffix_kind(Self::SUFFIX_PRE_RC); } } self.set_suffix_version(number); @@ -995,7 +995,7 @@ impl VersionSmall { #[inline] fn dev(&self) -> Option { - if self.suffix_kind() == VersionSmall::SUFFIX_DEV { + if self.suffix_kind() == Self::SUFFIX_DEV { Some(self.suffix_version()) } else { None @@ -1009,13 +1009,13 @@ impl VersionSmall { } match value { None => { - self.set_suffix_kind(VersionSmall::SUFFIX_NONE); + self.set_suffix_kind(Self::SUFFIX_NONE); } Some(number) => { - if number > VersionSmall::SUFFIX_MAX_VERSION { + if number > Self::SUFFIX_MAX_VERSION { return false; } - self.set_suffix_kind(VersionSmall::SUFFIX_DEV); + self.set_suffix_kind(Self::SUFFIX_DEV); self.set_suffix_version(number); } } @@ -1024,7 +1024,7 @@ impl VersionSmall { #[inline] fn min(&self) -> Option { - if self.suffix_kind() == VersionSmall::SUFFIX_MIN { + if self.suffix_kind() == Self::SUFFIX_MIN { Some(self.suffix_version()) } else { None @@ -1038,13 +1038,13 @@ impl VersionSmall { } match value { None => { - self.set_suffix_kind(VersionSmall::SUFFIX_NONE); + self.set_suffix_kind(Self::SUFFIX_NONE); } Some(number) => { - if number > VersionSmall::SUFFIX_MAX_VERSION { + if number > Self::SUFFIX_MAX_VERSION { return false; } - self.set_suffix_kind(VersionSmall::SUFFIX_MIN); + self.set_suffix_kind(Self::SUFFIX_MIN); self.set_suffix_version(number); } } @@ -1061,16 +1061,16 @@ impl VersionSmall { #[inline] fn suffix_kind(&self) -> u64 { let kind = (self.repr >> 21) & 0b111; - debug_assert!(kind <= VersionSmall::SUFFIX_POST); + debug_assert!(kind <= Self::SUFFIX_POST); kind } #[inline] fn set_suffix_kind(&mut self, kind: u64) { - debug_assert!(kind <= VersionSmall::SUFFIX_POST); + debug_assert!(kind <= Self::SUFFIX_POST); self.repr &= !0xE00000; self.repr |= kind << 21; - if kind == VersionSmall::SUFFIX_NONE { + if kind == Self::SUFFIX_NONE { self.set_suffix_version(0); } } @@ -1176,8 +1176,8 @@ impl VersionPattern { /// Creates a new verbatim version pattern that matches the given /// version exactly. #[inline] - pub fn verbatim(version: Version) -> VersionPattern { - VersionPattern { + pub fn verbatim(version: Version) -> Self { + Self { version, wildcard: false, } @@ -1186,8 +1186,8 @@ impl VersionPattern { /// Creates a new wildcard version pattern that matches any version with /// the given version as a prefix. #[inline] - pub fn wildcard(version: Version) -> VersionPattern { - VersionPattern { + pub fn wildcard(version: Version) -> Self { + Self { version, wildcard: true, } @@ -1215,7 +1215,7 @@ impl VersionPattern { impl FromStr for VersionPattern { type Err = VersionPatternParseError; - fn from_str(version: &str) -> Result { + fn from_str(version: &str) -> Result { Parser::new(version.as_bytes()).parse_pattern() } } @@ -1835,8 +1835,8 @@ enum ReleaseNumbers { impl ReleaseNumbers { /// Create a new empty set of release numbers. - fn new() -> ReleaseNumbers { - ReleaseNumbers::Inline { + fn new() -> Self { + Self::Inline { numbers: [0; 4], len: 0, } @@ -1846,7 +1846,7 @@ impl ReleaseNumbers { /// when the lengths grow too big. fn push(&mut self, n: u64) { match *self { - ReleaseNumbers::Inline { + Self::Inline { ref mut numbers, ref mut len, } => { @@ -1854,13 +1854,13 @@ impl ReleaseNumbers { if *len == 4 { let mut numbers = numbers.to_vec(); numbers.push(n); - *self = ReleaseNumbers::Vec(numbers.to_vec()); + *self = Self::Vec(numbers.clone()); } else { numbers[*len] = n; *len += 1; } } - ReleaseNumbers::Vec(ref mut numbers) => { + Self::Vec(ref mut numbers) => { numbers.push(n); } } @@ -1874,8 +1874,8 @@ impl ReleaseNumbers { /// Returns the release components as a slice. fn as_slice(&self) -> &[u64] { match *self { - ReleaseNumbers::Inline { ref numbers, len } => &numbers[..len], - ReleaseNumbers::Vec(ref vec) => vec, + Self::Inline { ref numbers, len } => &numbers[..len], + Self::Vec(ref vec) => vec, } } } @@ -1899,7 +1899,7 @@ impl StringSet { /// # Panics /// /// When the number of strings is too big. - const fn new(strings: &'static [&'static str]) -> StringSet { + const fn new(strings: &'static [&'static str]) -> Self { assert!( strings.len() <= 20, "only a small number of strings are supported" @@ -1916,7 +1916,7 @@ impl StringSet { i += 1; } let first_byte = ByteSet::new(&firsts); - StringSet { + Self { first_byte, strings, } @@ -1945,7 +1945,7 @@ struct ByteSet { impl ByteSet { /// Create a new byte set for searching from the given bytes. - const fn new(bytes: &[u8]) -> ByteSet { + const fn new(bytes: &[u8]) -> Self { let mut set = [false; 256]; let mut i = 0; while i < bytes.len() { @@ -1953,7 +1953,7 @@ impl ByteSet { set[bytes[i].to_ascii_lowercase() as usize] = true; i += 1; } - ByteSet { set } + Self { set } } /// Returns the first byte in the haystack if and only if that byte is in @@ -2003,8 +2003,7 @@ impl std::fmt::Display for VersionParseError { ErrorKind::InvalidDigit { got } => { write!( f, - "expected ASCII digit, but found non-ASCII byte \\x{:02X}", - got + "expected ASCII digit, but found non-ASCII byte \\x{got:02X}" ) } ErrorKind::NumberTooBig { ref bytes } => { @@ -2097,8 +2096,8 @@ pub(crate) enum ErrorKind { } impl From for VersionParseError { - fn from(kind: ErrorKind) -> VersionParseError { - VersionParseError { + fn from(kind: ErrorKind) -> Self { + Self { kind: Box::new(kind), } } @@ -2131,22 +2130,22 @@ pub(crate) enum PatternErrorKind { } impl From for VersionPatternParseError { - fn from(kind: PatternErrorKind) -> VersionPatternParseError { - VersionPatternParseError { + fn from(kind: PatternErrorKind) -> Self { + Self { kind: Box::new(kind), } } } impl From for VersionPatternParseError { - fn from(kind: ErrorKind) -> VersionPatternParseError { - VersionPatternParseError::from(VersionParseError::from(kind)) + fn from(kind: ErrorKind) -> Self { + Self::from(VersionParseError::from(kind)) } } impl From for VersionPatternParseError { - fn from(err: VersionParseError) -> VersionPatternParseError { - VersionPatternParseError { + fn from(err: VersionParseError) -> Self { + Self { kind: Box::new(PatternErrorKind::Version(err)), } } diff --git a/crates/pep440-rs/src/version_specifier.rs b/crates/pep440-rs/src/version_specifier.rs index 946f361be..2b2ad756b 100644 --- a/crates/pep440-rs/src/version_specifier.rs +++ b/crates/pep440-rs/src/version_specifier.rs @@ -223,8 +223,8 @@ impl std::fmt::Display for VersionSpecifiersParseError { start, end, } = *self.inner; - writeln!(f, "Failed to parse version: {}:", err)?; - writeln!(f, "{}", line)?; + writeln!(f, "Failed to parse version: {err}:")?; + writeln!(f, "{line}")?; let indent = line[..start].width(); let point = line[start..end].width(); writeln!(f, "{}{}", " ".repeat(indent), "^".repeat(point))?; @@ -548,7 +548,7 @@ impl FromStr for VersionSpecifier { } let vpat = version.parse().map_err(ParseErrorKind::InvalidVersion)?; let version_specifier = - VersionSpecifier::new(operator, vpat).map_err(ParseErrorKind::InvalidSpecifier)?; + Self::new(operator, vpat).map_err(ParseErrorKind::InvalidSpecifier)?; s.eat_while(|c: char| c.is_whitespace()); if !s.done() { return Err(ParseErrorKind::InvalidTrailing(s.after().to_string()).into()); @@ -636,8 +636,8 @@ enum BuildErrorKind { } impl From for VersionSpecifierBuildError { - fn from(kind: BuildErrorKind) -> VersionSpecifierBuildError { - VersionSpecifierBuildError { + fn from(kind: BuildErrorKind) -> Self { + Self { kind: Box::new(kind), } } @@ -690,8 +690,8 @@ enum ParseErrorKind { } impl From for VersionSpecifierParseError { - fn from(kind: ParseErrorKind) -> VersionSpecifierParseError { - VersionSpecifierParseError { + fn from(kind: ParseErrorKind) -> Self { + Self { kind: Box::new(kind), } } @@ -828,7 +828,7 @@ mod tests { // Below we'll generate every possible combination of VERSIONS_ALL that // should be true for the given operator - let operations: Vec<_> = [ + let operations = [ // Verify that the less than (<) operator works correctly versions .iter() @@ -852,8 +852,7 @@ mod tests { .collect::>(), ] .into_iter() - .flatten() - .collect(); + .flatten(); for (a, b, ordering) in operations { assert_eq!(a.cmp(b), ordering, "{a} {ordering:?} {b}"); @@ -984,24 +983,20 @@ mod tests { /// Well, except for #[test] fn test_operators_other() { - let versions: Vec = VERSIONS_0 + let versions = VERSIONS_0 .iter() - .map(|version| Version::from_str(version).unwrap()) - .collect(); + .map(|version| Version::from_str(version).unwrap()); let specifiers: Vec<_> = SPECIFIERS_OTHER .iter() .map(|specifier| VersionSpecifier::from_str(specifier).unwrap()) .collect(); - for (version, expected) in versions.iter().zip(EXPECTED_OTHER) { + for (version, expected) in versions.zip(EXPECTED_OTHER) { let actual = specifiers .iter() - .map(|specifier| specifier.contains(version)) - .collect::>(); - for ((actual, expected), _specifier) in - actual.iter().zip(expected).zip(SPECIFIERS_OTHER) - { - assert_eq!(actual, expected); + .map(|specifier| specifier.contains(&version)); + for ((actual, expected), _specifier) in actual.zip(expected).zip(SPECIFIERS_OTHER) { + assert_eq!(actual, *expected); } } } @@ -1253,11 +1248,11 @@ mod tests { let result = VersionSpecifiers::from_str("~= 0.9, %‍= 1.0, != 1.3.4.*"); assert_eq!( result.unwrap_err().to_string(), - indoc! {r#" + indoc! {r" Failed to parse version: Unexpected end of version specifier, expected operator: ~= 0.9, %‍= 1.0, != 1.3.4.* ^^^^^^^ - "#} + "} ); } diff --git a/crates/pep508-rs/src/lib.rs b/crates/pep508-rs/src/lib.rs index c590e3fd4..ec3db2057 100644 --- a/crates/pep508-rs/src/lib.rs +++ b/crates/pep508-rs/src/lib.rs @@ -1122,7 +1122,7 @@ mod tests { #[test] fn basic_examples() { - let input = r#"requests[security,tests] >=2.8.1, ==2.8.* ; python_version < '2.7'"#; + let input = r"requests[security,tests] >=2.8.1, ==2.8.* ; python_version < '2.7'"; let requests = Requirement::from_str(input).unwrap(); assert_eq!(input, requests.to_string()); let expected = Requirement { @@ -1364,7 +1364,7 @@ mod tests { #[test] fn error_marker_incomplete1() { assert_err( - r#"numpy; sys_platform"#, + r"numpy; sys_platform", indoc! {" Expected a valid marker operator (such as '>=' or 'not in'), found '' numpy; sys_platform @@ -1376,7 +1376,7 @@ mod tests { #[test] fn error_marker_incomplete2() { assert_err( - r#"numpy; sys_platform =="#, + r"numpy; sys_platform ==", indoc! {"\ Expected marker value, found end of dependency specification numpy; sys_platform == @@ -1421,7 +1421,7 @@ mod tests { #[test] fn error_pep440() { assert_err( - r#"numpy >=1.1.*"#, + r"numpy >=1.1.*", indoc! {" Operator >= cannot be used with a wildcard version specifier numpy >=1.1.* @@ -1433,7 +1433,7 @@ mod tests { #[test] fn error_no_name() { assert_err( - r#"==0.0"#, + r"==0.0", indoc! {" Expected package name starting with an alphanumeric character, found '=' ==0.0 @@ -1445,7 +1445,7 @@ mod tests { #[test] fn error_bare_url() { assert_err( - r#"git+https://github.com/pallets/flask.git"#, + r"git+https://github.com/pallets/flask.git", indoc! {" URL requirement must be preceded by a package name. Add the name of the package before the URL (e.g., `package_name @ https://...`). git+https://github.com/pallets/flask.git @@ -1457,7 +1457,7 @@ mod tests { #[test] fn error_no_comma_between_extras() { assert_err( - r#"name[bar baz]"#, + r"name[bar baz]", indoc! {" Expected either ',' (separating extras) or ']' (ending the extras section), found 'b' name[bar baz] @@ -1469,7 +1469,7 @@ mod tests { #[test] fn error_extra_comma_after_extras() { assert_err( - r#"name[bar, baz,]"#, + r"name[bar, baz,]", indoc! {" Expected an alphanumeric character starting the extra name, found ']' name[bar, baz,] @@ -1481,7 +1481,7 @@ mod tests { #[test] fn error_extras_not_closed() { assert_err( - r#"name[bar, baz >= 1.0"#, + r"name[bar, baz >= 1.0", indoc! {" Expected either ',' (separating extras) or ']' (ending the extras section), found '>' name[bar, baz >= 1.0 @@ -1493,7 +1493,7 @@ mod tests { #[test] fn error_no_space_after_url() { assert_err( - r#"name @ https://example.com/; extra == 'example'"#, + r"name @ https://example.com/; extra == 'example'", indoc! {" Missing space before ';', the end of the URL is ambiguous name @ https://example.com/; extra == 'example' @@ -1505,7 +1505,7 @@ mod tests { #[test] fn error_name_at_nothing() { assert_err( - r#"name @"#, + r"name @", indoc! {" Expected URL name @ @@ -1517,7 +1517,7 @@ mod tests { #[test] fn test_error_invalid_marker_key() { assert_err( - r#"name; invalid_name"#, + r"name; invalid_name", indoc! {" Expected a valid marker name, found 'invalid_name' name; invalid_name diff --git a/crates/pep508-rs/src/marker.rs b/crates/pep508-rs/src/marker.rs index f10b690c7..0fce8e3e6 100644 --- a/crates/pep508-rs/src/marker.rs +++ b/crates/pep508-rs/src/marker.rs @@ -235,15 +235,15 @@ impl MarkerOperator { /// Compare two versions, returning None for `in` and `not in` fn to_pep440_operator(&self) -> Option { match self { - MarkerOperator::Equal => Some(pep440_rs::Operator::Equal), - MarkerOperator::NotEqual => Some(pep440_rs::Operator::NotEqual), - MarkerOperator::GreaterThan => Some(pep440_rs::Operator::GreaterThan), - MarkerOperator::GreaterEqual => Some(pep440_rs::Operator::GreaterThanEqual), - MarkerOperator::LessThan => Some(pep440_rs::Operator::LessThan), - MarkerOperator::LessEqual => Some(pep440_rs::Operator::LessThanEqual), - MarkerOperator::TildeEqual => Some(pep440_rs::Operator::TildeEqual), - MarkerOperator::In => None, - MarkerOperator::NotIn => None, + Self::Equal => Some(pep440_rs::Operator::Equal), + Self::NotEqual => Some(pep440_rs::Operator::NotEqual), + Self::GreaterThan => Some(pep440_rs::Operator::GreaterThan), + Self::GreaterEqual => Some(pep440_rs::Operator::GreaterThanEqual), + Self::LessThan => Some(pep440_rs::Operator::LessThan), + Self::LessEqual => Some(pep440_rs::Operator::LessThanEqual), + Self::TildeEqual => Some(pep440_rs::Operator::TildeEqual), + Self::In => None, + Self::NotIn => None, } } } @@ -559,7 +559,7 @@ impl MarkerExpression { &self, env: &MarkerEnvironment, extras: &[ExtraName], - reporter: &mut impl FnMut(MarkerWarningKind, String, &MarkerExpression), + reporter: &mut impl FnMut(MarkerWarningKind, String, &Self), ) -> bool { match &self.l_value { // The only sound choice for this is ` ` @@ -830,7 +830,7 @@ impl MarkerExpression { &self, l_string: &str, r_string: &str, - reporter: &mut impl FnMut(MarkerWarningKind, String, &MarkerExpression), + reporter: &mut impl FnMut(MarkerWarningKind, String, &Self), ) -> bool { match self.operator { MarkerOperator::Equal => l_string == r_string, @@ -885,7 +885,7 @@ impl MarkerExpression { &self, value: &ExtraName, extras: &[ExtraName], - reporter: &mut impl FnMut(MarkerWarningKind, String, &MarkerExpression), + reporter: &mut impl FnMut(MarkerWarningKind, String, &Self), ) -> bool { match self.operator { MarkerOperator::Equal => extras.contains(value), @@ -957,11 +957,11 @@ impl MarkerTree { }; self.report_deprecated_options(&mut reporter); match self { - MarkerTree::Expression(expression) => expression.evaluate(env, extras, &mut reporter), - MarkerTree::And(expressions) => expressions + Self::Expression(expression) => expression.evaluate(env, extras, &mut reporter), + Self::And(expressions) => expressions .iter() .all(|x| x.evaluate_reporter_impl(env, extras, &mut reporter)), - MarkerTree::Or(expressions) => expressions + Self::Or(expressions) => expressions .iter() .any(|x| x.evaluate_reporter_impl(env, extras, &mut reporter)), } @@ -986,11 +986,11 @@ impl MarkerTree { reporter: &mut impl FnMut(MarkerWarningKind, String, &MarkerExpression), ) -> bool { match self { - MarkerTree::Expression(expression) => expression.evaluate(env, extras, reporter), - MarkerTree::And(expressions) => expressions + Self::Expression(expression) => expression.evaluate(env, extras, reporter), + Self::And(expressions) => expressions .iter() .all(|x| x.evaluate_reporter_impl(env, extras, reporter)), - MarkerTree::Or(expressions) => expressions + Self::Or(expressions) => expressions .iter() .any(|x| x.evaluate_reporter_impl(env, extras, reporter)), } @@ -1010,13 +1010,13 @@ impl MarkerTree { python_versions: &[Version], ) -> bool { match self { - MarkerTree::Expression(expression) => { + Self::Expression(expression) => { expression.evaluate_extras_and_python_version(extras, python_versions) } - MarkerTree::And(expressions) => expressions + Self::And(expressions) => expressions .iter() .all(|x| x.evaluate_extras_and_python_version(extras, python_versions)), - MarkerTree::Or(expressions) => expressions + Self::Or(expressions) => expressions .iter() .any(|x| x.evaluate_extras_and_python_version(extras, python_versions)), } @@ -1044,7 +1044,7 @@ impl MarkerTree { reporter: &mut impl FnMut(MarkerWarningKind, String, &MarkerExpression), ) { match self { - MarkerTree::Expression(expression) => { + Self::Expression(expression) => { for value in [&expression.l_value, &expression.r_value] { match value { MarkerValue::MarkerEnvString(MarkerValueString::OsNameDeprecated) => { @@ -1103,12 +1103,12 @@ impl MarkerTree { } } } - MarkerTree::And(expressions) => { + Self::And(expressions) => { for expression in expressions { expression.report_deprecated_options(reporter); } } - MarkerTree::Or(expressions) => { + Self::Or(expressions) => { for expression in expressions { expression.report_deprecated_options(reporter); } @@ -1119,23 +1119,23 @@ impl MarkerTree { impl Display for MarkerTree { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - let format_inner = |expression: &MarkerTree| { - if matches!(expression, MarkerTree::Expression(_)) { + let format_inner = |expression: &Self| { + if matches!(expression, Self::Expression(_)) { format!("{expression}") } else { format!("({expression})") } }; match self { - MarkerTree::Expression(expression) => write!(f, "{expression}"), - MarkerTree::And(and_list) => f.write_str( + Self::Expression(expression) => write!(f, "{expression}"), + Self::And(and_list) => f.write_str( &and_list .iter() .map(format_inner) .collect::>() .join(" and "), ), - MarkerTree::Or(or_list) => f.write_str( + Self::Or(or_list) => f.write_str( &or_list .iter() .map(format_inner) @@ -1392,7 +1392,7 @@ mod test { #[test] fn test_marker_equivalence() { let values = [ - (r#"python_version == '2.7'"#, r#"python_version == "2.7""#), + (r"python_version == '2.7'", r#"python_version == "2.7""#), (r#"python_version == "2.7""#, r#"python_version == "2.7""#), ( r#"python_version == "2.7" and os_name == "posix""#, diff --git a/crates/platform-host/src/lib.rs b/crates/platform-host/src/lib.rs index ebbc61741..5f8b53184 100644 --- a/crates/platform-host/src/lib.rs +++ b/crates/platform-host/src/lib.rs @@ -70,35 +70,50 @@ impl Os { let os = match target_triple.operating_system { target_lexicon::OperatingSystem::Linux => detect_linux_libc()?, - target_lexicon::OperatingSystem::Windows => Os::Windows, + target_lexicon::OperatingSystem::Windows => Self::Windows, target_lexicon::OperatingSystem::MacOSX { major, minor, .. } => { - Os::Macos { major, minor } + Self::Macos { major, minor } } target_lexicon::OperatingSystem::Darwin => { let (major, minor) = get_mac_os_version()?; - Os::Macos { major, minor } + Self::Macos { major, minor } } - target_lexicon::OperatingSystem::Netbsd => Os::NetBsd { - release: Os::platform_info()?.release().to_string_lossy().to_string(), + target_lexicon::OperatingSystem::Netbsd => Self::NetBsd { + release: Self::platform_info()? + .release() + .to_string_lossy() + .to_string(), }, - target_lexicon::OperatingSystem::Freebsd => Os::FreeBsd { - release: Os::platform_info()?.release().to_string_lossy().to_string(), + target_lexicon::OperatingSystem::Freebsd => Self::FreeBsd { + release: Self::platform_info()? + .release() + .to_string_lossy() + .to_string(), }, - target_lexicon::OperatingSystem::Openbsd => Os::OpenBsd { - release: Os::platform_info()?.release().to_string_lossy().to_string(), + target_lexicon::OperatingSystem::Openbsd => Self::OpenBsd { + release: Self::platform_info()? + .release() + .to_string_lossy() + .to_string(), }, - target_lexicon::OperatingSystem::Dragonfly => Os::Dragonfly { - release: Os::platform_info()?.release().to_string_lossy().to_string(), + target_lexicon::OperatingSystem::Dragonfly => Self::Dragonfly { + release: Self::platform_info()? + .release() + .to_string_lossy() + .to_string(), }, target_lexicon::OperatingSystem::Illumos => { - let platform_info = Os::platform_info()?; - Os::Illumos { + let platform_info = Self::platform_info()?; + Self::Illumos { release: platform_info.release().to_string_lossy().to_string(), arch: platform_info.machine().to_string_lossy().to_string(), } } - target_lexicon::OperatingSystem::Haiku => Os::Haiku { - release: Os::platform_info()?.release().to_string_lossy().to_string(), + target_lexicon::OperatingSystem::Haiku => Self::Haiku { + release: Self::platform_info()? + .release() + .to_string_lossy() + .to_string(), }, unsupported => { return Err(PlatformError::OsVersionDetectionError(format!( @@ -117,16 +132,16 @@ impl Os { impl fmt::Display for Os { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Os::Manylinux { .. } => write!(f, "Manylinux"), - Os::Musllinux { .. } => write!(f, "Musllinux"), - Os::Windows => write!(f, "Windows"), - Os::Macos { .. } => write!(f, "MacOS"), - Os::FreeBsd { .. } => write!(f, "FreeBSD"), - Os::NetBsd { .. } => write!(f, "NetBSD"), - Os::OpenBsd { .. } => write!(f, "OpenBSD"), - Os::Dragonfly { .. } => write!(f, "DragonFly"), - Os::Illumos { .. } => write!(f, "Illumos"), - Os::Haiku { .. } => write!(f, "Haiku"), + Self::Manylinux { .. } => write!(f, "Manylinux"), + Self::Musllinux { .. } => write!(f, "Musllinux"), + Self::Windows => write!(f, "Windows"), + Self::Macos { .. } => write!(f, "MacOS"), + Self::FreeBsd { .. } => write!(f, "FreeBSD"), + Self::NetBsd { .. } => write!(f, "NetBSD"), + Self::OpenBsd { .. } => write!(f, "OpenBSD"), + Self::Dragonfly { .. } => write!(f, "DragonFly"), + Self::Illumos { .. } => write!(f, "Illumos"), + Self::Haiku { .. } => write!(f, "Haiku"), } } } @@ -146,28 +161,28 @@ pub enum Arch { impl fmt::Display for Arch { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Arch::Aarch64 => write!(f, "aarch64"), - Arch::Armv7L => write!(f, "armv7l"), - Arch::Powerpc64Le => write!(f, "ppc64le"), - Arch::Powerpc64 => write!(f, "ppc64"), - Arch::X86 => write!(f, "i686"), - Arch::X86_64 => write!(f, "x86_64"), - Arch::S390X => write!(f, "s390x"), + Self::Aarch64 => write!(f, "aarch64"), + Self::Armv7L => write!(f, "armv7l"), + Self::Powerpc64Le => write!(f, "ppc64le"), + Self::Powerpc64 => write!(f, "ppc64"), + Self::X86 => write!(f, "i686"), + Self::X86_64 => write!(f, "x86_64"), + Self::S390X => write!(f, "s390x"), } } } impl Arch { - pub fn current() -> Result { + pub fn current() -> Result { let target_triple = target_lexicon::HOST; let arch = match target_triple.architecture { - target_lexicon::Architecture::X86_64 => Arch::X86_64, - target_lexicon::Architecture::X86_32(_) => Arch::X86, - target_lexicon::Architecture::Arm(_) => Arch::Armv7L, - target_lexicon::Architecture::Aarch64(_) => Arch::Aarch64, - target_lexicon::Architecture::Powerpc64 => Arch::Powerpc64, - target_lexicon::Architecture::Powerpc64le => Arch::Powerpc64Le, - target_lexicon::Architecture::S390x => Arch::S390X, + target_lexicon::Architecture::X86_64 => Self::X86_64, + target_lexicon::Architecture::X86_32(_) => Self::X86, + target_lexicon::Architecture::Arm(_) => Self::Armv7L, + target_lexicon::Architecture::Aarch64(_) => Self::Aarch64, + target_lexicon::Architecture::Powerpc64 => Self::Powerpc64, + target_lexicon::Architecture::Powerpc64le => Self::Powerpc64Le, + target_lexicon::Architecture::S390x => Self::S390X, unsupported => { return Err(PlatformError::OsVersionDetectionError(format!( "The architecture {unsupported} is not supported" @@ -181,9 +196,9 @@ impl Arch { pub fn get_minimum_manylinux_minor(&self) -> u16 { match self { // manylinux 2014 - Arch::Aarch64 | Arch::Armv7L | Arch::Powerpc64 | Arch::Powerpc64Le | Arch::S390X => 17, + Self::Aarch64 | Self::Armv7L | Self::Powerpc64 | Self::Powerpc64Le | Self::S390X => 17, // manylinux 1 - Arch::X86 | Arch::X86_64 => 5, + Self::X86 | Self::X86_64 => 5, } } } diff --git a/crates/platform-tags/src/lib.rs b/crates/platform-tags/src/lib.rs index 2d9f3492d..8a7503890 100644 --- a/crates/platform-tags/src/lib.rs +++ b/crates/platform-tags/src/lib.rs @@ -45,7 +45,7 @@ impl Ord for TagCompatibility { impl PartialOrd for TagCompatibility { fn partial_cmp(&self, other: &Self) -> Option { - Some(TagCompatibility::cmp(self, other)) + Some(Self::cmp(self, other)) } } @@ -264,16 +264,16 @@ impl Implementation { pub fn language_tag(&self, python_version: (u8, u8)) -> String { match self { // Ex) `cp39` - Implementation::CPython => format!("cp{}{}", python_version.0, python_version.1), + Self::CPython => format!("cp{}{}", python_version.0, python_version.1), // Ex) `pp39` - Implementation::PyPy => format!("pp{}{}", python_version.0, python_version.1), + Self::PyPy => format!("pp{}{}", python_version.0, python_version.1), } } pub fn abi_tag(&self, python_version: (u8, u8), implementation_version: (u8, u8)) -> String { match self { // Ex) `cp39` - Implementation::CPython => { + Self::CPython => { if python_version.1 <= 7 { format!("cp{}{}m", python_version.0, python_version.1) } else { @@ -281,7 +281,7 @@ impl Implementation { } } // Ex) `pypy39_pp73` - Implementation::PyPy => format!( + Self::PyPy => format!( "pypy{}{}_pp{}{}", python_version.0, python_version.1, diff --git a/crates/pypi-types/src/direct_url.rs b/crates/pypi-types/src/direct_url.rs index db4a9e6b7..14e6bf1dd 100644 --- a/crates/pypi-types/src/direct_url.rs +++ b/crates/pypi-types/src/direct_url.rs @@ -75,10 +75,10 @@ pub enum VcsKind { impl std::fmt::Display for VcsKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - VcsKind::Git => write!(f, "git"), - VcsKind::Hg => write!(f, "hg"), - VcsKind::Bzr => write!(f, "bzr"), - VcsKind::Svn => write!(f, "svn"), + Self::Git => write!(f, "git"), + Self::Hg => write!(f, "hg"), + Self::Bzr => write!(f, "bzr"), + Self::Svn => write!(f, "svn"), } } } @@ -88,13 +88,13 @@ impl TryFrom<&DirectUrl> for Url { fn try_from(value: &DirectUrl) -> Result { match value { - DirectUrl::LocalDirectory { url, .. } => Url::parse(url), + DirectUrl::LocalDirectory { url, .. } => Self::parse(url), DirectUrl::ArchiveUrl { url, subdirectory, archive_info: _, } => { - let mut url = Url::parse(url)?; + let mut url = Self::parse(url)?; if let Some(subdirectory) = subdirectory { url.set_fragment(Some(&format!("subdirectory={}", subdirectory.display()))); } @@ -105,7 +105,7 @@ impl TryFrom<&DirectUrl> for Url { vcs_info, subdirectory, } => { - let mut url = Url::parse(&format!("{}+{}", vcs_info.vcs, url))?; + let mut url = Self::parse(&format!("{}+{}", vcs_info.vcs, url))?; if let Some(commit_id) = &vcs_info.commit_id { url.set_path(&format!("{}@{commit_id}", url.path())); } else if let Some(requested_revision) = &vcs_info.requested_revision { diff --git a/crates/pypi-types/src/metadata.rs b/crates/pypi-types/src/metadata.rs index bfe2d6e22..3ab5620a8 100644 --- a/crates/pypi-types/src/metadata.rs +++ b/crates/pypi-types/src/metadata.rs @@ -129,7 +129,7 @@ impl Metadata21 { }) .collect::>(); - Ok(Metadata21 { + Ok(Self { metadata_version, name, version, @@ -143,7 +143,7 @@ impl Metadata21 { impl FromStr for Metadata21 { type Err = Error; fn from_str(s: &str) -> Result { - Metadata21::parse(s.as_bytes()) + Self::parse(s.as_bytes()) } } diff --git a/crates/pypi-types/src/simple_json.rs b/crates/pypi-types/src/simple_json.rs index 39b59261d..9380a9012 100644 --- a/crates/pypi-types/src/simple_json.rs +++ b/crates/pypi-types/src/simple_json.rs @@ -102,8 +102,8 @@ pub enum Yanked { impl Yanked { pub fn is_yanked(&self) -> bool { match self { - Yanked::Bool(is_yanked) => *is_yanked, - Yanked::Reason(_) => true, + Self::Bool(is_yanked) => *is_yanked, + Self::Reason(_) => true, } } } diff --git a/crates/requirements-txt/src/lib.rs b/crates/requirements-txt/src/lib.rs index 901e505a2..e685ca5f4 100644 --- a/crates/requirements-txt/src/lib.rs +++ b/crates/requirements-txt/src/lib.rs @@ -172,7 +172,7 @@ impl EditableRequirement { pub fn parse( given: &str, working_dir: impl AsRef, - ) -> Result { + ) -> Result { // Identify the extras. let (requirement, extras) = if let Some((requirement, extras)) = Self::split_extras(given) { let extras = Extras::parse(extras).map_err(|err| { @@ -241,7 +241,7 @@ impl EditableRequirement { // Add the verbatim representation of the URL to the `VerbatimUrl`. let url = url.with_given(requirement.to_string()); - Ok(EditableRequirement { url, extras, path }) + Ok(Self { url, extras, path }) } /// Identify the extras in an editable URL (e.g., `../editable[dev]`). @@ -434,7 +434,7 @@ impl RequirementsTxt { } /// Merges other into self - pub fn update_from(&mut self, other: RequirementsTxt) { + pub fn update_from(&mut self, other: Self) { self.requirements.extend(other.requirements); self.constraints.extend(other.constraints); } @@ -766,57 +766,41 @@ impl RequirementsTxtParserError { #[must_use] fn with_offset(self, offset: usize) -> Self { match self { - RequirementsTxtParserError::IO(err) => RequirementsTxtParserError::IO(err), - RequirementsTxtParserError::InvalidEditablePath(given) => { - RequirementsTxtParserError::InvalidEditablePath(given) - } - RequirementsTxtParserError::Url { + Self::IO(err) => Self::IO(err), + Self::InvalidEditablePath(given) => Self::InvalidEditablePath(given), + Self::Url { source, url, start, end, - } => RequirementsTxtParserError::Url { + } => Self::Url { source, url, start: start + offset, end: end + offset, }, - RequirementsTxtParserError::UnsupportedUrl(url) => { - RequirementsTxtParserError::UnsupportedUrl(url) - } - RequirementsTxtParserError::MissingRequirementPrefix(given) => { - RequirementsTxtParserError::MissingRequirementPrefix(given) - } - RequirementsTxtParserError::MissingEditablePrefix(given) => { - RequirementsTxtParserError::MissingEditablePrefix(given) - } - RequirementsTxtParserError::Parser { message, location } => { - RequirementsTxtParserError::Parser { - message, - location: location + offset, - } - } - RequirementsTxtParserError::UnsupportedRequirement { source, start, end } => { - RequirementsTxtParserError::UnsupportedRequirement { - source, - start: start + offset, - end: end + offset, - } - } - RequirementsTxtParserError::Pep508 { source, start, end } => { - RequirementsTxtParserError::Pep508 { - source, - start: start + offset, - end: end + offset, - } - } - RequirementsTxtParserError::Subfile { source, start, end } => { - RequirementsTxtParserError::Subfile { - source, - start: start + offset, - end: end + offset, - } - } + Self::UnsupportedUrl(url) => Self::UnsupportedUrl(url), + Self::MissingRequirementPrefix(given) => Self::MissingRequirementPrefix(given), + Self::MissingEditablePrefix(given) => Self::MissingEditablePrefix(given), + Self::Parser { message, location } => Self::Parser { + message, + location: location + offset, + }, + Self::UnsupportedRequirement { source, start, end } => Self::UnsupportedRequirement { + source, + start: start + offset, + end: end + offset, + }, + Self::Pep508 { source, start, end } => Self::Pep508 { + source, + start: start + offset, + end: end + offset, + }, + Self::Subfile { source, start, end } => Self::Subfile { + source, + start: start + offset, + end: end + offset, + }, } } } @@ -824,35 +808,35 @@ impl RequirementsTxtParserError { impl Display for RequirementsTxtParserError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - RequirementsTxtParserError::IO(err) => err.fmt(f), - RequirementsTxtParserError::InvalidEditablePath(given) => { + Self::IO(err) => err.fmt(f), + Self::InvalidEditablePath(given) => { write!(f, "Invalid editable path: {given}") } - RequirementsTxtParserError::Url { url, start, .. } => { + Self::Url { url, start, .. } => { write!(f, "Invalid URL at position {start}: `{url}`") } - RequirementsTxtParserError::UnsupportedUrl(url) => { + Self::UnsupportedUrl(url) => { write!(f, "Unsupported URL (expected a `file://` scheme): `{url}`") } - RequirementsTxtParserError::MissingRequirementPrefix(given) => { + Self::MissingRequirementPrefix(given) => { write!(f, "Requirement `{given}` looks like a requirements file but was passed as a package name. Did you mean `-r {given}`?") } - RequirementsTxtParserError::MissingEditablePrefix(given) => { + Self::MissingEditablePrefix(given) => { write!( f, "Requirement `{given}` looks like a directory but was passed as a package name. Did you mean `-e {given}`?" ) } - RequirementsTxtParserError::Parser { message, location } => { + Self::Parser { message, location } => { write!(f, "{message} at position {location}") } - RequirementsTxtParserError::UnsupportedRequirement { start, end, .. } => { + Self::UnsupportedRequirement { start, end, .. } => { write!(f, "Unsupported requirement in position {start} to {end}") } - RequirementsTxtParserError::Pep508 { start, .. } => { + Self::Pep508 { start, .. } => { write!(f, "Couldn't parse requirement at position {start}") } - RequirementsTxtParserError::Subfile { start, .. } => { + Self::Subfile { start, .. } => { write!(f, "Error parsing included file at position {start}") } } @@ -862,16 +846,16 @@ impl Display for RequirementsTxtParserError { impl std::error::Error for RequirementsTxtParserError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self { - RequirementsTxtParserError::IO(err) => err.source(), - RequirementsTxtParserError::Url { source, .. } => Some(source), - RequirementsTxtParserError::InvalidEditablePath(_) => None, - RequirementsTxtParserError::UnsupportedUrl(_) => None, - RequirementsTxtParserError::MissingRequirementPrefix(_) => None, - RequirementsTxtParserError::MissingEditablePrefix(_) => None, - RequirementsTxtParserError::UnsupportedRequirement { source, .. } => Some(source), - RequirementsTxtParserError::Pep508 { source, .. } => Some(source), - RequirementsTxtParserError::Subfile { source, .. } => Some(source.as_ref()), - RequirementsTxtParserError::Parser { .. } => None, + Self::IO(err) => err.source(), + Self::Url { source, .. } => Some(source), + Self::InvalidEditablePath(_) => None, + Self::UnsupportedUrl(_) => None, + Self::MissingRequirementPrefix(_) => None, + Self::MissingEditablePrefix(_) => None, + Self::UnsupportedRequirement { source, .. } => Some(source), + Self::Pep508 { source, .. } => Some(source), + Self::Subfile { source, .. } => Some(source.as_ref()), + Self::Parser { .. } => None, } } } diff --git a/crates/uv-auth/src/lib.rs b/crates/uv-auth/src/lib.rs index 0f9635d51..3db9fc864 100644 --- a/crates/uv-auth/src/lib.rs +++ b/crates/uv-auth/src/lib.rs @@ -28,10 +28,10 @@ pub fn safe_copy_url_auth(trusted_url: &Url, mut new_url: Url) -> Url { if should_retain_auth(trusted_url, &new_url) { new_url .set_username(trusted_url.username()) - .unwrap_or_else(|_| warn!("Failed to transfer username to response URL: {new_url}")); + .unwrap_or_else(|()| warn!("Failed to transfer username to response URL: {new_url}")); new_url .set_password(trusted_url.password()) - .unwrap_or_else(|_| warn!("Failed to transfer password to response URL: {new_url}")); + .unwrap_or_else(|()| warn!("Failed to transfer password to response URL: {new_url}")); } new_url } diff --git a/crates/uv-build/src/lib.rs b/crates/uv-build/src/lib.rs index 7de745b1c..8dae416ce 100644 --- a/crates/uv-build/src/lib.rs +++ b/crates/uv-build/src/lib.rs @@ -284,7 +284,7 @@ impl SourceBuild { setup_py: SetupPyStrategy, config_settings: ConfigSettings, build_kind: BuildKind, - ) -> Result { + ) -> Result { let temp_dir = tempdir_in(build_context.cache().root())?; let metadata = match fs::metadata(source) { diff --git a/crates/uv-cache/src/cli.rs b/crates/uv-cache/src/cli.rs index 90a87da06..8fe5aef9d 100644 --- a/crates/uv-cache/src/cli.rs +++ b/crates/uv-cache/src/cli.rs @@ -37,13 +37,13 @@ impl TryFrom for Cache { /// Returns an absolute cache dir. fn try_from(value: CacheArgs) -> Result { if value.no_cache { - Cache::temp() + Self::temp() } else if let Some(cache_dir) = value.cache_dir { - Cache::from_path(cache_dir) + Self::from_path(cache_dir) } else if let Some(project_dirs) = ProjectDirs::from("", "", "uv") { - Cache::from_path(project_dirs.cache_dir()) + Self::from_path(project_dirs.cache_dir()) } else { - Cache::from_path(".uv_cache") + Self::from_path(".uv_cache") } } } diff --git a/crates/uv-cache/src/lib.rs b/crates/uv-cache/src/lib.rs index 6a371d5cd..b23e28957 100644 --- a/crates/uv-cache/src/lib.rs +++ b/crates/uv-cache/src/lib.rs @@ -518,13 +518,13 @@ pub enum CacheBucket { impl CacheBucket { fn to_str(self) -> &'static str { match self { - CacheBucket::BuiltWheels => "built-wheels-v0", - CacheBucket::FlatIndex => "flat-index-v0", - CacheBucket::Git => "git-v0", - CacheBucket::Interpreter => "interpreter-v0", - CacheBucket::Simple => "simple-v3", - CacheBucket::Wheels => "wheels-v0", - CacheBucket::Archive => "archive-v0", + Self::BuiltWheels => "built-wheels-v0", + Self::FlatIndex => "flat-index-v0", + Self::Git => "git-v0", + Self::Interpreter => "interpreter-v0", + Self::Simple => "simple-v3", + Self::Wheels => "wheels-v0", + Self::Archive => "archive-v0", } } @@ -534,7 +534,7 @@ impl CacheBucket { fn remove(self, cache: &Cache, name: &PackageName) -> Result { let mut summary = Removal::default(); match self { - CacheBucket::Wheels => { + Self::Wheels => { // For `pypi` wheels, we expect a directory per package (indexed by name). let root = cache.bucket(self).join(WheelCacheKind::Pypi); summary += rm_rf(root.join(name.to_string()))?; @@ -553,7 +553,7 @@ impl CacheBucket { summary += rm_rf(directory.join(name.to_string()))?; } } - CacheBucket::BuiltWheels => { + Self::BuiltWheels => { // For `pypi` wheels, we expect a directory per package (indexed by name). let root = cache.bucket(self).join(WheelCacheKind::Pypi); summary += rm_rf(root.join(name.to_string()))?; @@ -588,7 +588,7 @@ impl CacheBucket { } } } - CacheBucket::Simple => { + Self::Simple => { // For `pypi` wheels, we expect a rkyv file per package, indexed by name. let root = cache.bucket(self).join(WheelCacheKind::Pypi); summary += rm_rf(root.join(format!("{name}.rkyv")))?; @@ -600,19 +600,19 @@ impl CacheBucket { summary += rm_rf(directory.join(format!("{name}.rkyv")))?; } } - CacheBucket::FlatIndex => { + Self::FlatIndex => { // We can't know if the flat index includes a package, so we just remove the entire // cache entry. let root = cache.bucket(self); summary += rm_rf(root)?; } - CacheBucket::Git => { + Self::Git => { // Nothing to do. } - CacheBucket::Interpreter => { + Self::Interpreter => { // Nothing to do. } - CacheBucket::Archive => { + Self::Archive => { // Nothing to do. } } diff --git a/crates/uv-cache/src/wheel.rs b/crates/uv-cache/src/wheel.rs index 2674ccf38..be6a9758b 100644 --- a/crates/uv-cache/src/wheel.rs +++ b/crates/uv-cache/src/wheel.rs @@ -75,11 +75,11 @@ pub(crate) enum WheelCacheKind { impl WheelCacheKind { pub(crate) fn to_str(self) -> &'static str { match self { - WheelCacheKind::Pypi => "pypi", - WheelCacheKind::Index => "index", - WheelCacheKind::Url => "url", - WheelCacheKind::Path => "path", - WheelCacheKind::Git => "git", + Self::Pypi => "pypi", + Self::Index => "index", + Self::Url => "url", + Self::Path => "path", + Self::Git => "git", } } diff --git a/crates/uv-client/src/cached_client.rs b/crates/uv-client/src/cached_client.rs index e05c7a518..864a1725d 100644 --- a/crates/uv-client/src/cached_client.rs +++ b/crates/uv-client/src/cached_client.rs @@ -79,14 +79,14 @@ where A::Archived: for<'a> rkyv::CheckBytes> + rkyv::Deserialize, { - type Target = OwnedArchive; + type Target = Self; - fn from_aligned_bytes(bytes: AlignedVec) -> Result, Error> { - OwnedArchive::new(bytes) + fn from_aligned_bytes(bytes: AlignedVec) -> Result { + Self::new(bytes) } fn to_bytes(&self) -> Result, Error> { - Ok(Cow::from(OwnedArchive::as_bytes(self))) + Ok(Cow::from(Self::as_bytes(self))) } fn into_target(self) -> Self::Target { @@ -103,18 +103,18 @@ pub enum CachedClientError { impl From for CachedClientError { fn from(error: Error) -> Self { - CachedClientError::Client(error) + Self::Client(error) } } impl From for CachedClientError { fn from(error: ErrorKind) -> Self { - CachedClientError::Client(error.into()) + Self::Client(error.into()) } } -impl> From> for Error { - fn from(error: CachedClientError) -> Error { +impl> From> for Error { + fn from(error: CachedClientError) -> Self { match error { CachedClientError::Client(error) => error, CachedClientError::Callback(error) => error.into(), @@ -135,9 +135,9 @@ pub enum CacheControl { impl From for CacheControl { fn from(value: Freshness) -> Self { match value { - Freshness::Fresh => CacheControl::None, - Freshness::Stale => CacheControl::MustRevalidate, - Freshness::Missing => CacheControl::None, + Freshness::Fresh => Self::None, + Freshness::Stale => Self::MustRevalidate, + Freshness::Missing => Self::None, } } } @@ -562,9 +562,9 @@ impl DataWithCachePolicy { /// /// If the given byte buffer is not in a valid format or if reading the /// file given fails, then this returns an error. - async fn from_path_async(path: &Path) -> Result { + async fn from_path_async(path: &Path) -> Result { let path = path.to_path_buf(); - tokio::task::spawn_blocking(move || DataWithCachePolicy::from_path_sync(&path)) + tokio::task::spawn_blocking(move || Self::from_path_sync(&path)) .await // This just forwards panics from the closure. .unwrap() @@ -577,13 +577,13 @@ impl DataWithCachePolicy { /// /// If the given byte buffer is not in a valid format or if reading the /// file given fails, then this returns an error. - fn from_path_sync(path: &Path) -> Result { + fn from_path_sync(path: &Path) -> Result { let file = fs_err::File::open(path).map_err(ErrorKind::Io)?; // Note that we don't wrap our file in a buffer because it will just // get passed to AlignedVec::extend_from_reader, which doesn't benefit // from an intermediary buffer. In effect, the AlignedVec acts as the // buffer. - DataWithCachePolicy::from_reader(file) + Self::from_reader(file) } /// Loads cached data and its associated HTTP cache policy from the given @@ -593,12 +593,12 @@ impl DataWithCachePolicy { /// /// If the given byte buffer is not in a valid format or if the reader /// fails, then this returns an error. - pub fn from_reader(mut rdr: impl std::io::Read) -> Result { + pub fn from_reader(mut rdr: impl std::io::Read) -> Result { let mut aligned_bytes = rkyv::util::AlignedVec::new(); aligned_bytes .extend_from_reader(&mut rdr) .map_err(ErrorKind::Io)?; - DataWithCachePolicy::from_aligned_bytes(aligned_bytes) + Self::from_aligned_bytes(aligned_bytes) } /// Loads cached data and its associated HTTP cache policy form an in @@ -608,9 +608,9 @@ impl DataWithCachePolicy { /// /// If the given byte buffer is not in a valid format, then this /// returns an error. - fn from_aligned_bytes(mut bytes: AlignedVec) -> Result { - let cache_policy = DataWithCachePolicy::deserialize_cache_policy(&mut bytes)?; - Ok(DataWithCachePolicy { + fn from_aligned_bytes(mut bytes: AlignedVec) -> Result { + let cache_policy = Self::deserialize_cache_policy(&mut bytes)?; + Ok(Self { data: bytes, cache_policy, }) @@ -625,7 +625,7 @@ impl DataWithCachePolicy { /// serialized representation, then this routine will return an error. fn serialize(cache_policy: &CachePolicy, data: &[u8]) -> Result, Error> { let mut buf = vec![]; - DataWithCachePolicy::serialize_to_writer(cache_policy, data, &mut buf)?; + Self::serialize_to_writer(cache_policy, data, &mut buf)?; Ok(buf) } @@ -669,7 +669,7 @@ impl DataWithCachePolicy { fn deserialize_cache_policy( bytes: &mut AlignedVec, ) -> Result, Error> { - let len = DataWithCachePolicy::deserialize_cache_policy_len(bytes)?; + let len = Self::deserialize_cache_policy_len(bytes)?; let cache_policy_bytes_start = bytes.len() - (len + 8); let cache_policy_bytes = &bytes[cache_policy_bytes_start..][..len]; let mut cache_policy_bytes_aligned = AlignedVec::with_capacity(len); @@ -711,9 +711,8 @@ impl DataWithCachePolicy { let len_u64 = u64::from_le_bytes(cache_policy_len_bytes); let Ok(len_usize) = usize::try_from(len_u64) else { let msg = format!( - "data-with-cache-policy has cache policy length of {}, \ + "data-with-cache-policy has cache policy length of {len_u64}, \ but overflows usize", - len_u64, ); return Err(ErrorKind::ArchiveRead(msg).into()); }; diff --git a/crates/uv-client/src/error.rs b/crates/uv-client/src/error.rs index f2bc0a1d6..28ec4fefe 100644 --- a/crates/uv-client/src/error.rs +++ b/crates/uv-client/src/error.rs @@ -33,8 +33,8 @@ impl Error { } impl From for Error { - fn from(kind: ErrorKind) -> Error { - Error { + fn from(kind: ErrorKind) -> Self { + Self { kind: Box::new(kind), } } @@ -149,7 +149,7 @@ impl ErrorKind { /// Returns true if this error kind corresponds to an I/O "not found" /// error. pub(crate) fn is_file_not_exists(&self) -> bool { - let ErrorKind::Io(ref err) = *self else { + let Self::Io(ref err) = *self else { return false; }; matches!(err.kind(), std::io::ErrorKind::NotFound) @@ -158,30 +158,28 @@ impl ErrorKind { pub(crate) fn from_middleware(err: reqwest_middleware::Error) -> Self { if let reqwest_middleware::Error::Middleware(ref underlying) = err { if let Some(err) = underlying.downcast_ref::() { - return ErrorKind::Offline(err.url().to_string()); + return Self::Offline(err.url().to_string()); } } if let reqwest_middleware::Error::Reqwest(err) = err { - return ErrorKind::RequestError(err); + return Self::RequestError(err); } - ErrorKind::RequestMiddlewareError(err) + Self::RequestMiddlewareError(err) } /// Returns `true` if the error is due to the server not supporting HTTP range requests. pub(crate) fn is_http_range_requests_unsupported(&self) -> bool { match self { // The server doesn't support range requests (as reported by the `HEAD` check). - ErrorKind::AsyncHttpRangeReader( - AsyncHttpRangeReaderError::HttpRangeRequestUnsupported, - ) => { + Self::AsyncHttpRangeReader(AsyncHttpRangeReaderError::HttpRangeRequestUnsupported) => { return true; } // The server returned a "Method Not Allowed" error, indicating it doesn't support // HEAD requests, so we can't check for range requests. - ErrorKind::RequestError(err) => { + Self::RequestError(err) => { if let Some(status) = err.status() { if status == reqwest::StatusCode::METHOD_NOT_ALLOWED { return true; @@ -191,7 +189,7 @@ impl ErrorKind { // The server doesn't support range requests, but we only discovered this while // unzipping due to erroneous server behavior. - ErrorKind::Zip(_, ZipError::UpstreamReadError(err)) => { + Self::Zip(_, ZipError::UpstreamReadError(err)) => { if let Some(inner) = err.get_ref() { if let Some(inner) = inner.downcast_ref::() { if matches!( diff --git a/crates/uv-client/src/flat_index.rs b/crates/uv-client/src/flat_index.rs index 02ec862c2..372d3459b 100644 --- a/crates/uv-client/src/flat_index.rs +++ b/crates/uv-client/src/flat_index.rs @@ -238,7 +238,7 @@ impl<'a> FlatIndexClient<'a> { requires_python: None, size: None, upload_time_utc_ms: None, - url: FileLocation::Path(entry.path().to_path_buf()), + url: FileLocation::Path(entry.path().clone()), yanked: None, }; @@ -329,7 +329,7 @@ impl FlatIndex { file: Box::new(file), index, })); - match distributions.0.entry(filename.version.clone()) { + match distributions.0.entry(filename.version) { Entry::Occupied(mut entry) => { entry .get_mut() diff --git a/crates/uv-client/src/html.rs b/crates/uv-client/src/html.rs index 0dc9c07b9..2d1a47c4c 100644 --- a/crates/uv-client/src/html.rs +++ b/crates/uv-client/src/html.rs @@ -557,7 +557,7 @@ mod tests { #[test] fn parse_missing_href() { - let text = r#" + let text = r" @@ -566,7 +566,7 @@ mod tests { - "#; + "; let base = Url::parse("https://download.pytorch.org/whl/jinja2/").unwrap(); let result = SimpleHtml::parse(text, &base).unwrap_err(); insta::assert_display_snapshot!(result, @"Missing href attribute on anchor link"); diff --git a/crates/uv-client/src/httpcache/control.rs b/crates/uv-client/src/httpcache/control.rs index c50856179..86aac3c3b 100644 --- a/crates/uv-client/src/httpcache/control.rs +++ b/crates/uv-client/src/httpcache/control.rs @@ -64,20 +64,20 @@ pub struct CacheControl { impl CacheControl { /// Convert this to an owned archive value. - pub fn to_archived(&self) -> OwnedArchive { + pub fn to_archived(&self) -> OwnedArchive { // There's no way (other than OOM) for serializing this type to fail. OwnedArchive::from_unarchived(self).expect("all possible values can be archived") } } impl<'b, B: 'b + ?Sized + AsRef<[u8]>> FromIterator<&'b B> for CacheControl { - fn from_iter>(it: T) -> CacheControl { - CacheControl::from_iter(CacheControlParser::new(it)) + fn from_iter>(it: T) -> Self { + Self::from_iter(CacheControlParser::new(it)) } } impl FromIterator for CacheControl { - fn from_iter>(it: T) -> CacheControl { + fn from_iter>(it: T) -> Self { fn parse_int(value: &[u8]) -> Option { if !value.iter().all(u8::is_ascii_digit) { return None; @@ -85,7 +85,7 @@ impl FromIterator for CacheControl { std::str::from_utf8(value).ok()?.parse().ok() } - let mut cc = CacheControl::default(); + let mut cc = Self::default(); for ccd in it { // Note that when we see invalid directive values, we follow [RFC // 9111 S4.2.1]. It says that invalid cache-control directives @@ -441,8 +441,8 @@ impl CacheControlDirective { /// Returns a `must-revalidate` directive. This is useful for forcing a /// cache decision that the response is stale, and thus the server should /// be consulted for whether the cached response ought to be used or not. - fn must_revalidate() -> CacheControlDirective { - CacheControlDirective { + fn must_revalidate() -> Self { + Self { name: "must-revalidate".to_string(), value: vec![], } @@ -604,9 +604,9 @@ mod tests { #[test] fn cache_control_parse_multiple_directives_across_multiple_header_values() { let headers = [ - r#"max-age=60, no-cache"#, + r"max-age=60, no-cache", r#"private="cookie""#, - r#"no-transform"#, + r"no-transform", ]; let directives = CacheControlParser::new(headers).collect::>(); assert_eq!( @@ -635,9 +635,9 @@ mod tests { #[test] fn cache_control_parse_one_header_invalid() { let headers = [ - r#"max-age=60, no-cache"#, + r"max-age=60, no-cache", r#", private="cookie""#, - r#"no-transform"#, + r"no-transform", ]; let directives = CacheControlParser::new(headers).collect::>(); assert_eq!( @@ -688,7 +688,7 @@ mod tests { #[test] fn cache_control_parse_name_normalized() { - let header = r#"MAX-AGE=60"#; + let header = r"MAX-AGE=60"; let directives = CacheControlParser::new([header]).collect::>(); assert_eq!( directives, @@ -704,7 +704,7 @@ mod tests { // things are stale and the client should do a re-check. #[test] fn cache_control_parse_duplicate_directives() { - let header = r#"max-age=60, no-cache, max-age=30"#; + let header = r"max-age=60, no-cache, max-age=30"; let directives = CacheControlParser::new([header]).collect::>(); assert_eq!( directives, @@ -727,7 +727,7 @@ mod tests { #[test] fn cache_control_parse_duplicate_directives_across_headers() { - let headers = [r#"max-age=60, no-cache"#, r#"max-age=30"#]; + let headers = [r"max-age=60, no-cache", r"max-age=30"]; let directives = CacheControlParser::new(headers).collect::>(); assert_eq!( directives, @@ -752,7 +752,7 @@ mod tests { // even when something is duplicated multiple times. #[test] fn cache_control_parse_duplicate_redux() { - let header = r#"max-age=60, no-cache, no-cache, max-age=30"#; + let header = r"max-age=60, no-cache, no-cache, max-age=30"; let directives = CacheControlParser::new([header]).collect::>(); assert_eq!( directives, diff --git a/crates/uv-client/src/httpcache/mod.rs b/crates/uv-client/src/httpcache/mod.rs index 90fc86738..f17769da0 100644 --- a/crates/uv-client/src/httpcache/mod.rs +++ b/crates/uv-client/src/httpcache/mod.rs @@ -162,8 +162,8 @@ struct CacheConfig { } impl Default for CacheConfig { - fn default() -> CacheConfig { - CacheConfig { + fn default() -> Self { + Self { // The caching uv does ought to be considered // private. shared: false, @@ -209,11 +209,11 @@ pub struct CachePolicyBuilder { impl CachePolicyBuilder { /// Create a new builder of a cache policy, starting with the request. - pub fn new(request: &reqwest::Request) -> CachePolicyBuilder { + pub fn new(request: &reqwest::Request) -> Self { let config = CacheConfig::default(); let request_headers = request.headers().clone(); let request = Request::from(request); - CachePolicyBuilder { + Self { config, request, request_headers, @@ -276,7 +276,7 @@ impl CachePolicy { /// you're actually performing an HTTP request. In that case, the extra /// cost that is done here to convert a `CachePolicy` to its archived form /// should be marginal. - pub fn to_archived(&self) -> OwnedArchive { + pub fn to_archived(&self) -> OwnedArchive { // There's no way (other than OOM) for serializing this type to fail. OwnedArchive::from_unarchived(self).expect("all possible values can be archived") } @@ -995,8 +995,8 @@ struct Request { } impl<'a> From<&'a reqwest::Request> for Request { - fn from(from: &'a reqwest::Request) -> Request { - Request { + fn from(from: &'a reqwest::Request) -> Self { + Self { uri: from.url().to_string(), method: Method::from(from.method()), headers: RequestHeaders::from(from.headers()), @@ -1017,8 +1017,8 @@ struct RequestHeaders { } impl<'a> From<&'a http::HeaderMap> for RequestHeaders { - fn from(from: &'a http::HeaderMap) -> RequestHeaders { - RequestHeaders { + fn from(from: &'a http::HeaderMap) -> Self { + Self { cc: from.get_all("cache-control").iter().collect(), authorization: from.contains_key("authorization"), } @@ -1041,13 +1041,13 @@ enum Method { } impl<'a> From<&'a http::Method> for Method { - fn from(from: &'a http::Method) -> Method { + fn from(from: &'a http::Method) -> Self { if from == http::Method::GET { - Method::Get + Self::Get } else if from == http::Method::HEAD { - Method::Head + Self::Head } else { - Method::Unrecognized + Self::Unrecognized } } } @@ -1094,8 +1094,8 @@ impl ArchivedResponse { } impl<'a> From<&'a reqwest::Response> for Response { - fn from(from: &'a reqwest::Response) -> Response { - Response { + fn from(from: &'a reqwest::Response) -> Self { + Self { status: from.status().as_u16(), headers: ResponseHeaders::from(from.headers()), unix_timestamp: unix_timestamp(SystemTime::now()), @@ -1149,8 +1149,8 @@ struct ResponseHeaders { } impl<'a> From<&'a http::HeaderMap> for ResponseHeaders { - fn from(from: &'a http::HeaderMap) -> ResponseHeaders { - ResponseHeaders { + fn from(from: &'a http::HeaderMap) -> Self { + Self { cc: from.get_all("cache-control").iter().collect(), age_seconds: from .get("age") @@ -1210,13 +1210,13 @@ impl ETag { /// where as [RFC 9110 S8.8.3] is a bit more restrictive. /// /// [RFC 9110 S8.8.3]: https://www.rfc-editor.org/rfc/rfc9110#section-8.8.3 - fn parse(header_value: &[u8]) -> ETag { + fn parse(header_value: &[u8]) -> Self { let (value, weak) = if header_value.starts_with(b"W/") { (&header_value[2..], true) } else { (header_value, false) }; - ETag { + Self { value: value.to_vec(), weak, } @@ -1241,8 +1241,8 @@ struct Vary { impl Vary { /// Returns a `Vary` header value that will never match any request. - fn always_fails_to_match() -> Vary { - Vary { + fn always_fails_to_match() -> Self { + Self { fields: vec![VaryField { name: "*".to_string(), value: vec![], @@ -1253,7 +1253,7 @@ impl Vary { fn from_request_response_headers( request: &http::HeaderMap, response: &http::HeaderMap, - ) -> Vary { + ) -> Self { // Parses the `Vary` header as per [RFC 9110 S12.5.5]. // // [RFC 9110 S12.5.5]: https://www.rfc-editor.org/rfc/rfc9110#section-12.5.5 @@ -1266,7 +1266,7 @@ impl Vary { // inevitability, regardless of anything else. So just give up // and return a `Vary` that will never match. if header_name == "*" { - return Vary::always_fails_to_match(); + return Self::always_fails_to_match(); } let value = request .get(&header_name) @@ -1278,7 +1278,7 @@ impl Vary { }); } } - Vary { fields } + Self { fields } } } diff --git a/crates/uv-client/src/registry_client.rs b/crates/uv-client/src/registry_client.rs index ed7eb4da2..0951645f8 100644 --- a/crates/uv-client/src/registry_client.rs +++ b/crates/uv-client/src/registry_client.rs @@ -128,8 +128,8 @@ impl RegistryClientBuilder { index_urls: self.index_urls, cache: self.cache, connectivity: self.connectivity, - client_raw: client_raw.clone(), - client: CachedClient::new(uncached_client.clone()), + client_raw, + client: CachedClient::new(uncached_client), } } } @@ -372,7 +372,7 @@ impl RegistryClient { .as_ref() .is_some_and(pypi_types::DistInfoMetadata::is_available) { - let url = Url::parse(&format!("{}.metadata", url)).map_err(ErrorKind::UrlParseError)?; + let url = Url::parse(&format!("{url}.metadata")).map_err(ErrorKind::UrlParseError)?; let cache_entry = self.cache.entry( CacheBucket::Wheels, @@ -711,7 +711,7 @@ impl SimpleMetadata { } } } - SimpleMetadata( + Self( map.into_iter() .map(|(version, files)| SimpleMetadatum { version, files }) .collect(), diff --git a/crates/uv-client/src/rkyvutil.rs b/crates/uv-client/src/rkyvutil.rs index c60d4c1f1..c41ab68b7 100644 --- a/crates/uv-client/src/rkyvutil.rs +++ b/crates/uv-client/src/rkyvutil.rs @@ -76,13 +76,13 @@ where /// /// If the bytes fail validation (e.g., contains unaligned pointers or /// strings aren't valid UTF-8), then this returns an error. - pub fn new(raw: rkyv::util::AlignedVec) -> Result, Error> { + pub fn new(raw: rkyv::util::AlignedVec) -> Result { // We convert the error to a simple string because... the error type // does not implement Send. And I don't think we really need to keep // the error type around anyway. let _ = rkyv::validation::validators::check_archived_root::(&raw) .map_err(|e| ErrorKind::ArchiveRead(e.to_string()))?; - Ok(OwnedArchive { + Ok(Self { raw, archive: std::marker::PhantomData, }) @@ -96,10 +96,10 @@ where /// /// If the bytes fail validation (e.g., contains unaligned pointers or /// strings aren't valid UTF-8), then this returns an error. - pub fn from_reader(mut rdr: R) -> Result, Error> { + pub fn from_reader(mut rdr: R) -> Result { let mut buf = rkyv::util::AlignedVec::with_capacity(1024); buf.extend_from_reader(&mut rdr).map_err(ErrorKind::Io)?; - OwnedArchive::new(buf) + Self::new(buf) } /// Creates an owned archive value from the unarchived value. @@ -109,7 +109,7 @@ where /// This can fail if creating an archive for the given type fails. /// Currently, this, at minimum, includes cases where an `A` contains a /// `PathBuf` that is not valid UTF-8. - pub fn from_unarchived(unarchived: &A) -> Result, Error> { + pub fn from_unarchived(unarchived: &A) -> Result { use rkyv::ser::Serializer; let mut serializer = crate::rkyvutil::Serializer::<4096>::default(); @@ -117,7 +117,7 @@ where .serialize_value(unarchived) .map_err(ErrorKind::ArchiveWrite)?; let raw = serializer.into_serializer().into_inner(); - Ok(OwnedArchive { + Ok(Self { raw, archive: std::marker::PhantomData, }) @@ -132,7 +132,7 @@ where /// # Errors /// /// Any failures from writing are returned to the caller. - pub fn write(this: &OwnedArchive, mut wtr: W) -> Result<(), Error> { + pub fn write(this: &Self, mut wtr: W) -> Result<(), Error> { Ok(wtr.write_all(&this.raw).map_err(ErrorKind::Io)?) } @@ -143,7 +143,7 @@ where /// Note that because this type has a `Deref` impl, this method requires /// fully-qualified syntax. So, if `o` is an `OwnedValue`, then use /// `OwnedValue::as_bytes(&o)`. - pub fn as_bytes(this: &OwnedArchive) -> &[u8] { + pub fn as_bytes(this: &Self) -> &[u8] { &this.raw } @@ -153,7 +153,7 @@ where /// Note that because this type has a `Deref` impl, this method requires /// fully-qualified syntax. So, if `o` is an `OwnedValue`, then use /// `OwnedValue::deserialize(&o)`. - pub fn deserialize(this: &OwnedArchive) -> A { + pub fn deserialize(this: &Self) -> A { (**this) .deserialize(&mut SharedDeserializeMap::new()) .expect("valid archive must deserialize correctly") @@ -299,8 +299,8 @@ pub enum SerializerError { impl std::fmt::Display for SerializerError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match *self { - SerializerError::Composite(ref e) => e.fmt(f), - SerializerError::AsString(ref e) => e.fmt(f), + Self::Composite(ref e) => e.fmt(f), + Self::AsString(ref e) => e.fmt(f), } } } @@ -308,8 +308,8 @@ impl std::fmt::Display for SerializerError { impl std::error::Error for SerializerError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match *self { - SerializerError::Composite(ref e) => Some(e), - SerializerError::AsString(ref e) => Some(e), + Self::Composite(ref e) => Some(e), + Self::AsString(ref e) => Some(e), } } } @@ -335,7 +335,7 @@ impl std::error::Error for SerializerError { /// /// [AsString]: https://docs.rs/rkyv/0.7.43/rkyv/with/struct.AsString.html impl From for SerializerError { - fn from(e: rkyv::with::AsStringError) -> SerializerError { - SerializerError::AsString(e) + fn from(e: rkyv::with::AsStringError) -> Self { + Self::AsString(e) } } diff --git a/crates/uv-dev/src/install_many.rs b/crates/uv-dev/src/install_many.rs index ef1f2a173..d5a778820 100644 --- a/crates/uv-dev/src/install_many.rs +++ b/crates/uv-dev/src/install_many.rs @@ -1,4 +1,3 @@ -use std::iter::Iterator; use std::path::PathBuf; use std::str::FromStr; diff --git a/crates/uv-dev/src/resolve_cli.rs b/crates/uv-dev/src/resolve_cli.rs index eee9606cc..7f4d812c0 100644 --- a/crates/uv-dev/src/resolve_cli.rs +++ b/crates/uv-dev/src/resolve_cli.rs @@ -121,10 +121,7 @@ pub(crate) async fn resolve_cli(args: ResolveCliArgs) -> Result<()> { &[DotConfig::NodeNoLabel, DotConfig::EdgeNoLabel], &|_graph, edge_ref| format!("label={:?}", edge_ref.weight().to_string()), &|_graph, (_node_index, dist)| { - format!( - "label={:?}", - dist.to_string().replace("==", "\n").to_string() - ) + format!("label={:?}", dist.to_string().replace("==", "\n")) }, ); write!(&mut writer, "{graphviz:?}")?; diff --git a/crates/uv-dev/src/resolve_many.rs b/crates/uv-dev/src/resolve_many.rs index 96cb7085b..1190ff1f2 100644 --- a/crates/uv-dev/src/resolve_many.rs +++ b/crates/uv-dev/src/resolve_many.rs @@ -51,7 +51,7 @@ async fn find_latest_version( let (_, raw_simple_metadata) = client.simple(package_name).await.ok()?; let simple_metadata = OwnedArchive::deserialize(&raw_simple_metadata); let version = simple_metadata.into_iter().next()?.version; - Some(version.clone()) + Some(version) } pub(crate) async fn resolve_many(args: ResolveManyArgs) -> Result<()> { diff --git a/crates/uv-distribution/src/download.rs b/crates/uv-distribution/src/download.rs index 7bde78230..9b0a3a563 100644 --- a/crates/uv-distribution/src/download.rs +++ b/crates/uv-distribution/src/download.rs @@ -55,40 +55,36 @@ impl LocalWheel { /// Return the path to the downloaded wheel's entry in the cache. pub fn target(&self) -> &Path { match self { - LocalWheel::Unzipped(wheel) => &wheel.archive, - LocalWheel::Disk(wheel) => &wheel.target, - LocalWheel::Built(wheel) => &wheel.target, + Self::Unzipped(wheel) => &wheel.archive, + Self::Disk(wheel) => &wheel.target, + Self::Built(wheel) => &wheel.target, } } /// Return the [`Dist`] from which this wheel was downloaded. pub fn remote(&self) -> &Dist { match self { - LocalWheel::Unzipped(wheel) => wheel.remote(), - LocalWheel::Disk(wheel) => wheel.remote(), - LocalWheel::Built(wheel) => wheel.remote(), + Self::Unzipped(wheel) => wheel.remote(), + Self::Disk(wheel) => wheel.remote(), + Self::Built(wheel) => wheel.remote(), } } /// Return the [`WheelFilename`] of this wheel. pub fn filename(&self) -> &WheelFilename { match self { - LocalWheel::Unzipped(wheel) => &wheel.filename, - LocalWheel::Disk(wheel) => &wheel.filename, - LocalWheel::Built(wheel) => &wheel.filename, + Self::Unzipped(wheel) => &wheel.filename, + Self::Disk(wheel) => &wheel.filename, + Self::Built(wheel) => &wheel.filename, } } /// Convert a [`LocalWheel`] into a [`CachedDist`]. pub fn into_cached_dist(self, archive: PathBuf) -> CachedDist { match self { - LocalWheel::Unzipped(wheel) => { - CachedDist::from_remote(wheel.dist, wheel.filename, archive) - } - LocalWheel::Disk(wheel) => CachedDist::from_remote(wheel.dist, wheel.filename, archive), - LocalWheel::Built(wheel) => { - CachedDist::from_remote(wheel.dist, wheel.filename, archive) - } + Self::Unzipped(wheel) => CachedDist::from_remote(wheel.dist, wheel.filename, archive), + Self::Disk(wheel) => CachedDist::from_remote(wheel.dist, wheel.filename, archive), + Self::Built(wheel) => CachedDist::from_remote(wheel.dist, wheel.filename, archive), } } } diff --git a/crates/uv-distribution/src/source/mod.rs b/crates/uv-distribution/src/source/mod.rs index 3c924e656..11f0e59f9 100644 --- a/crates/uv-distribution/src/source/mod.rs +++ b/crates/uv-distribution/src/source/mod.rs @@ -409,7 +409,7 @@ impl<'a, T: BuildContext> SourceDistCachedBuilder<'a, T> { let metadata_entry = cache_shard.entry(METADATA); if let Some(metadata) = read_cached_metadata(&metadata_entry).await? { debug!("Using cached metadata for {source_dist}"); - return Ok(metadata.clone()); + return Ok(metadata); } // Otherwise, we either need to build the metadata or the wheel. @@ -580,7 +580,7 @@ impl<'a, T: BuildContext> SourceDistCachedBuilder<'a, T> { { if let Some(metadata) = read_cached_metadata(&metadata_entry).await? { debug!("Using cached metadata for {source_dist}"); - return Ok(metadata.clone()); + return Ok(metadata); } } @@ -708,7 +708,7 @@ impl<'a, T: BuildContext> SourceDistCachedBuilder<'a, T> { { if let Some(metadata) = read_cached_metadata(&metadata_entry).await? { debug!("Using cached metadata for {source_dist}"); - return Ok(metadata.clone()); + return Ok(metadata); } } diff --git a/crates/uv-distribution/src/unzip.rs b/crates/uv-distribution/src/unzip.rs index b1015d029..8324816b3 100644 --- a/crates/uv-distribution/src/unzip.rs +++ b/crates/uv-distribution/src/unzip.rs @@ -25,9 +25,9 @@ impl Unzip for BuiltWheel { impl Unzip for LocalWheel { fn unzip(&self, target: &Path) -> Result<(), Error> { match self { - LocalWheel::Unzipped(_) => Ok(()), - LocalWheel::Disk(wheel) => wheel.unzip(target), - LocalWheel::Built(wheel) => wheel.unzip(target), + Self::Unzipped(_) => Ok(()), + Self::Disk(wheel) => wheel.unzip(target), + Self::Built(wheel) => wheel.unzip(target), } } } diff --git a/crates/uv-extract/src/stream.rs b/crates/uv-extract/src/stream.rs index 2798ab89e..8d8dfb11a 100644 --- a/crates/uv-extract/src/stream.rs +++ b/crates/uv-extract/src/stream.rs @@ -115,14 +115,12 @@ async fn untar_in>( // On Windows, skip symlink entries, as they're not supported. pip recursively copies the // symlink target instead. - if cfg!(windows) { - if file.header().entry_type().is_symlink() { - warn!( - "Skipping symlink in tar archive: {}", - file.path()?.display() - ); - continue; - } + if cfg!(windows) && file.header().entry_type().is_symlink() { + warn!( + "Skipping symlink in tar archive: {}", + file.path()?.display() + ); + continue; } file.unpack_in(dst.as_ref()).await?; @@ -188,15 +186,14 @@ pub async fn archive( .as_ref() .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("gz")) - { - if source.as_ref().file_stem().is_some_and(|stem| { + && source.as_ref().file_stem().is_some_and(|stem| { Path::new(stem) .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("tar")) - }) { - untar(reader, target).await?; - return Ok(()); - } + }) + { + untar(reader, target).await?; + return Ok(()); } Err(Error::UnsupportedArchive(source.as_ref().to_path_buf())) diff --git a/crates/uv-git/src/git.rs b/crates/uv-git/src/git.rs index 2ea743be1..89147f035 100644 --- a/crates/uv-git/src/git.rs +++ b/crates/uv-git/src/git.rs @@ -8,7 +8,7 @@ use std::{env, str}; use anyhow::{anyhow, Context, Result}; use cargo_util::{paths, ProcessBuilder}; -use git2::{self, ErrorClass, ObjectType}; +use git2::{ErrorClass, ObjectType}; use reqwest::Client; use reqwest::StatusCode; use tracing::{debug, warn}; @@ -69,25 +69,25 @@ impl GitReference { /// Views the short ID as a `str`. pub(crate) fn as_str(&self) -> &str { match self { - GitReference::Branch(rev) - | GitReference::Tag(rev) - | GitReference::BranchOrTag(rev) - | GitReference::FullCommit(rev) - | GitReference::ShortCommit(rev) - | GitReference::Ref(rev) => rev, - GitReference::DefaultBranch => "HEAD", + Self::Branch(rev) + | Self::Tag(rev) + | Self::BranchOrTag(rev) + | Self::FullCommit(rev) + | Self::ShortCommit(rev) + | Self::Ref(rev) => rev, + Self::DefaultBranch => "HEAD", } } pub(crate) fn kind_str(&self) -> &str { match self { - GitReference::Branch(_) => "branch", - GitReference::Tag(_) => "tag", - GitReference::BranchOrTag(_) => "branch or tag", - GitReference::FullCommit(_) => "commit", - GitReference::ShortCommit(_) => "short commit", - GitReference::Ref(_) => "ref", - GitReference::DefaultBranch => "default branch", + Self::Branch(_) => "branch", + Self::Tag(_) => "tag", + Self::BranchOrTag(_) => "branch or tag", + Self::FullCommit(_) => "commit", + Self::ShortCommit(_) => "short commit", + Self::Ref(_) => "ref", + Self::DefaultBranch => "default branch", } } } @@ -136,8 +136,8 @@ pub(crate) struct GitCheckout<'a> { impl GitRemote { /// Creates an instance for a remote repository URL. - pub(crate) fn new(url: &Url) -> GitRemote { - GitRemote { url: url.clone() } + pub(crate) fn new(url: &Url) -> Self { + Self { url: url.clone() } } /// Gets the remote repository URL. @@ -261,7 +261,7 @@ impl GitReference { let id = match self { // Note that we resolve the named tag here in sync with where it's // fetched into via `fetch` below. - GitReference::Tag(s) => (|| -> Result { + Self::Tag(s) => (|| -> Result { let refname = format!("refs/remotes/origin/tags/{s}"); let id = repo.refname_to_id(&refname)?; let obj = repo.find_object(id, None)?; @@ -272,7 +272,7 @@ impl GitReference { // Resolve the remote name since that's all we're configuring in // `fetch` below. - GitReference::Branch(s) => { + Self::Branch(s) => { let name = format!("origin/{s}"); let b = repo .find_branch(&name, git2::BranchType::Remote) @@ -283,7 +283,7 @@ impl GitReference { } // Attempt to resolve the branch, then the tag. - GitReference::BranchOrTag(s) => { + Self::BranchOrTag(s) => { let name = format!("origin/{s}"); repo.find_branch(&name, git2::BranchType::Remote) @@ -300,13 +300,13 @@ impl GitReference { } // We'll be using the HEAD commit - GitReference::DefaultBranch => { + Self::DefaultBranch => { let head_id = repo.refname_to_id("refs/remotes/origin/HEAD")?; let head = repo.find_object(head_id, None)?; head.peel(ObjectType::Commit)?.id() } - GitReference::FullCommit(s) | GitReference::ShortCommit(s) | GitReference::Ref(s) => { + Self::FullCommit(s) | Self::ShortCommit(s) | Self::Ref(s) => { let obj = repo.revparse_single(s)?; match obj.as_tag() { Some(tag) => tag.target_id(), diff --git a/crates/uv-git/src/known_hosts.rs b/crates/uv-git/src/known_hosts.rs index 7775a99f0..a7c82d4f4 100644 --- a/crates/uv-git/src/known_hosts.rs +++ b/crates/uv-git/src/known_hosts.rs @@ -101,8 +101,8 @@ enum KnownHostError { } impl From for KnownHostError { - fn from(err: anyhow::Error) -> KnownHostError { - KnownHostError::CheckError(err) + fn from(err: anyhow::Error) -> Self { + Self::CheckError(err) } } @@ -118,10 +118,10 @@ enum KnownHostLocation { impl Display for KnownHostLocation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let loc = match self { - KnownHostLocation::File { path, lineno } => { + Self::File { path, lineno } => { format!("{} line {lineno}", path.display()) } - KnownHostLocation::Bundled => "bundled with cargo".to_string(), + Self::Bundled => "bundled with cargo".to_string(), }; f.write_str(&loc) } diff --git a/crates/uv-git/src/util/retry.rs b/crates/uv-git/src/util/retry.rs index c83542233..1bf67ce24 100644 --- a/crates/uv-git/src/util/retry.rs +++ b/crates/uv-git/src/util/retry.rs @@ -94,8 +94,8 @@ const INITIAL_RETRY_SLEEP_BASE_MS: u64 = 500; const INITIAL_RETRY_JITTER_MS: u64 = 1000; impl Retry { - pub(crate) fn new() -> Retry { - Retry { + pub(crate) fn new() -> Self { + Self { retries: 0, max_retries: 3, } diff --git a/crates/uv-installer/src/site_packages.rs b/crates/uv-installer/src/site_packages.rs index 207a9f24e..0168c540e 100644 --- a/crates/uv-installer/src/site_packages.rs +++ b/crates/uv-installer/src/site_packages.rs @@ -258,10 +258,10 @@ impl<'a> SitePackages<'a> { // Add the direct requirements to the queue. for dependency in requirements { - if dependency.evaluate_markers(self.venv.interpreter().markers(), &[]) { - if seen.insert(dependency.clone()) { - stack.push(dependency.clone()); - } + if dependency.evaluate_markers(self.venv.interpreter().markers(), &[]) + && seen.insert(dependency.clone()) + { + stack.push(dependency.clone()); } } @@ -298,10 +298,9 @@ impl<'a> SitePackages<'a> { if dependency.evaluate_markers( self.venv.interpreter().markers(), &requirement.extras, - ) { - if seen.insert(dependency.clone()) { - stack.push(dependency); - } + ) && seen.insert(dependency.clone()) + { + stack.push(dependency); } } } @@ -363,10 +362,9 @@ impl<'a> SitePackages<'a> { if dependency.evaluate_markers( self.venv.interpreter().markers(), &requirement.extras, - ) { - if seen.insert(dependency.clone()) { - stack.push(dependency); - } + ) && seen.insert(dependency.clone()) + { + stack.push(dependency); } } } diff --git a/crates/uv-interpreter/src/python_query.rs b/crates/uv-interpreter/src/python_query.rs index a23e5c1d2..59e06c8bf 100644 --- a/crates/uv-interpreter/src/python_query.rs +++ b/crates/uv-interpreter/src/python_query.rs @@ -213,15 +213,15 @@ enum PythonInstallation { impl PythonInstallation { fn major(&self) -> u8 { match self { - PythonInstallation::PyListPath { major, .. } => *major, - PythonInstallation::Interpreter(interpreter) => interpreter.python_major(), + Self::PyListPath { major, .. } => *major, + Self::Interpreter(interpreter) => interpreter.python_major(), } } fn minor(&self) -> u8 { match self { - PythonInstallation::PyListPath { minor, .. } => *minor, - PythonInstallation::Interpreter(interpreter) => interpreter.python_minor(), + Self::PyListPath { minor, .. } => *minor, + Self::Interpreter(interpreter) => interpreter.python_minor(), } } @@ -268,10 +268,10 @@ impl PythonInstallation { cache: &Cache, ) -> Result { match self { - PythonInstallation::PyListPath { + Self::PyListPath { executable_path, .. } => Interpreter::query(&executable_path, platform, cache), - PythonInstallation::Interpreter(interpreter) => Ok(interpreter), + Self::Interpreter(interpreter) => Ok(interpreter), } } } @@ -297,20 +297,20 @@ impl PythonVersionSelector { }; match self { - PythonVersionSelector::Default => [Some(python3), Some(python), None, None], - PythonVersionSelector::Major(major) => [ + Self::Default => [Some(python3), Some(python), None, None], + Self::Major(major) => [ Some(Cow::Owned(format!("python{major}{extension}"))), Some(python), None, None, ], - PythonVersionSelector::MajorMinor(major, minor) => [ + Self::MajorMinor(major, minor) => [ Some(Cow::Owned(format!("python{major}.{minor}{extension}"))), Some(Cow::Owned(format!("python{major}{extension}"))), Some(python), None, ], - PythonVersionSelector::MajorMinorPatch(major, minor, patch) => [ + Self::MajorMinorPatch(major, minor, patch) => [ Some(Cow::Owned(format!( "python{major}.{minor}.{patch}{extension}", ))), @@ -323,10 +323,10 @@ impl PythonVersionSelector { fn major(self) -> Option { match self { - PythonVersionSelector::Default => None, - PythonVersionSelector::Major(major) => Some(major), - PythonVersionSelector::MajorMinor(major, _) => Some(major), - PythonVersionSelector::MajorMinorPatch(major, _, _) => Some(major), + Self::Default => None, + Self::Major(major) => Some(major), + Self::MajorMinor(major, _) => Some(major), + Self::MajorMinorPatch(major, _, _) => Some(major), } } } diff --git a/crates/uv-normalize/src/lib.rs b/crates/uv-normalize/src/lib.rs index 2dfb1cd8a..238f866e8 100644 --- a/crates/uv-normalize/src/lib.rs +++ b/crates/uv-normalize/src/lib.rs @@ -35,7 +35,7 @@ pub(crate) fn validate_and_normalize_ref( match last { // Names can't start with punctuation. None => return Err(InvalidNameError(name.as_ref().to_string())), - Some(b'-') | Some(b'_') | Some(b'.') => {} + Some(b'-' | b'_' | b'.') => {} Some(_) => normalized.push('-'), } } @@ -45,7 +45,7 @@ pub(crate) fn validate_and_normalize_ref( } // Names can't end with punctuation. - if matches!(last, Some(b'-') | Some(b'_') | Some(b'.')) { + if matches!(last, Some(b'-' | b'_' | b'.')) { return Err(InvalidNameError(name.as_ref().to_string())); } @@ -83,7 +83,7 @@ fn is_normalized(name: impl AsRef) -> Result { } // Names can't end with punctuation. - if matches!(last, Some(b'-') | Some(b'_') | Some(b'.')) { + if matches!(last, Some(b'-' | b'_' | b'.')) { return Err(InvalidNameError(name.as_ref().to_string())); } @@ -143,7 +143,7 @@ mod tests { fn check() { let inputs = ["friendly-bard", "friendlybard"]; for input in inputs { - assert!(is_normalized(input).unwrap(), "{:?}", input); + assert!(is_normalized(input).unwrap(), "{input:?}"); } let inputs = [ @@ -155,7 +155,7 @@ mod tests { "FrIeNdLy-._.-bArD", ]; for input in inputs { - assert!(!is_normalized(input).unwrap(), "{:?}", input); + assert!(!is_normalized(input).unwrap(), "{input:?}"); } } diff --git a/crates/uv-normalize/src/package_name.rs b/crates/uv-normalize/src/package_name.rs index 5ea4ce903..fbc9d4b30 100644 --- a/crates/uv-normalize/src/package_name.rs +++ b/crates/uv-normalize/src/package_name.rs @@ -54,9 +54,9 @@ impl PackageName { } } -impl From<&PackageName> for PackageName { +impl From<&Self> for PackageName { /// Required for `WaitMap::wait`. - fn from(package_name: &PackageName) -> Self { + fn from(package_name: &Self) -> Self { package_name.clone() } } diff --git a/crates/uv-resolver/src/candidate_selector.rs b/crates/uv-resolver/src/candidate_selector.rs index dc5f26b27..1a3bd285b 100644 --- a/crates/uv-resolver/src/candidate_selector.rs +++ b/crates/uv-resolver/src/candidate_selector.rs @@ -282,17 +282,15 @@ impl<'a> From<&'a PrioritizedDist> for CandidateDist<'a> { fn from(value: &'a PrioritizedDist) -> Self { if let Some(dist) = value.get() { CandidateDist::Compatible(dist) + } else if value.exclude_newer() && value.incompatible_wheel().is_none() { + // If empty because of exclude-newer, mark as a special case + CandidateDist::ExcludeNewer } else { - if value.exclude_newer() && value.incompatible_wheel().is_none() { - // If empty because of exclude-newer, mark as a special case - CandidateDist::ExcludeNewer - } else { - CandidateDist::Incompatible( - value - .incompatible_wheel() - .map(|(_, incompatibility)| incompatibility), - ) - } + CandidateDist::Incompatible( + value + .incompatible_wheel() + .map(|(_, incompatibility)| incompatibility), + ) } } } diff --git a/crates/uv-resolver/src/error.rs b/crates/uv-resolver/src/error.rs index 9aa1550b3..9f3857dbb 100644 --- a/crates/uv-resolver/src/error.rs +++ b/crates/uv-resolver/src/error.rs @@ -112,9 +112,9 @@ impl From, Infallibl | pubgrub::error::PubGrubError::ErrorRetrievingDependencies { .. } => { unreachable!() } - pubgrub::error::PubGrubError::Failure(inner) => ResolveError::Failure(inner), + pubgrub::error::PubGrubError::Failure(inner) => Self::Failure(inner), pubgrub::error::PubGrubError::NoSolution(derivation_tree) => { - ResolveError::NoSolution(NoSolutionError { + Self::NoSolution(NoSolutionError { derivation_tree, // The following should be populated before display for the best error messages available_versions: IndexMap::default(), @@ -125,7 +125,7 @@ impl From, Infallibl }) } pubgrub::error::PubGrubError::SelfDependency { package, version } => { - ResolveError::SelfDependency { + Self::SelfDependency { package: Box::new(package), version: Box::new(version), } diff --git a/crates/uv-resolver/src/pubgrub/dependencies.rs b/crates/uv-resolver/src/pubgrub/dependencies.rs index d024d3fcf..e2d376817 100644 --- a/crates/uv-resolver/src/pubgrub/dependencies.rs +++ b/crates/uv-resolver/src/pubgrub/dependencies.rs @@ -37,10 +37,8 @@ impl PubGrubDependencies { if !requirement.evaluate_markers(env, std::slice::from_ref(extra)) { continue; } - } else { - if !requirement.evaluate_markers(env, &[]) { - continue; - } + } else if !requirement.evaluate_markers(env, &[]) { + continue; } // Add the package, plus any extra variants. @@ -73,10 +71,8 @@ impl PubGrubDependencies { if !constraint.evaluate_markers(env, std::slice::from_ref(extra)) { continue; } - } else { - if !constraint.evaluate_markers(env, &[]) { - continue; - } + } else if !constraint.evaluate_markers(env, &[]) { + continue; } // Add the package, plus any extra variants. diff --git a/crates/uv-resolver/src/pubgrub/package.rs b/crates/uv-resolver/src/pubgrub/package.rs index cdec28678..922b2b54b 100644 --- a/crates/uv-resolver/src/pubgrub/package.rs +++ b/crates/uv-resolver/src/pubgrub/package.rs @@ -82,16 +82,16 @@ pub enum PubGrubPython { impl std::fmt::Display for PubGrubPackage { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - PubGrubPackage::Root(name) => { + Self::Root(name) => { if let Some(name) = name { write!(f, "{}", name.as_ref()) } else { write!(f, "root") } } - PubGrubPackage::Python(_) => write!(f, "Python"), - PubGrubPackage::Package(name, None, ..) => write!(f, "{name}"), - PubGrubPackage::Package(name, Some(extra), ..) => { + Self::Python(_) => write!(f, "Python"), + Self::Package(name, None, ..) => write!(f, "{name}"), + Self::Package(name, Some(extra), ..) => { write!(f, "{name}[{extra}]") } } diff --git a/crates/uv-resolver/src/pubgrub/report.rs b/crates/uv-resolver/src/pubgrub/report.rs index 2091b0158..e119fd884 100644 --- a/crates/uv-resolver/src/pubgrub/report.rs +++ b/crates/uv-resolver/src/pubgrub/report.rs @@ -95,7 +95,7 @@ impl ReportFormatter> for PubGrubReportFormatter< format!("there is no version of {package}{set}") } else { let complement = set.complement(); - let segments = complement.iter().collect::>().len(); + let segments = complement.iter().count(); // Simple case, there's a single range to report if segments == 1 { format!( @@ -455,7 +455,7 @@ pub(crate) enum PubGrubHint { impl std::fmt::Display for PubGrubHint { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - PubGrubHint::PreReleaseAvailable { package, version } => { + Self::PreReleaseAvailable { package, version } => { write!( f, "{}{} Pre-releases are available for {} in the requested range (e.g., {}), but pre-releases weren't enabled (try: `--prerelease=allow`)", @@ -465,7 +465,7 @@ impl std::fmt::Display for PubGrubHint { version.bold() ) } - PubGrubHint::PreReleaseRequested { package, range } => { + Self::PreReleaseRequested { package, range } => { write!( f, "{}{} {} was requested with a pre-release marker (e.g., {}), but pre-releases weren't enabled (try: `--prerelease=allow`)", @@ -475,7 +475,7 @@ impl std::fmt::Display for PubGrubHint { PackageRange::compatibility(package, range).bold() ) } - PubGrubHint::NoIndex => { + Self::NoIndex => { write!( f, "{}{} Packages were unavailable because index lookups were disabled and no additional package locations were provided (try: `--find-links `)", @@ -483,7 +483,7 @@ impl std::fmt::Display for PubGrubHint { ":".bold(), ) } - PubGrubHint::Offline => { + Self::Offline => { write!( f, "{}{} Packages were unavailable because the network was disabled", diff --git a/crates/uv-resolver/src/python_requirement.rs b/crates/uv-resolver/src/python_requirement.rs index f6ab142c0..005360975 100644 --- a/crates/uv-resolver/src/python_requirement.rs +++ b/crates/uv-resolver/src/python_requirement.rs @@ -47,10 +47,10 @@ impl PythonRequirement { // If the dist is a source distribution, and doesn't support the installed Python // version, return the failing version specifiers, since we won't be able to build it. - if matches!(dist.for_installation().dist, Dist::Source(_)) { - if !requires_python.contains(self.installed()) { - return Some(requires_python); - } + if matches!(dist.for_installation().dist, Dist::Source(_)) + && !requires_python.contains(self.installed()) + { + return Some(requires_python); } // Validate the resolved file. @@ -60,10 +60,10 @@ impl PythonRequirement { // version, return the failing version specifiers, since we won't be able to build it. // This isn't strictly necessary, since if `dist.resolve_metadata()` is a source distribution, it // should be the same file as `dist.install_metadata()` (validated above). - if matches!(dist.for_resolution().dist, Dist::Source(_)) { - if !requires_python.contains(self.installed()) { - return Some(requires_python); - } + if matches!(dist.for_resolution().dist, Dist::Source(_)) + && !requires_python.contains(self.installed()) + { + return Some(requires_python); } None diff --git a/crates/uv-resolver/src/resolver/mod.rs b/crates/uv-resolver/src/resolver/mod.rs index ef80eca9e..c8c98a388 100644 --- a/crates/uv-resolver/src/resolver/mod.rs +++ b/crates/uv-resolver/src/resolver/mod.rs @@ -1121,13 +1121,13 @@ pub(crate) enum Request { impl Display for Request { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - Request::Package(package_name) => { + Self::Package(package_name) => { write!(f, "Versions {package_name}") } - Request::Dist(dist) => { + Self::Dist(dist) => { write!(f, "Metadata {dist}") } - Request::Prefetch(package_name, range) => { + Self::Prefetch(package_name, range) => { write!(f, "Prefetch {package_name} {range}") } } diff --git a/crates/uv-resolver/src/version_map.rs b/crates/uv-resolver/src/version_map.rs index f83e5cd73..7210cfb37 100644 --- a/crates/uv-resolver/src/version_map.rs +++ b/crates/uv-resolver/src/version_map.rs @@ -85,7 +85,7 @@ impl VersionMap { NoBinary::All => true, NoBinary::Packages(packages) => packages.contains(package_name), }; - VersionMap { + Self { inner: VersionMapInner::Lazy(VersionMapLazy { map, simple_metadata, @@ -175,7 +175,7 @@ impl VersionMap { impl From for VersionMap { fn from(flat_index: FlatDistributions) -> Self { - VersionMap { + Self { inner: VersionMapInner::Eager(flat_index.into()), } } diff --git a/crates/uv-resolver/src/yanks.rs b/crates/uv-resolver/src/yanks.rs index 26579be4c..c6618d5b8 100644 --- a/crates/uv-resolver/src/yanks.rs +++ b/crates/uv-resolver/src/yanks.rs @@ -15,8 +15,7 @@ impl AllowedYanks { pub(crate) fn allowed(&self, package_name: &PackageName, version: &Version) -> bool { self.0 .get(package_name) - .map(|allowed_yanks| allowed_yanks.contains(version)) - .unwrap_or_default() + .is_some_and(|allowed_yanks| allowed_yanks.contains(version)) } } diff --git a/crates/uv-traits/src/lib.rs b/crates/uv-traits/src/lib.rs index df66fda75..b8c7ecfa7 100644 --- a/crates/uv-traits/src/lib.rs +++ b/crates/uv-traits/src/lib.rs @@ -163,8 +163,8 @@ pub enum BuildKind { impl Display for BuildKind { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - BuildKind::Wheel => f.write_str("wheel"), - BuildKind::Editable => f.write_str("editable"), + Self::Wheel => f.write_str("wheel"), + Self::Editable => f.write_str("editable"), } } } diff --git a/crates/uv/src/commands/mod.rs b/crates/uv/src/commands/mod.rs index acaf252fb..a83b1a1e4 100644 --- a/crates/uv/src/commands/mod.rs +++ b/crates/uv/src/commands/mod.rs @@ -41,9 +41,9 @@ pub(crate) enum ExitStatus { impl From for ExitCode { fn from(status: ExitStatus) -> Self { match status { - ExitStatus::Success => ExitCode::from(0), - ExitStatus::Failure => ExitCode::from(1), - ExitStatus::Error => ExitCode::from(2), + ExitStatus::Success => Self::from(0), + ExitStatus::Failure => Self::from(1), + ExitStatus::Error => Self::from(2), } } } diff --git a/crates/uv/src/commands/pip_sync.rs b/crates/uv/src/commands/pip_sync.rs index 5ca4c17f2..b2d634bb9 100644 --- a/crates/uv/src/commands/pip_sync.rs +++ b/crates/uv/src/commands/pip_sync.rs @@ -437,12 +437,10 @@ async fn resolve_editables( [dist] if not_modified(&editable, dist) => { if packages.contains(dist.name()) { uninstalled.push(editable); + } else if not_modified(&editable, dist) { + installed.push((*dist).clone()); } else { - if not_modified(&editable, dist) { - installed.push((*dist).clone()); - } else { - uninstalled.push(editable); - } + uninstalled.push(editable); } } _ => { diff --git a/crates/uv/src/main.rs b/crates/uv/src/main.rs index ab8384f03..e6ab42065 100644 --- a/crates/uv/src/main.rs +++ b/crates/uv/src/main.rs @@ -103,9 +103,9 @@ pub enum ColorChoice { impl From for anstream::ColorChoice { fn from(value: ColorChoice) -> Self { match value { - ColorChoice::Auto => anstream::ColorChoice::Auto, - ColorChoice::Always => anstream::ColorChoice::Always, - ColorChoice::Never => anstream::ColorChoice::Never, + ColorChoice::Auto => Self::Auto, + ColorChoice::Always => Self::Always, + ColorChoice::Never => Self::Never, } } } diff --git a/crates/uv/src/requirements.rs b/crates/uv/src/requirements.rs index 8358d493d..f957c09a1 100644 --- a/crates/uv/src/requirements.rs +++ b/crates/uv/src/requirements.rs @@ -47,33 +47,29 @@ impl RequirementsSource { // If the user provided a `requirements.txt` file without `-r` (as in // `uv pip install requirements.txt`), prompt them to correct it. #[allow(clippy::case_sensitive_file_extension_comparisons)] - if name.ends_with(".txt") || name.ends_with(".in") { - if Path::new(&name).is_file() { - let term = Term::stderr(); - if term.is_term() { - let prompt = format!( - "`{name}` looks like a requirements file but was passed as a package name. Did you mean `-r {name}`?" - ); - let confirmation = confirm::confirm(&prompt, &term, true).unwrap(); - if confirmation { - return Self::RequirementsTxt(name.into()); - } + if (name.ends_with(".txt") || name.ends_with(".in")) && Path::new(&name).is_file() { + let term = Term::stderr(); + if term.is_term() { + let prompt = format!( + "`{name}` looks like a requirements file but was passed as a package name. Did you mean `-r {name}`?" + ); + let confirmation = confirm::confirm(&prompt, &term, true).unwrap(); + if confirmation { + return Self::RequirementsTxt(name.into()); } } } // If the user provided a path to a local directory without `-e` (as in // `uv pip install ../flask`), prompt them to correct it. - if name.contains('/') || name.contains('\\') { - if Path::new(&name).is_dir() { - let term = Term::stderr(); - if term.is_term() { - let prompt = - format!("`{name}` looks like a local directory but was passed as a package name. Did you mean `-e {name}`?"); - let confirmation = confirm::confirm(&prompt, &term, true).unwrap(); - if confirmation { - return Self::RequirementsTxt(name.into()); - } + if (name.contains('/') || name.contains('\\')) && Path::new(&name).is_dir() { + let term = Term::stderr(); + if term.is_term() { + let prompt = + format!("`{name}` looks like a local directory but was passed as a package name. Did you mean `-e {name}`?"); + let confirmation = confirm::confirm(&prompt, &term, true).unwrap(); + if confirmation { + return Self::RequirementsTxt(name.into()); } } } @@ -236,15 +232,15 @@ impl RequirementsSpecification { })?); } - if requirements.is_empty() { - if pyproject_toml.build_system.is_some_and(|build_system| { + if requirements.is_empty() + && pyproject_toml.build_system.is_some_and(|build_system| { build_system .requires .iter() .any(|v| v.name.as_dist_info_name().starts_with("poetry")) - }) { - warn_user!("`{}` does not contain any dependencies (hint: specify dependencies in the `project.dependencies` section; `tool.poetry.dependencies` is not currently supported)", path.normalized_display()); - } + }) + { + warn_user!("`{}` does not contain any dependencies (hint: specify dependencies in the `project.dependencies` section; `tool.poetry.dependencies` is not currently supported)", path.normalized_display()); } Self { diff --git a/crates/uv/tests/common/mod.rs b/crates/uv/tests/common/mod.rs index cfbff46e4..75a266341 100644 --- a/crates/uv/tests/common/mod.rs +++ b/crates/uv/tests/common/mod.rs @@ -9,7 +9,7 @@ use assert_fs::fixture::PathChild; use fs_err::os::unix::fs::symlink as symlink_file; #[cfg(windows)] use fs_err::os::windows::fs::symlink_file; -use regex::{self, Regex}; +use regex::Regex; use std::borrow::BorrowMut; use std::env; use std::ffi::OsString; diff --git a/crates/uv/tests/pip_install.rs b/crates/uv/tests/pip_install.rs index bf1447e6a..751d8d95d 100644 --- a/crates/uv/tests/pip_install.rs +++ b/crates/uv/tests/pip_install.rs @@ -989,7 +989,7 @@ fn install_git_private_https_pat_not_authorized() { let token = "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"; let mut filters = context.filters(); - filters.insert(0, (&token, "***")); + filters.insert(0, (token, "***")); // We provide a username otherwise (since the token is invalid), the git cli will prompt for a password // and hang the test diff --git a/crates/uv/tests/venv.rs b/crates/uv/tests/venv.rs index 587c11267..27722258d 100644 --- a/crates/uv/tests/venv.rs +++ b/crates/uv/tests/venv.rs @@ -30,7 +30,7 @@ fn create_venv() -> Result<()> { ), (&filter_venv, "/home/ferris/project/.venv"), ( - &filter_prompt, + filter_prompt, "Activate with: source /home/ferris/project/.venv/bin/activate", ), ]; @@ -68,7 +68,7 @@ fn create_venv() -> Result<()> { ), (&filter_venv, "/home/ferris/project/.venv"), ( - &filter_prompt, + filter_prompt, "Activate with: source /home/ferris/project/.venv/bin/activate", ), ]; @@ -115,7 +115,7 @@ fn create_venv_defaults_to_cwd() -> Result<()> { "Using Python [VERSION] interpreter at [PATH]", ), (&filter_venv, "/home/ferris/project/.venv"), - (&filter_prompt, "Activate with: source .venv/bin/activate"), + (filter_prompt, "Activate with: source .venv/bin/activate"), ]; uv_snapshot!(filters, Command::new(get_bin()) .arg("venv") @@ -160,7 +160,7 @@ fn seed() -> Result<()> { ), (&filter_venv, "/home/ferris/project/.venv"), ( - &filter_prompt, + filter_prompt, "Activate with: source /home/ferris/project/.venv/bin/activate", ), ]; @@ -210,7 +210,7 @@ fn seed_older_python_version() -> Result<()> { ), (&filter_venv, "/home/ferris/project/.venv"), ( - &filter_prompt, + filter_prompt, "Activate with: source /home/ferris/project/.venv/bin/activate", ), ]; @@ -352,7 +352,7 @@ fn create_venv_python_patch() -> Result<()> { (r"interpreter at .+", "interpreter at [PATH]"), (&filter_venv, "/home/ferris/project/.venv"), ( - &filter_prompt, + filter_prompt, "Activate with: source /home/ferris/project/.venv/bin/activate", ), ]; @@ -450,7 +450,7 @@ fn empty_dir_exists() -> Result<()> { ), (&filter_venv, "/home/ferris/project/.venv"), ( - &filter_prompt, + filter_prompt, "Activate with: source /home/ferris/project/.venv/bin/activate", ), ]; @@ -614,7 +614,7 @@ fn virtualenv_compatibility() -> Result<()> { ), (&filter_venv, "/home/ferris/project/.venv"), ( - &filter_prompt, + filter_prompt, "Activate with: source /home/ferris/project/.venv/bin/activate", ), ]; @@ -628,7 +628,7 @@ fn virtualenv_compatibility() -> Result<()> { .arg(cache_dir.path()) .arg("--exclude-newer") .arg(EXCLUDE_NEWER) - .env("UV_TEST_PYTHON_PATH", bin.clone()) + .env("UV_TEST_PYTHON_PATH", bin) .current_dir(&temp_dir), @r###" success: true exit_code: 0