diff --git a/Cargo.toml b/Cargo.toml index 7df21ebf7..14471724d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -250,6 +250,7 @@ rc_buffer = "warn" rc_mutex = "warn" rest_pat_in_fully_bound_structs = "warn" if_not_else = "allow" +use_self = "warn" # Diagnostics are not actionable: Enable once https://github.com/rust-lang/rust-clippy/issues/13774 is resolved. large_stack_arrays = "allow" diff --git a/crates/uv-auth/src/cache.rs b/crates/uv-auth/src/cache.rs index 274efab60..58613ecbc 100644 --- a/crates/uv-auth/src/cache.rs +++ b/crates/uv-auth/src/cache.rs @@ -177,8 +177,8 @@ struct TrieState { } impl UrlTrie { - fn new() -> UrlTrie { - let mut trie = UrlTrie { states: vec![] }; + fn new() -> Self { + let mut trie = Self { states: vec![] }; trie.alloc(); trie } diff --git a/crates/uv-auth/src/credentials.rs b/crates/uv-auth/src/credentials.rs index 68d98b2e3..e3e22b271 100644 --- a/crates/uv-auth/src/credentials.rs +++ b/crates/uv-auth/src/credentials.rs @@ -158,7 +158,7 @@ impl Credentials { return None; } - Some(Credentials::Basic { + Some(Self::Basic { username: Username::new(Some(entry.login.clone())), password: Some(Password(entry.password.clone())), }) diff --git a/crates/uv-auth/src/index.rs b/crates/uv-auth/src/index.rs index b71bc9a62..35a7f1f19 100644 --- a/crates/uv-auth/src/index.rs +++ b/crates/uv-auth/src/index.rs @@ -42,9 +42,9 @@ pub enum AuthPolicy { impl Display for AuthPolicy { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { - AuthPolicy::Auto => write!(f, "auto"), - AuthPolicy::Always => write!(f, "always"), - AuthPolicy::Never => write!(f, "never"), + Self::Auto => write!(f, "auto"), + Self::Always => write!(f, "always"), + Self::Never => write!(f, "never"), } } } diff --git a/crates/uv-auth/src/middleware.rs b/crates/uv-auth/src/middleware.rs index 605675b61..28bbfb07a 100644 --- a/crates/uv-auth/src/middleware.rs +++ b/crates/uv-auth/src/middleware.rs @@ -26,7 +26,7 @@ enum NetrcMode { impl Default for NetrcMode { fn default() -> Self { - NetrcMode::Automatic(LazyLock::new(|| match Netrc::new() { + Self::Automatic(LazyLock::new(|| match Netrc::new() { Ok(netrc) => Some(netrc), Err(netrc::Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => { debug!("No netrc file found"); @@ -44,9 +44,9 @@ impl NetrcMode { /// Get the parsed netrc file if enabled. fn get(&self) -> Option<&Netrc> { match self { - NetrcMode::Automatic(lock) => lock.as_ref(), - NetrcMode::Enabled(netrc) => Some(netrc), - NetrcMode::Disabled => None, + Self::Automatic(lock) => lock.as_ref(), + Self::Enabled(netrc) => Some(netrc), + Self::Disabled => None, } } } @@ -129,7 +129,7 @@ impl AuthMiddleware { impl Default for AuthMiddleware { fn default() -> Self { - AuthMiddleware::new() + Self::new() } } diff --git a/crates/uv-build-backend/src/metadata.rs b/crates/uv-build-backend/src/metadata.rs index 9ccb3f6b2..1d0f758ad 100644 --- a/crates/uv-build-backend/src/metadata.rs +++ b/crates/uv-build-backend/src/metadata.rs @@ -723,9 +723,9 @@ impl Readme { /// If the readme is a file, return the path to the file. pub(crate) fn path(&self) -> Option<&Path> { match self { - Readme::String(path) => Some(path), - Readme::File { file, .. } => Some(file), - Readme::Text { .. } => None, + Self::String(path) => Some(path), + Self::File { file, .. } => Some(file), + Self::Text { .. } => None, } } } diff --git a/crates/uv-cache/src/cli.rs b/crates/uv-cache/src/cli.rs index 41e6917c3..092fe20ce 100644 --- a/crates/uv-cache/src/cli.rs +++ b/crates/uv-cache/src/cli.rs @@ -82,7 +82,7 @@ impl TryFrom for Cache { type Error = io::Error; fn try_from(value: CacheArgs) -> Result { - Cache::from_settings(value.no_cache, value.cache_dir) + Self::from_settings(value.no_cache, value.cache_dir) } } diff --git a/crates/uv-cache/src/lib.rs b/crates/uv-cache/src/lib.rs index d16c6427c..1eec4370b 100644 --- a/crates/uv-cache/src/lib.rs +++ b/crates/uv-cache/src/lib.rs @@ -1211,7 +1211,7 @@ impl Refresh { /// Combine two [`Refresh`] policies, taking the "max" of the two policies. #[must_use] - pub fn combine(self, other: Refresh) -> Self { + pub fn combine(self, other: Self) -> Self { /// Return the maximum of two timestamps. fn max(a: Timestamp, b: Timestamp) -> Timestamp { if a > b { a } else { b } @@ -1220,24 +1220,24 @@ impl Refresh { match (self, other) { // If the policy is `None`, return the existing refresh policy. // Take the `max` of the two timestamps. - (Self::None(t1), Refresh::None(t2)) => Refresh::None(max(t1, t2)), - (Self::None(t1), Refresh::All(t2)) => Refresh::All(max(t1, t2)), - (Self::None(t1), Refresh::Packages(packages, paths, t2)) => { - Refresh::Packages(packages, paths, max(t1, t2)) + (Self::None(t1), Self::None(t2)) => Self::None(max(t1, t2)), + (Self::None(t1), Self::All(t2)) => Self::All(max(t1, t2)), + (Self::None(t1), Self::Packages(packages, paths, t2)) => { + Self::Packages(packages, paths, max(t1, t2)) } // If the policy is `All`, refresh all packages. - (Self::All(t1), Refresh::None(t2)) => Refresh::All(max(t1, t2)), - (Self::All(t1), Refresh::All(t2)) => Refresh::All(max(t1, t2)), - (Self::All(t1), Refresh::Packages(.., t2)) => Refresh::All(max(t1, t2)), + (Self::All(t1), Self::None(t2)) => Self::All(max(t1, t2)), + (Self::All(t1), Self::All(t2)) => Self::All(max(t1, t2)), + (Self::All(t1), Self::Packages(.., t2)) => Self::All(max(t1, t2)), // If the policy is `Packages`, take the "max" of the two policies. - (Self::Packages(packages, paths, t1), Refresh::None(t2)) => { - Refresh::Packages(packages, paths, max(t1, t2)) + (Self::Packages(packages, paths, t1), Self::None(t2)) => { + Self::Packages(packages, paths, max(t1, t2)) } - (Self::Packages(.., t1), Refresh::All(t2)) => Refresh::All(max(t1, t2)), - (Self::Packages(packages1, paths1, t1), Refresh::Packages(packages2, paths2, t2)) => { - Refresh::Packages( + (Self::Packages(.., t1), Self::All(t2)) => Self::All(max(t1, t2)), + (Self::Packages(packages1, paths1, t1), Self::Packages(packages2, paths2, t2)) => { + Self::Packages( packages1.into_iter().chain(packages2).collect(), paths1.into_iter().chain(paths2).collect(), max(t1, t2), diff --git a/crates/uv-cache/src/wheel.rs b/crates/uv-cache/src/wheel.rs index 76103f0ff..406efd4eb 100644 --- a/crates/uv-cache/src/wheel.rs +++ b/crates/uv-cache/src/wheel.rs @@ -26,20 +26,20 @@ impl WheelCache<'_> { /// The root directory for a cache bucket. pub fn root(&self) -> PathBuf { match self { - WheelCache::Index(IndexUrl::Pypi(_)) => WheelCacheKind::Pypi.root(), - WheelCache::Index(url) => WheelCacheKind::Index + Self::Index(IndexUrl::Pypi(_)) => WheelCacheKind::Pypi.root(), + Self::Index(url) => WheelCacheKind::Index .root() .join(cache_digest(&CanonicalUrl::new(url.url()))), - WheelCache::Url(url) => WheelCacheKind::Url + Self::Url(url) => WheelCacheKind::Url .root() .join(cache_digest(&CanonicalUrl::new(url))), - WheelCache::Path(url) => WheelCacheKind::Path + Self::Path(url) => WheelCacheKind::Path .root() .join(cache_digest(&CanonicalUrl::new(url))), - WheelCache::Editable(url) => WheelCacheKind::Editable + Self::Editable(url) => WheelCacheKind::Editable .root() .join(cache_digest(&CanonicalUrl::new(url))), - WheelCache::Git(url, sha) => WheelCacheKind::Git + Self::Git(url, sha) => WheelCacheKind::Git .root() .join(cache_digest(&CanonicalUrl::new(url))) .join(sha), diff --git a/crates/uv-cli/src/lib.rs b/crates/uv-cli/src/lib.rs index f80abc06d..6bea81e84 100644 --- a/crates/uv-cli/src/lib.rs +++ b/crates/uv-cli/src/lib.rs @@ -680,15 +680,15 @@ pub enum VersionBump { impl std::fmt::Display for VersionBump { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let string = match self { - VersionBump::Major => "major", - VersionBump::Minor => "minor", - VersionBump::Patch => "patch", - VersionBump::Stable => "stable", - VersionBump::Alpha => "alpha", - VersionBump::Beta => "beta", - VersionBump::Rc => "rc", - VersionBump::Post => "post", - VersionBump::Dev => "dev", + Self::Major => "major", + Self::Minor => "minor", + Self::Patch => "patch", + Self::Stable => "stable", + Self::Alpha => "alpha", + Self::Beta => "beta", + Self::Rc => "rc", + Self::Post => "post", + Self::Dev => "dev", }; string.fmt(f) } @@ -1017,13 +1017,13 @@ pub enum Maybe { impl Maybe { pub fn into_option(self) -> Option { match self { - Maybe::Some(value) => Some(value), - Maybe::None => None, + Self::Some(value) => Some(value), + Self::None => None, } } pub fn is_some(&self) -> bool { - matches!(self, Maybe::Some(_)) + matches!(self, Self::Some(_)) } } diff --git a/crates/uv-cli/src/options.rs b/crates/uv-cli/src/options.rs index 54c2d80ca..79ca96a7c 100644 --- a/crates/uv-cli/src/options.rs +++ b/crates/uv-cli/src/options.rs @@ -97,7 +97,7 @@ impl From for PipOptions { exclude_newer_package: exclude_newer_package.map(ExcludeNewerPackage::from_iter), link_mode, no_sources: if no_sources { Some(true) } else { None }, - ..PipOptions::from(index_args) + ..Self::from(index_args) } } } @@ -141,7 +141,7 @@ impl From for PipOptions { link_mode, compile_bytecode: flag(compile_bytecode, no_compile_bytecode, "compile-bytecode"), no_sources: if no_sources { Some(true) } else { None }, - ..PipOptions::from(index_args) + ..Self::from(index_args) } } } @@ -203,7 +203,7 @@ impl From for PipOptions { link_mode, compile_bytecode: flag(compile_bytecode, no_compile_bytecode, "compile-bytecode"), no_sources: if no_sources { Some(true) } else { None }, - ..PipOptions::from(index_args) + ..Self::from(index_args) } } } @@ -221,7 +221,7 @@ impl From for PipOptions { index_strategy, keyring_provider, exclude_newer, - ..PipOptions::from(index_args) + ..Self::from(index_args) } } } @@ -262,7 +262,7 @@ impl From for PipOptions { .filter_map(Maybe::into_option) .collect() }), - ..PipOptions::default() + ..Self::default() } } } diff --git a/crates/uv-client/src/base_client.rs b/crates/uv-client/src/base_client.rs index e4945f5ee..aab5f5b70 100644 --- a/crates/uv-client/src/base_client.rs +++ b/crates/uv-client/src/base_client.rs @@ -98,8 +98,8 @@ pub enum RedirectPolicy { impl RedirectPolicy { pub fn reqwest_policy(self) -> reqwest::redirect::Policy { match self { - RedirectPolicy::BypassMiddleware => reqwest::redirect::Policy::default(), - RedirectPolicy::RetriggerMiddleware => reqwest::redirect::Policy::none(), + Self::BypassMiddleware => reqwest::redirect::Policy::default(), + Self::RetriggerMiddleware => reqwest::redirect::Policy::none(), } } } @@ -640,7 +640,7 @@ impl RedirectClientWithMiddleware { } impl From for ClientWithMiddleware { - fn from(item: RedirectClientWithMiddleware) -> ClientWithMiddleware { + fn from(item: RedirectClientWithMiddleware) -> Self { item.client } } diff --git a/crates/uv-client/src/cached_client.rs b/crates/uv-client/src/cached_client.rs index 349506325..24808f80f 100644 --- a/crates/uv-client/src/cached_client.rs +++ b/crates/uv-client/src/cached_client.rs @@ -117,17 +117,17 @@ impl CachedClientError Self { match self { - CachedClientError::Client { + Self::Client { retries: existing_retries, err, - } => CachedClientError::Client { + } => Self::Client { retries: Some(existing_retries.unwrap_or_default() + retries), err, }, - CachedClientError::Callback { + Self::Callback { retries: existing_retries, err, - } => CachedClientError::Callback { + } => Self::Callback { retries: Some(existing_retries.unwrap_or_default() + retries), err, }, @@ -136,15 +136,15 @@ impl CachedClientError Option { match self { - CachedClientError::Client { retries, .. } => *retries, - CachedClientError::Callback { retries, .. } => *retries, + Self::Client { retries, .. } => *retries, + Self::Callback { retries, .. } => *retries, } } fn error(&self) -> &dyn std::error::Error { match self { - CachedClientError::Client { err, .. } => err, - CachedClientError::Callback { err, .. } => err, + Self::Client { err, .. } => err, + Self::Callback { err, .. } => err, } } } @@ -176,12 +176,12 @@ impl + std::error::Error + 'static> From> for CachedClientError::Client { retries: Some(retries), err, - } => Error::new(err.into_kind(), retries), + } => Self::new(err.into_kind(), retries), CachedClientError::Client { retries: None, err } => err, CachedClientError::Callback { retries: Some(retries), err, - } => Error::new(err.into().into_kind(), retries), + } => Self::new(err.into().into_kind(), retries), CachedClientError::Callback { retries: None, err } => err.into(), } } diff --git a/crates/uv-client/src/httpcache/control.rs b/crates/uv-client/src/httpcache/control.rs index ddac9d1bc..fffc55cb5 100644 --- a/crates/uv-client/src/httpcache/control.rs +++ b/crates/uv-client/src/httpcache/control.rs @@ -179,7 +179,7 @@ struct CacheControlParser<'b, I> { impl<'b, B: 'b + ?Sized + AsRef<[u8]>, I: Iterator> CacheControlParser<'b, I> { /// Create a new parser of zero or more `Cache-Control` header values. The /// given iterator should yield elements that satisfy `AsRef<[u8]>`. - fn new>(headers: II) -> CacheControlParser<'b, I> { + fn new>(headers: II) -> Self { let mut directives = headers.into_iter(); let cur = directives.next().map(AsRef::as_ref).unwrap_or(b""); CacheControlParser { diff --git a/crates/uv-client/src/registry_client.rs b/crates/uv-client/src/registry_client.rs index 73932dbd4..3a7b049a3 100644 --- a/crates/uv-client/src/registry_client.rs +++ b/crates/uv-client/src/registry_client.rs @@ -1179,11 +1179,7 @@ impl SimpleMetadata { let SimpleHtml { base, files } = SimpleHtml::parse(text, url).map_err(|err| Error::from_html_err(err, url.clone()))?; - Ok(SimpleMetadata::from_files( - files, - package_name, - base.as_url(), - )) + Ok(Self::from_files(files, package_name, base.as_url())) } } diff --git a/crates/uv-configuration/src/concurrency.rs b/crates/uv-configuration/src/concurrency.rs index 8e9ef2200..77860474e 100644 --- a/crates/uv-configuration/src/concurrency.rs +++ b/crates/uv-configuration/src/concurrency.rs @@ -19,10 +19,10 @@ pub struct Concurrency { impl Default for Concurrency { fn default() -> Self { - Concurrency { - downloads: Concurrency::DEFAULT_DOWNLOADS, - builds: Concurrency::threads(), - installs: Concurrency::threads(), + Self { + downloads: Self::DEFAULT_DOWNLOADS, + builds: Self::threads(), + installs: Self::threads(), } } } diff --git a/crates/uv-configuration/src/config_settings.rs b/crates/uv-configuration/src/config_settings.rs index c6238deb2..d1e888696 100644 --- a/crates/uv-configuration/src/config_settings.rs +++ b/crates/uv-configuration/src/config_settings.rs @@ -67,8 +67,8 @@ enum ConfigSettingValue { impl serde::Serialize for ConfigSettingValue { fn serialize(&self, serializer: S) -> Result { match self { - ConfigSettingValue::String(value) => serializer.serialize_str(value), - ConfigSettingValue::List(values) => serializer.collect_seq(values.iter()), + Self::String(value) => serializer.serialize_str(value), + Self::List(values) => serializer.collect_seq(values.iter()), } } } @@ -153,7 +153,7 @@ impl ConfigSettings { /// Merge two sets of config settings, with the values in `self` taking precedence. #[must_use] - pub fn merge(self, other: ConfigSettings) -> ConfigSettings { + pub fn merge(self, other: Self) -> Self { let mut config = self.0; for (key, value) in other.0 { match config.entry(key) { @@ -277,7 +277,7 @@ impl PackageConfigSettings { /// Merge two sets of package config settings, with the values in `self` taking precedence. #[must_use] - pub fn merge(mut self, other: PackageConfigSettings) -> PackageConfigSettings { + pub fn merge(mut self, other: Self) -> Self { for (package, settings) in other.0 { match self.0.entry(package) { Entry::Vacant(vacant) => { diff --git a/crates/uv-configuration/src/dependency_groups.rs b/crates/uv-configuration/src/dependency_groups.rs index 70dd9db08..474406ba5 100644 --- a/crates/uv-configuration/src/dependency_groups.rs +++ b/crates/uv-configuration/src/dependency_groups.rs @@ -253,7 +253,7 @@ impl DependencyGroupsHistory { /// [`DependencyGroups::is_empty`][] when there aren't any defaults set. /// When there are defaults the two will disagree, and rightfully so! pub fn as_flags_pretty(&self) -> Vec> { - let DependencyGroupsHistory { + let Self { dev_mode, group, only_group, @@ -362,26 +362,26 @@ impl IncludeGroups { /// Returns `true` if the specification includes the given group. pub fn contains(&self, group: &GroupName) -> bool { match self { - IncludeGroups::Some(groups) => groups.contains(group), - IncludeGroups::All => true, + Self::Some(groups) => groups.contains(group), + Self::All => true, } } /// Returns `true` if the specification will have no effect. pub fn is_empty(&self) -> bool { match self { - IncludeGroups::Some(groups) => groups.is_empty(), + Self::Some(groups) => groups.is_empty(), // Although technically this is a noop if they have no groups, // conceptually they're *trying* to have an effect, so treat it as one. - IncludeGroups::All => false, + Self::All => false, } } /// Iterate over all groups referenced in the [`IncludeGroups`]. pub fn names(&self) -> std::slice::Iter { match self { - IncludeGroups::Some(groups) => groups.iter(), - IncludeGroups::All => [].iter(), + Self::Some(groups) => groups.iter(), + Self::All => [].iter(), } } } diff --git a/crates/uv-configuration/src/dry_run.rs b/crates/uv-configuration/src/dry_run.rs index cf28a1f6b..ac599a9d1 100644 --- a/crates/uv-configuration/src/dry_run.rs +++ b/crates/uv-configuration/src/dry_run.rs @@ -14,14 +14,14 @@ impl DryRun { /// Determine the [`DryRun`] setting based on the command-line arguments. pub fn from_args(dry_run: bool) -> Self { if dry_run { - DryRun::Enabled + Self::Enabled } else { - DryRun::Disabled + Self::Disabled } } /// Returns `true` if dry run mode is enabled. pub const fn enabled(&self) -> bool { - matches!(self, DryRun::Enabled) || matches!(self, DryRun::Check) + matches!(self, Self::Enabled) || matches!(self, Self::Check) } } diff --git a/crates/uv-configuration/src/extras.rs b/crates/uv-configuration/src/extras.rs index 5bb74240f..40fc72d28 100644 --- a/crates/uv-configuration/src/extras.rs +++ b/crates/uv-configuration/src/extras.rs @@ -214,7 +214,7 @@ impl ExtrasSpecificationHistory { /// [`ExtrasSpecification::is_empty`][] when there aren't any defaults set. /// When there are defaults the two will disagree, and rightfully so! pub fn as_flags_pretty(&self) -> Vec> { - let ExtrasSpecificationHistory { + let Self { extra, no_extra, all_extras, @@ -296,26 +296,26 @@ impl IncludeExtras { /// Returns `true` if the specification includes the given extra. pub fn contains(&self, extra: &ExtraName) -> bool { match self { - IncludeExtras::Some(extras) => extras.contains(extra), - IncludeExtras::All => true, + Self::Some(extras) => extras.contains(extra), + Self::All => true, } } /// Returns `true` if the specification will have no effect. pub fn is_empty(&self) -> bool { match self { - IncludeExtras::Some(extras) => extras.is_empty(), + Self::Some(extras) => extras.is_empty(), // Although technically this is a noop if they have no extras, // conceptually they're *trying* to have an effect, so treat it as one. - IncludeExtras::All => false, + Self::All => false, } } /// Iterate over all extras referenced in the [`IncludeExtras`]. pub fn names(&self) -> std::slice::Iter { match self { - IncludeExtras::Some(extras) => extras.iter(), - IncludeExtras::All => [].iter(), + Self::Some(extras) => extras.iter(), + Self::All => [].iter(), } } } diff --git a/crates/uv-configuration/src/preview.rs b/crates/uv-configuration/src/preview.rs index fab7dd34e..53fb462cf 100644 --- a/crates/uv-configuration/src/preview.rs +++ b/crates/uv-configuration/src/preview.rs @@ -40,7 +40,7 @@ impl Display for PreviewFeatures { if self.is_empty() { write!(f, "none") } else { - let features: Vec<&str> = self.iter().map(PreviewFeatures::flag_as_str).collect(); + let features: Vec<&str> = self.iter().map(Self::flag_as_str).collect(); write!(f, "{}", features.join(",")) } } @@ -56,7 +56,7 @@ impl FromStr for PreviewFeatures { type Err = PreviewFeaturesParseError; fn from_str(s: &str) -> Result { - let mut flags = PreviewFeatures::empty(); + let mut flags = Self::empty(); for part in s.split(',') { let part = part.trim(); diff --git a/crates/uv-configuration/src/trusted_host.rs b/crates/uv-configuration/src/trusted_host.rs index 07ff2998a..9cd1c6708 100644 --- a/crates/uv-configuration/src/trusted_host.rs +++ b/crates/uv-configuration/src/trusted_host.rs @@ -20,8 +20,8 @@ impl TrustedHost { /// Returns `true` if the [`Url`] matches this trusted host. pub fn matches(&self, url: &Url) -> bool { match self { - TrustedHost::Wildcard => true, - TrustedHost::Host { scheme, host, port } => { + Self::Wildcard => true, + Self::Host { scheme, host, port } => { if scheme.as_ref().is_some_and(|scheme| scheme != url.scheme()) { return false; } @@ -53,9 +53,9 @@ impl<'de> Deserialize<'de> for TrustedHost { } serde_untagged::UntaggedEnumVisitor::new() - .string(|string| TrustedHost::from_str(string).map_err(serde::de::Error::custom)) + .string(|string| Self::from_str(string).map_err(serde::de::Error::custom)) .map(|map| { - map.deserialize::().map(|inner| TrustedHost::Host { + map.deserialize::().map(|inner| Self::Host { scheme: inner.scheme, host: inner.host, port: inner.port, @@ -123,10 +123,10 @@ impl FromStr for TrustedHost { impl std::fmt::Display for TrustedHost { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { - TrustedHost::Wildcard => { + Self::Wildcard => { write!(f, "*")?; } - TrustedHost::Host { scheme, host, port } => { + Self::Host { scheme, host, port } => { if let Some(scheme) = &scheme { write!(f, "{scheme}://{host}")?; } else { diff --git a/crates/uv-dev/src/generate_options_reference.rs b/crates/uv-dev/src/generate_options_reference.rs index a2b8868eb..1ec353ff2 100644 --- a/crates/uv-dev/src/generate_options_reference.rs +++ b/crates/uv-dev/src/generate_options_reference.rs @@ -193,15 +193,15 @@ enum Set { impl Set { fn name(&self) -> Option<&str> { match self { - Set::Global { .. } => None, - Set::Named { name, .. } => Some(name), + Self::Global { .. } => None, + Self::Named { name, .. } => Some(name), } } fn metadata(&self) -> &OptionSet { match self { - Set::Global { set, .. } => set, - Set::Named { set, .. } => set, + Self::Global { set, .. } => set, + Self::Named { set, .. } => set, } } } diff --git a/crates/uv-dispatch/src/lib.rs b/crates/uv-dispatch/src/lib.rs index 2112be4ef..c70e18ecc 100644 --- a/crates/uv-dispatch/src/lib.rs +++ b/crates/uv-dispatch/src/lib.rs @@ -66,12 +66,12 @@ pub enum BuildDispatchError { impl IsBuildBackendError for BuildDispatchError { fn is_build_backend_error(&self) -> bool { match self { - BuildDispatchError::Tags(_) - | BuildDispatchError::Resolve(_) - | BuildDispatchError::Join(_) - | BuildDispatchError::Anyhow(_) - | BuildDispatchError::Prepare(_) => false, - BuildDispatchError::BuildFrontend(err) => err.is_build_backend_error(), + Self::Tags(_) + | Self::Resolve(_) + | Self::Join(_) + | Self::Anyhow(_) + | Self::Prepare(_) => false, + Self::BuildFrontend(err) => err.is_build_backend_error(), } } } diff --git a/crates/uv-distribution-filename/src/build_tag.rs b/crates/uv-distribution-filename/src/build_tag.rs index 64f49ef23..30c048f5b 100644 --- a/crates/uv-distribution-filename/src/build_tag.rs +++ b/crates/uv-distribution-filename/src/build_tag.rs @@ -58,10 +58,7 @@ impl FromStr for BuildTag { None => (s, None), }; - Ok(BuildTag( - prefix.parse::()?, - suffix.map(SmallString::from), - )) + Ok(Self(prefix.parse::()?, suffix.map(SmallString::from))) } } diff --git a/crates/uv-distribution-types/src/dist_error.rs b/crates/uv-distribution-types/src/dist_error.rs index d2cfee16d..8708081aa 100644 --- a/crates/uv-distribution-types/src/dist_error.rs +++ b/crates/uv-distribution-types/src/dist_error.rs @@ -32,26 +32,24 @@ pub enum DistErrorKind { impl DistErrorKind { pub fn from_requested_dist(dist: &RequestedDist, err: &impl IsBuildBackendError) -> Self { match dist { - RequestedDist::Installed(_) => DistErrorKind::Read, + RequestedDist::Installed(_) => Self::Read, RequestedDist::Installable(dist) => Self::from_dist(dist, err), } } pub fn from_dist(dist: &Dist, err: &impl IsBuildBackendError) -> Self { if err.is_build_backend_error() { - DistErrorKind::BuildBackend + Self::BuildBackend } else { match dist { - Dist::Built(BuiltDist::Path(_)) => DistErrorKind::Read, - Dist::Source(SourceDist::Path(_) | SourceDist::Directory(_)) => { - DistErrorKind::Build - } - Dist::Built(_) => DistErrorKind::Download, + Dist::Built(BuiltDist::Path(_)) => Self::Read, + Dist::Source(SourceDist::Path(_) | SourceDist::Directory(_)) => Self::Build, + Dist::Built(_) => Self::Download, Dist::Source(source_dist) => { if source_dist.is_local() { - DistErrorKind::Build + Self::Build } else { - DistErrorKind::DownloadAndBuild + Self::DownloadAndBuild } } } @@ -62,11 +60,11 @@ impl DistErrorKind { impl Display for DistErrorKind { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - DistErrorKind::Download => f.write_str("Failed to download"), - DistErrorKind::DownloadAndBuild => f.write_str("Failed to download and build"), - DistErrorKind::Build => f.write_str("Failed to build"), - DistErrorKind::BuildBackend => f.write_str("Failed to build"), - DistErrorKind::Read => f.write_str("Failed to read"), + Self::Download => f.write_str("Failed to download"), + Self::DownloadAndBuild => f.write_str("Failed to download and build"), + Self::Build => f.write_str("Failed to build"), + Self::BuildBackend => f.write_str("Failed to build"), + Self::Read => f.write_str("Failed to read"), } } } @@ -87,10 +85,7 @@ impl DerivationChain { /// /// This is used to construct a derivation chain upon install failure in the `uv pip` context, /// where we don't have a lockfile describing the resolution. - pub fn from_resolution( - resolution: &Resolution, - target: DistRef<'_>, - ) -> Option { + pub fn from_resolution(resolution: &Resolution, target: DistRef<'_>) -> Option { // Find the target distribution in the resolution graph. let target = resolution.graph().node_indices().find(|node| { let Node::Dist { @@ -117,7 +112,7 @@ impl DerivationChain { Node::Root => { path.reverse(); path.pop(); - return Some(DerivationChain::from_iter(path)); + return Some(Self::from_iter(path)); } Node::Dist { dist, .. } => { for edge in resolution.graph().edges_directed(node, Direction::Incoming) { diff --git a/crates/uv-distribution-types/src/file.rs b/crates/uv-distribution-types/src/file.rs index b16305f73..eb4794152 100644 --- a/crates/uv-distribution-types/src/file.rs +++ b/crates/uv-distribution-types/src/file.rs @@ -80,8 +80,8 @@ impl FileLocation { /// that page. pub fn new(url: SmallString, base: &SmallString) -> Self { match split_scheme(&url) { - Some(..) => FileLocation::AbsoluteUrl(UrlString::new(url)), - None => FileLocation::RelativeUrl(base.clone(), url), + Some(..) => Self::AbsoluteUrl(UrlString::new(url)), + None => Self::RelativeUrl(base.clone(), url), } } @@ -98,7 +98,7 @@ impl FileLocation { /// (Because URLs must be valid UTF-8.) pub fn to_url(&self) -> Result { match *self { - FileLocation::RelativeUrl(ref base, ref path) => { + Self::RelativeUrl(ref base, ref path) => { let base_url = DisplaySafeUrl::parse(base).map_err(|err| ToUrlError::InvalidBase { base: base.to_string(), @@ -111,7 +111,7 @@ impl FileLocation { })?; Ok(joined) } - FileLocation::AbsoluteUrl(ref absolute) => absolute.to_url(), + Self::AbsoluteUrl(ref absolute) => absolute.to_url(), } } } @@ -174,7 +174,7 @@ impl UrlString { pub fn without_fragment(&self) -> Cow<'_, Self> { self.as_ref() .split_once('#') - .map(|(path, _)| Cow::Owned(UrlString(SmallString::from(path)))) + .map(|(path, _)| Cow::Owned(Self(SmallString::from(path)))) .unwrap_or(Cow::Borrowed(self)) } } diff --git a/crates/uv-distribution-types/src/hash.rs b/crates/uv-distribution-types/src/hash.rs index def798af3..935001927 100644 --- a/crates/uv-distribution-types/src/hash.rs +++ b/crates/uv-distribution-types/src/hash.rs @@ -25,12 +25,12 @@ impl HashPolicy<'_> { /// Returns `true` if the hash policy indicates that hashes should be generated. pub fn is_generate(&self, dist: &crate::BuiltDist) -> bool { match self { - HashPolicy::Generate(HashGeneration::Url) => dist.file().is_none(), - HashPolicy::Generate(HashGeneration::All) => { + Self::Generate(HashGeneration::Url) => dist.file().is_none(), + Self::Generate(HashGeneration::All) => { dist.file().is_none_or(|file| file.hashes.is_empty()) } - HashPolicy::Validate(_) => false, - HashPolicy::None => false, + Self::Validate(_) => false, + Self::None => false, } } diff --git a/crates/uv-distribution-types/src/index_name.rs b/crates/uv-distribution-types/src/index_name.rs index 4b48164d0..2920306c3 100644 --- a/crates/uv-distribution-types/src/index_name.rs +++ b/crates/uv-distribution-types/src/index_name.rs @@ -62,7 +62,7 @@ impl<'de> serde::de::Deserialize<'de> for IndexName { D: serde::de::Deserializer<'de>, { let s = Cow::<'_, str>::deserialize(deserializer)?; - IndexName::new(&s).map_err(serde::de::Error::custom) + Self::new(&s).map_err(serde::de::Error::custom) } } diff --git a/crates/uv-distribution-types/src/index_url.rs b/crates/uv-distribution-types/src/index_url.rs index e995e059d..32cf12bc4 100644 --- a/crates/uv-distribution-types/src/index_url.rs +++ b/crates/uv-distribution-types/src/index_url.rs @@ -212,7 +212,7 @@ impl serde::ser::Serialize for IndexUrl { } impl<'de> serde::de::Deserialize<'de> for IndexUrl { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::de::Deserializer<'de>, { @@ -488,8 +488,8 @@ impl<'a> IndexLocations { } impl From<&IndexLocations> for uv_auth::Indexes { - fn from(index_locations: &IndexLocations) -> uv_auth::Indexes { - uv_auth::Indexes::from_indexes(index_locations.allowed_indexes().into_iter().map(|index| { + fn from(index_locations: &IndexLocations) -> Self { + Self::from_indexes(index_locations.allowed_indexes().into_iter().map(|index| { let mut url = index.url().url().clone(); url.set_username("").ok(); url.set_password(None).ok(); diff --git a/crates/uv-distribution-types/src/known_platform.rs b/crates/uv-distribution-types/src/known_platform.rs index f00694064..954d5d297 100644 --- a/crates/uv-distribution-types/src/known_platform.rs +++ b/crates/uv-distribution-types/src/known_platform.rs @@ -14,9 +14,9 @@ impl KnownPlatform { /// Return the platform's `sys.platform` value. pub fn sys_platform(self) -> &'static str { match self { - KnownPlatform::Linux => "linux", - KnownPlatform::Windows => "win32", - KnownPlatform::MacOS => "darwin", + Self::Linux => "linux", + Self::Windows => "win32", + Self::MacOS => "darwin", } } @@ -26,21 +26,21 @@ impl KnownPlatform { key: MarkerValueString::SysPlatform, operator: MarkerOperator::Equal, value: match self { - KnownPlatform::Linux => arcstr::literal!("linux"), - KnownPlatform::Windows => arcstr::literal!("win32"), - KnownPlatform::MacOS => arcstr::literal!("darwin"), + Self::Linux => arcstr::literal!("linux"), + Self::Windows => arcstr::literal!("win32"), + Self::MacOS => arcstr::literal!("darwin"), }, }) } /// Determine the [`KnownPlatform`] from a marker tree. - pub fn from_marker(marker: MarkerTree) -> Option { - if marker == KnownPlatform::Linux.marker() { - Some(KnownPlatform::Linux) - } else if marker == KnownPlatform::Windows.marker() { - Some(KnownPlatform::Windows) - } else if marker == KnownPlatform::MacOS.marker() { - Some(KnownPlatform::MacOS) + pub fn from_marker(marker: MarkerTree) -> Option { + if marker == Self::Linux.marker() { + Some(Self::Linux) + } else if marker == Self::Windows.marker() { + Some(Self::Windows) + } else if marker == Self::MacOS.marker() { + Some(Self::MacOS) } else { None } @@ -50,9 +50,9 @@ impl KnownPlatform { impl Display for KnownPlatform { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - KnownPlatform::Linux => write!(f, "Linux"), - KnownPlatform::Windows => write!(f, "Windows"), - KnownPlatform::MacOS => write!(f, "macOS"), + Self::Linux => write!(f, "Linux"), + Self::Windows => write!(f, "Windows"), + Self::MacOS => write!(f, "macOS"), } } } diff --git a/crates/uv-distribution-types/src/lib.rs b/crates/uv-distribution-types/src/lib.rs index 98cea2582..c6dd1b21c 100644 --- a/crates/uv-distribution-types/src/lib.rs +++ b/crates/uv-distribution-types/src/lib.rs @@ -122,8 +122,8 @@ impl VersionOrUrlRef<'_, T> { /// If it is a URL, return its value. pub fn url(&self) -> Option<&T> { match self { - VersionOrUrlRef::Version(_) => None, - VersionOrUrlRef::Url(url) => Some(url), + Self::Version(_) => None, + Self::Url(url) => Some(url), } } } @@ -131,8 +131,8 @@ impl VersionOrUrlRef<'_, T> { impl Verbatim for VersionOrUrlRef<'_> { fn verbatim(&self) -> Cow<'_, str> { match self { - VersionOrUrlRef::Version(version) => Cow::Owned(format!("=={version}")), - VersionOrUrlRef::Url(url) => Cow::Owned(format!(" @ {}", url.verbatim())), + Self::Version(version) => Cow::Owned(format!("=={version}")), + Self::Url(url) => Cow::Owned(format!(" @ {}", url.verbatim())), } } } @@ -140,8 +140,8 @@ impl Verbatim for VersionOrUrlRef<'_> { impl std::fmt::Display for VersionOrUrlRef<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - VersionOrUrlRef::Version(version) => write!(f, "=={version}"), - VersionOrUrlRef::Url(url) => write!(f, " @ {url}"), + Self::Version(version) => write!(f, "=={version}"), + Self::Url(url) => write!(f, " @ {url}"), } } } @@ -159,16 +159,16 @@ impl InstalledVersion<'_> { /// If it is a URL, return its value. pub fn url(&self) -> Option<&DisplaySafeUrl> { match self { - InstalledVersion::Version(_) => None, - InstalledVersion::Url(url, _) => Some(url), + Self::Version(_) => None, + Self::Url(url, _) => Some(url), } } /// If it is a version, return its value. pub fn version(&self) -> &Version { match self { - InstalledVersion::Version(version) => version, - InstalledVersion::Url(_, version) => version, + Self::Version(version) => version, + Self::Url(_, version) => version, } } } @@ -176,8 +176,8 @@ impl InstalledVersion<'_> { impl std::fmt::Display for InstalledVersion<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - InstalledVersion::Version(version) => write!(f, "=={version}"), - InstalledVersion::Url(url, version) => write!(f, "=={version} (from {url})"), + Self::Version(version) => write!(f, "=={version}"), + Self::Url(url, version) => write!(f, "=={version} (from {url})"), } } } @@ -361,7 +361,7 @@ impl Dist { location: DisplaySafeUrl, subdirectory: Option>, ext: DistExtension, - ) -> Result { + ) -> Result { match ext { DistExtension::Wheel => { // Validate that the name in the wheel matches that of the requirement. @@ -398,7 +398,7 @@ impl Dist { url: VerbatimUrl, install_path: &Path, ext: DistExtension, - ) -> Result { + ) -> Result { // Convert to an absolute path. let install_path = path::absolute(install_path)?; @@ -456,7 +456,7 @@ impl Dist { install_path: &Path, editable: Option, r#virtual: Option, - ) -> Result { + ) -> Result { // Convert to an absolute path. let install_path = path::absolute(install_path)?; @@ -484,7 +484,7 @@ impl Dist { url: VerbatimUrl, git: GitUrl, subdirectory: Option>, - ) -> Result { + ) -> Result { Ok(Self::Source(SourceDist::Git(GitSourceDist { name, git: Box::new(git), @@ -854,17 +854,17 @@ impl Name for Dist { impl Name for CompatibleDist<'_> { fn name(&self) -> &PackageName { match self { - CompatibleDist::InstalledDist(dist) => dist.name(), - CompatibleDist::SourceDist { + Self::InstalledDist(dist) => dist.name(), + Self::SourceDist { sdist, prioritized: _, } => sdist.name(), - CompatibleDist::CompatibleWheel { + Self::CompatibleWheel { wheel, priority: _, prioritized: _, } => wheel.name(), - CompatibleDist::IncompatibleWheel { + Self::IncompatibleWheel { sdist, wheel: _, prioritized: _, @@ -1450,15 +1450,15 @@ impl Identifier for SourceUrl<'_> { impl Identifier for BuildableSource<'_> { fn distribution_id(&self) -> DistributionId { match self { - BuildableSource::Dist(source) => source.distribution_id(), - BuildableSource::Url(source) => source.distribution_id(), + Self::Dist(source) => source.distribution_id(), + Self::Url(source) => source.distribution_id(), } } fn resource_id(&self) -> ResourceId { match self { - BuildableSource::Dist(source) => source.resource_id(), - BuildableSource::Url(source) => source.resource_id(), + Self::Dist(source) => source.resource_id(), + Self::Url(source) => source.resource_id(), } } } diff --git a/crates/uv-distribution-types/src/prioritized_distribution.rs b/crates/uv-distribution-types/src/prioritized_distribution.rs index 5046eea21..49ff51939 100644 --- a/crates/uv-distribution-types/src/prioritized_distribution.rs +++ b/crates/uv-distribution-types/src/prioritized_distribution.rs @@ -84,20 +84,20 @@ impl CompatibleDist<'_> { /// Return the `requires-python` specifier for the distribution, if any. pub fn requires_python(&self) -> Option<&VersionSpecifiers> { match self { - CompatibleDist::InstalledDist(_) => None, - CompatibleDist::SourceDist { sdist, .. } => sdist.file.requires_python.as_ref(), - CompatibleDist::CompatibleWheel { wheel, .. } => wheel.file.requires_python.as_ref(), - CompatibleDist::IncompatibleWheel { sdist, .. } => sdist.file.requires_python.as_ref(), + Self::InstalledDist(_) => None, + Self::SourceDist { sdist, .. } => sdist.file.requires_python.as_ref(), + Self::CompatibleWheel { wheel, .. } => wheel.file.requires_python.as_ref(), + Self::IncompatibleWheel { sdist, .. } => sdist.file.requires_python.as_ref(), } } // For installable distributions, return the prioritized distribution it was derived from. pub fn prioritized(&self) -> Option<&PrioritizedDist> { match self { - CompatibleDist::InstalledDist(_) => None, - CompatibleDist::SourceDist { prioritized, .. } - | CompatibleDist::CompatibleWheel { prioritized, .. } - | CompatibleDist::IncompatibleWheel { prioritized, .. } => Some(prioritized), + Self::InstalledDist(_) => None, + Self::SourceDist { prioritized, .. } + | Self::CompatibleWheel { prioritized, .. } + | Self::IncompatibleWheel { prioritized, .. } => Some(prioritized), } } @@ -654,10 +654,10 @@ impl<'a> CompatibleDist<'a> { /// wheel. pub fn wheel(&self) -> Option<&RegistryBuiltWheel> { match self { - CompatibleDist::InstalledDist(_) => None, - CompatibleDist::SourceDist { .. } => None, - CompatibleDist::CompatibleWheel { wheel, .. } => Some(wheel), - CompatibleDist::IncompatibleWheel { wheel, .. } => Some(wheel), + Self::InstalledDist(_) => None, + Self::SourceDist { .. } => None, + Self::CompatibleWheel { wheel, .. } => Some(wheel), + Self::IncompatibleWheel { wheel, .. } => Some(wheel), } } } diff --git a/crates/uv-distribution-types/src/requirement.rs b/crates/uv-distribution-types/src/requirement.rs index 49507aadf..4c845a8df 100644 --- a/crates/uv-distribution-types/src/requirement.rs +++ b/crates/uv-distribution-types/src/requirement.rs @@ -195,7 +195,7 @@ impl PartialOrd for Requirement { impl From for uv_pep508::Requirement { /// Convert a [`Requirement`] to a [`uv_pep508::Requirement`]. fn from(requirement: Requirement) -> Self { - uv_pep508::Requirement { + Self { name: requirement.name, extras: requirement.extras, marker: requirement.marker, @@ -216,7 +216,7 @@ impl From for uv_pep508::Requirement { impl From for uv_pep508::Requirement { /// Convert a [`Requirement`] to a [`uv_pep508::Requirement`]. fn from(requirement: Requirement) -> Self { - uv_pep508::Requirement { + Self { name: requirement.name, extras: requirement.extras, marker: requirement.marker, @@ -299,7 +299,7 @@ impl From> for Requirement { RequirementSource::from_parsed_url(url.parsed_url, url.verbatim) } }; - Requirement { + Self { name: requirement.name, groups: Box::new([]), extras: requirement.extras, @@ -544,23 +544,23 @@ impl RequirementSource { /// the PEP 508 string (after the `@`) as [`VerbatimUrl`]. pub fn from_parsed_url(parsed_url: ParsedUrl, url: VerbatimUrl) -> Self { match parsed_url { - ParsedUrl::Path(local_file) => RequirementSource::Path { + ParsedUrl::Path(local_file) => Self::Path { install_path: local_file.install_path.clone(), ext: local_file.ext, url, }, - ParsedUrl::Directory(directory) => RequirementSource::Directory { + ParsedUrl::Directory(directory) => Self::Directory { install_path: directory.install_path.clone(), editable: directory.editable, r#virtual: directory.r#virtual, url, }, - ParsedUrl::Git(git) => RequirementSource::Git { + ParsedUrl::Git(git) => Self::Git { git: git.url.clone(), url, subdirectory: git.subdirectory, }, - ParsedUrl::Archive(archive) => RequirementSource::Url { + ParsedUrl::Archive(archive) => Self::Url { url, location: archive.url, subdirectory: archive.subdirectory, @@ -668,21 +668,18 @@ impl RequirementSource { /// If the source is the registry, return the version specifiers pub fn version_specifiers(&self) -> Option<&VersionSpecifiers> { match self { - RequirementSource::Registry { specifier, .. } => Some(specifier), - RequirementSource::Url { .. } - | RequirementSource::Git { .. } - | RequirementSource::Path { .. } - | RequirementSource::Directory { .. } => None, + Self::Registry { specifier, .. } => Some(specifier), + Self::Url { .. } | Self::Git { .. } | Self::Path { .. } | Self::Directory { .. } => { + None + } } } /// Convert the source to a [`RequirementSource`] relative to the given path. pub fn relative_to(self, path: &Path) -> Result { match self { - RequirementSource::Registry { .. } - | RequirementSource::Url { .. } - | RequirementSource::Git { .. } => Ok(self), - RequirementSource::Path { + Self::Registry { .. } | Self::Url { .. } | Self::Git { .. } => Ok(self), + Self::Path { install_path, ext, url, @@ -693,7 +690,7 @@ impl RequirementSource { ext, url, }), - RequirementSource::Directory { + Self::Directory { install_path, editable, r#virtual, @@ -714,10 +711,8 @@ impl RequirementSource { #[must_use] pub fn to_absolute(self, root: &Path) -> Self { match self { - RequirementSource::Registry { .. } - | RequirementSource::Url { .. } - | RequirementSource::Git { .. } => self, - RequirementSource::Path { + Self::Registry { .. } | Self::Url { .. } | Self::Git { .. } => self, + Self::Path { install_path, ext, url, @@ -726,7 +721,7 @@ impl RequirementSource { ext, url, }, - RequirementSource::Directory { + Self::Directory { install_path, editable, r#virtual, @@ -920,7 +915,7 @@ impl From for RequirementSourceWire { impl TryFrom for RequirementSource { type Error = RequirementError; - fn try_from(wire: RequirementSourceWire) -> Result { + fn try_from(wire: RequirementSourceWire) -> Result { match wire { RequirementSourceWire::Registry { specifier, diff --git a/crates/uv-distribution-types/src/requires_python.rs b/crates/uv-distribution-types/src/requires_python.rs index 49a4fd5c4..eb46021a3 100644 --- a/crates/uv-distribution-types/src/requires_python.rs +++ b/crates/uv-distribution-types/src/requires_python.rs @@ -570,7 +570,7 @@ impl Default for RequiresPythonRange { impl From for Ranges { fn from(value: RequiresPythonRange) -> Self { - Ranges::from_range_bounds::<(Bound, Bound), _>(( + Self::from_range_bounds::<(Bound, Bound), _>(( value.0.into(), value.1.into(), )) @@ -590,8 +590,8 @@ pub struct SimplifiedMarkerTree(MarkerTree); impl SimplifiedMarkerTree { /// Simplifies the given markers by assuming the given `requires-python` /// bound is true. - pub fn new(requires_python: &RequiresPython, marker: MarkerTree) -> SimplifiedMarkerTree { - SimplifiedMarkerTree(requires_python.simplify_markers(marker)) + pub fn new(requires_python: &RequiresPython, marker: MarkerTree) -> Self { + Self(requires_python.simplify_markers(marker)) } /// Complexifies the given markers by adding the given `requires-python` as diff --git a/crates/uv-distribution-types/src/resolution.rs b/crates/uv-distribution-types/src/resolution.rs index e690b8693..667eb0338 100644 --- a/crates/uv-distribution-types/src/resolution.rs +++ b/crates/uv-distribution-types/src/resolution.rs @@ -215,7 +215,7 @@ impl From<&ResolvedDist> for RequirementSource { ResolvedDist::Installable { dist, .. } => match dist.as_ref() { Dist::Built(BuiltDist::Registry(wheels)) => { let wheel = wheels.best_wheel(); - RequirementSource::Registry { + Self::Registry { specifier: uv_pep440::VersionSpecifiers::from( uv_pep440::VersionSpecifier::equals_version( wheel.filename.version.clone(), @@ -228,19 +228,19 @@ impl From<&ResolvedDist> for RequirementSource { Dist::Built(BuiltDist::DirectUrl(wheel)) => { let mut location = wheel.url.to_url(); location.set_fragment(None); - RequirementSource::Url { + Self::Url { url: wheel.url.clone(), location, subdirectory: None, ext: DistExtension::Wheel, } } - Dist::Built(BuiltDist::Path(wheel)) => RequirementSource::Path { + Dist::Built(BuiltDist::Path(wheel)) => Self::Path { install_path: wheel.install_path.clone(), url: wheel.url.clone(), ext: DistExtension::Wheel, }, - Dist::Source(SourceDist::Registry(sdist)) => RequirementSource::Registry { + Dist::Source(SourceDist::Registry(sdist)) => Self::Registry { specifier: uv_pep440::VersionSpecifiers::from( uv_pep440::VersionSpecifier::equals_version(sdist.version.clone()), ), @@ -250,31 +250,31 @@ impl From<&ResolvedDist> for RequirementSource { Dist::Source(SourceDist::DirectUrl(sdist)) => { let mut location = sdist.url.to_url(); location.set_fragment(None); - RequirementSource::Url { + Self::Url { url: sdist.url.clone(), location, subdirectory: sdist.subdirectory.clone(), ext: DistExtension::Source(sdist.ext), } } - Dist::Source(SourceDist::Git(sdist)) => RequirementSource::Git { + Dist::Source(SourceDist::Git(sdist)) => Self::Git { git: (*sdist.git).clone(), url: sdist.url.clone(), subdirectory: sdist.subdirectory.clone(), }, - Dist::Source(SourceDist::Path(sdist)) => RequirementSource::Path { + Dist::Source(SourceDist::Path(sdist)) => Self::Path { install_path: sdist.install_path.clone(), url: sdist.url.clone(), ext: DistExtension::Source(sdist.ext), }, - Dist::Source(SourceDist::Directory(sdist)) => RequirementSource::Directory { + Dist::Source(SourceDist::Directory(sdist)) => Self::Directory { install_path: sdist.install_path.clone(), url: sdist.url.clone(), editable: sdist.editable, r#virtual: sdist.r#virtual, }, }, - ResolvedDist::Installed { dist } => RequirementSource::Registry { + ResolvedDist::Installed { dist } => Self::Registry { specifier: uv_pep440::VersionSpecifiers::from( uv_pep440::VersionSpecifier::equals_version(dist.version().clone()), ), diff --git a/crates/uv-distribution-types/src/status_code_strategy.rs b/crates/uv-distribution-types/src/status_code_strategy.rs index b019d0329..cced074ff 100644 --- a/crates/uv-distribution-types/src/status_code_strategy.rs +++ b/crates/uv-distribution-types/src/status_code_strategy.rs @@ -68,7 +68,7 @@ impl IndexStatusCodeStrategy { capabilities: &IndexCapabilities, ) -> IndexStatusCodeDecision { match self { - IndexStatusCodeStrategy::Default => match status_code { + Self::Default => match status_code { StatusCode::NOT_FOUND => IndexStatusCodeDecision::Ignore, StatusCode::UNAUTHORIZED => { capabilities.set_unauthorized(index_url.clone()); @@ -80,15 +80,11 @@ impl IndexStatusCodeStrategy { } _ => IndexStatusCodeDecision::Fail(status_code), }, - IndexStatusCodeStrategy::IgnoreErrorCodes { status_codes } => { + Self::IgnoreErrorCodes { status_codes } => { if status_codes.contains(&status_code) { IndexStatusCodeDecision::Ignore } else { - IndexStatusCodeStrategy::Default.handle_status_code( - status_code, - index_url, - capabilities, - ) + Self::Default.handle_status_code(status_code, index_url, capabilities) } } } diff --git a/crates/uv-distribution/src/distribution_database.rs b/crates/uv-distribution/src/distribution_database.rs index 30f3a243c..81a9bbe5c 100644 --- a/crates/uv-distribution/src/distribution_database.rs +++ b/crates/uv-distribution/src/distribution_database.rs @@ -1051,7 +1051,7 @@ pub struct ManagedClient<'a> { impl<'a> ManagedClient<'a> { /// Create a new `ManagedClient` using the given client and concurrency limit. - fn new(client: &'a RegistryClient, concurrency: usize) -> ManagedClient<'a> { + fn new(client: &'a RegistryClient, concurrency: usize) -> Self { ManagedClient { unmanaged: client, control: Semaphore::new(concurrency), @@ -1176,7 +1176,7 @@ impl LocalArchivePointer { /// Read an [`LocalArchivePointer`] from the cache. pub fn read_from(path: impl AsRef) -> Result, Error> { match fs_err::read(path) { - Ok(cached) => Ok(Some(rmp_serde::from_slice::(&cached)?)), + Ok(cached) => Ok(Some(rmp_serde::from_slice::(&cached)?)), Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(None), Err(err) => Err(Error::CacheRead(err)), } diff --git a/crates/uv-distribution/src/download.rs b/crates/uv-distribution/src/download.rs index 9bbe3a515..59582a762 100644 --- a/crates/uv-distribution/src/download.rs +++ b/crates/uv-distribution/src/download.rs @@ -55,8 +55,8 @@ impl Hashed for LocalWheel { /// Convert a [`LocalWheel`] into a [`CachedDist`]. impl From for CachedDist { - fn from(wheel: LocalWheel) -> CachedDist { - CachedDist::from_remote( + fn from(wheel: LocalWheel) -> Self { + Self::from_remote( wheel.dist, wheel.filename, wheel.hashes, diff --git a/crates/uv-distribution/src/error.rs b/crates/uv-distribution/src/error.rs index 7d0a9593b..12720eda6 100644 --- a/crates/uv-distribution/src/error.rs +++ b/crates/uv-distribution/src/error.rs @@ -189,7 +189,7 @@ impl Error { distribution: String, expected: &[HashDigest], actual: &[HashDigest], - ) -> Error { + ) -> Self { match (expected.is_empty(), actual.is_empty()) { (true, true) => Self::MissingHashes { distribution }, (true, false) => { diff --git a/crates/uv-distribution/src/metadata/lowering.rs b/crates/uv-distribution/src/metadata/lowering.rs index a8e899bb4..36b6ff3da 100644 --- a/crates/uv-distribution/src/metadata/lowering.rs +++ b/crates/uv-distribution/src/metadata/lowering.rs @@ -149,7 +149,7 @@ impl LoweredRequirement { let mut remaining = total.negate(); remaining.and(requirement.marker); - LoweredRequirement(Requirement { + Self(Requirement { marker: remaining, ..Requirement::from(requirement.clone()) }) @@ -389,7 +389,7 @@ impl LoweredRequirement { let mut remaining = total.negate(); remaining.and(requirement.marker); - LoweredRequirement(Requirement { + Self(Requirement { marker: remaining, ..Requirement::from(requirement.clone()) }) @@ -565,10 +565,10 @@ pub enum SourceKind { impl std::fmt::Display for SourceKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - SourceKind::Path => write!(f, "path"), - SourceKind::Url => write!(f, "URL"), - SourceKind::Git => write!(f, "Git"), - SourceKind::Registry => write!(f, "registry"), + Self::Path => write!(f, "path"), + Self::Url => write!(f, "URL"), + Self::Git => write!(f, "Git"), + Self::Registry => write!(f, "registry"), } } } diff --git a/crates/uv-distribution/src/source/mod.rs b/crates/uv-distribution/src/source/mod.rs index abcb57960..07ea80fa8 100644 --- a/crates/uv-distribution/src/source/mod.rs +++ b/crates/uv-distribution/src/source/mod.rs @@ -2889,9 +2889,7 @@ impl LocalRevisionPointer { /// Read an [`LocalRevisionPointer`] from the cache. pub(crate) fn read_from(path: impl AsRef) -> Result, Error> { match fs_err::read(path) { - Ok(cached) => Ok(Some(rmp_serde::from_slice::( - &cached, - )?)), + Ok(cached) => Ok(Some(rmp_serde::from_slice::(&cached)?)), Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(err) => Err(Error::CacheRead(err)), } diff --git a/crates/uv-extract/src/hash.rs b/crates/uv-extract/src/hash.rs index 1bcebaa08..0b70133a0 100644 --- a/crates/uv-extract/src/hash.rs +++ b/crates/uv-extract/src/hash.rs @@ -18,11 +18,11 @@ pub enum Hasher { impl Hasher { pub fn update(&mut self, data: &[u8]) { match self { - Hasher::Md5(hasher) => hasher.update(data), - Hasher::Sha256(hasher) => hasher.update(data), - Hasher::Sha384(hasher) => hasher.update(data), - Hasher::Sha512(hasher) => hasher.update(data), - Hasher::Blake2b(hasher) => hasher.update(data), + Self::Md5(hasher) => hasher.update(data), + Self::Sha256(hasher) => hasher.update(data), + Self::Sha384(hasher) => hasher.update(data), + Self::Sha512(hasher) => hasher.update(data), + Self::Blake2b(hasher) => hasher.update(data), } } } @@ -30,11 +30,11 @@ impl Hasher { impl From for Hasher { fn from(algorithm: HashAlgorithm) -> Self { match algorithm { - HashAlgorithm::Md5 => Hasher::Md5(md5::Md5::new()), - HashAlgorithm::Sha256 => Hasher::Sha256(sha2::Sha256::new()), - HashAlgorithm::Sha384 => Hasher::Sha384(sha2::Sha384::new()), - HashAlgorithm::Sha512 => Hasher::Sha512(sha2::Sha512::new()), - HashAlgorithm::Blake2b => Hasher::Blake2b(blake2::Blake2b::new()), + HashAlgorithm::Md5 => Self::Md5(md5::Md5::new()), + HashAlgorithm::Sha256 => Self::Sha256(sha2::Sha256::new()), + HashAlgorithm::Sha384 => Self::Sha384(sha2::Sha384::new()), + HashAlgorithm::Sha512 => Self::Sha512(sha2::Sha512::new()), + HashAlgorithm::Blake2b => Self::Blake2b(blake2::Blake2b::new()), } } } @@ -42,23 +42,23 @@ impl From for Hasher { impl From for HashDigest { fn from(hasher: Hasher) -> Self { match hasher { - Hasher::Md5(hasher) => HashDigest { + Hasher::Md5(hasher) => Self { algorithm: HashAlgorithm::Md5, digest: format!("{:x}", hasher.finalize()).into(), }, - Hasher::Sha256(hasher) => HashDigest { + Hasher::Sha256(hasher) => Self { algorithm: HashAlgorithm::Sha256, digest: format!("{:x}", hasher.finalize()).into(), }, - Hasher::Sha384(hasher) => HashDigest { + Hasher::Sha384(hasher) => Self { algorithm: HashAlgorithm::Sha384, digest: format!("{:x}", hasher.finalize()).into(), }, - Hasher::Sha512(hasher) => HashDigest { + Hasher::Sha512(hasher) => Self { algorithm: HashAlgorithm::Sha512, digest: format!("{:x}", hasher.finalize()).into(), }, - Hasher::Blake2b(hasher) => HashDigest { + Hasher::Blake2b(hasher) => Self { algorithm: HashAlgorithm::Blake2b, digest: format!("{:x}", hasher.finalize()).into(), }, diff --git a/crates/uv-git-types/src/oid.rs b/crates/uv-git-types/src/oid.rs index 9319f5e34..372d608c3 100644 --- a/crates/uv-git-types/src/oid.rs +++ b/crates/uv-git-types/src/oid.rs @@ -55,7 +55,7 @@ impl FromStr for GitOid { let mut bytes = [0; 40]; bytes.copy_from_slice(s.as_bytes()); - Ok(GitOid { bytes }) + Ok(Self { bytes }) } } @@ -75,7 +75,7 @@ impl serde::Serialize for GitOid { } impl<'de> serde::Deserialize<'de> for GitOid { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { diff --git a/crates/uv-git/src/git.rs b/crates/uv-git/src/git.rs index 4ee4c2670..4b37a5286 100644 --- a/crates/uv-git/src/git.rs +++ b/crates/uv-git/src/git.rs @@ -161,20 +161,20 @@ pub(crate) struct GitRepository { impl GitRepository { /// Opens an existing Git repository at `path`. - pub(crate) fn open(path: &Path) -> Result { + pub(crate) fn open(path: &Path) -> Result { // Make sure there is a Git repository at the specified path. ProcessBuilder::new(GIT.as_ref()?) .arg("rev-parse") .cwd(path) .exec_with_output()?; - Ok(GitRepository { + Ok(Self { path: path.to_path_buf(), }) } /// Initializes a Git repository at `path`. - fn init(path: &Path) -> Result { + fn init(path: &Path) -> Result { // TODO(ibraheem): see if this still necessary now that we no longer use libgit2 // Skip anything related to templates, they just call all sorts of issues as // we really don't want to use them yet they insist on being used. See #6240 @@ -187,7 +187,7 @@ impl GitRepository { .cwd(path) .exec_with_output()?; - Ok(GitRepository { + Ok(Self { path: path.to_path_buf(), }) } @@ -392,7 +392,7 @@ impl GitCheckout { } let repo = GitRepository::open(into)?; - let checkout = GitCheckout::new(revision, repo); + let checkout = Self::new(revision, repo); checkout.reset()?; Ok(checkout) } diff --git a/crates/uv-globfilter/src/portable_glob.rs b/crates/uv-globfilter/src/portable_glob.rs index 5e22b3fa8..3ae232c37 100644 --- a/crates/uv-globfilter/src/portable_glob.rs +++ b/crates/uv-globfilter/src/portable_glob.rs @@ -69,8 +69,8 @@ pub enum PortableGlobParser { impl PortableGlobParser { fn backslash_escape(self) -> bool { match self { - PortableGlobParser::Pep639 => false, - PortableGlobParser::Uv => true, + Self::Pep639 => false, + Self::Uv => true, } } @@ -165,13 +165,13 @@ impl PortableGlobParser { start_or_slash = false; } else if c == '\\' { match *self { - PortableGlobParser::Pep639 => { + Self::Pep639 => { return Err(PortableGlobError::InvalidBackslash { glob: glob.to_string(), pos, }); } - PortableGlobParser::Uv => { + Self::Uv => { match chars.next() { Some((pos, '/' | '\\')) => { // For cross-platform compatibility, we don't allow forward slashes or @@ -195,12 +195,12 @@ impl PortableGlobParser { } } else { let err = match *self { - PortableGlobParser::Pep639 => PortableGlobError::InvalidCharacter { + Self::Pep639 => PortableGlobError::InvalidCharacter { glob: glob.to_string(), pos, invalid: c, }, - PortableGlobParser::Uv => PortableGlobError::InvalidCharacterUv { + Self::Uv => PortableGlobError::InvalidCharacterUv { glob: glob.to_string(), pos, invalid: c, diff --git a/crates/uv-install-wheel/src/wheel.rs b/crates/uv-install-wheel/src/wheel.rs index 250143016..78ebab994 100644 --- a/crates/uv-install-wheel/src/wheel.rs +++ b/crates/uv-install-wheel/src/wheel.rs @@ -904,7 +904,7 @@ impl RenameOrCopy { Self::Rename => match fs_err::rename(from.as_ref(), to.as_ref()) { Ok(()) => {} Err(err) => { - *self = RenameOrCopy::Copy; + *self = Self::Copy; debug!("Failed to rename, falling back to copy: {err}"); fs_err::copy(from.as_ref(), to.as_ref())?; } diff --git a/crates/uv-normalize/src/extra_name.rs b/crates/uv-normalize/src/extra_name.rs index 00aa0f090..818aa8051 100644 --- a/crates/uv-normalize/src/extra_name.rs +++ b/crates/uv-normalize/src/extra_name.rs @@ -26,8 +26,8 @@ impl serde::Serialize for DefaultExtras { S: serde::Serializer, { match self { - DefaultExtras::All => serializer.serialize_str("all"), - DefaultExtras::List(extras) => { + Self::All => serializer.serialize_str("all"), + Self::List(extras) => { let mut seq = serializer.serialize_seq(Some(extras.len()))?; for extra in extras { seq.serialize_element(&extra)?; @@ -40,7 +40,7 @@ impl serde::Serialize for DefaultExtras { /// Deserialize a "all" or list of [`ExtraName`] into a [`DefaultExtras`] enum. impl<'de> serde::Deserialize<'de> for DefaultExtras { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { @@ -85,7 +85,7 @@ impl<'de> serde::Deserialize<'de> for DefaultExtras { impl Default for DefaultExtras { fn default() -> Self { - DefaultExtras::List(Vec::new()) + Self::List(Vec::new()) } } diff --git a/crates/uv-normalize/src/group_name.rs b/crates/uv-normalize/src/group_name.rs index e39044ad7..ce4c78bf8 100644 --- a/crates/uv-normalize/src/group_name.rs +++ b/crates/uv-normalize/src/group_name.rs @@ -176,8 +176,8 @@ impl serde::Serialize for DefaultGroups { S: serde::Serializer, { match self { - DefaultGroups::All => serializer.serialize_str("all"), - DefaultGroups::List(groups) => { + Self::All => serializer.serialize_str("all"), + Self::List(groups) => { let mut seq = serializer.serialize_seq(Some(groups.len()))?; for group in groups { seq.serialize_element(&group)?; @@ -190,7 +190,7 @@ impl serde::Serialize for DefaultGroups { /// Deserialize a "all" or list of [`GroupName`] into a [`DefaultGroups`] enum. impl<'de> serde::Deserialize<'de> for DefaultGroups { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { @@ -236,7 +236,7 @@ impl<'de> serde::Deserialize<'de> for DefaultGroups { impl Default for DefaultGroups { /// Note this is an "empty" default unlike other contexts where `["dev"]` is the default fn default() -> Self { - DefaultGroups::List(Vec::new()) + Self::List(Vec::new()) } } diff --git a/crates/uv-normalize/src/lib.rs b/crates/uv-normalize/src/lib.rs index cdc2d76df..2c00e3ef6 100644 --- a/crates/uv-normalize/src/lib.rs +++ b/crates/uv-normalize/src/lib.rs @@ -153,8 +153,8 @@ pub enum InvalidPipGroupError { impl Display for InvalidPipGroupError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - InvalidPipGroupError::Name(e) => e.fmt(f), - InvalidPipGroupError::Path(e) => e.fmt(f), + Self::Name(e) => e.fmt(f), + Self::Path(e) => e.fmt(f), } } } diff --git a/crates/uv-once-map/src/lib.rs b/crates/uv-once-map/src/lib.rs index cc754b4a6..caafc506f 100644 --- a/crates/uv-once-map/src/lib.rs +++ b/crates/uv-once-map/src/lib.rs @@ -21,15 +21,15 @@ pub struct OnceMap { impl OnceMap { /// Create a [`OnceMap`] with the specified hasher. - pub fn with_hasher(hasher: H) -> OnceMap { - OnceMap { + pub fn with_hasher(hasher: H) -> Self { + Self { items: DashMap::with_hasher(hasher), } } /// Create a [`OnceMap`] with the specified capacity and hasher. - pub fn with_capacity_and_hasher(capacity: usize, hasher: H) -> OnceMap { - OnceMap { + pub fn with_capacity_and_hasher(capacity: usize, hasher: H) -> Self { + Self { items: DashMap::with_capacity_and_hasher(capacity, hasher), } } @@ -133,7 +133,7 @@ where H: Default + Clone + BuildHasher, { fn from_iter>(iter: T) -> Self { - OnceMap { + Self { items: iter .into_iter() .map(|(k, v)| (k, Value::Filled(v))) diff --git a/crates/uv-options-metadata/src/lib.rs b/crates/uv-options-metadata/src/lib.rs index 4c0a5c322..8b8d38aa2 100644 --- a/crates/uv-options-metadata/src/lib.rs +++ b/crates/uv-options-metadata/src/lib.rs @@ -59,8 +59,8 @@ pub enum OptionEntry { impl Display for OptionEntry { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - OptionEntry::Set(set) => std::fmt::Display::fmt(set, f), - OptionEntry::Field(field) => std::fmt::Display::fmt(&field, f), + Self::Set(set) => std::fmt::Display::fmt(set, f), + Self::Field(field) => std::fmt::Display::fmt(&field, f), } } } diff --git a/crates/uv-pep440/src/version.rs b/crates/uv-pep440/src/version.rs index 31b5a8e35..5f52de0ab 100644 --- a/crates/uv-pep440/src/version.rs +++ b/crates/uv-pep440/src/version.rs @@ -63,18 +63,18 @@ impl Operator { /// Note that this routine is not reversible in all cases. For example /// `Operator::ExactEqual` negates to `Operator::NotEqual`, and /// `Operator::NotEqual` in turn negates to `Operator::Equal`. - pub fn negate(self) -> Option { + pub fn negate(self) -> Option { Some(match self { - Operator::Equal => Operator::NotEqual, - Operator::EqualStar => Operator::NotEqualStar, - Operator::ExactEqual => Operator::NotEqual, - Operator::NotEqual => Operator::Equal, - Operator::NotEqualStar => Operator::EqualStar, - Operator::TildeEqual => return None, - Operator::LessThan => Operator::GreaterThanEqual, - Operator::LessThanEqual => Operator::GreaterThan, - Operator::GreaterThan => Operator::LessThanEqual, - Operator::GreaterThanEqual => Operator::LessThan, + Self::Equal => Self::NotEqual, + Self::EqualStar => Self::NotEqualStar, + Self::ExactEqual => Self::NotEqual, + Self::NotEqual => Self::Equal, + Self::NotEqualStar => Self::EqualStar, + Self::TildeEqual => return None, + Self::LessThan => Self::GreaterThanEqual, + Self::LessThanEqual => Self::GreaterThan, + Self::GreaterThan => Self::LessThanEqual, + Self::GreaterThanEqual => Self::LessThan, }) } @@ -1721,8 +1721,8 @@ impl LocalVersion { /// Convert the local version segments into a slice. pub fn as_slice(&self) -> LocalVersionSlice<'_> { match self { - LocalVersion::Segments(segments) => LocalVersionSlice::Segments(segments), - LocalVersion::Max => LocalVersionSlice::Max, + Self::Segments(segments) => LocalVersionSlice::Segments(segments), + Self::Max => LocalVersionSlice::Max, } } @@ -1742,7 +1742,7 @@ impl LocalVersion { impl std::fmt::Display for LocalVersionSlice<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - LocalVersionSlice::Segments(segments) => { + Self::Segments(segments) => { for (i, segment) in segments.iter().enumerate() { if i > 0 { write!(f, ".")?; @@ -1751,7 +1751,7 @@ impl std::fmt::Display for LocalVersionSlice<'_> { } Ok(()) } - LocalVersionSlice::Max => write!(f, "[max]"), + Self::Max => write!(f, "[max]"), } } } @@ -1759,14 +1759,14 @@ impl std::fmt::Display for LocalVersionSlice<'_> { impl CacheKey for LocalVersionSlice<'_> { fn cache_key(&self, state: &mut CacheKeyHasher) { match self { - LocalVersionSlice::Segments(segments) => { + Self::Segments(segments) => { 0u8.cache_key(state); segments.len().cache_key(state); for segment in *segments { segment.cache_key(state); } } - LocalVersionSlice::Max => { + Self::Max => { 1u8.cache_key(state); } } @@ -1912,7 +1912,7 @@ impl<'a> Parser<'a> { const SEPARATOR: ByteSet = ByteSet::new(&[b'.', b'_', b'-']); /// Create a new `Parser` for parsing the version in the given byte string. - fn new(version: &'a [u8]) -> Parser<'a> { + fn new(version: &'a [u8]) -> Self { Parser { v: version, i: 0, diff --git a/crates/uv-pep440/src/version_ranges.rs b/crates/uv-pep440/src/version_ranges.rs index 38038ffcf..a586d1524 100644 --- a/crates/uv-pep440/src/version_ranges.rs +++ b/crates/uv-pep440/src/version_ranges.rs @@ -14,7 +14,7 @@ impl From for Ranges { /// Convert [`VersionSpecifiers`] to a PubGrub-compatible version range, using PEP 440 /// semantics. fn from(specifiers: VersionSpecifiers) -> Self { - let mut range = Ranges::full(); + let mut range = Self::full(); for specifier in specifiers { range = range.intersection(&Self::from(specifier)); } @@ -32,15 +32,15 @@ impl From for Ranges { LocalVersionSlice::Segments(&[]) => { let low = version; let high = low.clone().with_local(LocalVersion::Max); - Ranges::between(low, high) + Self::between(low, high) } - LocalVersionSlice::Segments(_) => Ranges::singleton(version), + LocalVersionSlice::Segments(_) => Self::singleton(version), LocalVersionSlice::Max => unreachable!( "found `LocalVersionSlice::Sentinel`, which should be an internal-only value" ), }, - Operator::ExactEqual => Ranges::singleton(version), - Operator::NotEqual => Ranges::from(VersionSpecifier { + Operator::ExactEqual => Self::singleton(version), + Operator::NotEqual => Self::from(VersionSpecifier { operator: Operator::Equal, version, }) @@ -54,32 +54,32 @@ impl From for Ranges { .with_epoch(version.epoch()) .with_dev(Some(0)); - Ranges::from_range_bounds(version..upper) + Self::from_range_bounds(version..upper) } Operator::LessThan => { if version.any_prerelease() { - Ranges::strictly_lower_than(version) + Self::strictly_lower_than(version) } else { // Per PEP 440: "The exclusive ordered comparison Ranges::lower_than(version.with_local(LocalVersion::Max)), + Operator::LessThanEqual => Self::lower_than(version.with_local(LocalVersion::Max)), Operator::GreaterThan => { // Per PEP 440: "The exclusive ordered comparison >V MUST NOT allow a post-release of // the given version unless V itself is a post release." if let Some(dev) = version.dev() { - Ranges::higher_than(version.with_dev(Some(dev + 1))) + Self::higher_than(version.with_dev(Some(dev + 1))) } else if let Some(post) = version.post() { - Ranges::higher_than(version.with_post(Some(post + 1))) + Self::higher_than(version.with_post(Some(post + 1))) } else { - Ranges::strictly_higher_than(version.with_max(Some(0))) + Self::strictly_higher_than(version.with_max(Some(0))) } } - Operator::GreaterThanEqual => Ranges::higher_than(version), + Operator::GreaterThanEqual => Self::higher_than(version), Operator::EqualStar => { let low = version.with_dev(Some(0)); let mut high = low.clone(); @@ -95,7 +95,7 @@ impl From for Ranges { *release.last_mut().unwrap() += 1; high = high.with_release(release); } - Ranges::from_range_bounds(low..high) + Self::from_range_bounds(low..high) } Operator::NotEqualStar => { let low = version.with_dev(Some(0)); @@ -112,7 +112,7 @@ impl From for Ranges { *release.last_mut().unwrap() += 1; high = high.with_release(release); } - Ranges::from_range_bounds(low..high).complement() + Self::from_range_bounds(low..high).complement() } } } diff --git a/crates/uv-pep440/src/version_specifier.rs b/crates/uv-pep440/src/version_specifier.rs index 13e2687cf..c632d3058 100644 --- a/crates/uv-pep440/src/version_specifier.rs +++ b/crates/uv-pep440/src/version_specifier.rs @@ -482,61 +482,57 @@ impl VersionSpecifier { /// This function is not applicable to ranges involving pre-release versions. pub fn from_release_only_bounds( bounds: (&Bound, &Bound), - ) -> impl Iterator { + ) -> impl Iterator { let (b1, b2) = match bounds { (Bound::Included(v1), Bound::Included(v2)) if v1 == v2 => { - (Some(VersionSpecifier::equals_version(v1.clone())), None) + (Some(Self::equals_version(v1.clone())), None) } // `v >= 3.7 && v < 3.8` is equivalent to `v == 3.7.*` (Bound::Included(v1), Bound::Excluded(v2)) => { match *v1.only_release_trimmed().release() { [major] if *v2.only_release_trimmed().release() == [major, 1] => { let version = Version::new([major, 0]); - (Some(VersionSpecifier::equals_star_version(version)), None) + (Some(Self::equals_star_version(version)), None) } [major, minor] if *v2.only_release_trimmed().release() == [major, minor + 1] => { let version = Version::new([major, minor]); - (Some(VersionSpecifier::equals_star_version(version)), None) + (Some(Self::equals_star_version(version)), None) } _ => ( - VersionSpecifier::from_lower_bound(&Bound::Included(v1.clone())), - VersionSpecifier::from_upper_bound(&Bound::Excluded(v2.clone())), + Self::from_lower_bound(&Bound::Included(v1.clone())), + Self::from_upper_bound(&Bound::Excluded(v2.clone())), ), } } - (lower, upper) => ( - VersionSpecifier::from_lower_bound(lower), - VersionSpecifier::from_upper_bound(upper), - ), + (lower, upper) => (Self::from_lower_bound(lower), Self::from_upper_bound(upper)), }; b1.into_iter().chain(b2) } /// Returns a version specifier representing the given lower bound. - pub fn from_lower_bound(bound: &Bound) -> Option { + pub fn from_lower_bound(bound: &Bound) -> Option { match bound { - Bound::Included(version) => Some( - VersionSpecifier::from_version(Operator::GreaterThanEqual, version.clone()) - .unwrap(), - ), - Bound::Excluded(version) => Some( - VersionSpecifier::from_version(Operator::GreaterThan, version.clone()).unwrap(), - ), + Bound::Included(version) => { + Some(Self::from_version(Operator::GreaterThanEqual, version.clone()).unwrap()) + } + Bound::Excluded(version) => { + Some(Self::from_version(Operator::GreaterThan, version.clone()).unwrap()) + } Bound::Unbounded => None, } } /// Returns a version specifier representing the given upper bound. - pub fn from_upper_bound(bound: &Bound) -> Option { + pub fn from_upper_bound(bound: &Bound) -> Option { match bound { - Bound::Included(version) => Some( - VersionSpecifier::from_version(Operator::LessThanEqual, version.clone()).unwrap(), - ), + Bound::Included(version) => { + Some(Self::from_version(Operator::LessThanEqual, version.clone()).unwrap()) + } Bound::Excluded(version) => { - Some(VersionSpecifier::from_version(Operator::LessThan, version.clone()).unwrap()) + Some(Self::from_version(Operator::LessThan, version.clone()).unwrap()) } Bound::Unbounded => None, } @@ -905,16 +901,14 @@ impl<'a> TildeVersionSpecifier<'a> { /// /// If a [`Operator::TildeEqual`] is not used, or the version includes more than minor and patch /// segments, this will return [`None`]. - pub fn from_specifier(specifier: VersionSpecifier) -> Option> { + pub fn from_specifier(specifier: VersionSpecifier) -> Option { TildeVersionSpecifier::new(Cow::Owned(specifier)) } /// Create a new [`TildeVersionSpecifier`] from a [`VersionSpecifier`] reference. /// /// See [`TildeVersionSpecifier::from_specifier`]. - pub fn from_specifier_ref( - specifier: &'a VersionSpecifier, - ) -> Option> { + pub fn from_specifier_ref(specifier: &'a VersionSpecifier) -> Option { TildeVersionSpecifier::new(Cow::Borrowed(specifier)) } diff --git a/crates/uv-pep508/src/lib.rs b/crates/uv-pep508/src/lib.rs index 9167d0964..b7a890a64 100644 --- a/crates/uv-pep508/src/lib.rs +++ b/crates/uv-pep508/src/lib.rs @@ -342,7 +342,7 @@ impl Pep508Url for Url { type Err = url::ParseError; fn parse_url(url: &str, _working_dir: Option<&Path>) -> Result { - Url::parse(url) + Self::parse(url) } fn displayable_with_credentials(&self) -> impl Display { diff --git a/crates/uv-pep508/src/marker/algebra.rs b/crates/uv-pep508/src/marker/algebra.rs index 6b166dbc6..f886bc440 100644 --- a/crates/uv-pep508/src/marker/algebra.rs +++ b/crates/uv-pep508/src/marker/algebra.rs @@ -1067,7 +1067,7 @@ impl Variable { /// For example, `sys_platform == 'win32'` and `platform_system == 'Darwin'` are known to /// never be true at the same time. fn is_conflicting_variable(&self) -> bool { - let Variable::String(marker) = self else { + let Self::String(marker) = self else { return false; }; marker.is_conflicting() @@ -1086,8 +1086,8 @@ pub(crate) struct Node { impl Node { /// Return the complement of this node, flipping all children IDs. - fn not(self) -> Node { - Node { + fn not(self) -> Self { + Self { var: self.var, children: self.children.not(), } @@ -1102,16 +1102,16 @@ pub(crate) struct NodeId(usize); impl NodeId { // The terminal node representing `true`, or a trivially `true` node. - pub(crate) const TRUE: NodeId = NodeId(0); + pub(crate) const TRUE: Self = Self(0); // The terminal node representing `false`, or an unsatisifable node. - pub(crate) const FALSE: NodeId = NodeId(1); + pub(crate) const FALSE: Self = Self(1); /// Create a new, optionally complemented, [`NodeId`] with the given index. - fn new(index: usize, complement: bool) -> NodeId { + fn new(index: usize, complement: bool) -> Self { // Ensure the index does not interfere with the lowest complement bit. let index = (index + 1) << 1; - NodeId(index | usize::from(complement)) + Self(index | usize::from(complement)) } /// Returns the index of this ID, ignoring the complemented edge. @@ -1127,16 +1127,16 @@ impl NodeId { } /// Returns the complement of this node. - pub(crate) fn not(self) -> NodeId { + pub(crate) fn not(self) -> Self { // Toggle the lowest bit. - NodeId(self.0 ^ 1) + Self(self.0 ^ 1) } /// Returns the complement of this node, if it's parent is complemented. /// /// This method is useful to restore the complemented state of children nodes /// when traversing the tree. - pub(crate) fn negate(self, parent: NodeId) -> NodeId { + pub(crate) fn negate(self, parent: Self) -> Self { if parent.is_complement() { self.not() } else { @@ -1146,12 +1146,12 @@ impl NodeId { /// Returns `true` if this node represents an unsatisfiable node. pub(crate) fn is_false(self) -> bool { - self == NodeId::FALSE + self == Self::FALSE } /// Returns `true` if this node represents a trivially `true` node. pub(crate) fn is_true(self) -> bool { - self == NodeId::TRUE + self == Self::TRUE } } @@ -1189,14 +1189,14 @@ pub(crate) enum Edges { impl Edges { /// Returns the [`Edges`] for a boolean variable. - fn from_bool(complemented: bool) -> Edges { + fn from_bool(complemented: bool) -> Self { if complemented { - Edges::Boolean { + Self::Boolean { high: NodeId::TRUE, low: NodeId::FALSE, } } else { - Edges::Boolean { + Self::Boolean { high: NodeId::FALSE, low: NodeId::TRUE, } @@ -1207,7 +1207,7 @@ impl Edges { /// /// This function will panic for the `In` and `Contains` marker operators, which /// should be represented as separate boolean variables. - fn from_string(operator: MarkerOperator, value: ArcStr) -> Edges { + fn from_string(operator: MarkerOperator, value: ArcStr) -> Self { let range: Ranges = match operator { MarkerOperator::Equal => Ranges::singleton(value), MarkerOperator::NotEqual => Ranges::singleton(value).complement(), @@ -1219,16 +1219,16 @@ impl Edges { _ => unreachable!("`in` and `contains` are treated as boolean variables"), }; - Edges::String { - edges: Edges::from_range(&range), + Self::String { + edges: Self::from_range(&range), } } /// Returns the [`Edges`] for a version specifier. - fn from_specifier(specifier: VersionSpecifier) -> Edges { + fn from_specifier(specifier: VersionSpecifier) -> Self { let specifier = release_specifier_to_range(specifier.only_release(), true); - Edges::Version { - edges: Edges::from_range(&specifier), + Self::Version { + edges: Self::from_range(&specifier), } } @@ -1238,7 +1238,7 @@ impl Edges { fn from_python_versions( versions: Vec, operator: ContainerOperator, - ) -> Result { + ) -> Result { let mut range: Ranges = versions .into_iter() .map(|version| { @@ -1253,13 +1253,13 @@ impl Edges { range = range.complement(); } - Ok(Edges::Version { - edges: Edges::from_range(&range), + Ok(Self::Version { + edges: Self::from_range(&range), }) } /// Returns an [`Edges`] where values in the given range are `true`. - fn from_versions(versions: &[Version], operator: ContainerOperator) -> Edges { + fn from_versions(versions: &[Version], operator: ContainerOperator) -> Self { let mut range: Ranges = versions .iter() .map(|version| { @@ -1274,8 +1274,8 @@ impl Edges { range = range.complement(); } - Edges::Version { - edges: Edges::from_range(&range), + Self::Version { + edges: Self::from_range(&range), } } @@ -1323,26 +1323,26 @@ impl Edges { fn apply( &self, parent: NodeId, - right_edges: &Edges, + right_edges: &Self, right_parent: NodeId, mut apply: impl FnMut(NodeId, NodeId) -> NodeId, - ) -> Edges { + ) -> Self { match (self, right_edges) { // For version or string variables, we have to split and merge the overlapping ranges. - (Edges::Version { edges }, Edges::Version { edges: right_edges }) => Edges::Version { - edges: Edges::apply_ranges(edges, parent, right_edges, right_parent, apply), + (Self::Version { edges }, Self::Version { edges: right_edges }) => Self::Version { + edges: Self::apply_ranges(edges, parent, right_edges, right_parent, apply), }, - (Edges::String { edges }, Edges::String { edges: right_edges }) => Edges::String { - edges: Edges::apply_ranges(edges, parent, right_edges, right_parent, apply), + (Self::String { edges }, Self::String { edges: right_edges }) => Self::String { + edges: Self::apply_ranges(edges, parent, right_edges, right_parent, apply), }, // For boolean variables, we simply merge the low and high edges. ( - Edges::Boolean { high, low }, - Edges::Boolean { + Self::Boolean { high, low }, + Self::Boolean { high: right_high, low: right_low, }, - ) => Edges::Boolean { + ) => Self::Boolean { high: apply(high.negate(parent), right_high.negate(right_parent)), low: apply(low.negate(parent), right_low.negate(right_parent)), }, @@ -1422,22 +1422,22 @@ impl Edges { fn is_disjoint( &self, parent: NodeId, - right_edges: &Edges, + right_edges: &Self, right_parent: NodeId, interner: &mut InternerGuard<'_>, ) -> bool { match (self, right_edges) { // For version or string variables, we have to split and check the overlapping ranges. - (Edges::Version { edges }, Edges::Version { edges: right_edges }) => { - Edges::is_disjoint_ranges(edges, parent, right_edges, right_parent, interner) + (Self::Version { edges }, Self::Version { edges: right_edges }) => { + Self::is_disjoint_ranges(edges, parent, right_edges, right_parent, interner) } - (Edges::String { edges }, Edges::String { edges: right_edges }) => { - Edges::is_disjoint_ranges(edges, parent, right_edges, right_parent, interner) + (Self::String { edges }, Self::String { edges: right_edges }) => { + Self::is_disjoint_ranges(edges, parent, right_edges, right_parent, interner) } // For boolean variables, we simply check the low and high edges. ( - Edges::Boolean { high, low }, - Edges::Boolean { + Self::Boolean { high, low }, + Self::Boolean { high: right_high, low: right_low, }, @@ -1482,23 +1482,23 @@ impl Edges { } // Apply the given function to all direct children of this node. - fn map(&self, parent: NodeId, mut f: impl FnMut(NodeId) -> NodeId) -> Edges { + fn map(&self, parent: NodeId, mut f: impl FnMut(NodeId) -> NodeId) -> Self { match self { - Edges::Version { edges: map } => Edges::Version { + Self::Version { edges: map } => Self::Version { edges: map .iter() .cloned() .map(|(range, node)| (range, f(node.negate(parent)))) .collect(), }, - Edges::String { edges: map } => Edges::String { + Self::String { edges: map } => Self::String { edges: map .iter() .cloned() .map(|(range, node)| (range, f(node.negate(parent)))) .collect(), }, - Edges::Boolean { high, low } => Edges::Boolean { + Self::Boolean { high, low } => Self::Boolean { low: f(low.negate(parent)), high: f(high.negate(parent)), }, @@ -1508,32 +1508,32 @@ impl Edges { // Returns an iterator over all direct children of this node. fn nodes(&self) -> impl Iterator + '_ { match self { - Edges::Version { edges: map } => { + Self::Version { edges: map } => { Either::Left(Either::Left(map.iter().map(|(_, node)| *node))) } - Edges::String { edges: map } => { + Self::String { edges: map } => { Either::Left(Either::Right(map.iter().map(|(_, node)| *node))) } - Edges::Boolean { high, low } => Either::Right([*high, *low].into_iter()), + Self::Boolean { high, low } => Either::Right([*high, *low].into_iter()), } } // Returns the complement of this [`Edges`]. - fn not(self) -> Edges { + fn not(self) -> Self { match self { - Edges::Version { edges: map } => Edges::Version { + Self::Version { edges: map } => Self::Version { edges: map .into_iter() .map(|(range, node)| (range, node.not())) .collect(), }, - Edges::String { edges: map } => Edges::String { + Self::String { edges: map } => Self::String { edges: map .into_iter() .map(|(range, node)| (range, node.not())) .collect(), }, - Edges::Boolean { high, low } => Edges::Boolean { + Self::Boolean { high, low } => Self::Boolean { high: high.not(), low: low.not(), }, diff --git a/crates/uv-pep508/src/marker/environment.rs b/crates/uv-pep508/src/marker/environment.rs index 62cfa3a91..ce36fa862 100644 --- a/crates/uv-pep508/src/marker/environment.rs +++ b/crates/uv-pep508/src/marker/environment.rs @@ -187,7 +187,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::implementation_name`]. #[inline] #[must_use] - pub fn with_implementation_name(mut self, value: impl Into) -> MarkerEnvironment { + pub fn with_implementation_name(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).implementation_name = value.into(); self } @@ -197,10 +197,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::implementation_version`]. #[inline] #[must_use] - pub fn with_implementation_version( - mut self, - value: impl Into, - ) -> MarkerEnvironment { + pub fn with_implementation_version(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).implementation_version = value.into(); self } @@ -210,7 +207,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::os_name`]. #[inline] #[must_use] - pub fn with_os_name(mut self, value: impl Into) -> MarkerEnvironment { + pub fn with_os_name(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).os_name = value.into(); self } @@ -220,7 +217,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::platform_machine`]. #[inline] #[must_use] - pub fn with_platform_machine(mut self, value: impl Into) -> MarkerEnvironment { + pub fn with_platform_machine(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).platform_machine = value.into(); self } @@ -231,10 +228,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::platform_python_implementation`]. #[inline] #[must_use] - pub fn with_platform_python_implementation( - mut self, - value: impl Into, - ) -> MarkerEnvironment { + pub fn with_platform_python_implementation(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).platform_python_implementation = value.into(); self } @@ -244,7 +238,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::platform_release`]. #[inline] #[must_use] - pub fn with_platform_release(mut self, value: impl Into) -> MarkerEnvironment { + pub fn with_platform_release(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).platform_release = value.into(); self } @@ -254,7 +248,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::platform_system`]. #[inline] #[must_use] - pub fn with_platform_system(mut self, value: impl Into) -> MarkerEnvironment { + pub fn with_platform_system(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).platform_system = value.into(); self } @@ -264,7 +258,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::platform_version`]. #[inline] #[must_use] - pub fn with_platform_version(mut self, value: impl Into) -> MarkerEnvironment { + pub fn with_platform_version(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).platform_version = value.into(); self } @@ -274,10 +268,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::python_full_version`]. #[inline] #[must_use] - pub fn with_python_full_version( - mut self, - value: impl Into, - ) -> MarkerEnvironment { + pub fn with_python_full_version(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).python_full_version = value.into(); self } @@ -287,7 +278,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::python_full_version`]. #[inline] #[must_use] - pub fn with_python_version(mut self, value: impl Into) -> MarkerEnvironment { + pub fn with_python_version(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).python_version = value.into(); self } @@ -297,7 +288,7 @@ impl MarkerEnvironment { /// See also [`MarkerEnvironment::sys_platform`]. #[inline] #[must_use] - pub fn with_sys_platform(mut self, value: impl Into) -> MarkerEnvironment { + pub fn with_sys_platform(mut self, value: impl Into) -> Self { Arc::make_mut(&mut self.inner).sys_platform = value.into(); self } @@ -331,7 +322,7 @@ impl<'a> TryFrom> for MarkerEnvironment { type Error = VersionParseError; fn try_from(builder: MarkerEnvironmentBuilder<'a>) -> Result { - Ok(MarkerEnvironment { + Ok(Self { inner: Arc::new(MarkerEnvironmentInner { implementation_name: builder.implementation_name.to_string(), implementation_version: builder.implementation_version.parse()?, diff --git a/crates/uv-pep508/src/marker/tree.rs b/crates/uv-pep508/src/marker/tree.rs index f874fd447..e33d5f5ab 100644 --- a/crates/uv-pep508/src/marker/tree.rs +++ b/crates/uv-pep508/src/marker/tree.rs @@ -268,7 +268,7 @@ impl MarkerOperator { } /// Inverts this marker operator. - pub(crate) fn invert(self) -> MarkerOperator { + pub(crate) fn invert(self) -> Self { match self { Self::LessThan => Self::GreaterThan, Self::LessEqual => Self::GreaterEqual, @@ -288,7 +288,7 @@ impl MarkerOperator { /// /// If a negation doesn't exist, which is only the case for ~=, then this /// returns `None`. - pub(crate) fn negate(self) -> Option { + pub(crate) fn negate(self) -> Option { Some(match self { Self::Equal => Self::NotEqual, Self::NotEqual => Self::Equal, @@ -307,37 +307,34 @@ impl MarkerOperator { /// Returns the marker operator and value whose union represents the given range. pub fn from_bounds( bounds: (&Bound, &Bound), - ) -> impl Iterator { + ) -> impl Iterator { let (b1, b2) = match bounds { (Bound::Included(v1), Bound::Included(v2)) if v1 == v2 => { - (Some((MarkerOperator::Equal, v1.clone())), None) + (Some((Self::Equal, v1.clone())), None) } (Bound::Excluded(v1), Bound::Excluded(v2)) if v1 == v2 => { - (Some((MarkerOperator::NotEqual, v1.clone())), None) + (Some((Self::NotEqual, v1.clone())), None) } - (lower, upper) => ( - MarkerOperator::from_lower_bound(lower), - MarkerOperator::from_upper_bound(upper), - ), + (lower, upper) => (Self::from_lower_bound(lower), Self::from_upper_bound(upper)), }; b1.into_iter().chain(b2) } /// Returns a value specifier representing the given lower bound. - pub fn from_lower_bound(bound: &Bound) -> Option<(MarkerOperator, ArcStr)> { + pub fn from_lower_bound(bound: &Bound) -> Option<(Self, ArcStr)> { match bound { - Bound::Included(value) => Some((MarkerOperator::GreaterEqual, value.clone())), - Bound::Excluded(value) => Some((MarkerOperator::GreaterThan, value.clone())), + Bound::Included(value) => Some((Self::GreaterEqual, value.clone())), + Bound::Excluded(value) => Some((Self::GreaterThan, value.clone())), Bound::Unbounded => None, } } /// Returns a value specifier representing the given upper bound. - pub fn from_upper_bound(bound: &Bound) -> Option<(MarkerOperator, ArcStr)> { + pub fn from_upper_bound(bound: &Bound) -> Option<(Self, ArcStr)> { match bound { - Bound::Included(value) => Some((MarkerOperator::LessEqual, value.clone())), - Bound::Excluded(value) => Some((MarkerOperator::LessThan, value.clone())), + Bound::Included(value) => Some((Self::LessEqual, value.clone())), + Bound::Excluded(value) => Some((Self::LessThan, value.clone())), Bound::Unbounded => None, } } @@ -574,19 +571,19 @@ impl ExtraOperator { /// Creates a [`ExtraOperator`] from an equivalent [`MarkerOperator`]. /// /// Returns `None` if the operator is not supported for extras. - pub(crate) fn from_marker_operator(operator: MarkerOperator) -> Option { + pub(crate) fn from_marker_operator(operator: MarkerOperator) -> Option { match operator { - MarkerOperator::Equal => Some(ExtraOperator::Equal), - MarkerOperator::NotEqual => Some(ExtraOperator::NotEqual), + MarkerOperator::Equal => Some(Self::Equal), + MarkerOperator::NotEqual => Some(Self::NotEqual), _ => None, } } /// Negates this operator. - pub(crate) fn negate(&self) -> ExtraOperator { + pub(crate) fn negate(&self) -> Self { match *self { - ExtraOperator::Equal => ExtraOperator::NotEqual, - ExtraOperator::NotEqual => ExtraOperator::Equal, + Self::Equal => Self::NotEqual, + Self::NotEqual => Self::Equal, } } } @@ -613,10 +610,10 @@ impl ContainerOperator { /// Creates a [`ContainerOperator`] from an equivalent [`MarkerOperator`]. /// /// Returns `None` if the operator is not supported for containers. - pub(crate) fn from_marker_operator(operator: MarkerOperator) -> Option { + pub(crate) fn from_marker_operator(operator: MarkerOperator) -> Option { match operator { - MarkerOperator::In => Some(ContainerOperator::In), - MarkerOperator::NotIn => Some(ContainerOperator::NotIn), + MarkerOperator::In => Some(Self::In), + MarkerOperator::NotIn => Some(Self::NotIn), _ => None, } } @@ -660,17 +657,17 @@ impl MarkerExpression { /// that are ignored, such as `os_name ~= 'foo'`. #[allow(clippy::should_implement_trait)] pub fn from_str(s: &str) -> Result, Pep508Error> { - MarkerExpression::parse_reporter(s, &mut TracingReporter) + Self::parse_reporter(s, &mut TracingReporter) } /// Return the kind of this marker expression. pub(crate) fn kind(&self) -> MarkerExpressionKind { match self { - MarkerExpression::Version { key, .. } => MarkerExpressionKind::Version(*key), - MarkerExpression::VersionIn { key, .. } => MarkerExpressionKind::VersionIn(*key), - MarkerExpression::String { key, .. } => MarkerExpressionKind::String(*key), - MarkerExpression::List { pair, .. } => MarkerExpressionKind::List(pair.key()), - MarkerExpression::Extra { .. } => MarkerExpressionKind::Extra, + Self::Version { key, .. } => MarkerExpressionKind::Version(*key), + Self::VersionIn { key, .. } => MarkerExpressionKind::VersionIn(*key), + Self::String { key, .. } => MarkerExpressionKind::String(*key), + Self::List { pair, .. } => MarkerExpressionKind::List(pair.key()), + Self::Extra { .. } => MarkerExpressionKind::Extra, } } } @@ -678,7 +675,7 @@ impl MarkerExpression { impl Display for MarkerExpression { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { - MarkerExpression::Version { key, specifier } => { + Self::Version { key, specifier } => { let (op, version) = (specifier.operator(), specifier.version()); if op == &uv_pep440::Operator::EqualStar || op == &uv_pep440::Operator::NotEqualStar { @@ -686,7 +683,7 @@ impl Display for MarkerExpression { } write!(f, "{key} {op} '{version}'") } - MarkerExpression::VersionIn { + Self::VersionIn { key, versions, operator, @@ -694,7 +691,7 @@ impl Display for MarkerExpression { let versions = versions.iter().map(ToString::to_string).join(" "); write!(f, "{key} {operator} '{versions}'") } - MarkerExpression::String { + Self::String { key, operator, value, @@ -708,10 +705,10 @@ impl Display for MarkerExpression { write!(f, "{key} {operator} '{value}'") } - MarkerExpression::List { pair, operator } => { + Self::List { pair, operator } => { write!(f, "'{}' {} {}", pair.value(), operator, pair.key()) } - MarkerExpression::Extra { operator, name } => { + Self::Extra { operator, name } => { write!(f, "extra {operator} '{name}'") } } @@ -773,7 +770,7 @@ pub struct MarkerTree(NodeId); impl Default for MarkerTree { fn default() -> Self { - MarkerTree::TRUE + Self::TRUE } } @@ -823,14 +820,14 @@ impl MarkerTree { } /// An empty marker that always evaluates to `true`. - pub const TRUE: MarkerTree = MarkerTree(NodeId::TRUE); + pub const TRUE: Self = Self(NodeId::TRUE); /// An unsatisfiable marker that always evaluates to `false`. - pub const FALSE: MarkerTree = MarkerTree(NodeId::FALSE); + pub const FALSE: Self = Self(NodeId::FALSE); /// Returns a marker tree for a single expression. - pub fn expression(expr: MarkerExpression) -> MarkerTree { - MarkerTree(INTERNER.lock().expression(expr)) + pub fn expression(expr: MarkerExpression) -> Self { + Self(INTERNER.lock().expression(expr)) } /// Whether the marker always evaluates to `true`. @@ -856,17 +853,17 @@ impl MarkerTree { /// Returns a new marker tree that is the negation of this one. #[must_use] - pub fn negate(self) -> MarkerTree { - MarkerTree(self.0.not()) + pub fn negate(self) -> Self { + Self(self.0.not()) } /// Combine this marker tree with the one given via a conjunction. - pub fn and(&mut self, tree: MarkerTree) { + pub fn and(&mut self, tree: Self) { self.0 = INTERNER.lock().and(self.0, tree.0); } /// Combine this marker tree with the one given via a disjunction. - pub fn or(&mut self, tree: MarkerTree) { + pub fn or(&mut self, tree: Self) { self.0 = INTERNER.lock().or(self.0, tree.0); } @@ -875,7 +872,7 @@ impl MarkerTree { /// /// If the marker set is always `true`, then it can be said that `self` /// implies `consequent`. - pub fn implies(&mut self, consequent: MarkerTree) { + pub fn implies(&mut self, consequent: Self) { // This could probably be optimized, but is clearly // correct, since logical implication is `-P or Q`. *self = self.negate(); @@ -889,7 +886,7 @@ impl MarkerTree { /// never both evaluate to `true` in a given environment. However, this method may return /// false negatives, i.e. it may not be able to detect that two markers are disjoint for /// complex expressions. - pub fn is_disjoint(self, other: MarkerTree) -> bool { + pub fn is_disjoint(self, other: Self) -> bool { INTERNER.lock().is_disjoint(self.0, other.0) } @@ -1240,12 +1237,8 @@ impl MarkerTree { /// results of that simplification. (If `requires-python` changes, then one /// should reconstitute all relevant markers from the source data.) #[must_use] - pub fn simplify_python_versions( - self, - lower: Bound<&Version>, - upper: Bound<&Version>, - ) -> MarkerTree { - MarkerTree( + pub fn simplify_python_versions(self, lower: Bound<&Version>, upper: Bound<&Version>) -> Self { + Self( INTERNER .lock() .simplify_python_versions(self.0, lower, upper), @@ -1264,8 +1257,8 @@ impl MarkerTree { self, lower: Bound<&Version>, upper: Bound<&Version>, - ) -> MarkerTree { - MarkerTree( + ) -> Self { + Self( INTERNER .lock() .complexify_python_versions(self.0, lower, upper), @@ -1281,7 +1274,7 @@ impl MarkerTree { /// For example, if `dev` is a provided extra, given `sys_platform == 'linux' and extra == 'dev'`, /// the marker will be simplified to `sys_platform == 'linux'`. #[must_use] - pub fn simplify_extras(self, extras: &[ExtraName]) -> MarkerTree { + pub fn simplify_extras(self, extras: &[ExtraName]) -> Self { self.simplify_extras_with(|name| extras.contains(name)) } @@ -1296,7 +1289,7 @@ impl MarkerTree { /// == 'linux' and extra != 'dev'`, the marker will be simplified to /// `sys_platform == 'linux'`. #[must_use] - pub fn simplify_not_extras(self, extras: &[ExtraName]) -> MarkerTree { + pub fn simplify_not_extras(self, extras: &[ExtraName]) -> Self { self.simplify_not_extras_with(|name| extras.contains(name)) } @@ -1310,7 +1303,7 @@ impl MarkerTree { /// `sys_platform == 'linux' and extra == 'dev'`, the marker will be simplified to /// `sys_platform == 'linux'`. #[must_use] - pub fn simplify_extras_with(self, is_extra: impl Fn(&ExtraName) -> bool) -> MarkerTree { + pub fn simplify_extras_with(self, is_extra: impl Fn(&ExtraName) -> bool) -> Self { // Because `simplify_extras_with_impl` is recursive, and we need to use // our predicate in recursive calls, we need the predicate itself to // have some indirection (or else we'd have to clone it). To avoid a @@ -1330,7 +1323,7 @@ impl MarkerTree { /// `sys_platform == 'linux' and extra != 'dev'`, the marker will be simplified to /// `sys_platform == 'linux'`. #[must_use] - pub fn simplify_not_extras_with(self, is_extra: impl Fn(&ExtraName) -> bool) -> MarkerTree { + pub fn simplify_not_extras_with(self, is_extra: impl Fn(&ExtraName) -> bool) -> Self { // Because `simplify_extras_with_impl` is recursive, and we need to use // our predicate in recursive calls, we need the predicate itself to // have some indirection (or else we'd have to clone it). To avoid a @@ -1344,8 +1337,8 @@ impl MarkerTree { /// If the marker only consisted of `extra` expressions, then a marker that /// is always true is returned. #[must_use] - pub fn without_extras(self) -> MarkerTree { - MarkerTree(INTERNER.lock().without_extras(self.0)) + pub fn without_extras(self) -> Self { + Self(INTERNER.lock().without_extras(self.0)) } /// Returns a new `MarkerTree` where only `extra` expressions are removed. @@ -1353,8 +1346,8 @@ impl MarkerTree { /// If the marker did not contain any `extra` expressions, then a marker /// that is always true is returned. #[must_use] - pub fn only_extras(self) -> MarkerTree { - MarkerTree(INTERNER.lock().only_extras(self.0)) + pub fn only_extras(self) -> Self { + Self(INTERNER.lock().only_extras(self.0)) } /// Calls the provided function on every `extra` in this tree. @@ -1405,15 +1398,15 @@ impl MarkerTree { imp(self, &mut f); } - fn simplify_extras_with_impl(self, is_extra: &impl Fn(&ExtraName) -> bool) -> MarkerTree { - MarkerTree(INTERNER.lock().restrict(self.0, &|var| match var { + fn simplify_extras_with_impl(self, is_extra: &impl Fn(&ExtraName) -> bool) -> Self { + Self(INTERNER.lock().restrict(self.0, &|var| match var { Variable::Extra(name) => is_extra(name.extra()).then_some(true), _ => None, })) } - fn simplify_not_extras_with_impl(self, is_extra: &impl Fn(&ExtraName) -> bool) -> MarkerTree { - MarkerTree(INTERNER.lock().restrict(self.0, &|var| match var { + fn simplify_not_extras_with_impl(self, is_extra: &impl Fn(&ExtraName) -> bool) -> Self { + Self(INTERNER.lock().restrict(self.0, &|var| match var { Variable::Extra(name) => is_extra(name.extra()).then_some(false), _ => None, })) diff --git a/crates/uv-pep508/src/origin.rs b/crates/uv-pep508/src/origin.rs index 4619e6f2e..77285fe49 100644 --- a/crates/uv-pep508/src/origin.rs +++ b/crates/uv-pep508/src/origin.rs @@ -22,11 +22,11 @@ impl RequirementOrigin { /// Returns the path of the requirement origin. pub fn path(&self) -> &Path { match self { - RequirementOrigin::File(path) => path.as_path(), - RequirementOrigin::Project(path, _) => path.as_path(), - RequirementOrigin::Group(path, _, _) => path.as_path(), + Self::File(path) => path.as_path(), + Self::Project(path, _) => path.as_path(), + Self::Group(path, _, _) => path.as_path(), // Multiple toml are merged and difficult to track files where Requirement is defined. Returns a dummy path instead. - RequirementOrigin::Workspace => Path::new("(workspace)"), + Self::Workspace => Path::new("(workspace)"), } } } diff --git a/crates/uv-pep508/src/verbatim_url.rs b/crates/uv-pep508/src/verbatim_url.rs index 480d4fb67..c25d40dd3 100644 --- a/crates/uv-pep508/src/verbatim_url.rs +++ b/crates/uv-pep508/src/verbatim_url.rs @@ -276,19 +276,19 @@ impl Deref for VerbatimUrl { impl From for VerbatimUrl { fn from(url: Url) -> Self { - VerbatimUrl::from_url(DisplaySafeUrl::from(url)) + Self::from_url(DisplaySafeUrl::from(url)) } } impl From for VerbatimUrl { fn from(url: DisplaySafeUrl) -> Self { - VerbatimUrl::from_url(url) + Self::from_url(url) } } impl From for Url { fn from(url: VerbatimUrl) -> Self { - Url::from(url.url) + Self::from(url.url) } } @@ -304,12 +304,12 @@ impl serde::Serialize for VerbatimUrl { #[cfg(feature = "serde")] impl<'de> serde::Deserialize<'de> for VerbatimUrl { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let url = DisplaySafeUrl::deserialize(deserializer)?; - Ok(VerbatimUrl::from_url(url)) + Ok(Self::from_url(url)) } } @@ -338,21 +338,19 @@ impl Pep508Url for VerbatimUrl { let path = normalize_url_path(path); if let Some(working_dir) = working_dir { - return Ok( - VerbatimUrl::from_path(path.as_ref(), working_dir)?.with_given(url) - ); + return Ok(Self::from_path(path.as_ref(), working_dir)?.with_given(url)); } - Ok(VerbatimUrl::from_absolute_path(path.as_ref())?.with_given(url)) + Ok(Self::from_absolute_path(path.as_ref())?.with_given(url)) } #[cfg(not(feature = "non-pep508-extensions"))] - Ok(VerbatimUrl::parse_url(expanded)?.with_given(url)) + Ok(Self::parse_url(expanded)?.with_given(url)) } // Ex) `https://download.pytorch.org/whl/torch_stable.html` Some(_) => { // Ex) `https://download.pytorch.org/whl/torch_stable.html` - Ok(VerbatimUrl::parse_url(expanded.as_ref())?.with_given(url)) + Ok(Self::parse_url(expanded.as_ref())?.with_given(url)) } // Ex) `C:\Users\ferris\wheel-0.42.0.tar.gz` @@ -360,11 +358,12 @@ impl Pep508Url for VerbatimUrl { #[cfg(feature = "non-pep508-extensions")] { if let Some(working_dir) = working_dir { - return Ok(VerbatimUrl::from_path(expanded.as_ref(), working_dir)? - .with_given(url)); + return Ok( + Self::from_path(expanded.as_ref(), working_dir)?.with_given(url) + ); } - Ok(VerbatimUrl::from_absolute_path(expanded.as_ref())?.with_given(url)) + Ok(Self::from_absolute_path(expanded.as_ref())?.with_given(url)) } #[cfg(not(feature = "non-pep508-extensions"))] Err(Self::Err::NotAUrl(expanded.to_string())) @@ -375,12 +374,10 @@ impl Pep508Url for VerbatimUrl { #[cfg(feature = "non-pep508-extensions")] { if let Some(working_dir) = working_dir { - return Ok( - VerbatimUrl::from_path(expanded.as_ref(), working_dir)?.with_given(url) - ); + return Ok(Self::from_path(expanded.as_ref(), working_dir)?.with_given(url)); } - Ok(VerbatimUrl::from_absolute_path(expanded.as_ref())?.with_given(url)) + Ok(Self::from_absolute_path(expanded.as_ref())?.with_given(url)) } #[cfg(not(feature = "non-pep508-extensions"))] diff --git a/crates/uv-platform-tags/src/abi_tag.rs b/crates/uv-platform-tags/src/abi_tag.rs index 70b11d8c2..a75777860 100644 --- a/crates/uv-platform-tags/src/abi_tag.rs +++ b/crates/uv-platform-tags/src/abi_tag.rs @@ -47,26 +47,26 @@ impl AbiTag { /// Return a pretty string representation of the ABI tag. pub fn pretty(self) -> Option { match self { - AbiTag::None => None, - AbiTag::Abi3 => None, - AbiTag::CPython { python_version, .. } => { + Self::None => None, + Self::Abi3 => None, + Self::CPython { python_version, .. } => { Some(format!("CPython {}.{}", python_version.0, python_version.1)) } - AbiTag::PyPy { + Self::PyPy { implementation_version, .. } => Some(format!( "PyPy {}.{}", implementation_version.0, implementation_version.1 )), - AbiTag::GraalPy { + Self::GraalPy { implementation_version, .. } => Some(format!( "GraalPy {}.{}", implementation_version.0, implementation_version.1 )), - AbiTag::Pyston { .. } => Some("Pyston".to_string()), + Self::Pyston { .. } => Some("Pyston".to_string()), } } } diff --git a/crates/uv-platform-tags/src/platform_tag.rs b/crates/uv-platform-tags/src/platform_tag.rs index 93a614bdf..b970a248c 100644 --- a/crates/uv-platform-tags/src/platform_tag.rs +++ b/crates/uv-platform-tags/src/platform_tag.rs @@ -79,27 +79,27 @@ impl PlatformTag { /// Return a pretty string representation of the language tag. pub fn pretty(&self) -> Option<&'static str> { match self { - PlatformTag::Any => None, - PlatformTag::Manylinux { .. } => Some("Linux"), - PlatformTag::Manylinux1 { .. } => Some("Linux"), - PlatformTag::Manylinux2010 { .. } => Some("Linux"), - PlatformTag::Manylinux2014 { .. } => Some("Linux"), - PlatformTag::Linux { .. } => Some("Linux"), - PlatformTag::Musllinux { .. } => Some("Linux"), - PlatformTag::Macos { .. } => Some("macOS"), - PlatformTag::Win32 => Some("Windows"), - PlatformTag::WinAmd64 => Some("Windows"), - PlatformTag::WinArm64 => Some("Windows"), - PlatformTag::WinIa64 => Some("Windows"), - PlatformTag::Android { .. } => Some("Android"), - PlatformTag::FreeBsd { .. } => Some("FreeBSD"), - PlatformTag::NetBsd { .. } => Some("NetBSD"), - PlatformTag::OpenBsd { .. } => Some("OpenBSD"), - PlatformTag::Dragonfly { .. } => Some("DragonFly"), - PlatformTag::Haiku { .. } => Some("Haiku"), - PlatformTag::Illumos { .. } => Some("Illumos"), - PlatformTag::Solaris { .. } => Some("Solaris"), - PlatformTag::Pyodide { .. } => Some("Pyodide"), + Self::Any => None, + Self::Manylinux { .. } => Some("Linux"), + Self::Manylinux1 { .. } => Some("Linux"), + Self::Manylinux2010 { .. } => Some("Linux"), + Self::Manylinux2014 { .. } => Some("Linux"), + Self::Linux { .. } => Some("Linux"), + Self::Musllinux { .. } => Some("Linux"), + Self::Macos { .. } => Some("macOS"), + Self::Win32 => Some("Windows"), + Self::WinAmd64 => Some("Windows"), + Self::WinArm64 => Some("Windows"), + Self::WinIa64 => Some("Windows"), + Self::Android { .. } => Some("Android"), + Self::FreeBsd { .. } => Some("FreeBSD"), + Self::NetBsd { .. } => Some("NetBSD"), + Self::OpenBsd { .. } => Some("OpenBSD"), + Self::Dragonfly { .. } => Some("DragonFly"), + Self::Haiku { .. } => Some("Haiku"), + Self::Illumos { .. } => Some("Illumos"), + Self::Solaris { .. } => Some("Solaris"), + Self::Pyodide { .. } => Some("Pyodide"), } } } diff --git a/crates/uv-platform-tags/src/tags.rs b/crates/uv-platform-tags/src/tags.rs index f2c6d6cbb..b321d1d85 100644 --- a/crates/uv-platform-tags/src/tags.rs +++ b/crates/uv-platform-tags/src/tags.rs @@ -719,7 +719,7 @@ impl BinaryFormat { /// /// This is roughly the inverse of the above: given a binary format, which `platform_machine` /// tags are supported? - pub fn platform_machine(&self) -> &'static [BinaryFormat] { + pub fn platform_machine(&self) -> &'static [Self] { match self { Self::Arm64 => &[Self::Arm64], Self::Fat => &[Self::X86_64, Self::Ppc], diff --git a/crates/uv-platform/src/arch.rs b/crates/uv-platform/src/arch.rs index f64312489..92c6b1e41 100644 --- a/crates/uv-platform/src/arch.rs +++ b/crates/uv-platform/src/arch.rs @@ -41,13 +41,13 @@ impl Ord for Arch { // should respect that request (this is the way users should "override" // this behaviour). let preferred = if cfg!(all(windows, target_arch = "aarch64")) { - Arch { + Self { family: target_lexicon::Architecture::X86_64, variant: None, } } else { // Prefer native architectures - Arch::from_env() + Self::from_env() }; match ( @@ -205,45 +205,45 @@ impl Display for ArchVariant { impl From<&uv_platform_tags::Arch> for Arch { fn from(value: &uv_platform_tags::Arch) -> Self { match value { - uv_platform_tags::Arch::Aarch64 => Arch::new( + uv_platform_tags::Arch::Aarch64 => Self::new( target_lexicon::Architecture::Aarch64(target_lexicon::Aarch64Architecture::Aarch64), None, ), - uv_platform_tags::Arch::Armv5TEL => Arch::new( + uv_platform_tags::Arch::Armv5TEL => Self::new( target_lexicon::Architecture::Arm(target_lexicon::ArmArchitecture::Armv5te), None, ), - uv_platform_tags::Arch::Armv6L => Arch::new( + uv_platform_tags::Arch::Armv6L => Self::new( target_lexicon::Architecture::Arm(target_lexicon::ArmArchitecture::Armv6), None, ), - uv_platform_tags::Arch::Armv7L => Arch::new( + uv_platform_tags::Arch::Armv7L => Self::new( target_lexicon::Architecture::Arm(target_lexicon::ArmArchitecture::Armv7), None, ), - uv_platform_tags::Arch::S390X => Arch::new(target_lexicon::Architecture::S390x, None), + uv_platform_tags::Arch::S390X => Self::new(target_lexicon::Architecture::S390x, None), uv_platform_tags::Arch::Powerpc => { - Arch::new(target_lexicon::Architecture::Powerpc, None) + Self::new(target_lexicon::Architecture::Powerpc, None) } uv_platform_tags::Arch::Powerpc64 => { - Arch::new(target_lexicon::Architecture::Powerpc64, None) + Self::new(target_lexicon::Architecture::Powerpc64, None) } uv_platform_tags::Arch::Powerpc64Le => { - Arch::new(target_lexicon::Architecture::Powerpc64le, None) + Self::new(target_lexicon::Architecture::Powerpc64le, None) } - uv_platform_tags::Arch::X86 => Arch::new( + uv_platform_tags::Arch::X86 => Self::new( target_lexicon::Architecture::X86_32(target_lexicon::X86_32Architecture::I686), None, ), - uv_platform_tags::Arch::X86_64 => Arch::new(target_lexicon::Architecture::X86_64, None), + uv_platform_tags::Arch::X86_64 => Self::new(target_lexicon::Architecture::X86_64, None), uv_platform_tags::Arch::LoongArch64 => { - Arch::new(target_lexicon::Architecture::LoongArch64, None) + Self::new(target_lexicon::Architecture::LoongArch64, None) } - uv_platform_tags::Arch::Riscv64 => Arch::new( + uv_platform_tags::Arch::Riscv64 => Self::new( target_lexicon::Architecture::Riscv64(target_lexicon::Riscv64Architecture::Riscv64), None, ), - uv_platform_tags::Arch::Wasm32 => Arch::new(target_lexicon::Architecture::Wasm32, None), + uv_platform_tags::Arch::Wasm32 => Self::new(target_lexicon::Architecture::Wasm32, None), } } } diff --git a/crates/uv-platform/src/libc.rs b/crates/uv-platform/src/libc.rs index 184f0487c..76fe92997 100644 --- a/crates/uv-platform/src/libc.rs +++ b/crates/uv-platform/src/libc.rs @@ -125,9 +125,9 @@ impl Display for Libc { impl From<&uv_platform_tags::Os> for Libc { fn from(value: &uv_platform_tags::Os) -> Self { match value { - uv_platform_tags::Os::Manylinux { .. } => Libc::Some(target_lexicon::Environment::Gnu), - uv_platform_tags::Os::Musllinux { .. } => Libc::Some(target_lexicon::Environment::Musl), - _ => Libc::None, + uv_platform_tags::Os::Manylinux { .. } => Self::Some(target_lexicon::Environment::Gnu), + uv_platform_tags::Os::Musllinux { .. } => Self::Some(target_lexicon::Environment::Musl), + _ => Self::None, } } } diff --git a/crates/uv-platform/src/os.rs b/crates/uv-platform/src/os.rs index 01f896f3f..245d799f3 100644 --- a/crates/uv-platform/src/os.rs +++ b/crates/uv-platform/src/os.rs @@ -58,30 +58,32 @@ impl From<&uv_platform_tags::Os> for Os { fn from(value: &uv_platform_tags::Os) -> Self { match value { uv_platform_tags::Os::Dragonfly { .. } => { - Os::new(target_lexicon::OperatingSystem::Dragonfly) + Self::new(target_lexicon::OperatingSystem::Dragonfly) } uv_platform_tags::Os::FreeBsd { .. } => { - Os::new(target_lexicon::OperatingSystem::Freebsd) + Self::new(target_lexicon::OperatingSystem::Freebsd) } - uv_platform_tags::Os::Haiku { .. } => Os::new(target_lexicon::OperatingSystem::Haiku), + uv_platform_tags::Os::Haiku { .. } => Self::new(target_lexicon::OperatingSystem::Haiku), uv_platform_tags::Os::Illumos { .. } => { - Os::new(target_lexicon::OperatingSystem::Illumos) + Self::new(target_lexicon::OperatingSystem::Illumos) } uv_platform_tags::Os::Macos { .. } => { - Os::new(target_lexicon::OperatingSystem::Darwin(None)) + Self::new(target_lexicon::OperatingSystem::Darwin(None)) } uv_platform_tags::Os::Manylinux { .. } | uv_platform_tags::Os::Musllinux { .. } | uv_platform_tags::Os::Android { .. } => { - Os::new(target_lexicon::OperatingSystem::Linux) + Self::new(target_lexicon::OperatingSystem::Linux) + } + uv_platform_tags::Os::NetBsd { .. } => { + Self::new(target_lexicon::OperatingSystem::Netbsd) } - uv_platform_tags::Os::NetBsd { .. } => Os::new(target_lexicon::OperatingSystem::Netbsd), uv_platform_tags::Os::OpenBsd { .. } => { - Os::new(target_lexicon::OperatingSystem::Openbsd) + Self::new(target_lexicon::OperatingSystem::Openbsd) } - uv_platform_tags::Os::Windows => Os::new(target_lexicon::OperatingSystem::Windows), + uv_platform_tags::Os::Windows => Self::new(target_lexicon::OperatingSystem::Windows), uv_platform_tags::Os::Pyodide { .. } => { - Os::new(target_lexicon::OperatingSystem::Emscripten) + Self::new(target_lexicon::OperatingSystem::Emscripten) } } } diff --git a/crates/uv-pypi-types/src/conflicts.rs b/crates/uv-pypi-types/src/conflicts.rs index 81064955a..9200402f4 100644 --- a/crates/uv-pypi-types/src/conflicts.rs +++ b/crates/uv-pypi-types/src/conflicts.rs @@ -22,8 +22,8 @@ impl Conflicts { /// Returns no conflicts. /// /// This results in no effect on resolution. - pub fn empty() -> Conflicts { - Conflicts::default() + pub fn empty() -> Self { + Self::default() } /// Push a single set of conflicts. @@ -54,7 +54,7 @@ impl Conflicts { /// Appends the given conflicts to this one. This drains all sets from the /// conflicts given, such that after this call, it is empty. - pub fn append(&mut self, other: &mut Conflicts) { + pub fn append(&mut self, other: &mut Self) { self.0.append(&mut other.0); } @@ -225,8 +225,8 @@ pub struct ConflictSet { impl ConflictSet { /// Create a pair of items that conflict with one another. - pub fn pair(item1: ConflictItem, item2: ConflictItem) -> ConflictSet { - ConflictSet { + pub fn pair(item1: ConflictItem, item2: ConflictItem) -> Self { + Self { set: BTreeSet::from_iter(vec![item1, item2]), is_inferred_conflict: false, } @@ -287,7 +287,7 @@ impl ConflictSet { } impl<'de> serde::Deserialize<'de> for ConflictSet { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { @@ -299,13 +299,13 @@ impl<'de> serde::Deserialize<'de> for ConflictSet { impl TryFrom> for ConflictSet { type Error = ConflictError; - fn try_from(items: Vec) -> Result { + fn try_from(items: Vec) -> Result { match items.len() { 0 => return Err(ConflictError::ZeroItems), 1 => return Err(ConflictError::OneItem), _ => {} } - Ok(ConflictSet { + Ok(Self { set: BTreeSet::from_iter(items), is_inferred_conflict: false, }) @@ -362,16 +362,16 @@ impl ConflictItem { } impl From<(PackageName, ExtraName)> for ConflictItem { - fn from((package, extra): (PackageName, ExtraName)) -> ConflictItem { + fn from((package, extra): (PackageName, ExtraName)) -> Self { let conflict = ConflictPackage::Extra(extra); - ConflictItem { package, conflict } + Self { package, conflict } } } impl From<(PackageName, GroupName)> for ConflictItem { - fn from((package, group): (PackageName, GroupName)) -> ConflictItem { + fn from((package, group): (PackageName, GroupName)) -> Self { let conflict = ConflictPackage::Group(group); - ConflictItem { package, conflict } + Self { package, conflict } } } @@ -418,14 +418,14 @@ impl<'a> ConflictItemRef<'a> { } impl<'a> From<(&'a PackageName, &'a ExtraName)> for ConflictItemRef<'a> { - fn from((package, extra): (&'a PackageName, &'a ExtraName)) -> ConflictItemRef<'a> { + fn from((package, extra): (&'a PackageName, &'a ExtraName)) -> Self { let conflict = ConflictPackageRef::Extra(extra); ConflictItemRef { package, conflict } } } impl<'a> From<(&'a PackageName, &'a GroupName)> for ConflictItemRef<'a> { - fn from((package, group): (&'a PackageName, &'a GroupName)) -> ConflictItemRef<'a> { + fn from((package, group): (&'a PackageName, &'a GroupName)) -> Self { let conflict = ConflictPackageRef::Group(group); ConflictItemRef { package, conflict } } @@ -451,8 +451,8 @@ impl ConflictPackage { /// extra name. pub fn extra(&self) -> Option<&ExtraName> { match *self { - ConflictPackage::Extra(ref extra) => Some(extra), - ConflictPackage::Group(_) => None, + Self::Extra(ref extra) => Some(extra), + Self::Group(_) => None, } } @@ -460,16 +460,16 @@ impl ConflictPackage { /// group name. pub fn group(&self) -> Option<&GroupName> { match *self { - ConflictPackage::Group(ref group) => Some(group), - ConflictPackage::Extra(_) => None, + Self::Group(ref group) => Some(group), + Self::Extra(_) => None, } } /// Returns this conflict as a new type with its fields borrowed. pub fn as_ref(&self) -> ConflictPackageRef<'_> { match *self { - ConflictPackage::Extra(ref extra) => ConflictPackageRef::Extra(extra), - ConflictPackage::Group(ref group) => ConflictPackageRef::Group(group), + Self::Extra(ref extra) => ConflictPackageRef::Extra(extra), + Self::Group(ref group) => ConflictPackageRef::Group(group), } } } @@ -512,13 +512,13 @@ impl<'a> ConflictPackageRef<'a> { } impl<'a> From<&'a ExtraName> for ConflictPackageRef<'a> { - fn from(extra: &'a ExtraName) -> ConflictPackageRef<'a> { + fn from(extra: &'a ExtraName) -> Self { ConflictPackageRef::Extra(extra) } } impl<'a> From<&'a GroupName> for ConflictPackageRef<'a> { - fn from(group: &'a GroupName) -> ConflictPackageRef<'a> { + fn from(group: &'a GroupName) -> Self { ConflictPackageRef::Group(group) } } @@ -650,7 +650,7 @@ impl schemars::JsonSchema for SchemaConflictItem { } impl<'de> serde::Deserialize<'de> for SchemaConflictSet { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { @@ -662,13 +662,13 @@ impl<'de> serde::Deserialize<'de> for SchemaConflictSet { impl TryFrom> for SchemaConflictSet { type Error = ConflictError; - fn try_from(items: Vec) -> Result { + fn try_from(items: Vec) -> Result { match items.len() { 0 => return Err(ConflictError::ZeroItems), 1 => return Err(ConflictError::OneItem), _ => {} } - Ok(SchemaConflictSet(items)) + Ok(Self(items)) } } @@ -690,28 +690,28 @@ struct ConflictItemWire { impl TryFrom for ConflictItem { type Error = ConflictError; - fn try_from(wire: ConflictItemWire) -> Result { + fn try_from(wire: ConflictItemWire) -> Result { let Some(package) = wire.package else { return Err(ConflictError::MissingPackage); }; match (wire.extra, wire.group) { (None, None) => Err(ConflictError::MissingExtraAndGroup), (Some(_), Some(_)) => Err(ConflictError::FoundExtraAndGroup), - (Some(extra), None) => Ok(ConflictItem::from((package, extra))), - (None, Some(group)) => Ok(ConflictItem::from((package, group))), + (Some(extra), None) => Ok(Self::from((package, extra))), + (None, Some(group)) => Ok(Self::from((package, group))), } } } impl From for ConflictItemWire { - fn from(item: ConflictItem) -> ConflictItemWire { + fn from(item: ConflictItem) -> Self { match item.conflict { - ConflictPackage::Extra(extra) => ConflictItemWire { + ConflictPackage::Extra(extra) => Self { package: Some(item.package), extra: Some(extra), group: None, }, - ConflictPackage::Group(group) => ConflictItemWire { + ConflictPackage::Group(group) => Self { package: Some(item.package), extra: None, group: Some(group), @@ -723,16 +723,16 @@ impl From for ConflictItemWire { impl TryFrom for SchemaConflictItem { type Error = ConflictError; - fn try_from(wire: ConflictItemWire) -> Result { + fn try_from(wire: ConflictItemWire) -> Result { let package = wire.package; match (wire.extra, wire.group) { (None, None) => Err(ConflictError::MissingExtraAndGroup), (Some(_), Some(_)) => Err(ConflictError::FoundExtraAndGroup), - (Some(extra), None) => Ok(SchemaConflictItem { + (Some(extra), None) => Ok(Self { package, conflict: ConflictPackage::Extra(extra), }), - (None, Some(group)) => Ok(SchemaConflictItem { + (None, Some(group)) => Ok(Self { package, conflict: ConflictPackage::Group(group), }), @@ -741,14 +741,14 @@ impl TryFrom for SchemaConflictItem { } impl From for ConflictItemWire { - fn from(item: SchemaConflictItem) -> ConflictItemWire { + fn from(item: SchemaConflictItem) -> Self { match item.conflict { - ConflictPackage::Extra(extra) => ConflictItemWire { + ConflictPackage::Extra(extra) => Self { package: item.package, extra: Some(extra), group: None, }, - ConflictPackage::Group(group) => ConflictItemWire { + ConflictPackage::Group(group) => Self { package: item.package, extra: None, group: Some(group), diff --git a/crates/uv-pypi-types/src/identifier.rs b/crates/uv-pypi-types/src/identifier.rs index 47439f2c9..7ce496ff0 100644 --- a/crates/uv-pypi-types/src/identifier.rs +++ b/crates/uv-pypi-types/src/identifier.rs @@ -86,7 +86,7 @@ impl<'de> serde::de::Deserialize<'de> for Identifier { D: serde::de::Deserializer<'de>, { let s = String::deserialize(deserializer)?; - Identifier::from_str(&s).map_err(serde::de::Error::custom) + Self::from_str(&s).map_err(serde::de::Error::custom) } } diff --git a/crates/uv-pypi-types/src/metadata/metadata23.rs b/crates/uv-pypi-types/src/metadata/metadata23.rs index b0c1235be..811f5773d 100644 --- a/crates/uv-pypi-types/src/metadata/metadata23.rs +++ b/crates/uv-pypi-types/src/metadata/metadata23.rs @@ -148,7 +148,7 @@ impl Metadata23 { let provides_extras = headers.get_all_values("Provides-Extra").collect(); let description_content_type = headers.get_first_value("Description-Content-Type"); let dynamic = headers.get_all_values("Dynamic").collect(); - Ok(Metadata23 { + Ok(Self { metadata_version, name, version, @@ -284,7 +284,7 @@ impl FromStr for Metadata23 { type Err = MetadataError; fn from_str(s: &str) -> Result { - Metadata23::parse(s.as_bytes()) + Self::parse(s.as_bytes()) } } diff --git a/crates/uv-pypi-types/src/metadata/pyproject_toml.rs b/crates/uv-pypi-types/src/metadata/pyproject_toml.rs index 8487f058a..58ef09fc5 100644 --- a/crates/uv-pypi-types/src/metadata/pyproject_toml.rs +++ b/crates/uv-pypi-types/src/metadata/pyproject_toml.rs @@ -21,7 +21,7 @@ impl PyProjectToml { pub fn from_toml(toml: &str) -> Result { let pyproject_toml = toml_edit::Document::from_str(toml) .map_err(MetadataError::InvalidPyprojectTomlSyntax)?; - let pyproject_toml = PyProjectToml::deserialize(pyproject_toml.into_deserializer()) + let pyproject_toml = Self::deserialize(pyproject_toml.into_deserializer()) .map_err(MetadataError::InvalidPyprojectTomlSchema)?; Ok(pyproject_toml) } @@ -67,7 +67,7 @@ impl TryFrom for Project { fn try_from(wire: PyprojectTomlWire) -> Result { let name = wire.name.ok_or(MetadataError::MissingName)?; - Ok(Project { + Ok(Self { name, version: wire.version, requires_python: wire.requires_python, diff --git a/crates/uv-pypi-types/src/simple_json.rs b/crates/uv-pypi-types/src/simple_json.rs index 45cc4e373..2aefd3f27 100644 --- a/crates/uv-pypi-types/src/simple_json.rs +++ b/crates/uv-pypi-types/src/simple_json.rs @@ -133,7 +133,7 @@ impl<'de> Deserialize<'de> for CoreMetadata { D: Deserializer<'de>, { serde_untagged::UntaggedEnumVisitor::new() - .bool(|bool| Ok(CoreMetadata::Bool(bool))) + .bool(|bool| Ok(Self::Bool(bool))) .map(|map| map.deserialize().map(CoreMetadata::Hashes)) .deserialize(deserializer) } @@ -161,8 +161,8 @@ impl<'de> Deserialize<'de> for Yanked { D: Deserializer<'de>, { serde_untagged::UntaggedEnumVisitor::new() - .bool(|bool| Ok(Yanked::Bool(bool))) - .string(|string| Ok(Yanked::Reason(SmallString::from(string)))) + .bool(|bool| Ok(Self::Bool(bool))) + .string(|string| Ok(Self::Reason(SmallString::from(string)))) .deserialize(deserializer) } } @@ -218,35 +218,35 @@ impl Hashes { } match name { - "md5" => Ok(Hashes { + "md5" => Ok(Self { md5: Some(SmallString::from(value)), sha256: None, sha384: None, sha512: None, blake2b: None, }), - "sha256" => Ok(Hashes { + "sha256" => Ok(Self { md5: None, sha256: Some(SmallString::from(value)), sha384: None, sha512: None, blake2b: None, }), - "sha384" => Ok(Hashes { + "sha384" => Ok(Self { md5: None, sha256: None, sha384: Some(SmallString::from(value)), sha512: None, blake2b: None, }), - "sha512" => Ok(Hashes { + "sha512" => Ok(Self { md5: None, sha256: None, sha384: None, sha512: Some(SmallString::from(value)), blake2b: None, }), - "blake2b" => Ok(Hashes { + "blake2b" => Ok(Self { md5: None, sha256: None, sha384: None, @@ -278,35 +278,35 @@ impl FromStr for Hashes { } match name { - "md5" => Ok(Hashes { + "md5" => Ok(Self { md5: Some(SmallString::from(value)), sha256: None, sha384: None, sha512: None, blake2b: None, }), - "sha256" => Ok(Hashes { + "sha256" => Ok(Self { md5: None, sha256: Some(SmallString::from(value)), sha384: None, sha512: None, blake2b: None, }), - "sha384" => Ok(Hashes { + "sha384" => Ok(Self { md5: None, sha256: None, sha384: Some(SmallString::from(value)), sha512: None, blake2b: None, }), - "sha512" => Ok(Hashes { + "sha512" => Ok(Self { md5: None, sha256: None, sha384: None, sha512: Some(SmallString::from(value)), blake2b: None, }), - "blake2b" => Ok(Hashes { + "blake2b" => Ok(Self { md5: None, sha256: None, sha384: None, @@ -523,7 +523,7 @@ impl From for HashDigests { impl From for Hashes { fn from(value: HashDigests) -> Self { - let mut hashes = Hashes::default(); + let mut hashes = Self::default(); for digest in value { match digest.algorithm() { HashAlgorithm::Md5 => hashes.md5 = Some(digest.digest), diff --git a/crates/uv-pypi-types/src/supported_environments.rs b/crates/uv-pypi-types/src/supported_environments.rs index 0e09c263e..72c330ad1 100644 --- a/crates/uv-pypi-types/src/supported_environments.rs +++ b/crates/uv-pypi-types/src/supported_environments.rs @@ -11,7 +11,7 @@ pub struct SupportedEnvironments(Vec); impl SupportedEnvironments { /// Create a new [`SupportedEnvironments`] struct from a list of marker trees. pub fn from_markers(markers: Vec) -> Self { - SupportedEnvironments(markers) + Self(markers) } /// Return the list of marker trees. @@ -56,7 +56,7 @@ impl serde::Serialize for SupportedEnvironments { /// Deserialize a marker string or list of marker strings into a [`SupportedEnvironments`] struct. impl<'de> serde::Deserialize<'de> for SupportedEnvironments { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { diff --git a/crates/uv-python/src/discovery.rs b/crates/uv-python/src/discovery.rs index ff6c2a7e3..abd8c8ac1 100644 --- a/crates/uv-python/src/discovery.rs +++ b/crates/uv-python/src/discovery.rs @@ -74,7 +74,7 @@ impl<'a> serde::Deserialize<'a> for PythonRequest { D: serde::Deserializer<'a>, { let s = String::deserialize(deserializer)?; - Ok(PythonRequest::parse(&s)) + Ok(Self::parse(&s)) } } @@ -129,9 +129,9 @@ impl FromStr for PythonDownloads { fn from_str(s: &str) -> Result { match s.to_ascii_lowercase().as_str() { - "auto" | "automatic" | "true" | "1" => Ok(PythonDownloads::Automatic), - "manual" => Ok(PythonDownloads::Manual), - "never" | "false" | "0" => Ok(PythonDownloads::Never), + "auto" | "automatic" | "true" | "1" => Ok(Self::Automatic), + "manual" => Ok(Self::Manual), + "never" | "false" | "0" => Ok(Self::Never), _ => Err(format!("Invalid value for `python-download`: '{s}'")), } } @@ -139,11 +139,7 @@ impl FromStr for PythonDownloads { impl From for PythonDownloads { fn from(value: bool) -> Self { - if value { - PythonDownloads::Automatic - } else { - PythonDownloads::Never - } + if value { Self::Automatic } else { Self::Never } } } @@ -966,7 +962,7 @@ impl Error { match self { // When querying the Python interpreter fails, we will only raise errors that demonstrate that something is broken // If the Python interpreter returned a bad response, we'll continue searching for one that works - Error::Query(err, _, source) => match &**err { + Self::Query(err, _, source) => match &**err { InterpreterError::Encode(_) | InterpreterError::Io(_) | InterpreterError::SpawnFailed { .. } => true, @@ -1007,7 +1003,7 @@ impl Error { } } }, - Error::VirtualEnv(VirtualEnvError::MissingPyVenvCfg(path)) => { + Self::VirtualEnv(VirtualEnvError::MissingPyVenvCfg(path)) => { trace!("Skipping broken virtualenv at {}", path.display()); false } @@ -1603,8 +1599,8 @@ fn is_windows_store_shim(_path: &Path) -> bool { impl PythonVariant { fn matches_interpreter(self, interpreter: &Interpreter) -> bool { match self { - PythonVariant::Default => !interpreter.gil_disabled(), - PythonVariant::Freethreaded => interpreter.gil_disabled(), + Self::Default => !interpreter.gil_disabled(), + Self::Freethreaded => interpreter.gil_disabled(), } } @@ -1717,7 +1713,7 @@ impl PythonRequest { /// /// This can only return `Err` if `@` is used. Otherwise, if no match is found, it returns /// `Ok(None)`. - pub fn try_from_tool_name(value: &str) -> Result, Error> { + pub fn try_from_tool_name(value: &str) -> Result, Error> { let lowercase_value = &value.to_ascii_lowercase(); // Omitting the empty string from these lists excludes bare versions like "39". let abstract_version_prefixes = if cfg!(windows) { @@ -1751,7 +1747,7 @@ impl PythonRequest { implementation_names: impl IntoIterator, // the string to parse lowercase_value: &str, - ) -> Result, Error> { + ) -> Result, Error> { for prefix in abstract_version_prefixes { if let Some(version_request) = Self::try_split_prefix_and_version(prefix, lowercase_value)? @@ -1826,15 +1822,15 @@ impl PythonRequest { /// Check if this request includes a specific patch version. pub fn includes_patch(&self) -> bool { match self { - PythonRequest::Default => false, - PythonRequest::Any => false, - PythonRequest::Version(version_request) => version_request.patch().is_some(), - PythonRequest::Directory(..) => false, - PythonRequest::File(..) => false, - PythonRequest::ExecutableName(..) => false, - PythonRequest::Implementation(..) => false, - PythonRequest::ImplementationVersion(_, version) => version.patch().is_some(), - PythonRequest::Key(request) => request + Self::Default => false, + Self::Any => false, + Self::Version(version_request) => version_request.patch().is_some(), + Self::Directory(..) => false, + Self::File(..) => false, + Self::ExecutableName(..) => false, + Self::Implementation(..) => false, + Self::ImplementationVersion(_, version) => version.patch().is_some(), + Self::Key(request) => request .version .as_ref() .is_some_and(|request| request.patch().is_some()), @@ -1849,11 +1845,9 @@ impl PythonRequest { } match self { - PythonRequest::Default | PythonRequest::Any => true, - PythonRequest::Version(version_request) => { - version_request.matches_interpreter(interpreter) - } - PythonRequest::Directory(directory) => { + Self::Default | Self::Any => true, + Self::Version(version_request) => version_request.matches_interpreter(interpreter), + Self::Directory(directory) => { // `sys.prefix` points to the environment root or `sys.executable` is the same is_same_executable(directory, interpreter.sys_prefix()) || is_same_executable( @@ -1861,7 +1855,7 @@ impl PythonRequest { interpreter.sys_executable(), ) } - PythonRequest::File(file) => { + Self::File(file) => { // The interpreter satisfies the request both if it is the venv... if is_same_executable(interpreter.sys_executable(), file) { return true; @@ -1893,7 +1887,7 @@ impl PythonRequest { } false } - PythonRequest::ExecutableName(name) => { + Self::ExecutableName(name) => { // First, see if we have a match in the venv ... if interpreter .sys_executable() @@ -1922,16 +1916,16 @@ impl PythonRequest { } false } - PythonRequest::Implementation(implementation) => interpreter + Self::Implementation(implementation) => interpreter .implementation_name() .eq_ignore_ascii_case(implementation.into()), - PythonRequest::ImplementationVersion(implementation, version) => { + Self::ImplementationVersion(implementation, version) => { version.matches_interpreter(interpreter) && interpreter .implementation_name() .eq_ignore_ascii_case(implementation.into()) } - PythonRequest::Key(request) => request.satisfied_by_interpreter(interpreter), + Self::Key(request) => request.satisfied_by_interpreter(interpreter), } } @@ -2076,12 +2070,12 @@ impl PythonPreference { } match self { - PythonPreference::OnlyManaged => matches!(source, PythonSource::Managed), + Self::OnlyManaged => matches!(source, PythonSource::Managed), Self::Managed | Self::System => matches!( source, PythonSource::Managed | PythonSource::SearchPath | PythonSource::Registry ), - PythonPreference::OnlySystem => { + Self::OnlySystem => { matches!(source, PythonSource::SearchPath | PythonSource::Registry) } } diff --git a/crates/uv-python/src/downloads.rs b/crates/uv-python/src/downloads.rs index 9e1e03c91..f4579f869 100644 --- a/crates/uv-python/src/downloads.rs +++ b/crates/uv-python/src/downloads.rs @@ -121,12 +121,12 @@ impl Error { // Unfortunately different variants of `Error` track retry counts in different ways. We // could consider unifying the variants we handle here in `Error::from_reqwest_middleware` // instead, but both approaches will be fragile as new variants get added over time. - if let Error::NetworkErrorWithRetries { retries, .. } = self { + if let Self::NetworkErrorWithRetries { retries, .. } = self { return retries + 1; } // TODO(jack): let-chains are stable as of Rust 1.88. We should use them here as soon as // our rust-version is high enough. - if let Error::NetworkMiddlewareError(_, anyhow_error) = self { + if let Self::NetworkMiddlewareError(_, anyhow_error) = self { if let Some(RetryError::WithRetries { retries, .. }) = anyhow_error.downcast_ref::() { @@ -632,7 +632,7 @@ impl ManagedPythonDownload { pub fn from_request( request: &PythonDownloadRequest, python_downloads_json_url: Option<&str>, - ) -> Result<&'static ManagedPythonDownload, Error> { + ) -> Result<&'static Self, Error> { if let Some(download) = request.iter_downloads(python_downloads_json_url)?.next() { return Ok(download); } @@ -658,7 +658,7 @@ impl ManagedPythonDownload { /// so `python_downloads_json_url` is only used in the first call to this function. pub fn iter_all( python_downloads_json_url: Option<&str>, - ) -> Result, Error> { + ) -> Result, Error> { let downloads = PYTHON_DOWNLOADS.get_or_try_init(|| { let json_downloads: HashMap = if let Some(json_source) = python_downloads_json_url @@ -1244,8 +1244,8 @@ pub enum Direction { impl Direction { fn as_str(&self) -> &str { match self { - Direction::Download => "download", - Direction::Extract => "extract", + Self::Download => "download", + Self::Extract => "extract", } } } diff --git a/crates/uv-python/src/installation.rs b/crates/uv-python/src/installation.rs index 8cdc33106..09810e6f1 100644 --- a/crates/uv-python/src/installation.rs +++ b/crates/uv-python/src/installation.rs @@ -690,6 +690,6 @@ impl Hash for PythonInstallationMinorVersionKey { impl From for PythonInstallationMinorVersionKey { fn from(key: PythonInstallationKey) -> Self { - PythonInstallationMinorVersionKey(key) + Self(key) } } diff --git a/crates/uv-python/src/lib.rs b/crates/uv-python/src/lib.rs index f08198d97..ee4451163 100644 --- a/crates/uv-python/src/lib.rs +++ b/crates/uv-python/src/lib.rs @@ -104,7 +104,7 @@ pub enum Error { impl Error { pub(crate) fn with_missing_python_hint(self, hint: String) -> Self { match self { - Error::MissingPython(err, _) => Error::MissingPython(err, Some(hint)), + Self::MissingPython(err, _) => Self::MissingPython(err, Some(hint)), _ => self, } } @@ -112,7 +112,7 @@ impl Error { impl From for Error { fn from(err: PythonNotFound) -> Self { - Error::MissingPython(err, None) + Self::MissingPython(err, None) } } @@ -360,7 +360,7 @@ mod tests { /// /// Adds them to the test context search path. fn add_python_to_workdir(&self, name: &str, version: &str) -> Result<()> { - TestContext::create_mock_interpreter( + Self::create_mock_interpreter( self.workdir.child(name).as_ref(), &PythonVersion::from_str(version).expect("Test uses valid version"), ImplementationName::default(), @@ -419,7 +419,7 @@ mod tests { .parent() .expect("A Python executable path should always have a parent"), )?; - TestContext::create_mock_interpreter( + Self::create_mock_interpreter( &executable, &PythonVersion::from_str(version) .expect("A valid Python version is used for tests"), @@ -441,7 +441,7 @@ mod tests { .parent() .expect("A Python executable path should always have a parent"), )?; - TestContext::create_mock_interpreter( + Self::create_mock_interpreter( &executable, &PythonVersion::from_str(version) .expect("A valid Python version is used for tests"), diff --git a/crates/uv-python/src/managed.rs b/crates/uv-python/src/managed.rs index 69d12a0a3..5ab44be08 100644 --- a/crates/uv-python/src/managed.rs +++ b/crates/uv-python/src/managed.rs @@ -263,7 +263,7 @@ impl ManagedPythonInstallations { let arch = Arch::from_env(); let libc = Libc::from_env()?; - let iter = ManagedPythonInstallations::from_settings(None)? + let iter = Self::from_settings(None)? .find_all()? .filter(move |installation| { installation.key.os == os @@ -627,7 +627,7 @@ impl ManagedPythonInstallation { } /// Returns `true` if self is a suitable upgrade of other. - pub fn is_upgrade_of(&self, other: &ManagedPythonInstallation) -> bool { + pub fn is_upgrade_of(&self, other: &Self) -> bool { // Require matching implementation if self.key.implementation != other.key.implementation { return false; @@ -764,7 +764,7 @@ impl PythonMinorVersionLink { installation: &ManagedPythonInstallation, preview: Preview, ) -> Option { - PythonMinorVersionLink::from_executable( + Self::from_executable( installation.executable(false).as_path(), installation.key(), preview, diff --git a/crates/uv-python/src/version_files.rs b/crates/uv-python/src/version_files.rs index 595a18f0f..6541cbfc4 100644 --- a/crates/uv-python/src/version_files.rs +++ b/crates/uv-python/src/version_files.rs @@ -227,7 +227,7 @@ impl PythonVersionFile { /// Returns `true` if the version file is a global version file. pub fn is_global(&self) -> bool { - PythonVersionFile::global().is_some_and(|global| self.path() == global.path()) + Self::global().is_some_and(|global| self.path() == global.path()) } /// Return the first request declared in the file, if any. diff --git a/crates/uv-python/src/virtualenv.rs b/crates/uv-python/src/virtualenv.rs index 8b51a5e1b..f4314ed5f 100644 --- a/crates/uv-python/src/virtualenv.rs +++ b/crates/uv-python/src/virtualenv.rs @@ -85,22 +85,22 @@ impl CondaEnvironmentKind { fn from_prefix_path(path: &Path) -> Self { // If we cannot read `CONDA_DEFAULT_ENV`, there's no way to know if the base environment let Ok(default_env) = env::var(EnvVars::CONDA_DEFAULT_ENV) else { - return CondaEnvironmentKind::Child; + return Self::Child; }; // These are the expected names for the base environment if default_env != "base" && default_env != "root" { - return CondaEnvironmentKind::Child; + return Self::Child; } let Some(name) = path.file_name() else { - return CondaEnvironmentKind::Child; + return Self::Child; }; if name.to_str().is_some_and(|name| name == default_env) { - CondaEnvironmentKind::Base + Self::Base } else { - CondaEnvironmentKind::Child + Self::Child } } } diff --git a/crates/uv-redacted/src/lib.rs b/crates/uv-redacted/src/lib.rs index a0534c46d..5441eec35 100644 --- a/crates/uv-redacted/src/lib.rs +++ b/crates/uv-redacted/src/lib.rs @@ -60,7 +60,7 @@ impl DisplaySafeUrl { /// Parse a string as an URL, with this URL as the base URL. #[inline] pub fn join(&self, input: &str) -> Result { - self.0.join(input).map(DisplaySafeUrl::from) + self.0.join(input).map(Self::from) } /// Serialize with Serde using the internal representation of the `Url` struct. @@ -78,12 +78,12 @@ impl DisplaySafeUrl { where D: serde::Deserializer<'de>, { - Url::deserialize_internal(deserializer).map(DisplaySafeUrl::from) + Url::deserialize_internal(deserializer).map(Self::from) } #[allow(clippy::result_unit_err)] - pub fn from_file_path>(path: P) -> Result { - Url::from_file_path(path).map(DisplaySafeUrl::from) + pub fn from_file_path>(path: P) -> Result { + Url::from_file_path(path).map(Self::from) } /// Remove the credentials from a URL, allowing the generic `git` username (without a password) @@ -177,7 +177,7 @@ impl Debug for DisplaySafeUrl { impl From for DisplaySafeUrl { fn from(url: Url) -> Self { - DisplaySafeUrl(url) + Self(url) } } diff --git a/crates/uv-requirements-txt/src/lib.rs b/crates/uv-requirements-txt/src/lib.rs index b95875768..4209dd6d4 100644 --- a/crates/uv-requirements-txt/src/lib.rs +++ b/crates/uv-requirements-txt/src/lib.rs @@ -428,7 +428,7 @@ impl RequirementsTxt { /// Merge the data from a nested `requirements` file (`other`) into this one. pub fn update_from(&mut self, other: Self) { - let RequirementsTxt { + let Self { requirements, constraints, editables, @@ -469,33 +469,33 @@ impl UnsupportedOption { /// The name of the unsupported option. fn name(self) -> &'static str { match self { - UnsupportedOption::PreferBinary => "--prefer-binary", - UnsupportedOption::RequireHashes => "--require-hashes", - UnsupportedOption::Pre => "--pre", - UnsupportedOption::TrustedHost => "--trusted-host", - UnsupportedOption::UseFeature => "--use-feature", + Self::PreferBinary => "--prefer-binary", + Self::RequireHashes => "--require-hashes", + Self::Pre => "--pre", + Self::TrustedHost => "--trusted-host", + Self::UseFeature => "--use-feature", } } /// Returns `true` if the option is supported on the CLI. fn cli(self) -> bool { match self { - UnsupportedOption::PreferBinary => false, - UnsupportedOption::RequireHashes => true, - UnsupportedOption::Pre => true, - UnsupportedOption::TrustedHost => true, - UnsupportedOption::UseFeature => false, + Self::PreferBinary => false, + Self::RequireHashes => true, + Self::Pre => true, + Self::TrustedHost => true, + Self::UseFeature => false, } } /// Returns an iterator over all unsupported options. - fn iter() -> impl Iterator { + fn iter() -> impl Iterator { [ - UnsupportedOption::PreferBinary, - UnsupportedOption::RequireHashes, - UnsupportedOption::Pre, - UnsupportedOption::TrustedHost, - UnsupportedOption::UseFeature, + Self::PreferBinary, + Self::RequireHashes, + Self::Pre, + Self::TrustedHost, + Self::UseFeature, ] .iter() .copied() diff --git a/crates/uv-requirements-txt/src/requirement.rs b/crates/uv-requirements-txt/src/requirement.rs index 6c7cf0b52..e161cc6cd 100644 --- a/crates/uv-requirements-txt/src/requirement.rs +++ b/crates/uv-requirements-txt/src/requirement.rs @@ -64,7 +64,7 @@ impl RequirementsTxtRequirement { /// Specifically, only local directory URLs are supported. pub fn into_editable(self) -> Result { match self { - RequirementsTxtRequirement::Named(requirement) => { + Self::Named(requirement) => { let Some(version_or_url) = requirement.version_or_url else { return Err(EditableError::MissingVersion(requirement.name)); }; @@ -97,7 +97,7 @@ impl RequirementsTxtRequirement { ..requirement })) } - RequirementsTxtRequirement::Unnamed(requirement) => { + Self::Unnamed(requirement) => { let parsed_url = match requirement.url.parsed_url { ParsedUrl::Directory(parsed_url) => parsed_url, ParsedUrl::Path(_) => { diff --git a/crates/uv-requirements/src/upgrade.rs b/crates/uv-requirements/src/upgrade.rs index c3fb6ff1e..66c4e96ed 100644 --- a/crates/uv-requirements/src/upgrade.rs +++ b/crates/uv-requirements/src/upgrade.rs @@ -22,7 +22,7 @@ impl LockedRequirements { pub fn from_preferences(preferences: Vec) -> Self { Self { preferences, - ..LockedRequirements::default() + ..Self::default() } } } diff --git a/crates/uv-resolver/src/candidate_selector.rs b/crates/uv-resolver/src/candidate_selector.rs index 57776bda4..b10be99c0 100644 --- a/crates/uv-resolver/src/candidate_selector.rs +++ b/crates/uv-resolver/src/candidate_selector.rs @@ -616,8 +616,8 @@ impl CandidateDist<'_> { /// For an installable dist, return the prioritized distribution. fn prioritized(&self) -> Option<&PrioritizedDist> { match self { - CandidateDist::Compatible(dist) => dist.prioritized(), - CandidateDist::Incompatible { + Self::Compatible(dist) => dist.prioritized(), + Self::Incompatible { incompatible_dist: _, prioritized_dist: prioritized, } => Some(prioritized), @@ -664,9 +664,9 @@ pub(crate) enum VersionChoiceKind { impl Display for VersionChoiceKind { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - VersionChoiceKind::Preference => f.write_str("preference"), - VersionChoiceKind::Installed => f.write_str("installed"), - VersionChoiceKind::Compatible => f.write_str("compatible"), + Self::Preference => f.write_str("preference"), + Self::Installed => f.write_str("installed"), + Self::Compatible => f.write_str("compatible"), } } } diff --git a/crates/uv-resolver/src/graph_ops.rs b/crates/uv-resolver/src/graph_ops.rs index 63ffed950..878074e77 100644 --- a/crates/uv-resolver/src/graph_ops.rs +++ b/crates/uv-resolver/src/graph_ops.rs @@ -298,30 +298,30 @@ pub(crate) trait Reachable { fn marker(&self) -> T; } -impl Reachable for MarkerTree { - fn true_marker() -> MarkerTree { - MarkerTree::TRUE +impl Reachable for MarkerTree { + fn true_marker() -> Self { + Self::TRUE } - fn false_marker() -> MarkerTree { - MarkerTree::FALSE + fn false_marker() -> Self { + Self::FALSE } - fn marker(&self) -> MarkerTree { + fn marker(&self) -> Self { *self } } -impl Reachable for UniversalMarker { - fn true_marker() -> UniversalMarker { - UniversalMarker::TRUE +impl Reachable for UniversalMarker { + fn true_marker() -> Self { + Self::TRUE } - fn false_marker() -> UniversalMarker { - UniversalMarker::FALSE + fn false_marker() -> Self { + Self::FALSE } - fn marker(&self) -> UniversalMarker { + fn marker(&self) -> Self { *self } } diff --git a/crates/uv-resolver/src/lock/export/pylock_toml.rs b/crates/uv-resolver/src/lock/export/pylock_toml.rs index cfd979f4f..e9d337372 100644 --- a/crates/uv-resolver/src/lock/export/pylock_toml.rs +++ b/crates/uv-resolver/src/lock/export/pylock_toml.rs @@ -173,7 +173,7 @@ where PylockTomlErrorKind: From, { fn from(err: E) -> Self { - PylockTomlError { + Self { kind: Box::new(PylockTomlErrorKind::from(err)), hint: None, } @@ -601,7 +601,7 @@ impl<'lock> PylockToml { packages.sort_by(|a, b| a.name.cmp(&b.name).then(a.version.cmp(&b.version))); // Return the constructed `pylock.toml`. - Ok(PylockToml { + Ok(Self { lock_version, created_by, requires_python: Some(requires_python), diff --git a/crates/uv-resolver/src/lock/mod.rs b/crates/uv-resolver/src/lock/mod.rs index 03d4f606b..79baa320e 100644 --- a/crates/uv-resolver/src/lock/mod.rs +++ b/crates/uv-resolver/src/lock/mod.rs @@ -1980,7 +1980,7 @@ impl<'tags> TagPolicy<'tags> { /// Returns the platform tags to consider. fn tags(&self) -> &'tags Tags { match self { - TagPolicy::Required(tags) | TagPolicy::Preferred(tags) => tags, + Self::Required(tags) | Self::Preferred(tags) => tags, } } } @@ -2207,7 +2207,7 @@ struct LockWire { impl TryFrom for Lock { type Error = LockError; - fn try_from(wire: LockWire) -> Result { + fn try_from(wire: LockWire) -> Result { // Count the number of sources for each package name. When // there's only one source for a particular package name (the // overwhelmingly common case), we can omit some data (like source and @@ -2246,7 +2246,7 @@ impl TryFrom for Lock { .map(|simplified_marker| simplified_marker.into_marker(&wire.requires_python)) .map(UniversalMarker::from_combined) .collect(); - let lock = Lock::new( + let lock = Self::new( wire.version, wire.revision.unwrap_or(0), packages, @@ -2353,7 +2353,7 @@ impl Package { }) .collect::>()? }; - Ok(Package { + Ok(Self { id, sdist, wheels, @@ -3159,7 +3159,7 @@ struct PackageMetadata { } impl PackageMetadata { - fn unwire(self, requires_python: &RequiresPython) -> PackageMetadata { + fn unwire(self, requires_python: &RequiresPython) -> Self { // We need to complexify these markers so things like // `requires_python < '0'` get normalized to False let unwire_requirements = |requirements: BTreeSet| -> BTreeSet { @@ -3174,7 +3174,7 @@ impl PackageMetadata { .collect() }; - PackageMetadata { + Self { requires_dist: unwire_requirements(self.requires_dist), provides_extras: self.provides_extras, dependency_groups: self @@ -3252,10 +3252,7 @@ pub(crate) struct PackageId { } impl PackageId { - fn from_annotated_dist( - annotated_dist: &AnnotatedDist, - root: &Path, - ) -> Result { + fn from_annotated_dist(annotated_dist: &AnnotatedDist, root: &Path) -> Result { // Identify the source of the package. let source = Source::from_resolved_dist(&annotated_dist.dist, root)?; // Omit versions for dynamic source trees. @@ -3355,8 +3352,8 @@ impl PackageIdForDependency { } impl From for PackageIdForDependency { - fn from(id: PackageId) -> PackageIdForDependency { - PackageIdForDependency { + fn from(id: PackageId) -> Self { + Self { name: id.name, version: id.version, source: Some(id.source), @@ -3391,50 +3388,48 @@ enum Source { } impl Source { - fn from_resolved_dist(resolved_dist: &ResolvedDist, root: &Path) -> Result { + fn from_resolved_dist(resolved_dist: &ResolvedDist, root: &Path) -> Result { match *resolved_dist { // We pass empty installed packages for locking. ResolvedDist::Installed { .. } => unreachable!(), - ResolvedDist::Installable { ref dist, .. } => Source::from_dist(dist, root), + ResolvedDist::Installable { ref dist, .. } => Self::from_dist(dist, root), } } - fn from_dist(dist: &Dist, root: &Path) -> Result { + fn from_dist(dist: &Dist, root: &Path) -> Result { match *dist { - Dist::Built(ref built_dist) => Source::from_built_dist(built_dist, root), - Dist::Source(ref source_dist) => Source::from_source_dist(source_dist, root), + Dist::Built(ref built_dist) => Self::from_built_dist(built_dist, root), + Dist::Source(ref source_dist) => Self::from_source_dist(source_dist, root), } } - fn from_built_dist(built_dist: &BuiltDist, root: &Path) -> Result { + fn from_built_dist(built_dist: &BuiltDist, root: &Path) -> Result { match *built_dist { - BuiltDist::Registry(ref reg_dist) => Source::from_registry_built_dist(reg_dist, root), - BuiltDist::DirectUrl(ref direct_dist) => { - Ok(Source::from_direct_built_dist(direct_dist)) - } - BuiltDist::Path(ref path_dist) => Source::from_path_built_dist(path_dist, root), + BuiltDist::Registry(ref reg_dist) => Self::from_registry_built_dist(reg_dist, root), + BuiltDist::DirectUrl(ref direct_dist) => Ok(Self::from_direct_built_dist(direct_dist)), + BuiltDist::Path(ref path_dist) => Self::from_path_built_dist(path_dist, root), } } fn from_source_dist( source_dist: &uv_distribution_types::SourceDist, root: &Path, - ) -> Result { + ) -> Result { match *source_dist { uv_distribution_types::SourceDist::Registry(ref reg_dist) => { - Source::from_registry_source_dist(reg_dist, root) + Self::from_registry_source_dist(reg_dist, root) } uv_distribution_types::SourceDist::DirectUrl(ref direct_dist) => { - Ok(Source::from_direct_source_dist(direct_dist)) + Ok(Self::from_direct_source_dist(direct_dist)) } uv_distribution_types::SourceDist::Git(ref git_dist) => { - Ok(Source::from_git_dist(git_dist)) + Ok(Self::from_git_dist(git_dist)) } uv_distribution_types::SourceDist::Path(ref path_dist) => { - Source::from_path_source_dist(path_dist, root) + Self::from_path_source_dist(path_dist, root) } uv_distribution_types::SourceDist::Directory(ref directory) => { - Source::from_directory_source_dist(directory, root) + Self::from_directory_source_dist(directory, root) } } } @@ -3442,26 +3437,26 @@ impl Source { fn from_registry_built_dist( reg_dist: &RegistryBuiltDist, root: &Path, - ) -> Result { - Source::from_index_url(®_dist.best_wheel().index, root) + ) -> Result { + Self::from_index_url(®_dist.best_wheel().index, root) } fn from_registry_source_dist( reg_dist: &RegistrySourceDist, root: &Path, - ) -> Result { - Source::from_index_url(®_dist.index, root) + ) -> Result { + Self::from_index_url(®_dist.index, root) } - fn from_direct_built_dist(direct_dist: &DirectUrlBuiltDist) -> Source { - Source::Direct( + fn from_direct_built_dist(direct_dist: &DirectUrlBuiltDist) -> Self { + Self::Direct( normalize_url(direct_dist.url.to_url()), DirectSource { subdirectory: None }, ) } - fn from_direct_source_dist(direct_dist: &DirectUrlSourceDist) -> Source { - Source::Direct( + fn from_direct_source_dist(direct_dist: &DirectUrlSourceDist) -> Self { + Self::Direct( normalize_url(direct_dist.url.to_url()), DirectSource { subdirectory: direct_dist.subdirectory.clone(), @@ -3469,43 +3464,43 @@ impl Source { ) } - fn from_path_built_dist(path_dist: &PathBuiltDist, root: &Path) -> Result { + fn from_path_built_dist(path_dist: &PathBuiltDist, root: &Path) -> Result { let path = relative_to(&path_dist.install_path, root) .or_else(|_| std::path::absolute(&path_dist.install_path)) .map_err(LockErrorKind::DistributionRelativePath)?; - Ok(Source::Path(path.into_boxed_path())) + Ok(Self::Path(path.into_boxed_path())) } - fn from_path_source_dist(path_dist: &PathSourceDist, root: &Path) -> Result { + fn from_path_source_dist(path_dist: &PathSourceDist, root: &Path) -> Result { let path = relative_to(&path_dist.install_path, root) .or_else(|_| std::path::absolute(&path_dist.install_path)) .map_err(LockErrorKind::DistributionRelativePath)?; - Ok(Source::Path(path.into_boxed_path())) + Ok(Self::Path(path.into_boxed_path())) } fn from_directory_source_dist( directory_dist: &DirectorySourceDist, root: &Path, - ) -> Result { + ) -> Result { let path = relative_to(&directory_dist.install_path, root) .or_else(|_| std::path::absolute(&directory_dist.install_path)) .map_err(LockErrorKind::DistributionRelativePath)?; if directory_dist.editable.unwrap_or(false) { - Ok(Source::Editable(path.into_boxed_path())) + Ok(Self::Editable(path.into_boxed_path())) } else if directory_dist.r#virtual.unwrap_or(false) { - Ok(Source::Virtual(path.into_boxed_path())) + Ok(Self::Virtual(path.into_boxed_path())) } else { - Ok(Source::Directory(path.into_boxed_path())) + Ok(Self::Directory(path.into_boxed_path())) } } - fn from_index_url(index_url: &IndexUrl, root: &Path) -> Result { + fn from_index_url(index_url: &IndexUrl, root: &Path) -> Result { match index_url { IndexUrl::Pypi(_) | IndexUrl::Url(_) => { // Remove any sensitive credentials from the index URL. let redacted = index_url.without_credentials(); let source = RegistrySource::Url(UrlString::from(redacted.as_ref())); - Ok(Source::Registry(source)) + Ok(Self::Registry(source)) } IndexUrl::Path(url) => { let path = url @@ -3515,13 +3510,13 @@ impl Source { .or_else(|_| std::path::absolute(&path)) .map_err(LockErrorKind::IndexRelativePath)?; let source = RegistrySource::Path(path.into_boxed_path()); - Ok(Source::Registry(source)) + Ok(Self::Registry(source)) } } } - fn from_git_dist(git_dist: &GitSourceDist) -> Source { - Source::Git( + fn from_git_dist(git_dist: &GitSourceDist) -> Self { + Self::Git( UrlString::from(locked_git_url(git_dist)), GitSource { kind: GitSourceKind::from(git_dist.git.reference().clone()), @@ -3546,46 +3541,46 @@ impl Source { /// Returns `true` if the source is that of a wheel. fn is_wheel(&self) -> bool { match &self { - Source::Path(path) => { + Self::Path(path) => { matches!( DistExtension::from_path(path).ok(), Some(DistExtension::Wheel) ) } - Source::Direct(url, _) => { + Self::Direct(url, _) => { matches!( DistExtension::from_path(url.as_ref()).ok(), Some(DistExtension::Wheel) ) } - Source::Directory(..) => false, - Source::Editable(..) => false, - Source::Virtual(..) => false, - Source::Git(..) => false, - Source::Registry(..) => false, + Self::Directory(..) => false, + Self::Editable(..) => false, + Self::Virtual(..) => false, + Self::Git(..) => false, + Self::Registry(..) => false, } } /// Returns `true` if the source is that of a source tree. fn is_source_tree(&self) -> bool { match self { - Source::Directory(..) | Source::Editable(..) | Source::Virtual(..) => true, - Source::Path(..) | Source::Git(..) | Source::Registry(..) | Source::Direct(..) => false, + Self::Directory(..) | Self::Editable(..) | Self::Virtual(..) => true, + Self::Path(..) | Self::Git(..) | Self::Registry(..) | Self::Direct(..) => false, } } /// Returns the path to the source tree, if the source is a source tree. fn as_source_tree(&self) -> Option<&Path> { match self { - Source::Directory(path) | Source::Editable(path) | Source::Virtual(path) => Some(path), - Source::Path(..) | Source::Git(..) | Source::Registry(..) | Source::Direct(..) => None, + Self::Directory(path) | Self::Editable(path) | Self::Virtual(path) => Some(path), + Self::Path(..) | Self::Git(..) | Self::Registry(..) | Self::Direct(..) => None, } } fn to_toml(&self, table: &mut Table) { let mut source_table = InlineTable::new(); match *self { - Source::Registry(ref source) => match source { + Self::Registry(ref source) => match source { RegistrySource::Url(url) => { source_table.insert("registry", Value::from(url.as_ref())); } @@ -3596,10 +3591,10 @@ impl Source { ); } }, - Source::Git(ref url, _) => { + Self::Git(ref url, _) => { source_table.insert("git", Value::from(url.as_ref())); } - Source::Direct(ref url, DirectSource { ref subdirectory }) => { + Self::Direct(ref url, DirectSource { ref subdirectory }) => { source_table.insert("url", Value::from(url.as_ref())); if let Some(ref subdirectory) = *subdirectory { source_table.insert( @@ -3608,22 +3603,22 @@ impl Source { ); } } - Source::Path(ref path) => { + Self::Path(ref path) => { source_table.insert("path", Value::from(PortablePath::from(path).to_string())); } - Source::Directory(ref path) => { + Self::Directory(ref path) => { source_table.insert( "directory", Value::from(PortablePath::from(path).to_string()), ); } - Source::Editable(ref path) => { + Self::Editable(ref path) => { source_table.insert( "editable", Value::from(PortablePath::from(path).to_string()), ); } - Source::Virtual(ref path) => { + Self::Virtual(ref path) => { source_table.insert("virtual", Value::from(PortablePath::from(path).to_string())); } } @@ -3634,16 +3629,14 @@ impl Source { impl Display for Source { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { - Source::Registry(RegistrySource::Url(url)) - | Source::Git(url, _) - | Source::Direct(url, _) => { + Self::Registry(RegistrySource::Url(url)) | Self::Git(url, _) | Self::Direct(url, _) => { write!(f, "{}+{}", self.name(), url) } - Source::Registry(RegistrySource::Path(path)) - | Source::Path(path) - | Source::Directory(path) - | Source::Editable(path) - | Source::Virtual(path) => { + Self::Registry(RegistrySource::Path(path)) + | Self::Path(path) + | Self::Directory(path) + | Self::Editable(path) + | Self::Virtual(path) => { write!(f, "{}+{}", self.name(), PortablePath::from(path)) } } @@ -3711,12 +3704,12 @@ enum SourceWire { impl TryFrom for Source { type Error = LockError; - fn try_from(wire: SourceWire) -> Result { + fn try_from(wire: SourceWire) -> Result { #[allow(clippy::enum_glob_use)] use self::SourceWire::*; match wire { - Registry { registry } => Ok(Source::Registry(registry.into())), + Registry { registry } => Ok(Self::Registry(registry.into())), Git { git } => { let url = DisplaySafeUrl::parse(&git) .map_err(|err| SourceParseError::InvalidUrl { @@ -3736,18 +3729,18 @@ impl TryFrom for Source { }) .map_err(LockErrorKind::InvalidGitSourceUrl)?; - Ok(Source::Git(UrlString::from(url), git_source)) + Ok(Self::Git(UrlString::from(url), git_source)) } - Direct { url, subdirectory } => Ok(Source::Direct( + Direct { url, subdirectory } => Ok(Self::Direct( url, DirectSource { subdirectory: subdirectory.map(Box::::from), }, )), - Path { path } => Ok(Source::Path(path.into())), - Directory { directory } => Ok(Source::Directory(directory.into())), - Editable { editable } => Ok(Source::Editable(editable.into())), - Virtual { r#virtual } => Ok(Source::Virtual(r#virtual.into())), + Path { path } => Ok(Self::Path(path.into())), + Directory { directory } => Ok(Self::Directory(directory.into())), + Editable { editable } => Ok(Self::Editable(editable.into())), + Virtual { r#virtual } => Ok(Self::Virtual(r#virtual.into())), } } } @@ -3764,8 +3757,8 @@ enum RegistrySource { impl Display for RegistrySource { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { - RegistrySource::Url(url) => write!(f, "{url}"), - RegistrySource::Path(path) => write!(f, "{}", path.display()), + Self::Url(url) => write!(f, "{url}"), + Self::Path(path) => write!(f, "{}", path.display()), } } } @@ -3854,7 +3847,7 @@ enum GitSourceError { impl GitSource { /// Extracts a Git source reference from the query pairs and the hash /// fragment in the given URL. - fn from_url(url: &Url) -> Result { + fn from_url(url: &Url) -> Result { let mut kind = GitSourceKind::DefaultBranch; let mut subdirectory = None; for (key, val) in url.query_pairs() { @@ -3869,7 +3862,7 @@ impl GitSource { let precise = GitOid::from_str(url.fragment().ok_or(GitSourceError::MissingSha)?) .map_err(|_| GitSourceError::InvalidSha)?; - Ok(GitSource { + Ok(Self { precise, subdirectory, kind, @@ -3927,43 +3920,41 @@ enum SourceDist { impl SourceDist { fn filename(&self) -> Option> { match self { - SourceDist::Metadata { .. } => None, - SourceDist::Url { url, .. } => url.filename().ok(), - SourceDist::Path { path, .. } => { - path.file_name().map(|filename| filename.to_string_lossy()) - } + Self::Metadata { .. } => None, + Self::Url { url, .. } => url.filename().ok(), + Self::Path { path, .. } => path.file_name().map(|filename| filename.to_string_lossy()), } } fn url(&self) -> Option<&UrlString> { match &self { - SourceDist::Metadata { .. } => None, - SourceDist::Url { url, .. } => Some(url), - SourceDist::Path { .. } => None, + Self::Metadata { .. } => None, + Self::Url { url, .. } => Some(url), + Self::Path { .. } => None, } } pub(crate) fn hash(&self) -> Option<&Hash> { match &self { - SourceDist::Metadata { metadata } => metadata.hash.as_ref(), - SourceDist::Url { metadata, .. } => metadata.hash.as_ref(), - SourceDist::Path { metadata, .. } => metadata.hash.as_ref(), + Self::Metadata { metadata } => metadata.hash.as_ref(), + Self::Url { metadata, .. } => metadata.hash.as_ref(), + Self::Path { metadata, .. } => metadata.hash.as_ref(), } } pub(crate) fn size(&self) -> Option { match &self { - SourceDist::Metadata { metadata } => metadata.size, - SourceDist::Url { metadata, .. } => metadata.size, - SourceDist::Path { metadata, .. } => metadata.size, + Self::Metadata { metadata } => metadata.size, + Self::Url { metadata, .. } => metadata.size, + Self::Path { metadata, .. } => metadata.size, } } pub(crate) fn upload_time(&self) -> Option { match &self { - SourceDist::Metadata { metadata } => metadata.upload_time, - SourceDist::Url { metadata, .. } => metadata.upload_time, - SourceDist::Path { metadata, .. } => metadata.upload_time, + Self::Metadata { metadata } => metadata.upload_time, + Self::Url { metadata, .. } => metadata.upload_time, + Self::Path { metadata, .. } => metadata.upload_time, } } } @@ -3972,11 +3963,11 @@ impl SourceDist { fn from_annotated_dist( id: &PackageId, annotated_dist: &AnnotatedDist, - ) -> Result, LockError> { + ) -> Result, LockError> { match annotated_dist.dist { // We pass empty installed packages for locking. ResolvedDist::Installed { .. } => unreachable!(), - ResolvedDist::Installable { ref dist, .. } => SourceDist::from_dist( + ResolvedDist::Installable { ref dist, .. } => Self::from_dist( id, dist, annotated_dist.hashes.as_slice(), @@ -3990,18 +3981,16 @@ impl SourceDist { dist: &Dist, hashes: &[HashDigest], index: Option<&IndexUrl>, - ) -> Result, LockError> { + ) -> Result, LockError> { match *dist { Dist::Built(BuiltDist::Registry(ref built_dist)) => { let Some(sdist) = built_dist.sdist.as_ref() else { return Ok(None); }; - SourceDist::from_registry_dist(sdist, index) + Self::from_registry_dist(sdist, index) } Dist::Built(_) => Ok(None), - Dist::Source(ref source_dist) => { - SourceDist::from_source_dist(id, source_dist, hashes, index) - } + Dist::Source(ref source_dist) => Self::from_source_dist(id, source_dist, hashes, index), } } @@ -4010,16 +3999,16 @@ impl SourceDist { source_dist: &uv_distribution_types::SourceDist, hashes: &[HashDigest], index: Option<&IndexUrl>, - ) -> Result, LockError> { + ) -> Result, LockError> { match *source_dist { uv_distribution_types::SourceDist::Registry(ref reg_dist) => { - SourceDist::from_registry_dist(reg_dist, index) + Self::from_registry_dist(reg_dist, index) } uv_distribution_types::SourceDist::DirectUrl(_) => { - SourceDist::from_direct_dist(id, hashes).map(Some) + Self::from_direct_dist(id, hashes).map(Some) } uv_distribution_types::SourceDist::Path(_) => { - SourceDist::from_path_dist(id, hashes).map(Some) + Self::from_path_dist(id, hashes).map(Some) } // An actual sdist entry in the lockfile is only required when // it's from a registry or a direct URL. Otherwise, it's strictly @@ -4032,7 +4021,7 @@ impl SourceDist { fn from_registry_dist( reg_dist: &RegistrySourceDist, index: Option<&IndexUrl>, - ) -> Result, LockError> { + ) -> Result, LockError> { // Reject distributions from registries that don't match the index URL, as can occur with // `--find-links`. if index.is_none_or(|index| *index != reg_dist.index) { @@ -4052,7 +4041,7 @@ impl SourceDist { .map(Timestamp::from_millisecond) .transpose() .map_err(LockErrorKind::InvalidTimestamp)?; - Ok(Some(SourceDist::Url { + Ok(Some(Self::Url { url, metadata: SourceDistMetadata { hash, @@ -4087,7 +4076,7 @@ impl SourceDist { .map(Timestamp::from_millisecond) .transpose() .map_err(LockErrorKind::InvalidTimestamp)?; - Ok(Some(SourceDist::Path { + Ok(Some(Self::Path { path, metadata: SourceDistMetadata { hash, @@ -4107,7 +4096,7 @@ impl SourceDist { .map(Timestamp::from_millisecond) .transpose() .map_err(LockErrorKind::InvalidTimestamp)?; - Ok(Some(SourceDist::Url { + Ok(Some(Self::Url { url, metadata: SourceDistMetadata { hash, @@ -4120,7 +4109,7 @@ impl SourceDist { } } - fn from_direct_dist(id: &PackageId, hashes: &[HashDigest]) -> Result { + fn from_direct_dist(id: &PackageId, hashes: &[HashDigest]) -> Result { let Some(hash) = hashes.iter().max().cloned().map(Hash::from) else { let kind = LockErrorKind::Hash { id: id.clone(), @@ -4129,7 +4118,7 @@ impl SourceDist { }; return Err(kind.into()); }; - Ok(SourceDist::Metadata { + Ok(Self::Metadata { metadata: SourceDistMetadata { hash: Some(hash), size: None, @@ -4138,7 +4127,7 @@ impl SourceDist { }) } - fn from_path_dist(id: &PackageId, hashes: &[HashDigest]) -> Result { + fn from_path_dist(id: &PackageId, hashes: &[HashDigest]) -> Result { let Some(hash) = hashes.iter().max().cloned().map(Hash::from) else { let kind = LockErrorKind::Hash { id: id.clone(), @@ -4147,7 +4136,7 @@ impl SourceDist { }; return Err(kind.into()); }; - Ok(SourceDist::Metadata { + Ok(Self::Metadata { metadata: SourceDistMetadata { hash: Some(hash), size: None, @@ -4181,11 +4170,11 @@ impl SourceDist { fn to_toml(&self) -> Result { let mut table = InlineTable::new(); match &self { - SourceDist::Metadata { .. } => {} - SourceDist::Url { url, .. } => { + Self::Metadata { .. } => {} + Self::Url { url, .. } => { table.insert("url", Value::from(url.as_ref())); } - SourceDist::Path { path, .. } => { + Self::Path { path, .. } => { table.insert("path", Value::from(PortablePath::from(path).to_string())); } } @@ -4206,14 +4195,14 @@ impl SourceDist { } impl From for SourceDist { - fn from(wire: SourceDistWire) -> SourceDist { + fn from(wire: SourceDistWire) -> Self { match wire { - SourceDistWire::Url { url, metadata } => SourceDist::Url { url, metadata }, - SourceDistWire::Path { path, metadata } => SourceDist::Path { + SourceDistWire::Url { url, metadata } => Self::Url { url, metadata }, + SourceDistWire::Path { path, metadata } => Self::Path { path: path.into(), metadata, }, - SourceDistWire::Metadata { metadata } => SourceDist::Metadata { metadata }, + SourceDistWire::Metadata { metadata } => Self::Metadata { metadata }, } } } @@ -4221,12 +4210,12 @@ impl From for SourceDist { impl From for GitSourceKind { fn from(value: GitReference) -> Self { match value { - GitReference::Branch(branch) => GitSourceKind::Branch(branch.to_string()), - GitReference::Tag(tag) => GitSourceKind::Tag(tag.to_string()), - GitReference::BranchOrTag(rev) => GitSourceKind::Rev(rev.to_string()), - GitReference::BranchOrTagOrCommit(rev) => GitSourceKind::Rev(rev.to_string()), - GitReference::NamedRef(rev) => GitSourceKind::Rev(rev.to_string()), - GitReference::DefaultBranch => GitSourceKind::DefaultBranch, + GitReference::Branch(branch) => Self::Branch(branch.to_string()), + GitReference::Tag(tag) => Self::Tag(tag.to_string()), + GitReference::BranchOrTag(rev) => Self::Rev(rev.to_string()), + GitReference::BranchOrTagOrCommit(rev) => Self::Rev(rev.to_string()), + GitReference::NamedRef(rev) => Self::Rev(rev.to_string()), + GitReference::DefaultBranch => Self::DefaultBranch, } } } @@ -4234,10 +4223,10 @@ impl From for GitSourceKind { impl From for GitReference { fn from(value: GitSourceKind) -> Self { match value { - GitSourceKind::Branch(branch) => GitReference::Branch(branch), - GitSourceKind::Tag(tag) => GitReference::Tag(tag), - GitSourceKind::Rev(rev) => GitReference::from_rev(rev), - GitSourceKind::DefaultBranch => GitReference::DefaultBranch, + GitSourceKind::Branch(branch) => Self::Branch(branch), + GitSourceKind::Tag(tag) => Self::Tag(tag), + GitSourceKind::Rev(rev) => Self::from_rev(rev), + GitSourceKind::DefaultBranch => Self::DefaultBranch, } } } @@ -4327,11 +4316,11 @@ struct Wheel { } impl Wheel { - fn from_annotated_dist(annotated_dist: &AnnotatedDist) -> Result, LockError> { + fn from_annotated_dist(annotated_dist: &AnnotatedDist) -> Result, LockError> { match annotated_dist.dist { // We pass empty installed packages for locking. ResolvedDist::Installed { .. } => unreachable!(), - ResolvedDist::Installable { ref dist, .. } => Wheel::from_dist( + ResolvedDist::Installable { ref dist, .. } => Self::from_dist( dist, annotated_dist.hashes.as_slice(), annotated_dist.index(), @@ -4343,9 +4332,9 @@ impl Wheel { dist: &Dist, hashes: &[HashDigest], index: Option<&IndexUrl>, - ) -> Result, LockError> { + ) -> Result, LockError> { match *dist { - Dist::Built(ref built_dist) => Wheel::from_built_dist(built_dist, hashes, index), + Dist::Built(ref built_dist) => Self::from_built_dist(built_dist, hashes, index), Dist::Source(uv_distribution_types::SourceDist::Registry(ref source_dist)) => { source_dist .wheels @@ -4355,7 +4344,7 @@ impl Wheel { // `--find-links`. index.is_some_and(|index| *index == wheel.index) }) - .map(Wheel::from_registry_wheel) + .map(Self::from_registry_wheel) .collect() } Dist::Source(_) => Ok(vec![]), @@ -4366,20 +4355,20 @@ impl Wheel { built_dist: &BuiltDist, hashes: &[HashDigest], index: Option<&IndexUrl>, - ) -> Result, LockError> { + ) -> Result, LockError> { match *built_dist { - BuiltDist::Registry(ref reg_dist) => Wheel::from_registry_dist(reg_dist, index), + BuiltDist::Registry(ref reg_dist) => Self::from_registry_dist(reg_dist, index), BuiltDist::DirectUrl(ref direct_dist) => { - Ok(vec![Wheel::from_direct_dist(direct_dist, hashes)]) + Ok(vec![Self::from_direct_dist(direct_dist, hashes)]) } - BuiltDist::Path(ref path_dist) => Ok(vec![Wheel::from_path_dist(path_dist, hashes)]), + BuiltDist::Path(ref path_dist) => Ok(vec![Self::from_path_dist(path_dist, hashes)]), } } fn from_registry_dist( reg_dist: &RegistryBuiltDist, index: Option<&IndexUrl>, - ) -> Result, LockError> { + ) -> Result, LockError> { reg_dist .wheels .iter() @@ -4388,11 +4377,11 @@ impl Wheel { // `--find-links`. index.is_some_and(|index| *index == wheel.index) }) - .map(Wheel::from_registry_wheel) + .map(Self::from_registry_wheel) .collect() } - fn from_registry_wheel(wheel: &RegistryBuiltWheel) -> Result { + fn from_registry_wheel(wheel: &RegistryBuiltWheel) -> Result { let url = match &wheel.index { IndexUrl::Pypi(_) | IndexUrl::Url(_) => { let url = normalize_file_location(&wheel.file.url) @@ -4432,7 +4421,7 @@ impl Wheel { .map(Timestamp::from_millisecond) .transpose() .map_err(LockErrorKind::InvalidTimestamp)?; - Ok(Wheel { + Ok(Self { url, hash, size, @@ -4441,8 +4430,8 @@ impl Wheel { }) } - fn from_direct_dist(direct_dist: &DirectUrlBuiltDist, hashes: &[HashDigest]) -> Wheel { - Wheel { + fn from_direct_dist(direct_dist: &DirectUrlBuiltDist, hashes: &[HashDigest]) -> Self { + Self { url: WheelWireSource::Url { url: normalize_url(direct_dist.url.to_url()), }, @@ -4453,8 +4442,8 @@ impl Wheel { } } - fn from_path_dist(path_dist: &PathBuiltDist, hashes: &[HashDigest]) -> Wheel { - Wheel { + fn from_path_dist(path_dist: &PathBuiltDist, hashes: &[HashDigest]) -> Self { + Self { url: WheelWireSource::Filename { filename: path_dist.filename.clone(), }, @@ -4634,7 +4623,7 @@ impl Wheel { impl TryFrom for Wheel { type Error = String; - fn try_from(wire: WheelWire) -> Result { + fn try_from(wire: WheelWire) -> Result { let filename = match &wire.url { WheelWireSource::Url { url } => { let filename = url.filename().map_err(|err| err.to_string())?; @@ -4656,7 +4645,7 @@ impl TryFrom for Wheel { WheelWireSource::Filename { filename } => filename.clone(), }; - Ok(Wheel { + Ok(Self { url: wire.url, hash: wire.hash, size: wire.size, @@ -4703,10 +4692,10 @@ impl Dependency { package_id: PackageId, extra: BTreeSet, complexified_marker: UniversalMarker, - ) -> Dependency { + ) -> Self { let simplified_marker = SimplifiedMarkerTree::new(requires_python, complexified_marker.combined()); - Dependency { + Self { package_id, extra, simplified_marker, @@ -4719,10 +4708,10 @@ impl Dependency { annotated_dist: &AnnotatedDist, complexified_marker: UniversalMarker, root: &Path, - ) -> Result { + ) -> Result { let package_id = PackageId::from_annotated_dist(annotated_dist, root)?; let extra = annotated_dist.extra.iter().cloned().collect(); - Ok(Dependency::new( + Ok(Self::new( requires_python, package_id, extra, @@ -4813,22 +4802,22 @@ impl DependencyWire { struct Hash(HashDigest); impl From for Hash { - fn from(hd: HashDigest) -> Hash { - Hash(hd) + fn from(hd: HashDigest) -> Self { + Self(hd) } } impl FromStr for Hash { type Err = HashParseError; - fn from_str(s: &str) -> Result { + fn from_str(s: &str) -> Result { let (algorithm, digest) = s.split_once(':').ok_or(HashParseError( "expected '{algorithm}:{digest}', but found no ':' in hash digest", ))?; let algorithm = algorithm .parse() .map_err(|_| HashParseError("unrecognized hash algorithm"))?; - Ok(Hash(HashDigest { + Ok(Self(HashDigest { algorithm, digest: digest.into(), })) @@ -4842,7 +4831,7 @@ impl Display for Hash { } impl<'de> serde::Deserialize<'de> for Hash { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: serde::de::Deserializer<'de>, { @@ -4867,35 +4856,35 @@ impl<'de> serde::Deserialize<'de> for Hash { impl From for Hashes { fn from(value: Hash) -> Self { match value.0.algorithm { - HashAlgorithm::Md5 => Hashes { + HashAlgorithm::Md5 => Self { md5: Some(value.0.digest), sha256: None, sha384: None, sha512: None, blake2b: None, }, - HashAlgorithm::Sha256 => Hashes { + HashAlgorithm::Sha256 => Self { md5: None, sha256: Some(value.0.digest), sha384: None, sha512: None, blake2b: None, }, - HashAlgorithm::Sha384 => Hashes { + HashAlgorithm::Sha384 => Self { md5: None, sha256: None, sha384: Some(value.0.digest), sha512: None, blake2b: None, }, - HashAlgorithm::Sha512 => Hashes { + HashAlgorithm::Sha512 => Self { md5: None, sha256: None, sha384: None, sha512: Some(value.0.digest), blake2b: None, }, - HashAlgorithm::Blake2b => Hashes { + HashAlgorithm::Blake2b => Self { md5: None, sha256: None, sha384: None, @@ -5122,7 +5111,7 @@ where LockErrorKind: From, { fn from(err: E) -> Self { - LockError { + Self { kind: Box::new(LockErrorKind::from(err)), hint: None, } @@ -5165,7 +5154,7 @@ impl WheelTagHint { version: Option<&Version>, filenames: &[&WheelFilename], tags: &Tags, - ) -> Option { + ) -> Option { let incompatibility = filenames .iter() .map(|filename| { @@ -5183,7 +5172,7 @@ impl WheelTagHint { if tags.is_empty() { None } else { - Some(WheelTagHint::LanguageTags { + Some(Self::LanguageTags { package: name.clone(), version: version.cloned(), tags, @@ -5207,7 +5196,7 @@ impl WheelTagHint { if tags.is_empty() { None } else { - Some(WheelTagHint::AbiTags { + Some(Self::AbiTags { package: name.clone(), version: version.cloned(), tags, @@ -5223,7 +5212,7 @@ impl WheelTagHint { if tags.is_empty() { None } else { - Some(WheelTagHint::PlatformTags { + Some(Self::PlatformTags { package: name.clone(), version: version.cloned(), tags, diff --git a/crates/uv-resolver/src/prerelease.rs b/crates/uv-resolver/src/prerelease.rs index b646dce15..d1d1181ee 100644 --- a/crates/uv-resolver/src/prerelease.rs +++ b/crates/uv-resolver/src/prerelease.rs @@ -109,17 +109,17 @@ impl PrereleaseStrategy { env: &ResolverEnvironment, ) -> AllowPrerelease { match self { - PrereleaseStrategy::Disallow => AllowPrerelease::No, - PrereleaseStrategy::Allow => AllowPrerelease::Yes, - PrereleaseStrategy::IfNecessary => AllowPrerelease::IfNecessary, - PrereleaseStrategy::Explicit(packages) => { + Self::Disallow => AllowPrerelease::No, + Self::Allow => AllowPrerelease::Yes, + Self::IfNecessary => AllowPrerelease::IfNecessary, + Self::Explicit(packages) => { if packages.contains(package_name, env) { AllowPrerelease::Yes } else { AllowPrerelease::No } } - PrereleaseStrategy::IfNecessaryOrExplicit(packages) => { + Self::IfNecessaryOrExplicit(packages) => { if packages.contains(package_name, env) { AllowPrerelease::Yes } else { diff --git a/crates/uv-resolver/src/pubgrub/dependencies.rs b/crates/uv-resolver/src/pubgrub/dependencies.rs index f22754ead..daea414b5 100644 --- a/crates/uv-resolver/src/pubgrub/dependencies.rs +++ b/crates/uv-resolver/src/pubgrub/dependencies.rs @@ -89,12 +89,12 @@ impl PubGrubDependency { url, } = requirement; match &*package { - PubGrubPackageInner::Package { .. } => PubGrubDependency { + PubGrubPackageInner::Package { .. } => Self { package, version, url, }, - PubGrubPackageInner::Marker { .. } => PubGrubDependency { + PubGrubPackageInner::Marker { .. } => Self { package, version, url, @@ -107,7 +107,7 @@ impl PubGrubDependency { "extras not flattened for {name}" ); } - PubGrubDependency { + Self { package, version, url, @@ -121,7 +121,7 @@ impl PubGrubDependency { "group not flattened for {name}" ); } - PubGrubDependency { + Self { package, version, url, @@ -227,7 +227,7 @@ impl PubGrubRequirement { extra: Option, group: Option, requirement: &Requirement, - ) -> PubGrubRequirement { + ) -> Self { Self { package: PubGrubPackage::from_package( requirement.name.clone(), diff --git a/crates/uv-resolver/src/pubgrub/package.rs b/crates/uv-resolver/src/pubgrub/package.rs index 2e67a715a..86aa379bb 100644 --- a/crates/uv-resolver/src/pubgrub/package.rs +++ b/crates/uv-resolver/src/pubgrub/package.rs @@ -370,8 +370,8 @@ impl std::fmt::Display for PubGrubPackageInner { } } -impl From<&PubGrubPackage> for PubGrubPackage { - fn from(package: &PubGrubPackage) -> Self { +impl From<&Self> for PubGrubPackage { + fn from(package: &Self) -> Self { package.clone() } } diff --git a/crates/uv-resolver/src/pubgrub/report.rs b/crates/uv-resolver/src/pubgrub/report.rs index 5c62f0b1f..1779bf242 100644 --- a/crates/uv-resolver/src/pubgrub/report.rs +++ b/crates/uv-resolver/src/pubgrub/report.rs @@ -2011,7 +2011,7 @@ impl<'a> DependsOn<'a> { /// Adds an additional dependency. /// /// Note this overwrites previous calls to `DependsOn::and`. - fn and(mut self, package: &'a PubGrubPackage, range: &'a Range) -> DependsOn<'a> { + fn and(mut self, package: &'a PubGrubPackage, range: &'a Range) -> Self { self.dependency2 = Some(PackageRange { package, range, diff --git a/crates/uv-resolver/src/resolution/display.rs b/crates/uv-resolver/src/resolution/display.rs index 318fb4e54..e5b5dfef5 100644 --- a/crates/uv-resolver/src/resolution/display.rs +++ b/crates/uv-resolver/src/resolution/display.rs @@ -61,7 +61,7 @@ impl<'a> DisplayResolutionGraph<'a> { include_annotations: bool, include_index_annotation: bool, annotation_style: AnnotationStyle, - ) -> DisplayResolutionGraph<'a> { + ) -> Self { for fork_marker in &underlying.fork_markers { assert!( fork_marker.conflict().is_true(), diff --git a/crates/uv-resolver/src/resolution/output.rs b/crates/uv-resolver/src/resolution/output.rs index 8df52f4f0..e1da40f25 100644 --- a/crates/uv-resolver/src/resolution/output.rs +++ b/crates/uv-resolver/src/resolution/output.rs @@ -68,15 +68,15 @@ pub(crate) enum ResolutionGraphNode { impl ResolutionGraphNode { pub(crate) fn marker(&self) -> &UniversalMarker { match self { - ResolutionGraphNode::Root => &UniversalMarker::TRUE, - ResolutionGraphNode::Dist(dist) => &dist.marker, + Self::Root => &UniversalMarker::TRUE, + Self::Dist(dist) => &dist.marker, } } pub(crate) fn package_extra_names(&self) -> Option<(&PackageName, &ExtraName)> { match *self { - ResolutionGraphNode::Root => None, - ResolutionGraphNode::Dist(ref dist) => { + Self::Root => None, + Self::Dist(ref dist) => { let extra = dist.extra.as_ref()?; Some((&dist.name, extra)) } @@ -85,8 +85,8 @@ impl ResolutionGraphNode { pub(crate) fn package_group_names(&self) -> Option<(&PackageName, &GroupName)> { match *self { - ResolutionGraphNode::Root => None, - ResolutionGraphNode::Dist(ref dist) => { + Self::Root => None, + Self::Dist(ref dist) => { let group = dist.dev.as_ref()?; Some((&dist.name, group)) } @@ -95,8 +95,8 @@ impl ResolutionGraphNode { pub(crate) fn package_name(&self) -> Option<&PackageName> { match *self { - ResolutionGraphNode::Root => None, - ResolutionGraphNode::Dist(ref dist) => Some(&dist.name), + Self::Root => None, + Self::Dist(ref dist) => Some(&dist.name), } } } @@ -104,8 +104,8 @@ impl ResolutionGraphNode { impl Display for ResolutionGraphNode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - ResolutionGraphNode::Root => f.write_str("root"), - ResolutionGraphNode::Dist(dist) => Display::fmt(dist, f), + Self::Root => f.write_str("root"), + Self::Dist(dist) => Display::fmt(dist, f), } } } @@ -832,7 +832,7 @@ impl std::error::Error for ConflictingDistributionError {} impl Display for ConflictingDistributionError { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { - let ConflictingDistributionError { + let Self { ref name, ref version1, ref version2, @@ -928,7 +928,7 @@ impl From for uv_distribution_types::Resolution { } } - uv_distribution_types::Resolution::new(transformed).with_diagnostics(diagnostics) + Self::new(transformed).with_diagnostics(diagnostics) } } diff --git a/crates/uv-resolver/src/resolver/availability.rs b/crates/uv-resolver/src/resolver/availability.rs index 64721b4b6..0015199be 100644 --- a/crates/uv-resolver/src/resolver/availability.rs +++ b/crates/uv-resolver/src/resolver/availability.rs @@ -48,12 +48,12 @@ pub enum UnavailableVersion { impl UnavailableVersion { pub(crate) fn message(&self) -> String { match self { - UnavailableVersion::IncompatibleDist(invalid_dist) => format!("{invalid_dist}"), - UnavailableVersion::InvalidMetadata => "invalid metadata".into(), - UnavailableVersion::InconsistentMetadata => "inconsistent metadata".into(), - UnavailableVersion::InvalidStructure => "an invalid package format".into(), - UnavailableVersion::Offline => "to be downloaded from a registry".into(), - UnavailableVersion::RequiresPython(requires_python) => { + Self::IncompatibleDist(invalid_dist) => format!("{invalid_dist}"), + Self::InvalidMetadata => "invalid metadata".into(), + Self::InconsistentMetadata => "inconsistent metadata".into(), + Self::InvalidStructure => "an invalid package format".into(), + Self::Offline => "to be downloaded from a registry".into(), + Self::RequiresPython(requires_python) => { format!("Python {requires_python}") } } @@ -61,23 +61,23 @@ impl UnavailableVersion { pub(crate) fn singular_message(&self) -> String { match self { - UnavailableVersion::IncompatibleDist(invalid_dist) => invalid_dist.singular_message(), - UnavailableVersion::InvalidMetadata => format!("has {self}"), - UnavailableVersion::InconsistentMetadata => format!("has {self}"), - UnavailableVersion::InvalidStructure => format!("has {self}"), - UnavailableVersion::Offline => format!("needs {self}"), - UnavailableVersion::RequiresPython(..) => format!("requires {self}"), + Self::IncompatibleDist(invalid_dist) => invalid_dist.singular_message(), + Self::InvalidMetadata => format!("has {self}"), + Self::InconsistentMetadata => format!("has {self}"), + Self::InvalidStructure => format!("has {self}"), + Self::Offline => format!("needs {self}"), + Self::RequiresPython(..) => format!("requires {self}"), } } pub(crate) fn plural_message(&self) -> String { match self { - UnavailableVersion::IncompatibleDist(invalid_dist) => invalid_dist.plural_message(), - UnavailableVersion::InvalidMetadata => format!("have {self}"), - UnavailableVersion::InconsistentMetadata => format!("have {self}"), - UnavailableVersion::InvalidStructure => format!("have {self}"), - UnavailableVersion::Offline => format!("need {self}"), - UnavailableVersion::RequiresPython(..) => format!("require {self}"), + Self::IncompatibleDist(invalid_dist) => invalid_dist.plural_message(), + Self::InvalidMetadata => format!("have {self}"), + Self::InconsistentMetadata => format!("have {self}"), + Self::InvalidStructure => format!("have {self}"), + Self::Offline => format!("need {self}"), + Self::RequiresPython(..) => format!("require {self}"), } } @@ -87,14 +87,14 @@ impl UnavailableVersion { requires_python: Option, ) -> Option { match self { - UnavailableVersion::IncompatibleDist(invalid_dist) => { + Self::IncompatibleDist(invalid_dist) => { invalid_dist.context_message(tags, requires_python) } - UnavailableVersion::InvalidMetadata => None, - UnavailableVersion::InconsistentMetadata => None, - UnavailableVersion::InvalidStructure => None, - UnavailableVersion::Offline => None, - UnavailableVersion::RequiresPython(..) => None, + Self::InvalidMetadata => None, + Self::InconsistentMetadata => None, + Self::InvalidStructure => None, + Self::Offline => None, + Self::RequiresPython(..) => None, } } } @@ -108,14 +108,12 @@ impl Display for UnavailableVersion { impl From<&MetadataUnavailable> for UnavailableVersion { fn from(reason: &MetadataUnavailable) -> Self { match reason { - MetadataUnavailable::Offline => UnavailableVersion::Offline, - MetadataUnavailable::InvalidMetadata(_) => UnavailableVersion::InvalidMetadata, - MetadataUnavailable::InconsistentMetadata(_) => { - UnavailableVersion::InconsistentMetadata - } - MetadataUnavailable::InvalidStructure(_) => UnavailableVersion::InvalidStructure, + MetadataUnavailable::Offline => Self::Offline, + MetadataUnavailable::InvalidMetadata(_) => Self::InvalidMetadata, + MetadataUnavailable::InconsistentMetadata(_) => Self::InconsistentMetadata, + MetadataUnavailable::InvalidStructure(_) => Self::InvalidStructure, MetadataUnavailable::RequiresPython(requires_python, _python_version) => { - UnavailableVersion::RequiresPython(requires_python.clone()) + Self::RequiresPython(requires_python.clone()) } } } @@ -139,21 +137,21 @@ pub enum UnavailablePackage { impl UnavailablePackage { pub(crate) fn message(&self) -> &'static str { match self { - UnavailablePackage::NoIndex => "not found in the provided package locations", - UnavailablePackage::Offline => "not found in the cache", - UnavailablePackage::NotFound => "not found in the package registry", - UnavailablePackage::InvalidMetadata(_) => "invalid metadata", - UnavailablePackage::InvalidStructure(_) => "an invalid package format", + Self::NoIndex => "not found in the provided package locations", + Self::Offline => "not found in the cache", + Self::NotFound => "not found in the package registry", + Self::InvalidMetadata(_) => "invalid metadata", + Self::InvalidStructure(_) => "an invalid package format", } } pub(crate) fn singular_message(&self) -> String { match self { - UnavailablePackage::NoIndex => format!("was {self}"), - UnavailablePackage::Offline => format!("was {self}"), - UnavailablePackage::NotFound => format!("was {self}"), - UnavailablePackage::InvalidMetadata(_) => format!("has {self}"), - UnavailablePackage::InvalidStructure(_) => format!("has {self}"), + Self::NoIndex => format!("was {self}"), + Self::Offline => format!("was {self}"), + Self::NotFound => format!("was {self}"), + Self::InvalidMetadata(_) => format!("has {self}"), + Self::InvalidStructure(_) => format!("has {self}"), } } } diff --git a/crates/uv-resolver/src/resolver/environment.rs b/crates/uv-resolver/src/resolver/environment.rs index 6e816f991..8faec48c4 100644 --- a/crates/uv-resolver/src/resolver/environment.rs +++ b/crates/uv-resolver/src/resolver/environment.rs @@ -122,9 +122,9 @@ impl ResolverEnvironment { /// This enables `uv pip`-style resolutions. That is, the resolution /// returned is only guaranteed to be installable for this specific marker /// environment. - pub fn specific(marker_env: ResolverMarkerEnvironment) -> ResolverEnvironment { + pub fn specific(marker_env: ResolverMarkerEnvironment) -> Self { let kind = Kind::Specific { marker_env }; - ResolverEnvironment { kind } + Self { kind } } /// Create a resolver environment for producing a multi-platform @@ -145,14 +145,14 @@ impl ResolverEnvironment { /// the order of dependencies specified is also significant but has no /// specific guarantees around it). Changing the ordering can help when our /// custom fork prioritization fails. - pub fn universal(initial_forks: Vec) -> ResolverEnvironment { + pub fn universal(initial_forks: Vec) -> Self { let kind = Kind::Universal { initial_forks: initial_forks.into(), markers: MarkerTree::TRUE, include: Arc::new(crate::FxHashbrownSet::default()), exclude: Arc::new(crate::FxHashbrownSet::default()), }; - ResolverEnvironment { kind } + Self { kind } } /// Returns the marker environment corresponding to this resolver @@ -217,7 +217,7 @@ impl ResolverEnvironment { /// /// This panics if the resolver environment corresponds to one and only one /// specific marker environment. i.e., "pip"-style resolution. - fn narrow_environment(&self, rhs: MarkerTree) -> ResolverEnvironment { + fn narrow_environment(&self, rhs: MarkerTree) -> Self { match self.kind { Kind::Specific { .. } => { unreachable!("environment narrowing only happens in universal resolution") @@ -236,7 +236,7 @@ impl ResolverEnvironment { include: Arc::clone(include), exclude: Arc::clone(exclude), }; - ResolverEnvironment { kind } + Self { kind } } } } @@ -263,7 +263,7 @@ impl ResolverEnvironment { pub(crate) fn filter_by_group( &self, rules: impl IntoIterator>, - ) -> Option { + ) -> Option { match self.kind { Kind::Specific { .. } => { unreachable!("environment narrowing only happens in universal resolution") @@ -298,7 +298,7 @@ impl ResolverEnvironment { include: Arc::new(include), exclude: Arc::new(exclude), }; - Some(ResolverEnvironment { kind }) + Some(Self { kind }) } } } @@ -453,10 +453,7 @@ pub(crate) enum ForkingPossibility<'d> { } impl<'d> ForkingPossibility<'d> { - pub(crate) fn new( - env: &ResolverEnvironment, - dep: &'d PubGrubDependency, - ) -> ForkingPossibility<'d> { + pub(crate) fn new(env: &ResolverEnvironment, dep: &'d PubGrubDependency) -> Self { let marker = dep.package.marker(); if !env.included_by_marker(marker) { ForkingPossibility::DependencyAlwaysExcluded @@ -479,7 +476,7 @@ pub(crate) struct Forker<'d> { marker: MarkerTree, } -impl<'d> Forker<'d> { +impl Forker<'_> { /// Attempt a fork based on the given resolver environment. /// /// If a fork is possible, then a new forker and at least one new @@ -490,7 +487,7 @@ impl<'d> Forker<'d> { pub(crate) fn fork( &self, env: &ResolverEnvironment, - ) -> Option<(Forker<'d>, Vec)> { + ) -> Option<(Self, Vec)> { if !env.included_by_marker(self.marker) { return None; } diff --git a/crates/uv-resolver/src/resolver/mod.rs b/crates/uv-resolver/src/resolver/mod.rs index 7b4466394..4d0ecf125 100644 --- a/crates/uv-resolver/src/resolver/mod.rs +++ b/crates/uv-resolver/src/resolver/mod.rs @@ -3327,7 +3327,7 @@ pub(crate) enum Request { } impl<'a> From> for Request { - fn from(dist: ResolvedDistRef<'a>) -> Request { + fn from(dist: ResolvedDistRef<'a>) -> Self { // N.B. This is almost identical to `ResolvedDistRef::to_owned`, but // creates a `Request` instead of a `ResolvedDist`. There's probably // some room for DRYing this up a bit. The obvious way would be to @@ -3343,7 +3343,7 @@ impl<'a> From> for Request { (&source.name, &source.version), "expected chosen sdist to match prioritized sdist" ); - Request::Dist(Dist::Source(SourceDist::Registry(source))) + Self::Dist(Dist::Source(SourceDist::Registry(source))) } ResolvedDistRef::InstallableRegistryBuiltDist { wheel, prioritized, .. @@ -3356,9 +3356,9 @@ impl<'a> From> for Request { // This is okay because we're only here if the prioritized dist // has at least one wheel, so this always succeeds. let built = prioritized.built_dist().expect("at least one wheel"); - Request::Dist(Dist::Built(BuiltDist::Registry(built))) + Self::Dist(Dist::Built(BuiltDist::Registry(built))) } - ResolvedDistRef::Installed { dist } => Request::Installed(dist.clone()), + ResolvedDistRef::Installed { dist } => Self::Installed(dist.clone()), } } } @@ -3435,9 +3435,9 @@ impl Dependencies { conflicts: &Conflicts, ) -> ForkedDependencies { let deps = match self { - Dependencies::Available(deps) => deps, - Dependencies::Unforkable(deps) => return ForkedDependencies::Unforked(deps), - Dependencies::Unavailable(err) => return ForkedDependencies::Unavailable(err), + Self::Available(deps) => deps, + Self::Unforkable(deps) => return ForkedDependencies::Unforked(deps), + Self::Unavailable(err) => return ForkedDependencies::Unavailable(err), }; let mut name_to_deps: BTreeMap> = BTreeMap::new(); for dep in deps { @@ -3509,7 +3509,7 @@ impl Forks { env: &ResolverEnvironment, python_requirement: &PythonRequirement, conflicts: &Conflicts, - ) -> Forks { + ) -> Self { let python_marker = python_requirement.to_marker_tree(); let mut forks = vec![Fork::new(env.clone())]; @@ -3673,7 +3673,7 @@ impl Forks { } forks = new; } - Forks { + Self { forks, diverging_packages, } @@ -3723,8 +3723,8 @@ struct Fork { impl Fork { /// Create a new fork with no dependencies with the given resolver /// environment. - fn new(env: ResolverEnvironment) -> Fork { - Fork { + fn new(env: ResolverEnvironment) -> Self { + Self { dependencies: vec![], conflicts: crate::FxHashbrownSet::default(), env, @@ -3772,7 +3772,7 @@ impl Fork { fn filter( mut self, rules: impl IntoIterator>, - ) -> Option { + ) -> Option { self.env = self.env.filter_by_group(rules)?; self.dependencies.retain(|dep| { let Some(conflicting_item) = dep.package.conflicting_item() else { @@ -3835,7 +3835,7 @@ impl Fork { impl Eq for Fork {} impl PartialEq for Fork { - fn eq(&self, other: &Fork) -> bool { + fn eq(&self, other: &Self) -> bool { self.dependencies == other.dependencies && self.env == other.env } } diff --git a/crates/uv-resolver/src/resolver/provider.rs b/crates/uv-resolver/src/resolver/provider.rs index b06067df5..3fd314ec4 100644 --- a/crates/uv-resolver/src/resolver/provider.rs +++ b/crates/uv-resolver/src/resolver/provider.rs @@ -67,11 +67,11 @@ impl MetadataUnavailable { /// formatting system is more custom. pub(crate) fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - MetadataUnavailable::Offline => None, - MetadataUnavailable::InvalidMetadata(err) => Some(err), - MetadataUnavailable::InconsistentMetadata(err) => Some(err), - MetadataUnavailable::InvalidStructure(err) => Some(err), - MetadataUnavailable::RequiresPython(_, _) => None, + Self::Offline => None, + Self::InvalidMetadata(err) => Some(err), + Self::InconsistentMetadata(err) => Some(err), + Self::InvalidStructure(err) => Some(err), + Self::RequiresPython(_, _) => None, } } } diff --git a/crates/uv-resolver/src/resolver/system.rs b/crates/uv-resolver/src/resolver/system.rs index a815697da..b8965064c 100644 --- a/crates/uv-resolver/src/resolver/system.rs +++ b/crates/uv-resolver/src/resolver/system.rs @@ -45,7 +45,7 @@ impl std::fmt::Display for SystemDependency { impl From for PubGrubDependency { fn from(value: SystemDependency) -> Self { - PubGrubDependency { + Self { package: PubGrubPackage::from(PubGrubPackageInner::System(value.name)), version: Ranges::singleton(value.version), url: None, diff --git a/crates/uv-resolver/src/universal_marker.rs b/crates/uv-resolver/src/universal_marker.rs index 5e5c4f17b..4114825fb 100644 --- a/crates/uv-resolver/src/universal_marker.rs +++ b/crates/uv-resolver/src/universal_marker.rs @@ -85,30 +85,27 @@ pub struct UniversalMarker { impl UniversalMarker { /// A constant universal marker that always evaluates to `true`. - pub(crate) const TRUE: UniversalMarker = UniversalMarker { + pub(crate) const TRUE: Self = Self { marker: MarkerTree::TRUE, pep508: MarkerTree::TRUE, }; /// A constant universal marker that always evaluates to `false`. - pub(crate) const FALSE: UniversalMarker = UniversalMarker { + pub(crate) const FALSE: Self = Self { marker: MarkerTree::FALSE, pep508: MarkerTree::FALSE, }; /// Creates a new universal marker from its constituent pieces. - pub(crate) fn new( - mut pep508_marker: MarkerTree, - conflict_marker: ConflictMarker, - ) -> UniversalMarker { + pub(crate) fn new(mut pep508_marker: MarkerTree, conflict_marker: ConflictMarker) -> Self { pep508_marker.and(conflict_marker.marker); - UniversalMarker::from_combined(pep508_marker) + Self::from_combined(pep508_marker) } /// Creates a new universal marker from a marker that has already been /// combined from a PEP 508 and conflict marker. - pub(crate) fn from_combined(marker: MarkerTree) -> UniversalMarker { - UniversalMarker { + pub(crate) fn from_combined(marker: MarkerTree) -> Self { + Self { marker, pep508: marker.without_extras(), } @@ -117,7 +114,7 @@ impl UniversalMarker { /// Combine this universal marker with the one given in a way that unions /// them. That is, the updated marker will evaluate to `true` if `self` or /// `other` evaluate to `true`. - pub(crate) fn or(&mut self, other: UniversalMarker) { + pub(crate) fn or(&mut self, other: Self) { self.marker.or(other.marker); self.pep508.or(other.pep508); } @@ -125,7 +122,7 @@ impl UniversalMarker { /// Combine this universal marker with the one given in a way that /// intersects them. That is, the updated marker will evaluate to `true` if /// `self` and `other` evaluate to `true`. - pub(crate) fn and(&mut self, other: UniversalMarker) { + pub(crate) fn and(&mut self, other: Self) { self.marker.and(other.marker); self.pep508.and(other.pep508); } @@ -230,7 +227,7 @@ impl UniversalMarker { /// /// Two universal markers are disjoint when it is impossible for them both /// to evaluate to `true` simultaneously. - pub(crate) fn is_disjoint(self, other: UniversalMarker) -> bool { + pub(crate) fn is_disjoint(self, other: Self) -> bool { self.marker.is_disjoint(other.marker) } @@ -321,26 +318,26 @@ pub struct ConflictMarker { impl ConflictMarker { /// A constant conflict marker that always evaluates to `true`. - pub const TRUE: ConflictMarker = ConflictMarker { + pub const TRUE: Self = Self { marker: MarkerTree::TRUE, }; /// A constant conflict marker that always evaluates to `false`. - pub const FALSE: ConflictMarker = ConflictMarker { + pub const FALSE: Self = Self { marker: MarkerTree::FALSE, }; /// Creates a new conflict marker from the declared conflicts provided. - pub fn from_conflicts(conflicts: &Conflicts) -> ConflictMarker { + pub fn from_conflicts(conflicts: &Conflicts) -> Self { if conflicts.is_empty() { - return ConflictMarker::TRUE; + return Self::TRUE; } - let mut marker = ConflictMarker::TRUE; + let mut marker = Self::TRUE; for set in conflicts.iter() { for (item1, item2) in set.iter().tuple_combinations() { - let pair = ConflictMarker::from_conflict_item(item1) + let pair = Self::from_conflict_item(item1) .negate() - .or(ConflictMarker::from_conflict_item(item2).negate()); + .or(Self::from_conflict_item(item2).negate()); marker = marker.and(pair); } } @@ -349,37 +346,37 @@ impl ConflictMarker { /// Create a conflict marker that is true only when the given extra or /// group (for a specific package) is activated. - pub fn from_conflict_item(item: &ConflictItem) -> ConflictMarker { + pub fn from_conflict_item(item: &ConflictItem) -> Self { match *item.conflict() { - ConflictPackage::Extra(ref extra) => ConflictMarker::extra(item.package(), extra), - ConflictPackage::Group(ref group) => ConflictMarker::group(item.package(), group), + ConflictPackage::Extra(ref extra) => Self::extra(item.package(), extra), + ConflictPackage::Group(ref group) => Self::group(item.package(), group), } } /// Create a conflict marker that is true only when the given extra for the /// given package is activated. - pub fn extra(package: &PackageName, extra: &ExtraName) -> ConflictMarker { + pub fn extra(package: &PackageName, extra: &ExtraName) -> Self { let operator = uv_pep508::ExtraOperator::Equal; let name = uv_pep508::MarkerValueExtra::Extra(encode_package_extra(package, extra)); let expr = uv_pep508::MarkerExpression::Extra { operator, name }; let marker = MarkerTree::expression(expr); - ConflictMarker { marker } + Self { marker } } /// Create a conflict marker that is true only when the given group for the /// given package is activated. - pub fn group(package: &PackageName, group: &GroupName) -> ConflictMarker { + pub fn group(package: &PackageName, group: &GroupName) -> Self { let operator = uv_pep508::ExtraOperator::Equal; let name = uv_pep508::MarkerValueExtra::Extra(encode_package_group(package, group)); let expr = uv_pep508::MarkerExpression::Extra { operator, name }; let marker = MarkerTree::expression(expr); - ConflictMarker { marker } + Self { marker } } /// Returns a new conflict marker that is the negation of this one. #[must_use] - pub fn negate(self) -> ConflictMarker { - ConflictMarker { + pub fn negate(self) -> Self { + Self { marker: self.marker.negate(), } } @@ -387,19 +384,19 @@ impl ConflictMarker { /// Returns a new conflict marker corresponding to the union of `self` and /// `other`. #[must_use] - pub fn or(self, other: ConflictMarker) -> ConflictMarker { + pub fn or(self, other: Self) -> Self { let mut marker = self.marker; marker.or(other.marker); - ConflictMarker { marker } + Self { marker } } /// Returns a new conflict marker corresponding to the intersection of /// `self` and `other`. #[must_use] - pub fn and(self, other: ConflictMarker) -> ConflictMarker { + pub fn and(self, other: Self) -> Self { let mut marker = self.marker; marker.and(other.marker); - ConflictMarker { marker } + Self { marker } } /// Returns a new conflict marker corresponding to the logical implication @@ -408,10 +405,10 @@ impl ConflictMarker { /// If the conflict marker returned is always `true`, then it can be said /// that `self` implies `consequent`. #[must_use] - pub fn implies(self, other: ConflictMarker) -> ConflictMarker { + pub fn implies(self, other: Self) -> Self { let mut marker = self.marker; marker.implies(other.marker); - ConflictMarker { marker } + Self { marker } } /// Returns true if this conflict marker will always evaluate to `true`. @@ -526,7 +523,7 @@ enum ParsedRawExtra<'a> { } impl<'a> ParsedRawExtra<'a> { - fn parse(raw_extra: &'a ExtraName) -> Result, ResolveError> { + fn parse(raw_extra: &'a ExtraName) -> Result { fn mkerr(raw_extra: &ExtraName, reason: impl Into) -> ResolveError { let raw_extra = raw_extra.to_owned(); let reason = reason.into(); diff --git a/crates/uv-settings/src/combine.rs b/crates/uv-settings/src/combine.rs index 084846948..6c08cbc61 100644 --- a/crates/uv-settings/src/combine.rs +++ b/crates/uv-settings/src/combine.rs @@ -40,7 +40,7 @@ pub trait Combine { impl Combine for Option { /// Combine the options used in two [`FilesystemOptions`]s. Retains the root of `self`. - fn combine(self, other: Option) -> Option { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(a), Some(b)) => Some(FilesystemOptions( a.into_options().combine(b.into_options()), @@ -52,7 +52,7 @@ impl Combine for Option { impl Combine for Option { /// Combine the options used in two [`Options`]s. Retains the root of `self`. - fn combine(self, other: Option) -> Option { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(a), Some(b)) => Some(a.combine(b)), (a, b) => a.or(b), @@ -61,7 +61,7 @@ impl Combine for Option { } impl Combine for Option { - fn combine(self, other: Option) -> Option { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(a), Some(b)) => Some(a.combine(b)), (a, b) => a.or(b), @@ -114,7 +114,7 @@ impl_combine_or!(bool); impl Combine for Option> { /// Combine two vectors by extending the vector in `self` with the vector in `other`, if they're /// both `Some`. - fn combine(self, other: Option>) -> Option> { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(mut a), Some(b)) => { a.extend(b); @@ -127,7 +127,7 @@ impl Combine for Option> { impl Combine for Option>> { /// Combine two maps of vecs by combining their vecs - fn combine(self, other: Option>>) -> Option>> { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(mut a), Some(b)) => { for (key, value) in b { @@ -142,7 +142,7 @@ impl Combine for Option>> { impl Combine for Option { /// Combine two [`ExcludeNewerPackage`] instances by merging them, with the values in `self` taking precedence. - fn combine(self, other: Option) -> Option { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(mut a), Some(b)) => { // Extend with values from b, but a takes precedence (we don't overwrite existing keys) @@ -159,7 +159,7 @@ impl Combine for Option { impl Combine for Option { /// Combine two maps by merging the map in `self` with the map in `other`, if they're both /// `Some`. - fn combine(self, other: Option) -> Option { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(a), Some(b)) => Some(a.merge(b)), (a, b) => a.or(b), @@ -170,7 +170,7 @@ impl Combine for Option { impl Combine for Option { /// Combine two maps by merging the map in `self` with the map in `other`, if they're both /// `Some`. - fn combine(self, other: Option) -> Option { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(a), Some(b)) => Some(a.merge(b)), (a, b) => a.or(b), @@ -228,7 +228,7 @@ impl Combine for ExtraBuildDependencies { } impl Combine for Option { - fn combine(self, other: Option) -> Option { + fn combine(self, other: Self) -> Self { match (self, other) { (Some(a), Some(b)) => Some(a.combine(b)), (a, b) => a.or(b), diff --git a/crates/uv-settings/src/settings.rs b/crates/uv-settings/src/settings.rs index 8e50d6999..cf4bb18fe 100644 --- a/crates/uv-settings/src/settings.rs +++ b/crates/uv-settings/src/settings.rs @@ -886,7 +886,7 @@ pub struct PythonInstallMirrors { impl Default for PythonInstallMirrors { fn default() -> Self { - PythonInstallMirrors::resolve(None, None, None) + Self::resolve(None, None, None) } } @@ -900,7 +900,7 @@ impl PythonInstallMirrors { let pypy_mirror_env = std::env::var(EnvVars::UV_PYPY_INSTALL_MIRROR).ok(); let python_downloads_json_url_env = std::env::var(EnvVars::UV_PYTHON_DOWNLOADS_JSON_URL).ok(); - PythonInstallMirrors { + Self { python_install_mirror: python_mirror_env.or(python_mirror), pypy_install_mirror: pypy_mirror_env.or(pypy_mirror), python_downloads_json_url: python_downloads_json_url_env.or(python_downloads_json_url), diff --git a/crates/uv-shell/src/lib.rs b/crates/uv-shell/src/lib.rs index 83f3f62e8..5593a4947 100644 --- a/crates/uv-shell/src/lib.rs +++ b/crates/uv-shell/src/lib.rs @@ -41,27 +41,27 @@ impl Shell { /// /// If `SHELL` is set, but contains a value that doesn't correspond to one of the supported /// shell types, then return `None`. - pub fn from_env() -> Option { + pub fn from_env() -> Option { if std::env::var_os(EnvVars::NU_VERSION).is_some() { - Some(Shell::Nushell) + Some(Self::Nushell) } else if std::env::var_os(EnvVars::FISH_VERSION).is_some() { - Some(Shell::Fish) + Some(Self::Fish) } else if std::env::var_os(EnvVars::BASH_VERSION).is_some() { - Some(Shell::Bash) + Some(Self::Bash) } else if std::env::var_os(EnvVars::ZSH_VERSION).is_some() { - Some(Shell::Zsh) + Some(Self::Zsh) } else if std::env::var_os(EnvVars::KSH_VERSION).is_some() { - Some(Shell::Ksh) + Some(Self::Ksh) } else if let Some(env_shell) = std::env::var_os(EnvVars::SHELL) { - Shell::from_shell_path(env_shell) + Self::from_shell_path(env_shell) } else if cfg!(windows) { // Command Prompt relies on PROMPT for its appearance whereas PowerShell does not. // See: https://stackoverflow.com/a/66415037. if std::env::var_os(EnvVars::PROMPT).is_some() { - Some(Shell::Cmd) + Some(Self::Cmd) } else { // Fallback to PowerShell if the PROMPT environment variable is not set. - Some(Shell::Powershell) + Some(Self::Powershell) } } else { None @@ -79,14 +79,14 @@ impl Shell { /// assert_eq!(Shell::from_shell_path("/usr/bin/zsh"), Some(Shell::Zsh)); /// assert_eq!(Shell::from_shell_path("/opt/my_custom_shell"), None); /// ``` - pub fn from_shell_path(path: impl AsRef) -> Option { + pub fn from_shell_path(path: impl AsRef) -> Option { parse_shell_from_path(path.as_ref()) } /// Returns `true` if the shell supports a `PATH` update command. pub fn supports_update(self) -> bool { match self { - Shell::Powershell | Shell::Cmd => true, + Self::Powershell | Self::Cmd => true, shell => !shell.configuration_files().is_empty(), } } @@ -101,7 +101,7 @@ impl Shell { return vec![]; }; match self { - Shell::Bash => { + Self::Bash => { // On Bash, we need to update both `.bashrc` and `.bash_profile`. The former is // sourced for non-login shells, and the latter is sourced for login shells. // @@ -116,11 +116,11 @@ impl Shell { home_dir.join(".bashrc"), ] } - Shell::Ksh => { + Self::Ksh => { // On Ksh it's standard POSIX `.profile` for login shells, and `.kshrc` for non-login. vec![home_dir.join(".profile"), home_dir.join(".kshrc")] } - Shell::Zsh => { + Self::Zsh => { // On Zsh, we only need to update `.zshenv`. This file is sourced for both login and // non-login shells. However, we match rustup's logic for determining _which_ // `.zshenv` to use. @@ -154,7 +154,7 @@ impl Shell { vec![home_dir.join(".zshenv")] } } - Shell::Fish => { + Self::Fish => { // On Fish, we only need to update `config.fish`. This file is sourced for both // login and non-login shells. However, we must respect Fish's logic, which reads // from `$XDG_CONFIG_HOME/fish/config.fish` if set, and `~/.config/fish/config.fish` @@ -169,16 +169,16 @@ impl Shell { vec![home_dir.join(".config/fish/config.fish")] } } - Shell::Csh => { + Self::Csh => { // On Csh, we need to update both `.cshrc` and `.login`, like Bash. vec![home_dir.join(".cshrc"), home_dir.join(".login")] } // TODO(charlie): Add support for Nushell. - Shell::Nushell => vec![], + Self::Nushell => vec![], // See: [`crate::windows::prepend_path`]. - Shell::Powershell => vec![], + Self::Powershell => vec![], // See: [`crate::windows::prepend_path`]. - Shell::Cmd => vec![], + Self::Cmd => vec![], } } @@ -209,24 +209,24 @@ impl Shell { /// Returns the command necessary to prepend a directory to the `PATH` in this shell. pub fn prepend_path(self, path: &Path) -> Option { match self { - Shell::Nushell => None, - Shell::Bash | Shell::Zsh | Shell::Ksh => Some(format!( + Self::Nushell => None, + Self::Bash | Self::Zsh | Self::Ksh => Some(format!( "export PATH=\"{}:$PATH\"", backslash_escape(&path.simplified_display().to_string()), )), - Shell::Fish => Some(format!( + Self::Fish => Some(format!( "fish_add_path \"{}\"", backslash_escape(&path.simplified_display().to_string()), )), - Shell::Csh => Some(format!( + Self::Csh => Some(format!( "setenv PATH \"{}:$PATH\"", backslash_escape(&path.simplified_display().to_string()), )), - Shell::Powershell => Some(format!( + Self::Powershell => Some(format!( "$env:PATH = \"{};$env:PATH\"", backtick_escape(&path.simplified_display().to_string()), )), - Shell::Cmd => Some(format!( + Self::Cmd => Some(format!( "set PATH=\"{};%PATH%\"", backslash_escape(&path.simplified_display().to_string()), )), @@ -237,14 +237,14 @@ impl Shell { impl std::fmt::Display for Shell { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Shell::Bash => write!(f, "Bash"), - Shell::Fish => write!(f, "Fish"), - Shell::Powershell => write!(f, "PowerShell"), - Shell::Cmd => write!(f, "Command Prompt"), - Shell::Zsh => write!(f, "Zsh"), - Shell::Nushell => write!(f, "Nushell"), - Shell::Csh => write!(f, "Csh"), - Shell::Ksh => write!(f, "Ksh"), + Self::Bash => write!(f, "Bash"), + Self::Fish => write!(f, "Fish"), + Self::Powershell => write!(f, "PowerShell"), + Self::Cmd => write!(f, "Command Prompt"), + Self::Zsh => write!(f, "Zsh"), + Self::Nushell => write!(f, "Nushell"), + Self::Csh => write!(f, "Csh"), + Self::Ksh => write!(f, "Ksh"), } } } diff --git a/crates/uv-state/src/lib.rs b/crates/uv-state/src/lib.rs index 2fd663b7f..c207c1da9 100644 --- a/crates/uv-state/src/lib.rs +++ b/crates/uv-state/src/lib.rs @@ -83,16 +83,16 @@ impl StateStore { /// Returns an absolute cache dir. pub fn from_settings(state_dir: Option) -> Result { if let Some(state_dir) = state_dir { - StateStore::from_path(state_dir) + Self::from_path(state_dir) } else if let Some(data_dir) = uv_dirs::legacy_user_state_dir().filter(|dir| dir.exists()) { // If the user has an existing directory at (e.g.) `/Users/user/Library/Application Support/uv`, // respect it for backwards compatibility. Otherwise, prefer the XDG strategy, even on // macOS. - StateStore::from_path(data_dir) + Self::from_path(data_dir) } else if let Some(data_dir) = uv_dirs::user_state_dir() { - StateStore::from_path(data_dir) + Self::from_path(data_dir) } else { - StateStore::from_path(".uv") + Self::from_path(".uv") } } } diff --git a/crates/uv-tool/src/receipt.rs b/crates/uv-tool/src/receipt.rs index 84b57ca00..ed7be9829 100644 --- a/crates/uv-tool/src/receipt.rs +++ b/crates/uv-tool/src/receipt.rs @@ -19,13 +19,13 @@ impl ToolReceipt { /// Parse a [`ToolReceipt`] from a raw TOML string. pub(crate) fn from_string(raw: String) -> Result { let tool = toml::from_str(&raw)?; - Ok(ToolReceipt { raw, ..tool }) + Ok(Self { raw, ..tool }) } /// Read a [`ToolReceipt`] from the given path. - pub(crate) fn from_path(path: &Path) -> Result { + pub(crate) fn from_path(path: &Path) -> Result { match fs_err::read_to_string(path) { - Ok(contents) => Ok(ToolReceipt::from_string(contents) + Ok(contents) => Ok(Self::from_string(contents) .map_err(|err| crate::Error::ReceiptRead(path.to_owned(), Box::new(err)))?), Err(err) => Err(err.into()), } @@ -44,7 +44,7 @@ impl ToolReceipt { impl From for ToolReceipt { fn from(tool: Tool) -> Self { - ToolReceipt { + Self { tool, raw: String::new(), } diff --git a/crates/uv-torch/src/backend.rs b/crates/uv-torch/src/backend.rs index 5ad71b385..44658b93f 100644 --- a/crates/uv-torch/src/backend.rs +++ b/crates/uv-torch/src/backend.rs @@ -276,7 +276,7 @@ impl TorchStrategy { /// Return the appropriate index URLs for the given [`TorchStrategy`]. pub fn index_urls(&self) -> impl Iterator { match self { - TorchStrategy::Cuda { os, driver_version } => { + Self::Cuda { os, driver_version } => { // If this is a GPU-enabled package, and CUDA drivers are installed, use PyTorch's CUDA // indexes. // @@ -321,7 +321,7 @@ impl TorchStrategy { } } } - TorchStrategy::Amd { + Self::Amd { os, gpu_architecture, } => match os { @@ -350,7 +350,7 @@ impl TorchStrategy { Either::Right(Either::Left(std::iter::once(TorchBackend::Cpu.index_url()))) } }, - TorchStrategy::Xpu { os } => match os { + Self::Xpu { os } => match os { Os::Manylinux { .. } => Either::Right(Either::Right(Either::Left( std::iter::once(TorchBackend::Xpu.index_url()), ))), @@ -368,9 +368,9 @@ impl TorchStrategy { Either::Right(Either::Left(std::iter::once(TorchBackend::Cpu.index_url()))) } }, - TorchStrategy::Backend(backend) => Either::Right(Either::Right(Either::Right( - std::iter::once(backend.index_url()), - ))), + Self::Backend(backend) => Either::Right(Either::Right(Either::Right(std::iter::once( + backend.index_url(), + )))), } } } @@ -489,96 +489,96 @@ impl TorchBackend { /// Returns the CUDA [`Version`] for the given [`TorchBackend`]. pub fn cuda_version(&self) -> Option { match self { - TorchBackend::Cpu => None, - TorchBackend::Cu128 => Some(Version::new([12, 8])), - TorchBackend::Cu126 => Some(Version::new([12, 6])), - TorchBackend::Cu125 => Some(Version::new([12, 5])), - TorchBackend::Cu124 => Some(Version::new([12, 4])), - TorchBackend::Cu123 => Some(Version::new([12, 3])), - TorchBackend::Cu122 => Some(Version::new([12, 2])), - TorchBackend::Cu121 => Some(Version::new([12, 1])), - TorchBackend::Cu120 => Some(Version::new([12, 0])), - TorchBackend::Cu118 => Some(Version::new([11, 8])), - TorchBackend::Cu117 => Some(Version::new([11, 7])), - TorchBackend::Cu116 => Some(Version::new([11, 6])), - TorchBackend::Cu115 => Some(Version::new([11, 5])), - TorchBackend::Cu114 => Some(Version::new([11, 4])), - TorchBackend::Cu113 => Some(Version::new([11, 3])), - TorchBackend::Cu112 => Some(Version::new([11, 2])), - TorchBackend::Cu111 => Some(Version::new([11, 1])), - TorchBackend::Cu110 => Some(Version::new([11, 0])), - TorchBackend::Cu102 => Some(Version::new([10, 2])), - TorchBackend::Cu101 => Some(Version::new([10, 1])), - TorchBackend::Cu100 => Some(Version::new([10, 0])), - TorchBackend::Cu92 => Some(Version::new([9, 2])), - TorchBackend::Cu91 => Some(Version::new([9, 1])), - TorchBackend::Cu90 => Some(Version::new([9, 0])), - TorchBackend::Cu80 => Some(Version::new([8, 0])), - TorchBackend::Rocm63 => None, - TorchBackend::Rocm624 => None, - TorchBackend::Rocm62 => None, - TorchBackend::Rocm61 => None, - TorchBackend::Rocm60 => None, - TorchBackend::Rocm57 => None, - TorchBackend::Rocm56 => None, - TorchBackend::Rocm55 => None, - TorchBackend::Rocm542 => None, - TorchBackend::Rocm54 => None, - TorchBackend::Rocm53 => None, - TorchBackend::Rocm52 => None, - TorchBackend::Rocm511 => None, - TorchBackend::Rocm42 => None, - TorchBackend::Rocm41 => None, - TorchBackend::Rocm401 => None, - TorchBackend::Xpu => None, + Self::Cpu => None, + Self::Cu128 => Some(Version::new([12, 8])), + Self::Cu126 => Some(Version::new([12, 6])), + Self::Cu125 => Some(Version::new([12, 5])), + Self::Cu124 => Some(Version::new([12, 4])), + Self::Cu123 => Some(Version::new([12, 3])), + Self::Cu122 => Some(Version::new([12, 2])), + Self::Cu121 => Some(Version::new([12, 1])), + Self::Cu120 => Some(Version::new([12, 0])), + Self::Cu118 => Some(Version::new([11, 8])), + Self::Cu117 => Some(Version::new([11, 7])), + Self::Cu116 => Some(Version::new([11, 6])), + Self::Cu115 => Some(Version::new([11, 5])), + Self::Cu114 => Some(Version::new([11, 4])), + Self::Cu113 => Some(Version::new([11, 3])), + Self::Cu112 => Some(Version::new([11, 2])), + Self::Cu111 => Some(Version::new([11, 1])), + Self::Cu110 => Some(Version::new([11, 0])), + Self::Cu102 => Some(Version::new([10, 2])), + Self::Cu101 => Some(Version::new([10, 1])), + Self::Cu100 => Some(Version::new([10, 0])), + Self::Cu92 => Some(Version::new([9, 2])), + Self::Cu91 => Some(Version::new([9, 1])), + Self::Cu90 => Some(Version::new([9, 0])), + Self::Cu80 => Some(Version::new([8, 0])), + Self::Rocm63 => None, + Self::Rocm624 => None, + Self::Rocm62 => None, + Self::Rocm61 => None, + Self::Rocm60 => None, + Self::Rocm57 => None, + Self::Rocm56 => None, + Self::Rocm55 => None, + Self::Rocm542 => None, + Self::Rocm54 => None, + Self::Rocm53 => None, + Self::Rocm52 => None, + Self::Rocm511 => None, + Self::Rocm42 => None, + Self::Rocm41 => None, + Self::Rocm401 => None, + Self::Xpu => None, } } /// Returns the ROCM [`Version`] for the given [`TorchBackend`]. pub fn rocm_version(&self) -> Option { match self { - TorchBackend::Cpu => None, - TorchBackend::Cu128 => None, - TorchBackend::Cu126 => None, - TorchBackend::Cu125 => None, - TorchBackend::Cu124 => None, - TorchBackend::Cu123 => None, - TorchBackend::Cu122 => None, - TorchBackend::Cu121 => None, - TorchBackend::Cu120 => None, - TorchBackend::Cu118 => None, - TorchBackend::Cu117 => None, - TorchBackend::Cu116 => None, - TorchBackend::Cu115 => None, - TorchBackend::Cu114 => None, - TorchBackend::Cu113 => None, - TorchBackend::Cu112 => None, - TorchBackend::Cu111 => None, - TorchBackend::Cu110 => None, - TorchBackend::Cu102 => None, - TorchBackend::Cu101 => None, - TorchBackend::Cu100 => None, - TorchBackend::Cu92 => None, - TorchBackend::Cu91 => None, - TorchBackend::Cu90 => None, - TorchBackend::Cu80 => None, - TorchBackend::Rocm63 => Some(Version::new([6, 3])), - TorchBackend::Rocm624 => Some(Version::new([6, 2, 4])), - TorchBackend::Rocm62 => Some(Version::new([6, 2])), - TorchBackend::Rocm61 => Some(Version::new([6, 1])), - TorchBackend::Rocm60 => Some(Version::new([6, 0])), - TorchBackend::Rocm57 => Some(Version::new([5, 7])), - TorchBackend::Rocm56 => Some(Version::new([5, 6])), - TorchBackend::Rocm55 => Some(Version::new([5, 5])), - TorchBackend::Rocm542 => Some(Version::new([5, 4, 2])), - TorchBackend::Rocm54 => Some(Version::new([5, 4])), - TorchBackend::Rocm53 => Some(Version::new([5, 3])), - TorchBackend::Rocm52 => Some(Version::new([5, 2])), - TorchBackend::Rocm511 => Some(Version::new([5, 1, 1])), - TorchBackend::Rocm42 => Some(Version::new([4, 2])), - TorchBackend::Rocm41 => Some(Version::new([4, 1])), - TorchBackend::Rocm401 => Some(Version::new([4, 0, 1])), - TorchBackend::Xpu => None, + Self::Cpu => None, + Self::Cu128 => None, + Self::Cu126 => None, + Self::Cu125 => None, + Self::Cu124 => None, + Self::Cu123 => None, + Self::Cu122 => None, + Self::Cu121 => None, + Self::Cu120 => None, + Self::Cu118 => None, + Self::Cu117 => None, + Self::Cu116 => None, + Self::Cu115 => None, + Self::Cu114 => None, + Self::Cu113 => None, + Self::Cu112 => None, + Self::Cu111 => None, + Self::Cu110 => None, + Self::Cu102 => None, + Self::Cu101 => None, + Self::Cu100 => None, + Self::Cu92 => None, + Self::Cu91 => None, + Self::Cu90 => None, + Self::Cu80 => None, + Self::Rocm63 => Some(Version::new([6, 3])), + Self::Rocm624 => Some(Version::new([6, 2, 4])), + Self::Rocm62 => Some(Version::new([6, 2])), + Self::Rocm61 => Some(Version::new([6, 1])), + Self::Rocm60 => Some(Version::new([6, 0])), + Self::Rocm57 => Some(Version::new([5, 7])), + Self::Rocm56 => Some(Version::new([5, 6])), + Self::Rocm55 => Some(Version::new([5, 5])), + Self::Rocm542 => Some(Version::new([5, 4, 2])), + Self::Rocm54 => Some(Version::new([5, 4])), + Self::Rocm53 => Some(Version::new([5, 3])), + Self::Rocm52 => Some(Version::new([5, 2])), + Self::Rocm511 => Some(Version::new([5, 1, 1])), + Self::Rocm42 => Some(Version::new([4, 2])), + Self::Rocm41 => Some(Version::new([4, 1])), + Self::Rocm401 => Some(Version::new([4, 0, 1])), + Self::Xpu => None, } } } @@ -588,48 +588,48 @@ impl FromStr for TorchBackend { fn from_str(s: &str) -> Result { match s { - "cpu" => Ok(TorchBackend::Cpu), - "cu128" => Ok(TorchBackend::Cu128), - "cu126" => Ok(TorchBackend::Cu126), - "cu125" => Ok(TorchBackend::Cu125), - "cu124" => Ok(TorchBackend::Cu124), - "cu123" => Ok(TorchBackend::Cu123), - "cu122" => Ok(TorchBackend::Cu122), - "cu121" => Ok(TorchBackend::Cu121), - "cu120" => Ok(TorchBackend::Cu120), - "cu118" => Ok(TorchBackend::Cu118), - "cu117" => Ok(TorchBackend::Cu117), - "cu116" => Ok(TorchBackend::Cu116), - "cu115" => Ok(TorchBackend::Cu115), - "cu114" => Ok(TorchBackend::Cu114), - "cu113" => Ok(TorchBackend::Cu113), - "cu112" => Ok(TorchBackend::Cu112), - "cu111" => Ok(TorchBackend::Cu111), - "cu110" => Ok(TorchBackend::Cu110), - "cu102" => Ok(TorchBackend::Cu102), - "cu101" => Ok(TorchBackend::Cu101), - "cu100" => Ok(TorchBackend::Cu100), - "cu92" => Ok(TorchBackend::Cu92), - "cu91" => Ok(TorchBackend::Cu91), - "cu90" => Ok(TorchBackend::Cu90), - "cu80" => Ok(TorchBackend::Cu80), - "rocm6.3" => Ok(TorchBackend::Rocm63), - "rocm6.2.4" => Ok(TorchBackend::Rocm624), - "rocm6.2" => Ok(TorchBackend::Rocm62), - "rocm6.1" => Ok(TorchBackend::Rocm61), - "rocm6.0" => Ok(TorchBackend::Rocm60), - "rocm5.7" => Ok(TorchBackend::Rocm57), - "rocm5.6" => Ok(TorchBackend::Rocm56), - "rocm5.5" => Ok(TorchBackend::Rocm55), - "rocm5.4.2" => Ok(TorchBackend::Rocm542), - "rocm5.4" => Ok(TorchBackend::Rocm54), - "rocm5.3" => Ok(TorchBackend::Rocm53), - "rocm5.2" => Ok(TorchBackend::Rocm52), - "rocm5.1.1" => Ok(TorchBackend::Rocm511), - "rocm4.2" => Ok(TorchBackend::Rocm42), - "rocm4.1" => Ok(TorchBackend::Rocm41), - "rocm4.0.1" => Ok(TorchBackend::Rocm401), - "xpu" => Ok(TorchBackend::Xpu), + "cpu" => Ok(Self::Cpu), + "cu128" => Ok(Self::Cu128), + "cu126" => Ok(Self::Cu126), + "cu125" => Ok(Self::Cu125), + "cu124" => Ok(Self::Cu124), + "cu123" => Ok(Self::Cu123), + "cu122" => Ok(Self::Cu122), + "cu121" => Ok(Self::Cu121), + "cu120" => Ok(Self::Cu120), + "cu118" => Ok(Self::Cu118), + "cu117" => Ok(Self::Cu117), + "cu116" => Ok(Self::Cu116), + "cu115" => Ok(Self::Cu115), + "cu114" => Ok(Self::Cu114), + "cu113" => Ok(Self::Cu113), + "cu112" => Ok(Self::Cu112), + "cu111" => Ok(Self::Cu111), + "cu110" => Ok(Self::Cu110), + "cu102" => Ok(Self::Cu102), + "cu101" => Ok(Self::Cu101), + "cu100" => Ok(Self::Cu100), + "cu92" => Ok(Self::Cu92), + "cu91" => Ok(Self::Cu91), + "cu90" => Ok(Self::Cu90), + "cu80" => Ok(Self::Cu80), + "rocm6.3" => Ok(Self::Rocm63), + "rocm6.2.4" => Ok(Self::Rocm624), + "rocm6.2" => Ok(Self::Rocm62), + "rocm6.1" => Ok(Self::Rocm61), + "rocm6.0" => Ok(Self::Rocm60), + "rocm5.7" => Ok(Self::Rocm57), + "rocm5.6" => Ok(Self::Rocm56), + "rocm5.5" => Ok(Self::Rocm55), + "rocm5.4.2" => Ok(Self::Rocm542), + "rocm5.4" => Ok(Self::Rocm54), + "rocm5.3" => Ok(Self::Rocm53), + "rocm5.2" => Ok(Self::Rocm52), + "rocm5.1.1" => Ok(Self::Rocm511), + "rocm4.2" => Ok(Self::Rocm42), + "rocm4.1" => Ok(Self::Rocm41), + "rocm4.0.1" => Ok(Self::Rocm401), + "xpu" => Ok(Self::Xpu), _ => Err(format!("Unknown PyTorch backend: {s}")), } } diff --git a/crates/uv-virtualenv/src/virtualenv.rs b/crates/uv-virtualenv/src/virtualenv.rs index dceb1c5a6..fd0b64d4f 100644 --- a/crates/uv-virtualenv/src/virtualenv.rs +++ b/crates/uv-virtualenv/src/virtualenv.rs @@ -638,11 +638,11 @@ pub enum OnExisting { impl OnExisting { pub fn from_args(allow_existing: bool, clear: bool) -> Self { if allow_existing { - OnExisting::Allow + Self::Allow } else if clear { - OnExisting::Remove + Self::Remove } else { - OnExisting::default() + Self::default() } } } @@ -679,52 +679,52 @@ impl WindowsExecutable { /// The name of the Python executable. fn exe(self, interpreter: &Interpreter) -> String { match self { - WindowsExecutable::Python => String::from("python.exe"), - WindowsExecutable::PythonMajor => { + Self::Python => String::from("python.exe"), + Self::PythonMajor => { format!("python{}.exe", interpreter.python_major()) } - WindowsExecutable::PythonMajorMinor => { + Self::PythonMajorMinor => { format!( "python{}.{}.exe", interpreter.python_major(), interpreter.python_minor() ) } - WindowsExecutable::PythonMajorMinort => { + Self::PythonMajorMinort => { format!( "python{}.{}t.exe", interpreter.python_major(), interpreter.python_minor() ) } - WindowsExecutable::Pythonw => String::from("pythonw.exe"), - WindowsExecutable::PythonwMajorMinort => { + Self::Pythonw => String::from("pythonw.exe"), + Self::PythonwMajorMinort => { format!( "pythonw{}.{}t.exe", interpreter.python_major(), interpreter.python_minor() ) } - WindowsExecutable::PyPy => String::from("pypy.exe"), - WindowsExecutable::PyPyMajor => { + Self::PyPy => String::from("pypy.exe"), + Self::PyPyMajor => { format!("pypy{}.exe", interpreter.python_major()) } - WindowsExecutable::PyPyMajorMinor => { + Self::PyPyMajorMinor => { format!( "pypy{}.{}.exe", interpreter.python_major(), interpreter.python_minor() ) } - WindowsExecutable::PyPyw => String::from("pypyw.exe"), - WindowsExecutable::PyPyMajorMinorw => { + Self::PyPyw => String::from("pypyw.exe"), + Self::PyPyMajorMinorw => { format!( "pypy{}.{}w.exe", interpreter.python_major(), interpreter.python_minor() ) } - WindowsExecutable::GraalPy => String::from("graalpy.exe"), + Self::GraalPy => String::from("graalpy.exe"), } } @@ -745,7 +745,7 @@ impl WindowsExecutable { // These are not relevant as of now for PyPy as it doesn't yet support Python 3.13. Self::PyPy | Self::PyPyMajor | Self::PyPyMajorMinor => "venvlauncher.exe", Self::PyPyw | Self::PyPyMajorMinorw => "venvwlauncher.exe", - WindowsExecutable::GraalPy => "venvlauncher.exe", + Self::GraalPy => "venvlauncher.exe", } } } diff --git a/crates/uv-workspace/src/dependency_groups.rs b/crates/uv-workspace/src/dependency_groups.rs index 2dc2090bf..7f58e4170 100644 --- a/crates/uv-workspace/src/dependency_groups.rs +++ b/crates/uv-workspace/src/dependency_groups.rs @@ -56,19 +56,18 @@ impl FlatDependencyGroups { .unwrap_or(&empty_settings); // Flatten the dependency groups. - let mut dependency_groups = FlatDependencyGroups::from_dependency_groups( - &dependency_groups, - group_settings.inner(), - ) - .map_err(|err| DependencyGroupError { - package: pyproject_toml - .project - .as_ref() - .map(|project| project.name.to_string()) - .unwrap_or_default(), - path: path.user_display().to_string(), - error: err.with_dev_dependencies(dev_dependencies), - })?; + let mut dependency_groups = + Self::from_dependency_groups(&dependency_groups, group_settings.inner()).map_err( + |err| DependencyGroupError { + package: pyproject_toml + .project + .as_ref() + .map(|project| project.name.to_string()) + .unwrap_or_default(), + path: path.user_display().to_string(), + error: err.with_dev_dependencies(dev_dependencies), + }, + )?; // Add the `dev` group, if the legacy `dev-dependencies` is defined. // diff --git a/crates/uv-workspace/src/pyproject.rs b/crates/uv-workspace/src/pyproject.rs index a54ac1497..321e65d63 100644 --- a/crates/uv-workspace/src/pyproject.rs +++ b/crates/uv-workspace/src/pyproject.rs @@ -124,9 +124,9 @@ impl PyProjectToml { pub fn from_string(raw: String) -> Result { let pyproject = toml_edit::Document::from_str(&raw).map_err(PyprojectTomlError::TomlSyntax)?; - let pyproject = PyProjectToml::deserialize(pyproject.into_deserializer()) + let pyproject = Self::deserialize(pyproject.into_deserializer()) .map_err(PyprojectTomlError::TomlSchema)?; - Ok(PyProjectToml { raw, ..pyproject }) + Ok(Self { raw, ..pyproject }) } /// Returns `true` if the project should be considered a Python package, as opposed to a @@ -255,7 +255,7 @@ impl TryFrom for Project { return Err(PyprojectTomlError::MissingVersion); } - Ok(Project { + Ok(Self { name, version: value.version, requires_python: value.requires_python, @@ -1612,7 +1612,7 @@ impl Source { branch: Option, root: &Path, existing_sources: Option<&BTreeMap>, - ) -> Result, SourceError> { + ) -> Result, SourceError> { // If the user specified a Git reference for a non-Git source, try existing Git sources before erroring. if !matches!(source, RequirementSource::Git { .. }) && (branch.is_some() || tag.is_some() || rev.is_some()) @@ -1620,7 +1620,7 @@ impl Source { if let Some(sources) = existing_sources { if let Some(package_sources) = sources.get(name) { for existing_source in package_sources.iter() { - if let Source::Git { + if let Self::Git { git, subdirectory, marker, @@ -1629,7 +1629,7 @@ impl Source { .. } = existing_source { - return Ok(Some(Source::Git { + return Ok(Some(Self::Git { git: git.clone(), subdirectory: subdirectory.clone(), rev, @@ -1672,7 +1672,7 @@ impl Source { if workspace { return match source { RequirementSource::Registry { .. } | RequirementSource::Directory { .. } => { - Ok(Some(Source::Workspace { + Ok(Some(Self::Workspace { workspace: true, marker: MarkerTree::TRUE, extra: None, @@ -1697,7 +1697,7 @@ impl Source { } RequirementSource::Registry { index: None, .. } => { if let Some(index) = index { - Source::Registry { + Self::Registry { index, marker: MarkerTree::TRUE, extra: None, @@ -1708,7 +1708,7 @@ impl Source { } } RequirementSource::Path { install_path, .. } - | RequirementSource::Directory { install_path, .. } => Source::Path { + | RequirementSource::Directory { install_path, .. } => Self::Path { editable, package: None, path: PortablePathBuf::from( @@ -1725,7 +1725,7 @@ impl Source { location, subdirectory, .. - } => Source::Url { + } => Self::Url { url: location, subdirectory: subdirectory.map(PortablePathBuf::from), marker: MarkerTree::TRUE, @@ -1744,7 +1744,7 @@ impl Source { GitReference::NamedRef(rev) => Some(rev), GitReference::DefaultBranch => None, }; - Source::Git { + Self::Git { rev: rev.cloned(), tag, branch, @@ -1755,7 +1755,7 @@ impl Source { group: None, } } else { - Source::Git { + Self::Git { rev, tag, branch, @@ -1775,33 +1775,33 @@ impl Source { /// Return the [`MarkerTree`] for the source. pub fn marker(&self) -> MarkerTree { match self { - Source::Git { marker, .. } => *marker, - Source::Url { marker, .. } => *marker, - Source::Path { marker, .. } => *marker, - Source::Registry { marker, .. } => *marker, - Source::Workspace { marker, .. } => *marker, + Self::Git { marker, .. } => *marker, + Self::Url { marker, .. } => *marker, + Self::Path { marker, .. } => *marker, + Self::Registry { marker, .. } => *marker, + Self::Workspace { marker, .. } => *marker, } } /// Return the extra name for the source. pub fn extra(&self) -> Option<&ExtraName> { match self { - Source::Git { extra, .. } => extra.as_ref(), - Source::Url { extra, .. } => extra.as_ref(), - Source::Path { extra, .. } => extra.as_ref(), - Source::Registry { extra, .. } => extra.as_ref(), - Source::Workspace { extra, .. } => extra.as_ref(), + Self::Git { extra, .. } => extra.as_ref(), + Self::Url { extra, .. } => extra.as_ref(), + Self::Path { extra, .. } => extra.as_ref(), + Self::Registry { extra, .. } => extra.as_ref(), + Self::Workspace { extra, .. } => extra.as_ref(), } } /// Return the dependency group name for the source. pub fn group(&self) -> Option<&GroupName> { match self { - Source::Git { group, .. } => group.as_ref(), - Source::Url { group, .. } => group.as_ref(), - Source::Path { group, .. } => group.as_ref(), - Source::Registry { group, .. } => group.as_ref(), - Source::Workspace { group, .. } => group.as_ref(), + Self::Git { group, .. } => group.as_ref(), + Self::Url { group, .. } => group.as_ref(), + Self::Path { group, .. } => group.as_ref(), + Self::Registry { group, .. } => group.as_ref(), + Self::Workspace { group, .. } => group.as_ref(), } } } @@ -1828,7 +1828,7 @@ impl<'de> Deserialize<'de> for BuildBackendSettingsSchema { where D: Deserializer<'de>, { - Ok(BuildBackendSettingsSchema) + Ok(Self) } } diff --git a/crates/uv-workspace/src/pyproject_mut.rs b/crates/uv-workspace/src/pyproject_mut.rs index efdc308c6..e87824879 100644 --- a/crates/uv-workspace/src/pyproject_mut.rs +++ b/crates/uv-workspace/src/pyproject_mut.rs @@ -129,10 +129,10 @@ impl AddBoundsKind { // second most significant component, so most versions are either major.minor.patch or // 0.major.minor. match self { - AddBoundsKind::Lower => { + Self::Lower => { VersionSpecifiers::from(VersionSpecifier::greater_than_equal_version(version)) } - AddBoundsKind::Major => { + Self::Major => { let leading_zeroes = version .release() .iter() @@ -173,7 +173,7 @@ impl AddBoundsKind { VersionSpecifier::less_than_version(upper_bound), ]) } - AddBoundsKind::Minor => { + Self::Minor => { let leading_zeroes = version .release() .iter() @@ -242,7 +242,7 @@ impl AddBoundsKind { VersionSpecifier::less_than_version(upper_bound), ]) } - AddBoundsKind::Exact => { + Self::Exact => { VersionSpecifiers::from_iter([VersionSpecifier::equals_version(version)]) } } diff --git a/crates/uv-workspace/src/workspace.rs b/crates/uv-workspace/src/workspace.rs index 53342865e..63b489b73 100644 --- a/crates/uv-workspace/src/workspace.rs +++ b/crates/uv-workspace/src/workspace.rs @@ -149,7 +149,7 @@ impl Workspace { path: &Path, options: &DiscoveryOptions, cache: &WorkspaceCache, - ) -> Result { + ) -> Result { let path = std::path::absolute(path) .map_err(WorkspaceError::Normalize)? .clone(); @@ -763,7 +763,7 @@ impl Workspace { current_project: Option, options: &DiscoveryOptions, cache: &WorkspaceCache, - ) -> Result { + ) -> Result { let cache_key = WorkspaceCacheKey { workspace_root: workspace_root.clone(), discovery_options: options.clone(), @@ -833,7 +833,7 @@ impl Workspace { &workspace_pyproject_toml, ); - Ok(Workspace { + Ok(Self { install_path: workspace_root, packages: workspace_members, required_members, @@ -1691,14 +1691,14 @@ impl VirtualProject { /// Return the [`PackageName`] of the project, if available. pub fn project_name(&self) -> Option<&PackageName> { match self { - VirtualProject::Project(project) => Some(project.project_name()), - VirtualProject::NonProject(_) => None, + Self::Project(project) => Some(project.project_name()), + Self::NonProject(_) => None, } } /// Returns `true` if the project is a virtual workspace root. pub fn is_non_project(&self) -> bool { - matches!(self, VirtualProject::NonProject(_)) + matches!(self, Self::NonProject(_)) } } diff --git a/crates/uv/src/child.rs b/crates/uv/src/child.rs index 6a8033fff..5df6a1b0c 100644 --- a/crates/uv/src/child.rs +++ b/crates/uv/src/child.rs @@ -57,8 +57,8 @@ pub(crate) async fn run_to_completion(mut handle: Child) -> anyhow::Result Option<()> { match self { - PlatformSpecificSignal::Signal(signal) => signal.recv().await, - PlatformSpecificSignal::Dummy => std::future::pending().await, + Self::Signal(signal) => signal.recv().await, + Self::Dummy => std::future::pending().await, } } } diff --git a/crates/uv/src/commands/build_frontend.rs b/crates/uv/src/commands/build_frontend.rs index 106b16739..726295592 100644 --- a/crates/uv/src/commands/build_frontend.rs +++ b/crates/uv/src/commands/build_frontend.rs @@ -1176,11 +1176,11 @@ impl BuildMessage { /// The normalized filename of the wheel or source distribution. fn normalized_filename(&self) -> &DistFilename { match self { - BuildMessage::Build { + Self::Build { normalized_filename: name, .. } => name, - BuildMessage::List { + Self::List { normalized_filename: name, .. } => name, @@ -1190,10 +1190,10 @@ impl BuildMessage { /// The filename of the wheel or source distribution before normalization. fn raw_filename(&self) -> &str { match self { - BuildMessage::Build { + Self::Build { raw_filename: name, .. } => name, - BuildMessage::List { + Self::List { raw_filename: name, .. } => name, } @@ -1201,7 +1201,7 @@ impl BuildMessage { fn print(&self, printer: Printer) -> Result<()> { match self { - BuildMessage::Build { + Self::Build { raw_filename, output_dir, .. @@ -1212,7 +1212,7 @@ impl BuildMessage { output_dir.join(raw_filename).user_display().bold().cyan() )?; } - BuildMessage::List { + Self::List { raw_filename, file_list, source_tree, diff --git a/crates/uv/src/commands/help.rs b/crates/uv/src/commands/help.rs index 990f53635..337a6126f 100644 --- a/crates/uv/src/commands/help.rs +++ b/crates/uv/src/commands/help.rs @@ -221,21 +221,21 @@ impl Pager { /// /// Supports the `PAGER` environment variable, otherwise checks for `less` and `more` in the /// search path. - fn try_from_env() -> Option { + fn try_from_env() -> Option { if let Some(pager) = std::env::var_os(EnvVars::PAGER) { if !pager.is_empty() { - return Pager::from_str(&pager.to_string_lossy()).ok(); + return Self::from_str(&pager.to_string_lossy()).ok(); } } if let Ok(less) = which("less") { - Some(Pager { + Some(Self { kind: PagerKind::Less, args: vec![], path: Some(less), }) } else if let Ok(more) = which("more") { - Some(Pager { + Some(Self { kind: PagerKind::More, args: vec![], path: Some(more), diff --git a/crates/uv/src/commands/project/init.rs b/crates/uv/src/commands/project/init.rs index 6e04524fb..98845d1f4 100644 --- a/crates/uv/src/commands/project/init.rs +++ b/crates/uv/src/commands/project/init.rs @@ -684,7 +684,7 @@ pub(crate) enum InitKind { impl Default for InitKind { fn default() -> Self { - InitKind::Project(InitProjectKind::default()) + Self::Project(InitProjectKind::default()) } } @@ -701,7 +701,7 @@ pub(crate) enum InitProjectKind { impl InitKind { /// Returns `true` if the project should be packaged by default. pub(crate) fn packaged_by_default(self) -> bool { - matches!(self, InitKind::Project(InitProjectKind::Library)) + matches!(self, Self::Project(InitProjectKind::Library)) } } @@ -723,7 +723,7 @@ impl InitProjectKind { package: bool, ) -> Result<()> { match self { - InitProjectKind::Application => InitProjectKind::init_application( + Self::Application => Self::init_application( name, path, requires_python, @@ -736,7 +736,7 @@ impl InitProjectKind { no_readme, package, ), - InitProjectKind::Library => InitProjectKind::init_library( + Self::Library => Self::init_library( name, path, requires_python, diff --git a/crates/uv/src/commands/project/lock.rs b/crates/uv/src/commands/project/lock.rs index 92302aa3b..29fd3b949 100644 --- a/crates/uv/src/commands/project/lock.rs +++ b/crates/uv/src/commands/project/lock.rs @@ -62,15 +62,15 @@ pub(crate) enum LockResult { impl LockResult { pub(crate) fn lock(&self) -> &Lock { match self { - LockResult::Unchanged(lock) => lock, - LockResult::Changed(_, lock) => lock, + Self::Unchanged(lock) => lock, + Self::Changed(_, lock) => lock, } } pub(crate) fn into_lock(self) -> Lock { match self { - LockResult::Unchanged(lock) => lock, - LockResult::Changed(_, lock) => lock, + Self::Unchanged(lock) => lock, + Self::Changed(_, lock) => lock, } } } diff --git a/crates/uv/src/commands/project/mod.rs b/crates/uv/src/commands/project/mod.rs index 51b62cc4d..73b1f98d2 100644 --- a/crates/uv/src/commands/project/mod.rs +++ b/crates/uv/src/commands/project/mod.rs @@ -740,8 +740,8 @@ impl ScriptInterpreter { /// Consume the [`PythonInstallation`] and return the [`Interpreter`]. pub(crate) fn into_interpreter(self) -> Interpreter { match self { - ScriptInterpreter::Interpreter(interpreter) => interpreter, - ScriptInterpreter::Environment(venv) => venv.into_interpreter(), + Self::Interpreter(interpreter) => interpreter, + Self::Environment(venv) => venv.into_interpreter(), } } @@ -1037,8 +1037,8 @@ impl ProjectInterpreter { /// Convert the [`ProjectInterpreter`] into an [`Interpreter`]. pub(crate) fn into_interpreter(self) -> Interpreter { match self { - ProjectInterpreter::Interpreter(interpreter) => interpreter, - ProjectInterpreter::Environment(venv) => venv.into_interpreter(), + Self::Interpreter(interpreter) => interpreter, + Self::Environment(venv) => venv.into_interpreter(), } } @@ -1077,11 +1077,11 @@ pub(crate) enum PythonRequestSource { impl std::fmt::Display for PythonRequestSource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - PythonRequestSource::UserRequest => write!(f, "explicit request"), - PythonRequestSource::DotPythonVersion(file) => { + Self::UserRequest => write!(f, "explicit request"), + Self::DotPythonVersion(file) => { write!(f, "version file at `{}`", file.path().user_display()) } - PythonRequestSource::RequiresPython => write!(f, "`requires-python` metadata"), + Self::RequiresPython => write!(f, "`requires-python` metadata"), } } } diff --git a/crates/uv/src/commands/project/sync.rs b/crates/uv/src/commands/project/sync.rs index ecef201c9..44d9dfe82 100644 --- a/crates/uv/src/commands/project/sync.rs +++ b/crates/uv/src/commands/project/sync.rs @@ -949,8 +949,8 @@ impl From<&VirtualProject> for ProjectReport { impl From<&SyncTarget> for TargetName { fn from(target: &SyncTarget) -> Self { match target { - SyncTarget::Project(_) => TargetName::Project, - SyncTarget::Script(_) => TargetName::Script, + SyncTarget::Project(_) => Self::Project, + SyncTarget::Script(_) => Self::Script, } } } @@ -1016,8 +1016,8 @@ enum TargetName { impl std::fmt::Display for TargetName { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - TargetName::Project => write!(f, "project"), - TargetName::Script => write!(f, "script"), + Self::Project => write!(f, "project"), + Self::Script => write!(f, "script"), } } } @@ -1039,16 +1039,16 @@ enum SyncAction { impl From<&SyncEnvironment> for SyncAction { fn from(env: &SyncEnvironment) -> Self { match &env { - SyncEnvironment::Project(ProjectEnvironment::Existing(..)) => SyncAction::Check, - SyncEnvironment::Project(ProjectEnvironment::Created(..)) => SyncAction::Create, - SyncEnvironment::Project(ProjectEnvironment::WouldCreate(..)) => SyncAction::Create, - SyncEnvironment::Project(ProjectEnvironment::WouldReplace(..)) => SyncAction::Replace, - SyncEnvironment::Project(ProjectEnvironment::Replaced(..)) => SyncAction::Update, - SyncEnvironment::Script(ScriptEnvironment::Existing(..)) => SyncAction::Check, - SyncEnvironment::Script(ScriptEnvironment::Created(..)) => SyncAction::Create, - SyncEnvironment::Script(ScriptEnvironment::WouldCreate(..)) => SyncAction::Create, - SyncEnvironment::Script(ScriptEnvironment::WouldReplace(..)) => SyncAction::Replace, - SyncEnvironment::Script(ScriptEnvironment::Replaced(..)) => SyncAction::Update, + SyncEnvironment::Project(ProjectEnvironment::Existing(..)) => Self::Check, + SyncEnvironment::Project(ProjectEnvironment::Created(..)) => Self::Create, + SyncEnvironment::Project(ProjectEnvironment::WouldCreate(..)) => Self::Create, + SyncEnvironment::Project(ProjectEnvironment::WouldReplace(..)) => Self::Replace, + SyncEnvironment::Project(ProjectEnvironment::Replaced(..)) => Self::Update, + SyncEnvironment::Script(ScriptEnvironment::Existing(..)) => Self::Check, + SyncEnvironment::Script(ScriptEnvironment::Created(..)) => Self::Create, + SyncEnvironment::Script(ScriptEnvironment::WouldCreate(..)) => Self::Create, + SyncEnvironment::Script(ScriptEnvironment::WouldReplace(..)) => Self::Replace, + SyncEnvironment::Script(ScriptEnvironment::Replaced(..)) => Self::Update, } } } @@ -1057,22 +1057,22 @@ impl SyncAction { fn message(&self, target: TargetName, dry_run: bool) -> Option<&'static str> { let message = if dry_run { match self { - SyncAction::Check => "Would use", - SyncAction::Update => "Would update", - SyncAction::Replace => "Would replace", - SyncAction::Create => "Would create", + Self::Check => "Would use", + Self::Update => "Would update", + Self::Replace => "Would replace", + Self::Create => "Would create", } } else { // For projects, we omit some of these messages when we're not in dry-run mode let is_project = matches!(target, TargetName::Project); match self { - SyncAction::Check | SyncAction::Update | SyncAction::Create if is_project => { + Self::Check | Self::Update | Self::Create if is_project => { return None; } - SyncAction::Check => "Using", - SyncAction::Update => "Updating", - SyncAction::Replace => "Replacing", - SyncAction::Create => "Creating", + Self::Check => "Using", + Self::Update => "Updating", + Self::Replace => "Replacing", + Self::Create => "Creating", } }; Some(message) @@ -1097,10 +1097,10 @@ impl LockAction { fn message(&self, dry_run: bool) -> Option<&'static str> { let message = if dry_run { match self { - LockAction::Use => return None, - LockAction::Check => "Found up-to-date", - LockAction::Update => "Would update", - LockAction::Create => "Would create", + Self::Use => return None, + Self::Check => "Found up-to-date", + Self::Update => "Would update", + Self::Create => "Would create", } } else { return None; @@ -1154,7 +1154,7 @@ impl From<&PythonEnvironment> for EnvironmentReport { impl From<&SyncEnvironment> for EnvironmentReport { fn from(env: &SyncEnvironment) -> Self { - let report = EnvironmentReport::from(&**env); + let report = Self::from(&**env); // Replace the path if necessary; we construct a temporary virtual environment during dry // run invocations and want to report the path we _would_ use. if let Some(path) = env.dry_run_target() { diff --git a/crates/uv/src/commands/reporters.rs b/crates/uv/src/commands/reporters.rs index 3943c941e..6bfbf0a74 100644 --- a/crates/uv/src/commands/reporters.rs +++ b/crates/uv/src/commands/reporters.rs @@ -113,9 +113,9 @@ enum Direction { impl Direction { fn as_str(&self) -> &str { match self { - Direction::Download => "Downloading", - Direction::Upload => "Uploading", - Direction::Extract => "Extracting", + Self::Download => "Downloading", + Self::Upload => "Uploading", + Self::Extract => "Extracting", } } } @@ -130,7 +130,7 @@ impl From for Direction { } impl ProgressReporter { - fn new(root: ProgressBar, multi_progress: MultiProgress, printer: Printer) -> ProgressReporter { + fn new(root: ProgressBar, multi_progress: MultiProgress, printer: Printer) -> Self { let mode = if env::var(EnvVars::JPY_SESSION_NAME).is_ok() { // Disable concurrent progress bars when running inside a Jupyter notebook // because the Jupyter terminal does not support clearing previous lines. @@ -143,7 +143,7 @@ impl ProgressReporter { } }; - ProgressReporter { + Self { printer, root, mode, @@ -827,8 +827,8 @@ impl ColorDisplay for SourceDist { impl ColorDisplay for BuildableSource<'_> { fn to_color_string(&self) -> String { match self { - BuildableSource::Dist(dist) => dist.to_color_string(), - BuildableSource::Url(url) => url.to_string(), + Self::Dist(dist) => dist.to_color_string(), + Self::Url(url) => url.to_string(), } } } diff --git a/crates/uv/src/commands/tool/run.rs b/crates/uv/src/commands/tool/run.rs index 1c86feb3a..64628e56a 100644 --- a/crates/uv/src/commands/tool/run.rs +++ b/crates/uv/src/commands/tool/run.rs @@ -70,8 +70,8 @@ pub(crate) enum ToolRunCommand { impl Display for ToolRunCommand { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ToolRunCommand::Uvx => write!(f, "uvx"), - ToolRunCommand::ToolRun => write!(f, "uv tool run"), + Self::Uvx => write!(f, "uvx"), + Self::ToolRun => write!(f, "uv tool run"), } } } @@ -647,8 +647,8 @@ pub(crate) enum ToolRequirement { impl ToolRequirement { fn executable(&self) -> &str { match self { - ToolRequirement::Python { executable, .. } => executable, - ToolRequirement::Package { executable, .. } => executable, + Self::Python { executable, .. } => executable, + Self::Package { executable, .. } => executable, } } } @@ -656,8 +656,8 @@ impl ToolRequirement { impl std::fmt::Display for ToolRequirement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ToolRequirement::Python { .. } => write!(f, "python"), - ToolRequirement::Package { requirement, .. } => write!(f, "{requirement}"), + Self::Python { .. } => write!(f, "python"), + Self::Package { requirement, .. } => write!(f, "{requirement}"), } } } diff --git a/crates/uv/tests/it/common/mod.rs b/crates/uv/tests/it/common/mod.rs index c894b70a0..d0982642d 100644 --- a/crates/uv/tests/it/common/mod.rs +++ b/crates/uv/tests/it/common/mod.rs @@ -1360,7 +1360,7 @@ impl TestContext { /// the new one is then returned. /// /// This assumes that a lock has already been performed. - pub fn diff_lock(&self, change: impl Fn(&TestContext) -> Command) -> String { + pub fn diff_lock(&self, change: impl Fn(&Self) -> Command) -> String { static TRIM_TRAILING_WHITESPACE: std::sync::LazyLock = std::sync::LazyLock::new(|| Regex::new(r"(?m)^\s+$").unwrap());