From c96c85872307d43180da57bde687136caa82d312 Mon Sep 17 00:00:00 2001 From: Jessica Black Date: Mon, 21 Apr 2025 11:04:06 -0700 Subject: [PATCH] Add `Locator::try_promote_strict` method (#22) --- Cargo.toml | 2 +- src/locator.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 65c21e8..35d6e4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "locator" -version = "2.4.0" +version = "2.4.1" edition = "2024" [dependencies] diff --git a/src/locator.rs b/src/locator.rs index 9405b81..78569f8 100644 --- a/src/locator.rs +++ b/src/locator.rs @@ -247,6 +247,23 @@ impl Locator { }) } + /// Promote a `Locator` to a [`StrictLocator`] if it has a `revision` component; + /// if not this function returns `Err` with the original locator. + pub fn try_promote_strict(self) -> Result { + let locator = match self.revision { + None => return Err(self), + Some(rev) => StrictLocator::builder() + .fetcher(self.fetcher) + .package(self.package) + .revision(rev), + }; + + Ok(match self.org_id { + None => locator.build(), + Some(OrgId(id)) => locator.org_id(id).build(), + }) + } + /// Promote a `Locator` to a [`StrictLocator`] by providing the default value to use /// for the `revision` component, if one is not specified in the locator already. /// @@ -732,6 +749,7 @@ mod tests { let promoted = input.clone().promote_strict_with(|| String::from("bar")); assert_eq!(expected, promoted, "promote {input}"); } + #[test] fn promotes_strict_existing_lazy() { let input = Locator::builder() @@ -754,6 +772,39 @@ mod tests { assert_eq!(expected, promoted, "promote {input}"); } + #[test] + fn try_promote_strict_with_revision() { + let input = Locator::builder() + .fetcher(Fetcher::Custom) + .package("foo") + .revision("1234") + .org_id(1) + .build(); + + let expected = StrictLocator::builder() + .fetcher(Fetcher::Custom) + .package("foo") + .org_id(1) + .revision("1234") + .build(); + + let result = input.try_promote_strict().expect("must promote strict"); + assert_eq!(expected, result); + } + + #[test] + fn try_promote_strict_without_revision() { + let input = Locator::builder() + .fetcher(Fetcher::Custom) + .package("foo") + .org_id(1) + .build(); + + input + .try_promote_strict() + .expect_err("must fail to promote"); + } + #[test] fn ordering() { let locators = vec![