diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/lib.rs | 64 | ||||
| -rw-r--r-- | src/main.rs | 61 | ||||
| -rw-r--r-- | src/model.rs | 142 | ||||
| -rw-r--r-- | src/plan.rs | 19 |
4 files changed, 167 insertions, 119 deletions
@@ -1,61 +1,5 @@ -use std::fs; -use std::path::{Path, PathBuf}; +pub mod model; +pub mod plan; -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Profile { - pub packages: Vec<String>, - pub regex_packages: Vec<String>, -} - -impl Profile { - pub fn load(path: &Path) -> Result<Self, String> { - let profile = fs::read_to_string(path).map_err(|error| error.to_string())?; - let parent = path.parent().ok_or("profile path has no parent")?; - let mut packages = Vec::new(); - let mut regex_packages = Vec::new(); - - for line in profile.lines() { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - if let Some(values) = line.strip_prefix("base:") { - extend_words(&mut packages, values); - } else if let Some(relative) = line.strip_prefix("include:") { - let list = parent.join(relative.trim()); - let contents = fs::read_to_string(&list) - .map_err(|error| format!("{}: {error}", list.display()))?; - for entry in contents.lines().map(str::trim) { - if entry.is_empty() || entry.starts_with('#') { - continue; - } - let package = entry.split('@').next().unwrap_or(entry).trim(); - if !package.is_empty() { - packages.push(package.to_owned()); - } - } - } else if let Some(value) = line.strip_prefix("regex:") { - regex_packages.push(value.trim().to_owned()); - } else { - return Err(format!("unsupported profile statement: {line}")); - } - } - packages.sort(); - packages.dedup(); - regex_packages.sort(); - regex_packages.dedup(); - Ok(Self { packages, regex_packages }) - } - - pub fn install_arguments(&self) -> Vec<String> { - self.regex_packages.iter().chain(self.packages.iter()).cloned().collect() - } -} - -fn extend_words(target: &mut Vec<String>, values: &str) { - target.extend(values.split_whitespace().map(str::to_owned)); -} - -pub fn artifact_path(project: &Path) -> PathBuf { - project.join("out/alt-controller-rootfs.tar") -} +pub use model::{Architecture, BootSpec, ImageSpec, OutputFormat, PackageSelector, PackageSpec, Target}; +pub use plan::BuildPlan; diff --git a/src/main.rs b/src/main.rs index f468124..1ca0cab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,61 +1,4 @@ -use std::env; -use std::fs; -use std::path::PathBuf; -use std::process::Command; - -use alt_controller_image::{artifact_path, Profile}; - -fn run(command: &mut Command, description: &str) { - let status = command.status().unwrap_or_else(|error| panic!("{description}: {error}")); - assert!(status.success(), "{description} exited with {status}"); -} - fn main() { - let project = env::current_dir().expect("current directory"); - let profile_path = project.join("profiles/alt-controller.profile"); - let profile = Profile::load(&profile_path).unwrap_or_else(|error| panic!("profile: {error}")); - let workdir: PathBuf = project.join("work/alt-controller"); - let rootfs = workdir.join("chroot"); - let artifact = artifact_path(&project); - - let archive_existing = env::args().any(|argument| argument == "--archive-existing"); - if !archive_existing { - if workdir.exists() { - run( - Command::new("sudo").args(["rm", "-rf"]).arg(&workdir), - "remove previous Hasher workdir", - ); - } - fs::create_dir_all(&workdir).expect("create Hasher workdir"); - run( - Command::new("hsh") - .args(["--mountpoints=/proc", "--initroot-only", "--workdir"]) - .arg(&workdir), - "initialize isolated Hasher root", - ); - - let mut install = Command::new("hsh-install"); - install.args(["--mountpoints=/proc", "--workdir"]); - install.arg(&workdir); - install.args(profile.install_arguments()); - run(&mut install, "install target rootfs packages"); - } - assert!(rootfs.is_dir(), "isolated rootfs is missing: {}", rootfs.display()); - fs::create_dir_all(artifact.parent().expect("artifact parent")).expect("create output directory"); - - if artifact.exists() { - fs::remove_file(&artifact).expect("remove previous artifact"); - } - run( - Command::new("sudo") - .arg("tar") - .args(["--numeric-owner", "--exclude=./.host", "-C"]) - .arg(&rootfs) - .args(["-cpf"]) - .arg(&artifact) - .arg("."), - "archive isolated rootfs", - ); - - println!("{}", artifact.display()); + eprintln!("The command-line interface is not available yet. Use the library to load an ImageSpec."); + std::process::exit(2); } diff --git a/src/model.rs b/src/model.rs new file mode 100644 index 0000000..13fa5e8 --- /dev/null +++ b/src/model.rs @@ -0,0 +1,142 @@ +use std::collections::HashSet; +use std::fs; +use std::path::Path; + +use anyhow::{bail, Context, Result}; +use serde::Deserialize; + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct ImageSpec { + pub target: Target, + pub kernel: Kernel, + pub boot: BootSpec, + pub packages: PackageSpec, +} + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct Target { + pub name: String, + pub architecture: Architecture, + pub format: OutputFormat, +} + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct Kernel { + pub flavour: String, +} + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct BootSpec { + pub initrd_features: Vec<String>, + pub initrd_modules: Vec<String>, +} + +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct PackageSpec { + pub base: Vec<String>, + pub selectors: Vec<PackageSelector>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PackageSelector(String); + +impl PackageSelector { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl<'de> Deserialize<'de> for PackageSelector { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + let value = String::deserialize(deserializer)?; + if value.trim().is_empty() { + return Err(serde::de::Error::custom("package selector cannot be empty")); + } + Ok(Self(value)) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Architecture { + X86_64, +} + +impl Architecture { + pub fn as_str(&self) -> &'static str { + match self { + Self::X86_64 => "x86_64", + } + } +} + +impl<'de> Deserialize<'de> for Architecture { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + match String::deserialize(deserializer)?.as_str() { + "x86_64" => Ok(Self::X86_64), + value => Err(serde::de::Error::custom(format!( + "unsupported architecture: {value}" + ))), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OutputFormat { + Tar, +} + +impl<'de> Deserialize<'de> for OutputFormat { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + match String::deserialize(deserializer)?.as_str() { + "tar" => Ok(Self::Tar), + value => Err(serde::de::Error::custom(format!( + "unsupported output format: {value}" + ))), + } + } +} + +impl ImageSpec { + pub fn load(path: &Path) -> Result<Self> { + let contents = fs::read_to_string(path) + .with_context(|| format!("read image specification {}", path.display()))?; + let spec: Self = toml::from_str(&contents) + .with_context(|| format!("parse image specification {}", path.display()))?; + spec.validate()?; + Ok(spec) + } + + pub fn validate(&self) -> Result<()> { + if self.target.name.trim().is_empty() { + bail!("target name cannot be empty"); + } + + let mut selectors = HashSet::new(); + for selector in &self.packages.selectors { + if !selectors.insert(selector.as_str()) { + bail!("duplicate package selector: {}", selector.as_str()); + } + } + + for module in &self.boot.initrd_modules { + if module.is_empty() + || module.contains('/') + || !module + .chars() + .all(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-')) + { + bail!("invalid initrd module: {module}"); + } + } + Ok(()) + } +} diff --git a/src/plan.rs b/src/plan.rs new file mode 100644 index 0000000..16158e5 --- /dev/null +++ b/src/plan.rs @@ -0,0 +1,19 @@ +use anyhow::Result; + +use crate::ImageSpec; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BuildPlan { + spec: ImageSpec, +} + +impl BuildPlan { + pub fn compile(spec: ImageSpec) -> Result<Self> { + spec.validate()?; + Ok(Self { spec }) + } + + pub fn spec(&self) -> &ImageSpec { + &self.spec + } +} |