lanzaboote/rust/lanzatool/src/generation.rs

71 lines
1.9 KiB
Rust
Raw Normal View History

2022-11-26 08:55:15 -05:00
use std::fmt;
use std::fs;
2022-11-26 08:55:15 -05:00
use std::path::Path;
use anyhow::{Context, Result};
use crate::bootspec::Bootspec;
2022-11-26 08:55:15 -05:00
#[derive(Debug)]
pub struct Generation {
version: u64,
2022-11-27 05:19:02 -05:00
specialisation_name: Option<String>,
pub bootspec: Bootspec,
}
2022-11-26 08:55:15 -05:00
impl Generation {
pub fn from_toplevel(toplevel: impl AsRef<Path>) -> Result<Self> {
let bootspec_path = toplevel.as_ref().join("bootspec/boot.v1.json");
let bootspec: Bootspec = serde_json::from_slice(
2022-11-26 17:19:08 -05:00
&fs::read(bootspec_path).context("Failed to read bootspec file")?,
)
.context("Failed to parse bootspec json")?;
Ok(Self {
version: parse_version(toplevel)?,
2022-11-27 05:19:02 -05:00
specialisation_name: None,
bootspec,
})
2022-11-26 08:55:15 -05:00
}
2022-11-27 05:19:02 -05:00
pub fn specialise(&self, name: &str, bootspec: &Bootspec) -> Self {
Self {
version: self.version,
specialisation_name: Some(String::from(name)),
bootspec: bootspec.clone(),
}
}
pub fn is_specialized(&self) -> Option<String> {
self.specialisation_name.clone()
}
2022-11-26 08:55:15 -05:00
}
impl fmt::Display for Generation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.version)
2022-11-26 08:55:15 -05:00
}
}
fn parse_version(toplevel: impl AsRef<Path>) -> Result<u64> {
2022-11-26 17:19:08 -05:00
let file_name = toplevel
.as_ref()
.file_name()
.ok_or_else(|| anyhow::anyhow!("Failed to extract file name from generation"))?;
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
2022-11-26 17:19:08 -05:00
.split('-')
.nth(1)
2022-11-26 17:19:08 -05:00
.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)
}