Skip to content

Commit 294c385

Browse files
committed
refactor: Pull out constructor for PackageIdSpec
1 parent f3999d5 commit 294c385

File tree

1 file changed

+36
-24
lines changed

1 file changed

+36
-24
lines changed

src/cargo/core/package_id_spec.rs

Lines changed: 36 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,30 @@ pub struct PackageIdSpec {
3232
}
3333

3434
impl PackageIdSpec {
35+
pub fn new(name: String) -> Self {
36+
Self {
37+
name,
38+
version: None,
39+
url: None,
40+
kind: None,
41+
}
42+
}
43+
44+
pub fn with_version(mut self, version: PartialVersion) -> Self {
45+
self.version = Some(version);
46+
self
47+
}
48+
49+
pub fn with_url(mut self, url: Url) -> Self {
50+
self.url = Some(url);
51+
self
52+
}
53+
54+
pub fn with_kind(mut self, kind: SourceKind) -> Self {
55+
self.kind = Some(kind);
56+
self
57+
}
58+
3559
/// Parses a spec string and returns a `PackageIdSpec` if the string was valid.
3660
///
3761
/// # Examples
@@ -88,12 +112,10 @@ impl PackageIdSpec {
88112
/// Convert a `PackageId` to a `PackageIdSpec`, which will have both the `PartialVersion` and `Url`
89113
/// fields filled in.
90114
pub fn from_package_id(package_id: PackageId) -> PackageIdSpec {
91-
PackageIdSpec {
92-
name: String::from(package_id.name().as_str()),
93-
version: Some(package_id.version().clone().into()),
94-
url: Some(package_id.source_id().url().clone()),
95-
kind: Some(package_id.source_id().kind().clone()),
96-
}
115+
PackageIdSpec::new(String::from(package_id.name().as_str()))
116+
.with_version(package_id.version().clone().into())
117+
.with_url(package_id.source_id().url().clone())
118+
.with_kind(package_id.source_id().kind().clone())
97119
}
98120

99121
/// Tries to convert a valid `Url` to a `PackageIdSpec`.
@@ -341,26 +363,16 @@ impl PackageIdSpecQuery for PackageIdSpec {
341363
}
342364
};
343365
if self.url.is_some() {
344-
try_spec(
345-
PackageIdSpec {
346-
name: self.name.clone(),
347-
version: self.version.clone(),
348-
url: None,
349-
kind: None,
350-
},
351-
&mut suggestion,
352-
);
366+
let spec = PackageIdSpec::new(self.name.clone());
367+
let spec = if let Some(version) = self.version.clone() {
368+
spec.with_version(version)
369+
} else {
370+
spec
371+
};
372+
try_spec(spec, &mut suggestion);
353373
}
354374
if suggestion.is_empty() && self.version.is_some() {
355-
try_spec(
356-
PackageIdSpec {
357-
name: self.name.clone(),
358-
version: None,
359-
url: None,
360-
kind: None,
361-
},
362-
&mut suggestion,
363-
);
375+
try_spec(PackageIdSpec::new(self.name.clone()), &mut suggestion);
364376
}
365377
if suggestion.is_empty() {
366378
suggestion.push_str(&edit_distance::closest_msg(

0 commit comments

Comments
 (0)