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> {
let file_name = toplevel
/// Parse version number from a path.
///
/// 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()
.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
.to_str()
.with_context(|| "Failed to convert file name of generation to string")?;
let generation_version = file_name_str
.split('-')
.nth(1)
.ok_or_else(|| anyhow::anyhow!("Failed to extract version from generation"))?;
let parsed_generation_version = generation_version
.parse()
.with_context(|| format!("Failed to parse generation version: {}", generation_version))?;
Ok(parsed_generation_version)
Ok(generation_version)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_version_correctly() {
let path = Path::new("system-2-link");
let parsed_version = parse_version(path).unwrap();
assert_eq!(parsed_version, 2,);
}
}