refactor(nix-compat/store_path): simplify build_ca_path

Move the the `fixed:out:[r:]{}:` generation to a helper function,
use matches! for more clarity.

Change-Id: I4e930c42aacbf5c7451d1f8c8c80ccb4c45389f0
Reviewed-on: https://cl.tvl.fyi/c/depot/+/11006
Tested-by: BuildkiteCI
Reviewed-by: aspen <root@gws.fyi>
Autosubmit: flokli <flokli@flokli.de>
This commit is contained in:
Florian Klink 2024-02-22 16:07:00 +07:00 committed by clbot
parent c461595b7f
commit 91d5745c3d

View file

@ -62,10 +62,8 @@ pub fn build_ca_path<'a, S: AsRef<str>, I: IntoIterator<Item = S>>(
self_reference: bool,
) -> Result<StorePathRef<'a>, BuildStorePathError> {
// self references are only allowed for CAHash::Nar(NixHash::Sha256(_)).
if self_reference {
let CAHash::Nar(NixHash::Sha256(_)) = ca_hash else {
return Err(BuildStorePathError::InvalidReference());
};
if self_reference && matches!(ca_hash, CAHash::Nar(NixHash::Sha256(_))) {
return Err(BuildStorePathError::InvalidReference());
}
let (ty, hash) = match &ca_hash {
@ -86,11 +84,7 @@ pub fn build_ca_path<'a, S: AsRef<str>, I: IntoIterator<Item = S>>(
(
"output:out".to_string(),
NixHash::Sha256(
Sha256::new_with_prefix(format!("fixed:out:r:{}:", hash.to_nix_hex_string()))
.finalize()
.into(),
),
NixHash::Sha256(fixed_out_digest("fixed:out:r", hash)),
)
}
// CaHash::Flat is using something very similar, except the `r:` prefix.
@ -101,11 +95,7 @@ pub fn build_ca_path<'a, S: AsRef<str>, I: IntoIterator<Item = S>>(
(
"output:out".to_string(),
NixHash::Sha256(
Sha256::new_with_prefix(format!("fixed:out:{}:", hash.to_nix_hex_string()))
.finalize()
.into(),
),
NixHash::Sha256(fixed_out_digest("fixed:out", hash)),
)
}
};
@ -114,6 +104,14 @@ pub fn build_ca_path<'a, S: AsRef<str>, I: IntoIterator<Item = S>>(
.map_err(BuildStorePathError::InvalidStorePath)
}
/// Helper function, used in [build_ca_path] for the non-sha256 [CAHash::Nar]
/// and [CAHash::Flat].
fn fixed_out_digest(prefix: &str, hash: &NixHash) -> [u8; 32] {
Sha256::new_with_prefix(format!("{}:{}:", prefix, hash.to_nix_hex_string()))
.finalize()
.into()
}
/// For given NAR sha256 digest and name, return the new [StorePathRef] this
/// would have, or an error, in case the name is invalid.
pub fn build_nar_based_store_path<'a>(