lanzatool: clean up parse_version and add simple test

This commit is contained in:
nikstur 2022-12-30 22:23:52 +01:00
parent 463d9496bf
commit 0a58b290e2
1 changed files with 22 additions and 17 deletions

View File

@ -87,24 +87,29 @@ impl fmt::Display for Generation {
} }
} }
fn parse_version(toplevel: impl AsRef<Path>) -> Result<u64> { /// Parse version number from a path.
let file_name = toplevel ///
/// Expects a path in the format of "system-{version}-link".
fn parse_version(path: impl AsRef<Path>) -> Result<u64> {
let generation_version = path
.as_ref() .as_ref()
.file_name() .file_name()
.ok_or_else(|| anyhow::anyhow!("Failed to extract file name from generation"))?; .and_then(|x| x.to_str())
.and_then(|x| x.split('-').nth(1))
.and_then(|x| x.parse::<u64>().ok())
.with_context(|| format!("Failed to extract version from: {:?}", path.as_ref()))?;
let file_name_str = file_name Ok(generation_version)
.to_str() }
.with_context(|| "Failed to convert file name of generation to string")?;
#[cfg(test)]
let generation_version = file_name_str mod tests {
.split('-') use super::*;
.nth(1)
.ok_or_else(|| anyhow::anyhow!("Failed to extract version from generation"))?; #[test]
fn parse_version_correctly() {
let parsed_generation_version = generation_version let path = Path::new("system-2-link");
.parse() let parsed_version = parse_version(path).unwrap();
.with_context(|| format!("Failed to parse generation version: {}", generation_version))?; assert_eq!(parsed_version, 2,);
}
Ok(parsed_generation_version)
} }