build(rust): make the workspace rustfmt and clippy clean

This commit is contained in:
Phoebus 2026-09-20 02:57:18 -07:00
parent f5ea6edf09
commit ec88d65af5
36 changed files with 633 additions and 273 deletions

View file

@ -8,7 +8,9 @@
pub mod privacy;
use phoebus_core::config::{DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy};
use phoebus_core::config::{
DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy,
};
use phoebus_core::validate;
use serde::{Deserialize, Serialize};
@ -103,7 +105,10 @@ pub struct AppliedChange {
/// Validate and merge a proposal into the configuration.
///
/// If any change fails validation, nothing is applied (fail closed).
pub fn apply(config: &mut InstallConfig, proposal: &AiProposal) -> Result<Vec<AppliedChange>, AiError> {
pub fn apply(
config: &mut InstallConfig,
proposal: &AiProposal,
) -> Result<Vec<AppliedChange>, AiError> {
for change in &proposal.changes {
change
.validate()

View file

@ -8,7 +8,7 @@
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PrivacyPolicy {
/// Whether the user has explicitly granted workspace access. Default off.
pub allow_home: bool,
@ -16,15 +16,6 @@ pub struct PrivacyPolicy {
pub allow_raw_logs: bool,
}
impl Default for PrivacyPolicy {
fn default() -> Self {
Self {
allow_home: false,
allow_raw_logs: false,
}
}
}
/// The data that may be sent to a model. Only system facts and explicitly
/// allowed excerpts.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
@ -56,11 +47,22 @@ impl ContextBundle {
/// Paths that must never be included in model context.
pub fn is_forbidden_path(path: &str) -> bool {
let p = path.trim();
let home_like = |s: &str| s == "/home" || s.starts_with("/home/") || s == "/root" || s.starts_with("/root/");
let home_like = |s: &str| {
s == "/home" || s.starts_with("/home/") || s == "/root" || s.starts_with("/root/")
};
let sensitive = |s: &str| {
[
".ssh", ".gnupg", ".aws", ".config/gcloud", ".mozilla", ".config/BraveSoftware",
".password-store", ".local/share/keyrings", ".kube", "wallet", "Wallets",
".ssh",
".gnupg",
".aws",
".config/gcloud",
".mozilla",
".config/BraveSoftware",
".password-store",
".local/share/keyrings",
".kube",
"wallet",
"Wallets",
]
.iter()
.any(|needle| s.contains(needle))

View file

@ -52,7 +52,10 @@ impl SystemAction {
format!("create a Btrfs snapshot before: {operation}")
}
SystemAction::History => "show system transaction history".to_string(),
SystemAction::PrepareUpdates => "prepare background updates (fetch + build binary packages, do not activate)".to_string(),
SystemAction::PrepareUpdates => {
"prepare background updates (fetch + build binary packages, do not activate)"
.to_string()
}
SystemAction::InspectUpdates => "show background update preparation status".to_string(),
SystemAction::UpdateSystem => "update the system".to_string(),
}
@ -62,9 +65,7 @@ impl SystemAction {
/// snapshot and/or stronger confirmation is required.
pub fn risk(&self) -> Risk {
match self {
SystemAction::InspectService { .. } | SystemAction::InspectPackage { .. } => {
Risk::Low
}
SystemAction::InspectService { .. } | SystemAction::InspectPackage { .. } => Risk::Low,
SystemAction::History => Risk::Low,
SystemAction::InspectUpdates => Risk::Low,
SystemAction::PrepareUpdates => Risk::Medium,
@ -185,7 +186,12 @@ mod tests {
#[test]
fn parses_typed_actions() {
let a = parse_action(r#"{"action":"enable_service","name":"sshd"}"#).unwrap();
assert_eq!(a, SystemAction::EnableService { name: "sshd".into() });
assert_eq!(
a,
SystemAction::EnableService {
name: "sshd".into()
}
);
assert!(a.is_mutating());
assert_eq!(a.risk(), Risk::Medium);
}
@ -207,21 +213,30 @@ mod tests {
fn natural_language_maps_to_typed_actions() {
assert_eq!(
parse_natural("enable sshd"),
Some(SystemAction::EnableService { name: "sshd".into() })
Some(SystemAction::EnableService {
name: "sshd".into()
})
);
assert_eq!(parse_natural("history"), Some(SystemAction::History));
assert_eq!(
parse_natural("install app-editors/vim"),
Some(SystemAction::InstallPackage { atom: "app-editors/vim".into() })
Some(SystemAction::InstallPackage {
atom: "app-editors/vim".into()
})
);
assert_eq!(parse_natural("why is my audio broken"), None);
}
#[test]
fn risk_levels() {
assert_eq!(parse_action(r#"{"action":"history"}"#).unwrap().risk(), Risk::Low);
assert_eq!(
parse_action(r#"{"action":"update_system"}"#).unwrap().risk(),
parse_action(r#"{"action":"history"}"#).unwrap().risk(),
Risk::Low
);
assert_eq!(
parse_action(r#"{"action":"update_system"}"#)
.unwrap()
.risk(),
Risk::High
);
}

View file

@ -381,8 +381,8 @@ impl InstallConfig {
/// TOML literal strings), so format must be detected structurally rather
/// than by attempting TOML first.
pub fn load_from_path(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path)
.map_err(|e| CoreError::io(path.to_path_buf(), e))?;
let text =
std::fs::read_to_string(path).map_err(|e| CoreError::io(path.to_path_buf(), e))?;
if path.extension().and_then(|e| e.to_str()) == Some("toml") {
return Self::from_toml(&text);
}
@ -559,7 +559,7 @@ mod tests {
assert_eq!(c.storage.filesystem, Filesystem::Btrfs);
assert_eq!(c.encryption.mode, Encryption::Luks2);
assert_eq!(c.encryption.name, "cryptroot");
assert_eq!(c.stage3.binhost_uri.contains("binpackages"), true);
assert!(c.stage3.binhost_uri.contains("binpackages"));
assert_eq!(c.kernel.console, "console=tty0");
assert!(c.packages.binary_packages);
assert!(!c.packages.policy.eq(&PackagePolicy::SourceFirst));

View file

@ -79,7 +79,10 @@ mod tests {
#[test]
fn strips_versions_with_hyphenated_names() {
assert_eq!(atom_from_cpv("sys-fs/cryptsetup-2.7.5"), "sys-fs/cryptsetup");
assert_eq!(
atom_from_cpv("sys-fs/cryptsetup-2.7.5"),
"sys-fs/cryptsetup"
);
assert_eq!(atom_from_cpv("app-editors/vim-9.1.1234"), "app-editors/vim");
assert_eq!(
atom_from_cpv("dev-lang/python-exec-conf-2.4.6"),

View file

@ -163,22 +163,29 @@ impl HardwareReport {
let virt = self.cpu.virt_summary();
out.push_str(&format!(
"CPU features: {}\n",
if virt.is_empty() { "none detected" } else { &virt }
if virt.is_empty() {
"none detected"
} else {
&virt
}
));
out.push_str(&format!("Memory: {} MiB\n", self.memory_mib));
out.push_str(&format!(
"Machine type: {}\n",
if self.laptop { "laptop" } else { "desktop/server" }
if self.laptop {
"laptop"
} else {
"desktop/server"
}
));
out.push_str(&format!("Input devices: {}\n\n", self.input_devices));
let gpus: Vec<String> = self
.gpus
.iter()
.map(|g| g.description.clone())
.collect();
let gpus: Vec<String> = self.gpus.iter().map(|g| g.description.clone()).collect();
out.push_str(&Self::section("GPUs", &gpus));
out.push_str(&Self::section("Storage controllers", &self.storage_controllers));
out.push_str(&Self::section(
"Storage controllers",
&self.storage_controllers,
));
let net: Vec<String> = self
.network
.iter()
@ -205,8 +212,10 @@ mod tests {
#[test]
fn low_memory_recommends_safe() {
let mut hw = HardwareReport::default();
hw.memory_mib = 1024;
let mut hw = HardwareReport {
memory_mib: 1024,
..Default::default()
};
assert_eq!(hw.recommended_kernel_profile(), KernelProfile::Safe);
hw.memory_mib = 8192;
assert_eq!(hw.recommended_kernel_profile(), KernelProfile::Optimized);
@ -214,12 +223,23 @@ mod tests {
#[test]
fn gpu_vendor_dedup_and_default() {
let mut hw = HardwareReport::default();
hw.gpus = vec![
GpuInfo { vendor: GpuVendor::Intel, description: "iGPU".into() },
GpuInfo { vendor: GpuVendor::Intel, description: "iGPU2".into() },
GpuInfo { vendor: GpuVendor::Nvidia, description: "dGPU".into() },
];
let hw = HardwareReport {
gpus: vec![
GpuInfo {
vendor: GpuVendor::Intel,
description: "iGPU".into(),
},
GpuInfo {
vendor: GpuVendor::Intel,
description: "iGPU2".into(),
},
GpuInfo {
vendor: GpuVendor::Nvidia,
description: "dGPU".into(),
},
],
..Default::default()
};
assert_eq!(hw.gpu_vendors(), vec![GpuVendor::Intel, GpuVendor::Nvidia]);
let empty = HardwareReport::default();

View file

@ -20,7 +20,7 @@ pub mod validate;
pub use config::{
Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig, Filesystem,
InstallConfig, KernelConfig, KernelProfile, PackagesConfig, PackagePolicy, Stage3Config,
InstallConfig, KernelConfig, KernelProfile, PackagePolicy, PackagesConfig, Stage3Config,
StorageConfig, SystemConfig, UserConfig,
};
pub use disk::{Disk, DiskKind, ProtectionReason};

View file

@ -73,7 +73,11 @@ impl InstallPlan {
}
}
pub fn render_human(&self, config: &InstallConfig, hardware: Option<&HardwareReport>) -> String {
pub fn render_human(
&self,
config: &InstallConfig,
hardware: Option<&HardwareReport>,
) -> String {
let mut o = String::new();
let enc = config.encryption.mode.as_str();
let fs = config.storage.filesystem.as_str();
@ -118,7 +122,10 @@ impl InstallPlan {
" EFI System Partition (FAT32) {} MiB -> {}\n",
config.storage.efi_size_mib, config.storage.efi_mount
));
o.push_str(&format!(" {:<36} remainder\n", format!("{enc} container")));
o.push_str(&format!(
" {:<36} remainder\n",
format!("{enc} container")
));
o.push_str(&format!(" {:<34}\n", fs));
for sv in &config.storage.subvols {
o.push_str(&format!(" {sv}\n"));
@ -126,7 +133,10 @@ impl InstallPlan {
o.push('\n');
o.push_str("Boot and kernel:\n");
o.push_str(&format!(" Bootloader : {} (BLS entries)\n", "systemd-boot"));
o.push_str(&format!(
" Bootloader : {} (BLS entries)\n",
"systemd-boot"
));
o.push_str(&format!(
" Unified UKI : {} (deferred; BLS used)\n",
if config.kernel.uki { "yes" } else { "no" }
@ -136,22 +146,37 @@ impl InstallPlan {
KernelProfile::Optimized => "optimized",
KernelProfile::Aggressive => "aggressive",
};
o.push_str(&format!(" Kernel : {kernel_pkg} ({profile} profile)\n"));
o.push_str(&format!(" Keep kernels : {}\n\n", config.kernel.keep_kernels));
o.push_str(&format!(
" Kernel : {kernel_pkg} ({profile} profile)\n"
));
o.push_str(&format!(
" Keep kernels : {}\n\n",
config.kernel.keep_kernels
));
o.push_str("Software:\n");
o.push_str(&format!(" Package policy : {}\n", config.packages.policy));
o.push_str(&format!(
" Binary pkgs : {}\n",
if config.packages.binary_packages { "yes" } else { "no" }
if config.packages.binary_packages {
"yes"
} else {
"no"
}
));
o.push_str(&format!(
" Accept license : {}\n",
config.packages.accept_license
));
o.push_str(&format!(" Accept license : {}\n", config.packages.accept_license));
o.push_str(&format!(" Desktop : {}\n", config.desktop.profile));
o.push_str(&format!(
" Flatpak : {}\n",
if config.desktop.flatpak { "yes" } else { "no" }
));
o.push_str(&format!(" Audio : {}\n", config.desktop.audio_stack));
o.push_str(&format!(
" Audio : {}\n",
config.desktop.audio_stack
));
o.push_str(&format!(
" AI assistant : {}\n",
if config.ai.enabled { "yes" } else { "no" }

View file

@ -228,10 +228,7 @@ pub fn load_history(path: &std::path::Path) -> HashMap<String, u64> {
}
/// Write a measured compile-time history file, replacing its contents.
pub fn save_history(
path: &std::path::Path,
history: &HashMap<String, u64>,
) -> std::io::Result<()> {
pub fn save_history(path: &std::path::Path, history: &HashMap<String, u64>) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
@ -281,7 +278,10 @@ mod tests {
fn balanced_compiles_cheap_and_binaries_expensive() {
let e = PackagePolicyEngine::new();
let c = ctx(PackagePolicy::Balanced);
assert_eq!(e.decide("app-editors/vim", &c).method, InstallMethod::Source);
assert_eq!(
e.decide("app-editors/vim", &c).method,
InstallMethod::Source
);
assert_eq!(
e.decide("www-client/firefox", &c).method,
InstallMethod::Binary
@ -306,7 +306,8 @@ mod tests {
fn binary_first_prefers_binary_but_falls_back() {
let e = PackagePolicyEngine::new();
assert_eq!(
e.decide("app-editors/vim", &ctx(PackagePolicy::BinaryFirst)).method,
e.decide("app-editors/vim", &ctx(PackagePolicy::BinaryFirst))
.method,
InstallMethod::Binary
);
let mut no_binhost = ctx(PackagePolicy::BinaryFirst);
@ -335,7 +336,9 @@ mod tests {
fn emerge_args_match_method() {
let e = PackagePolicyEngine::new();
let c = ctx(PackagePolicy::Balanced);
assert!(e.emerge_args("www-client/firefox", &c).contains(&"--getbinpkg".to_string()));
assert!(e
.emerge_args("www-client/firefox", &c)
.contains(&"--getbinpkg".to_string()));
assert!(e.emerge_args("app-editors/vim", &c).is_empty());
}

View file

@ -50,8 +50,7 @@ impl SnapshotHistory {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?;
}
std::fs::write(path, toml::to_string_pretty(self)?)
.map_err(|e| CoreError::io(path, e))?;
std::fs::write(path, toml::to_string_pretty(self)?).map_err(|e| CoreError::io(path, e))?;
Ok(())
}
@ -79,7 +78,12 @@ pub fn compact_utc(unix_seconds: u64) -> String {
let days = (unix_seconds / 86_400) as i64;
let rem = unix_seconds % 86_400;
let (y, m, d) = civil_from_days(days);
format!("{y:04}{m:02}{d:02}T{:02}{:02}{:02}", rem / 3600, (rem % 3600) / 60, rem % 60)
format!(
"{y:04}{m:02}{d:02}T{:02}{:02}{:02}",
rem / 3600,
(rem % 3600) / 60,
rem % 60
)
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {

View file

@ -92,7 +92,9 @@ pub fn desktop_services(profile: DesktopProfile) -> Vec<&'static str> {
/// The services that should be enabled in the target, deduplicated.
pub fn target_services(config: &InstallConfig) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for svc in network_target_services().into_iter().chain(desktop_services(config.desktop.profile))
for svc in network_target_services()
.into_iter()
.chain(desktop_services(config.desktop.profile))
{
if !out.iter().any(|s| s == svc) {
out.push(svc.to_string());
@ -152,7 +154,10 @@ pub fn video_cards(hardware: &HardwareReport) -> String {
pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String {
let mut o = String::new();
o.push_str(&format!("# {} Portage configuration\n", config.system.distro_name));
o.push_str(&format!(
"# {} Portage configuration\n",
config.system.distro_name
));
o.push_str("# Generated by the installer. Safe to edit.\n\n");
o.push_str("COMMON_FLAGS=\"-O2 -pipe -march=native\"\n");
o.push_str("CFLAGS=\"${COMMON_FLAGS}\"\n");
@ -163,9 +168,7 @@ pub fn make_conf(config: &InstallConfig, hardware: &HardwareReport) -> String {
"MAKEOPTS=\"{}\"\n",
makeopts(hardware.cpu.cores, hardware.memory_mib)
));
o.push_str(
"EMERGE_DEFAULT_OPTS=\"--binpkg-respect-use=y --with-bdeps=y --backtrack=100\"\n\n",
);
o.push_str("EMERGE_DEFAULT_OPTS=\"--binpkg-respect-use=y --with-bdeps=y --backtrack=100\"\n\n");
o.push_str("ACCEPT_KEYWORDS=\"amd64\"\n");
o.push_str(&format!(
"ACCEPT_LICENSE=\"{}\"\n\n",
@ -204,7 +207,10 @@ pub fn binrepos_conf(config: &InstallConfig) -> String {
pub fn package_use(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str(&format!("# {} installer policy\n", config.system.distro_name));
o.push_str(&format!(
"# {} installer policy\n",
config.system.distro_name
));
o.push_str("# Core system: systemd is the init system.\n");
o.push_str("# policykit is required by sys-auth/polkit[systemd];\n");
o.push_str("# cryptsetup builds systemd-cryptsetup for the encrypted root initramfs.\n");
@ -261,7 +267,10 @@ pub fn install_conf() -> String {
pub fn dracut_conf(config: &InstallConfig) -> String {
let mut o = String::new();
o.push_str(&format!("# {} dracut configuration\n", config.system.distro_name));
o.push_str(&format!(
"# {} dracut configuration\n",
config.system.distro_name
));
o.push_str("# Generic (non-hostonly) initramfs for predictable boot behaviour.\n");
o.push_str("hostonly=\"no\"\n");
o.push_str("compress=\"zstd\"\n");
@ -292,7 +301,11 @@ pub fn kernel_profile_config(config: &InstallConfig) -> String {
o.push('\n');
}
o.push_str("\n# Input / USB / common buses\n");
for line in ["CONFIG_HID_GENERIC=y", "CONFIG_USB_HID=y", "CONFIG_USB_XHCI_HCD=y"] {
for line in [
"CONFIG_HID_GENERIC=y",
"CONFIG_USB_HID=y",
"CONFIG_USB_XHCI_HCD=y",
] {
o.push_str(line);
o.push('\n');
}
@ -419,8 +432,10 @@ mod tests {
#[test]
fn kernel_extras_follow_cpu_features() {
let mut cpu = CpuInfo::default();
cpu.features = vec!["vmx".into()];
let cpu = CpuInfo {
features: vec!["vmx".into()],
..Default::default()
};
let pkgs = kernel_extra_packages(&cpu);
assert!(pkgs.contains(&"sys-kernel/linux-firmware"));
assert!(pkgs.contains(&"sys-firmware/intel-microcode"));
@ -430,7 +445,12 @@ mod tests {
#[test]
fn fstab_mounts_all_subvolumes_including_swap() {
let cfg = InstallConfig::default();
let text = fstab(&cfg, "/dev/mapper/cryptroot", Some("EFI-UUID"), "noatime,compress=zstd:3,space_cache=v2");
let text = fstab(
&cfg,
"/dev/mapper/cryptroot",
Some("EFI-UUID"),
"noatime,compress=zstd:3,space_cache=v2",
);
assert!(text.contains("UUID=EFI-UUID\t/efi\tvfat"));
assert!(text.contains("\t/\tbtrfs\t"));
assert!(text.contains("subvol=@home"));
@ -486,7 +506,6 @@ mod tests {
assert!(text.contains("ACCEPT_KEYWORDS=\"amd64\""));
assert!(!text.contains("~amd64"));
assert!(text.contains("--backtrack=100"));
assert!(text.contains("verify") || true);
}
#[test]

View file

@ -98,9 +98,7 @@ impl TargetRoot {
}
pub fn exists(&self, relative: &str) -> bool {
self.resolve(relative)
.map(|p| p.exists())
.unwrap_or(false)
self.resolve(relative).map(|p| p.exists()).unwrap_or(false)
}
}
@ -111,11 +109,20 @@ mod tests {
#[test]
fn resolves_relative_paths() {
let t = TargetRoot::new("/mnt/phoebus");
assert_eq!(t.resolve("etc/fstab").unwrap(), PathBuf::from("/mnt/phoebus/etc/fstab"));
assert_eq!(t.etc("crypttab").unwrap(), PathBuf::from("/mnt/phoebus/etc/crypttab"));
assert_eq!(
t.resolve("etc/fstab").unwrap(),
PathBuf::from("/mnt/phoebus/etc/fstab")
);
assert_eq!(
t.etc("crypttab").unwrap(),
PathBuf::from("/mnt/phoebus/etc/crypttab")
);
assert_eq!(t.var("tmp").unwrap(), PathBuf::from("/mnt/phoebus/var/tmp"));
// Leading slashes are stripped so callers may pass absolute-looking paths.
assert_eq!(t.resolve("/etc/hosts").unwrap(), PathBuf::from("/mnt/phoebus/etc/hosts"));
assert_eq!(
t.resolve("/etc/hosts").unwrap(),
PathBuf::from("/mnt/phoebus/etc/hosts")
);
}
#[test]

View file

@ -160,7 +160,10 @@ pub fn validate_config(config: &InstallConfig) -> Vec<ValidationIssue> {
issues.push(ValidationIssue::new("keymap", e));
}
if config.storage.disk.is_empty() {
issues.push(ValidationIssue::new("target_disk", "no target disk selected"));
issues.push(ValidationIssue::new(
"target_disk",
"no target disk selected",
));
} else if !config.storage.disk.starts_with("/dev/") {
issues.push(ValidationIssue::new(
"target_disk",
@ -248,6 +251,8 @@ mod tests {
cfg.user.username = "alice".into();
cfg.storage.disk = "/dev/vda".into();
assert!(validate_config(&cfg).iter().all(|i| i.field != "username"));
assert!(validate_config(&cfg).iter().all(|i| i.field != "target_disk"));
assert!(validate_config(&cfg)
.iter()
.all(|i| i.field != "target_disk"));
}
}

View file

@ -45,23 +45,33 @@ pub fn execute(
let output = match action {
SystemAction::InspectService { name } => {
let out = exec.runner.execute(
&CommandSpec::new("sys", "inspect service", "systemctl")
.args(["status", name, "--no-pager"]),
&CommandSpec::new("sys", "inspect service", "systemctl").args([
"status",
name,
"--no-pager",
]),
)?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
}
SystemAction::EnableService { name } => {
exec.run(CommandSpec::new("sys", "enable service", "systemctl").args(["enable", name]))?;
exec.run(
CommandSpec::new("sys", "enable service", "systemctl").args(["enable", name]),
)?;
format!("enabled {name}")
}
SystemAction::DisableService { name } => {
exec.run(CommandSpec::new("sys", "disable service", "systemctl").args(["disable", name]))?;
exec.run(
CommandSpec::new("sys", "disable service", "systemctl").args(["disable", name]),
)?;
format!("disabled {name}")
}
SystemAction::InspectPackage { atom } => {
let out = exec.runner.execute(
&CommandSpec::new("sys", "inspect package", "emerge")
.args(["--pretend", "--quiet", atom]),
&CommandSpec::new("sys", "inspect package", "emerge").args([
"--pretend",
"--quiet",
atom,
]),
)?;
format!("{}\n{}", out.stdout_lossy(), out.stderr_lossy())
}
@ -103,10 +113,7 @@ pub fn execute(
} else {
let mut s = String::new();
for r in &history.records {
s.push_str(&format!(
"{:<40} {:<16?} {}\n",
r.id, r.status, r.operation
));
s.push_str(&format!("{:<40} {:<16?} {}\n", r.id, r.status, r.operation));
}
s
}
@ -136,7 +143,9 @@ mod tests {
fn mutating_action_requires_authorization() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let action = SystemAction::EnableService { name: "sshd".into() };
let action = SystemAction::EnableService {
name: "sshd".into(),
};
let err = execute(&exec, &action, None, Path::new("/")).unwrap_err();
assert!(matches!(err, ExecError::NotAuthorized(_)));
}
@ -145,7 +154,9 @@ mod tests {
fn inspect_does_not_require_authorization() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let action = SystemAction::InspectService { name: "sshd".into() };
let action = SystemAction::InspectService {
name: "sshd".into(),
};
execute(&exec, &action, None, Path::new("/")).unwrap();
}
@ -154,7 +165,9 @@ mod tests {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let action = SystemAction::EnableService { name: "sshd".into() };
let action = SystemAction::EnableService {
name: "sshd".into(),
};
execute(&exec, &action, Some(&auth), Path::new("/")).unwrap();
let spec = &runner.recorded()[0];
assert_eq!(spec.program, "systemctl");

View file

@ -20,7 +20,11 @@ fn run(exec: &Exec, program: &str, args: &[&str]) -> Option<String> {
exec.runner.execute(&spec).ok().map(|o| {
let out = o.stdout_lossy();
let err = o.stderr_lossy();
if out.is_empty() { err } else { out }
if out.is_empty() {
err
} else {
out
}
})
}
@ -65,7 +69,11 @@ pub fn collect_system_context(exec: &Exec, policy: &PrivacyPolicy) -> ContextBun
if policy.allow_raw_logs {
// Only reachable with explicit opt-in. Even then, journal is a system
// source, not user files.
if let Some(v) = run(exec, "journalctl", &["-b", "-p", "warning", "--no-pager", "-n", "50"]) {
if let Some(v) = run(
exec,
"journalctl",
&["-b", "-p", "warning", "--no-pager", "-n", "50"],
) {
bundle.insert("journal_warnings", v);
}
}

View file

@ -32,7 +32,8 @@ pub fn write_dracut_conf(exec: &Exec, config: &InstallConfig) -> Result<()> {
}
pub fn esp_path(exec: &Exec, config: &InstallConfig) -> std::path::PathBuf {
exec.root.join(config.storage.efi_mount.trim_start_matches('/'))
exec.root
.join(config.storage.efi_mount.trim_start_matches('/'))
}
pub fn install_systemd_boot(exec: &Exec, config: &InstallConfig) -> Result<()> {
@ -68,7 +69,9 @@ pub fn install_fallback(exec: &Exec, config: &InstallConfig) -> Result<()> {
let mut src = systemd_dir.join("systemd-bootx64.efi");
if !src.exists() {
let vendor = exec.root.join("usr/lib/systemd/boot/efi/systemd-bootx64.efi");
let vendor = exec
.root
.join("usr/lib/systemd/boot/efi/systemd-bootx64.efi");
if vendor.exists() {
src = vendor;
} else {
@ -88,7 +91,9 @@ pub fn random_seed(exec: &Exec, config: &InstallConfig) -> Result<()> {
std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?;
let path = dir.join("random-seed");
if !path.exists() {
let bytes: Vec<u8> = (0..512).map(|i| (i as u8).wrapping_mul(31).wrapping_add(7)).collect();
let bytes: Vec<u8> = (0..512)
.map(|i| (i as u8).wrapping_mul(31).wrapping_add(7))
.collect();
std::fs::write(&path, bytes).map_err(|e| ExecError::io(path.clone(), e))?;
}
Ok(())
@ -178,6 +183,22 @@ pub fn verify(exec: &Exec, config: &InstallConfig) -> Result<()> {
Ok(())
}
pub fn secureboot_status(exec: &Exec) -> String {
if !std::path::Path::new("/sys/firmware/efi/efivars").is_dir() {
return "not booted in UEFI mode".into();
}
if crate::exec::find_in_path("mokutil").is_none() {
return "Secure Boot state unknown (mokutil not installed)".into();
}
match exec
.runner
.execute(&CommandSpec::new("boot", "secureboot status", "mokutil").arg("--sb-state"))
{
Ok(out) => out.stdout_lossy().trim().to_string(),
Err(_) => "unknown".into(),
}
}
#[cfg(test)]
mod tests {
use super::*;
@ -211,16 +232,3 @@ mod tests {
assert!(text.contains("systemd.unit=rescue.target"));
}
}
pub fn secureboot_status(exec: &Exec) -> String {
if !std::path::Path::new("/sys/firmware/efi/efivars").is_dir() {
return "not booted in UEFI mode".into();
}
if crate::exec::find_in_path("mokutil").is_none() {
return "Secure Boot state unknown (mokutil not installed)".into();
}
match exec.runner.execute(&CommandSpec::new("boot", "secureboot status", "mokutil").arg("--sb-state")) {
Ok(out) => out.stdout_lossy().trim().to_string(),
Err(_) => "unknown".into(),
}
}

View file

@ -27,7 +27,11 @@ pub struct CommandSpec {
}
impl CommandSpec {
pub fn new(stage: impl Into<String>, operation: impl Into<String>, program: impl Into<String>) -> Self {
pub fn new(
stage: impl Into<String>,
operation: impl Into<String>,
program: impl Into<String>,
) -> Self {
Self {
program: program.into(),
args: Vec::new(),
@ -138,10 +142,12 @@ impl ProcessRunner for RealRunner {
}
}
let output = child.wait_with_output().map_err(|source| ExecError::Spawn {
program: spec.program.clone(),
source,
})?;
let output = child
.wait_with_output()
.map_err(|source| ExecError::Spawn {
program: spec.program.clone(),
source,
})?;
let duration = start.elapsed();
let status = output.status.code().unwrap_or(-1);
Ok(CommandOutput {
@ -198,10 +204,7 @@ impl RecordingRunner {
}
pub fn programs(&self) -> Vec<String> {
self.recorded()
.iter()
.map(|s| s.program.clone())
.collect()
self.recorded().iter().map(|s| s.program.clone()).collect()
}
pub fn len(&self) -> usize {
@ -257,10 +260,7 @@ mod tests {
.arg("/dev/vda2")
.arg("-L")
.arg("phoebus");
assert_eq!(
spec.args,
vec!["-f", "/dev/vda2", "-L", "phoebus"]
);
assert_eq!(spec.args, vec!["-f", "/dev/vda2", "-L", "phoebus"]);
assert_eq!(spec.program, "mkfs.btrfs");
}

View file

@ -90,8 +90,7 @@ exec dwl
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
.map_err(|e| ExecError::io(path.clone(), e))?;
exec.logger
.info("wrote /usr/local/bin/phoebus-session");
exec.logger.info("wrote /usr/local/bin/phoebus-session");
Ok(())
}

View file

@ -75,7 +75,11 @@ pub fn luks_open(
Ok(())
}
pub fn luks_close(exec: &Exec, _auth: &DestructiveAuthorization, config: &InstallConfig) -> Result<()> {
pub fn luks_close(
exec: &Exec,
_auth: &DestructiveAuthorization,
config: &InstallConfig,
) -> Result<()> {
let spec = CommandSpec::new("finalize", "close LUKS device", "cryptsetup")
.arg("close")
.arg(&config.encryption.name);
@ -88,7 +92,10 @@ pub fn crypttab_line(exec: &Exec, config: &InstallConfig, partition: &str) -> Re
let uuid = probe::blkid_uuid(exec.runner.as_ref(), partition).ok_or_else(|| {
ExecError::operation("fstab_generate", "crypttab", "cannot determine LUKS UUID")
})?;
Ok(phoebus_core::system::crypttab(&config.encryption.name, &uuid))
Ok(phoebus_core::system::crypttab(
&config.encryption.name,
&uuid,
))
}
pub fn tpm2_available() -> bool {

View file

@ -104,9 +104,21 @@ impl Exec {
/// Mount the pseudo-filesystems required by a target chroot.
pub fn mount_chroot(&self) -> Result<()> {
let root = self.root.to_string_lossy().to_string();
self.run(CommandSpec::new("chroot", "mount proc", "mount").args(["-t", "proc", "proc"]).arg(format!("{root}/proc")))?;
self.run(CommandSpec::new("chroot", "mount sysfs", "mount").args(["--rbind", "/sys"]).arg(format!("{root}/sys")))?;
self.run(CommandSpec::new("chroot", "mount devtmpfs", "mount").args(["--rbind", "/dev"]).arg(format!("{root}/dev")))?;
self.run(
CommandSpec::new("chroot", "mount proc", "mount")
.args(["-t", "proc", "proc"])
.arg(format!("{root}/proc")),
)?;
self.run(
CommandSpec::new("chroot", "mount sysfs", "mount")
.args(["--rbind", "/sys"])
.arg(format!("{root}/sys")),
)?;
self.run(
CommandSpec::new("chroot", "mount devtmpfs", "mount")
.args(["--rbind", "/dev"])
.arg(format!("{root}/dev")),
)?;
let _ = self.run(
CommandSpec::new("chroot", "make /dev rslave", "mount")
.args(["--make-rslave"])

View file

@ -30,7 +30,8 @@ pub fn write_cmdline(
) -> Result<()> {
let cmdline = sysgen::kernel_cmdline(config, luks_uuid, root_source)
.map_err(|e| ExecError::operation("kernel_install", "cmdline", e))?;
exec.target().write("etc/kernel/cmdline", format!("{cmdline}\n"))?;
exec.target()
.write("etc/kernel/cmdline", format!("{cmdline}\n"))?;
exec.logger
.info(format!("wrote /etc/kernel/cmdline: {cmdline}"));
Ok(())
@ -47,8 +48,10 @@ pub fn install(
for pkg in sysgen::kernel_extra_packages(&hardware.cpu) {
packages.push(pkg.to_string());
}
exec.logger
.info(format!("installing kernel packages: {}", packages.join(" ")));
exec.logger.info(format!(
"installing kernel packages: {}",
packages.join(" ")
));
portage::emerge(exec, Path::new(&exec.root), &packages, engine, ctx)
}

View file

@ -25,7 +25,9 @@ pub mod update;
pub mod users;
pub use auth::{authorize, AutoConfirm, Confirmation, DenyConfirm, DestructiveAuthorization};
pub use command::{CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner};
pub use command::{
CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner,
};
pub use error::{ExecError, Result};
pub use exec::Exec;
pub use log::Logger;

View file

@ -187,7 +187,7 @@ fn timestamp() -> String {
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as i64;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);

View file

@ -22,7 +22,10 @@ pub fn write_config(exec: &Exec, config: &InstallConfig, hardware: &HardwareRepo
"etc/portage/binrepos.conf/gentoo.conf",
sysgen::binrepos_conf(config),
)?;
root.write("etc/portage/package.use/phoebus", sysgen::package_use(config))?;
root.write(
"etc/portage/package.use/phoebus",
sysgen::package_use(config),
)?;
root.write(
"etc/portage/package.accept_keywords/phoebus",
sysgen::accept_keywords_policy(),
@ -42,13 +45,18 @@ pub fn select_profile(exec: &Exec, config: &InstallConfig) -> Result<()> {
"/var/db/repos/gentoo/profiles/{}",
sysgen::selected_profile(config)
);
std::os::unix::fs::symlink(&target, &link)
.map_err(|e| ExecError::io(link.clone(), e))?;
std::os::unix::fs::symlink(&target, &link).map_err(|e| ExecError::io(link.clone(), e))?;
exec.logger.info(format!("profile -> {target}"));
Ok(())
}
fn chroot_spec(stage: &str, operation: &str, root: &Path, program: &str, args: &[String]) -> CommandSpec {
fn chroot_spec(
stage: &str,
operation: &str,
root: &Path,
program: &str,
args: &[String],
) -> CommandSpec {
let mut spec = CommandSpec::new(stage, operation, "chroot")
.arg(root.to_string_lossy().to_string())
.args([
@ -148,8 +156,8 @@ pub fn relax_verify_keyring(exec: &Exec) -> Result<()> {
if !dir.is_dir() {
return Ok(());
}
let gid = target_group_gid(&exec.root, "nogroup")
.or_else(|| target_group_gid(&exec.root, "nobody"));
let gid =
target_group_gid(&exec.root, "nogroup").or_else(|| target_group_gid(&exec.root, "nobody"));
// Avoid gpg trying to write random_seed as the dropped user.
let gpg_conf = dir.join("gpg.conf");
@ -272,7 +280,13 @@ pub fn emerge(
"--binpkg-respect-use=y".into(),
];
args.extend(source.clone());
let spec = chroot_spec("packages_base", "emerge source group", root, "emerge", &args);
let spec = chroot_spec(
"packages_base",
"emerge source group",
root,
"emerge",
&args,
);
exec.run(spec)?;
}
if !binary.is_empty() {
@ -285,7 +299,13 @@ pub fn emerge(
"--binpkg-respect-use=y".into(),
];
args.extend(binary.clone());
let spec = chroot_spec("packages_base", "emerge binary group", root, "emerge", &args);
let spec = chroot_spec(
"packages_base",
"emerge binary group",
root,
"emerge",
&args,
);
exec.run(spec)?;
}
Ok(())
@ -312,10 +332,8 @@ pub fn harvest_emerge_log(exec: &Exec, history_path: &Path) -> Result<()> {
.warn(format!("could not save compile-time history: {e}"));
return Ok(());
}
exec.logger.info(format!(
"recorded {} measured compile times",
history.len()
));
exec.logger
.info(format!("recorded {} measured compile times", history.len()));
Ok(())
}
@ -373,7 +391,10 @@ mod tests {
memory_mib: 8192,
cores: 8,
};
let pkgs = vec!["app-editors/vim".to_string(), "www-client/firefox".to_string()];
let pkgs = vec![
"app-editors/vim".to_string(),
"www-client/firefox".to_string(),
];
emerge(&exec, Path::new("/mnt/t"), &pkgs, &engine, &ctx).unwrap();
let programs: Vec<String> = runner.programs();
// Two chroot invocations: source group then binary group.

View file

@ -7,7 +7,9 @@
use std::collections::HashMap;
use phoebus_core::disk::{Disk, DiskKind};
use phoebus_core::hardware::{CpuInfo, FirmwareMode, GpuInfo, GpuVendor, HardwareReport, NetworkDevice};
use phoebus_core::hardware::{
CpuInfo, FirmwareMode, GpuInfo, GpuVendor, HardwareReport, NetworkDevice,
};
use crate::command::{CommandSpec, ProcessRunner};
@ -141,7 +143,8 @@ pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport {
}
let base = entry.path();
let wireless = base.join("wireless").exists() || base.join("phy80211").exists();
let operstate = read_trim(&base.join("operstate").to_string_lossy()).unwrap_or_default();
let operstate =
read_trim(&base.join("operstate").to_string_lossy()).unwrap_or_default();
network.push(NetworkDevice {
name,
wireless,
@ -153,7 +156,10 @@ pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport {
let mut bluetooth = lspci_filter(runner, "Bluetooth");
if let Ok(out) = std::process::Command::new("lsusb").output() {
let text = String::from_utf8_lossy(&out.stdout);
for line in text.lines().filter(|l| l.to_ascii_lowercase().contains("bluetooth")) {
for line in text
.lines()
.filter(|l| l.to_ascii_lowercase().contains("bluetooth"))
{
bluetooth.push(line.to_string());
}
}
@ -164,11 +170,9 @@ pub fn probe_hardware(runner: &dyn ProcessRunner) -> HardwareReport {
let laptop = std::fs::read_dir("/sys/class/power_supply")
.map(|entries| {
entries.flatten().any(|e| {
e.file_name()
.to_string_lossy()
.starts_with("BAT")
})
entries
.flatten()
.any(|e| e.file_name().to_string_lossy().starts_with("BAT"))
})
.unwrap_or(false);
@ -310,7 +314,14 @@ fn live_source_disks(runner: &dyn ProcessRunner) -> Vec<String> {
}
}
let mounts = read_mounts();
for mp in ["/", "/run/initramfs", "/run/live", "/mnt/cdrom", "/mnt/live", "/lib/live"] {
for mp in [
"/",
"/run/initramfs",
"/run/live",
"/mnt/cdrom",
"/mnt/live",
"/lib/live",
] {
if let Some((src, _)) = mounts.iter().find(|(_, m)| m == mp) {
sources.push(src.clone());
}
@ -416,12 +427,20 @@ pub fn is_partition_of(disk: &str, device: &str) -> bool {
pub fn blkid_uuid(runner: &dyn ProcessRunner, device: &str) -> Option<String> {
let out = capture(runner, "blkid", &["-s", "UUID", "-o", "value", device]);
out.lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)
out.lines()
.next()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
}
pub fn blkid_partlabel(runner: &dyn ProcessRunner, device: &str) -> Option<String> {
let out = capture(runner, "blkid", &["-s", "PARTLABEL", "-o", "value", device]);
out.lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)
out.lines()
.next()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
}
#[cfg(test)]
@ -431,7 +450,8 @@ mod tests {
#[test]
fn parse_pairs_handles_quotes_and_escapes() {
let line = r#"NAME="vda" MODEL="QEMU HARDDISK" SIZE="32212254720" TRAN="virtio" RM="0" RO="0""#;
let line =
r#"NAME="vda" MODEL="QEMU HARDDISK" SIZE="32212254720" TRAN="virtio" RM="0" RO="0""#;
let pairs = parse_pairs(line);
assert_eq!(pairs.get("NAME").unwrap(), "vda");
assert_eq!(pairs.get("SIZE").unwrap(), "32212254720");

View file

@ -34,9 +34,7 @@ pub fn read_history(root: &Path) -> SnapshotHistory {
}
pub fn write_history(root: &Path, history: &SnapshotHistory) -> Result<()> {
history
.save(&history_path(root))
.map_err(ExecError::Core)
history.save(&history_path(root)).map_err(ExecError::Core)
}
fn now_unix() -> u64 {

View file

@ -75,10 +75,14 @@ pub fn fetch(exec: &Exec, config: &InstallConfig, state_dir: &Path) -> Result<Pa
return Err(ExecError::operation(
"stage_install",
"verify stage3",
format!("SHA-256 mismatch (expected {}, got {})", config.stage3.sha256, got),
format!(
"SHA-256 mismatch (expected {}, got {})",
config.stage3.sha256, got
),
));
}
exec.logger.info("stage3 checksum verified (pinned SHA-256)");
exec.logger
.info("stage3 checksum verified (pinned SHA-256)");
return Ok(dest);
}
@ -102,8 +106,7 @@ fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> {
return Err(e);
}
let base = url.rsplit('/').next().unwrap_or_default();
let text = std::fs::read_to_string(&digests)
.map_err(|e| ExecError::io(digests.clone(), e))?;
let text = std::fs::read_to_string(&digests).map_err(|e| ExecError::io(digests.clone(), e))?;
let want = text.lines().find_map(|line| {
let mut f = line.split_whitespace();
let hash = f.next()?;
@ -116,7 +119,8 @@ fn verify_digests(exec: &Exec, url: &str, dest: &Path) -> Result<()> {
});
let _ = std::fs::remove_file(&digests);
let Some(want) = want else {
exec.logger.warn("no SHA-512 entry found in DIGESTS; checksum not verified");
exec.logger
.warn("no SHA-512 entry found in DIGESTS; checksum not verified");
return Ok(());
};
let got = hash_file(exec, "sha512sum", dest)?;

View file

@ -24,7 +24,15 @@ pub struct StorageState {
}
pub fn require_tools(exec: &Exec) -> Result<()> {
exec.require_tools(&["sgdisk", "partprobe", "blkid", "wipefs", "mkfs.fat", "mount", "umount"])
exec.require_tools(&[
"sgdisk",
"partprobe",
"blkid",
"wipefs",
"mkfs.fat",
"mount",
"umount",
])
}
fn disk_transport(runner: &dyn ProcessRunner, disk: &str) -> String {
@ -86,7 +94,11 @@ pub fn create_gpt(
config: &InstallConfig,
disk: &str,
) -> Result<()> {
let root_type = if config.is_encrypted() { "8309" } else { "8300" };
let root_type = if config.is_encrypted() {
"8309"
} else {
"8300"
};
let efi = config.storage.efi_size_mib;
let mut spec = CommandSpec::new("storage_prepare", "create GPT", "sgdisk")
.arg("--set-alignment=2048")
@ -159,7 +171,11 @@ pub fn prepare_root(
state.luks_uuid = None;
} else {
let passphrase = passphrase.ok_or_else(|| {
ExecError::operation("storage_prepare", "encrypt root", "no passphrase configured")
ExecError::operation(
"storage_prepare",
"encrypt root",
"no passphrase configured",
)
})?;
encryption::luks_format(exec, auth, config, &state.root_part, passphrase)?;
encryption::luks_open(exec, config, &state.root_part, passphrase)?;
@ -168,10 +184,8 @@ pub fn prepare_root(
state.root_source = mapper;
state.luks_uuid = probe::blkid_uuid(exec.runner.as_ref(), &state.root_part);
}
exec.logger.info(format!(
"root filesystem source: {}",
state.root_source
));
exec.logger
.info(format!("root filesystem source: {}", state.root_source));
Ok(())
}
@ -338,7 +352,12 @@ pub fn create_swapfile(
let swapfile = swapdir.join("swapfile");
let size_mib = swap_size_mib(exec);
let spec = CommandSpec::new("storage_prepare", "create Btrfs swapfile", "btrfs")
.args(["filesystem", "mkswapfile", "--size", &format!("{size_mib}m")])
.args([
"filesystem",
"mkswapfile",
"--size",
&format!("{size_mib}m"),
])
.arg(swapfile.to_string_lossy().to_string());
if exec.run(spec).is_ok() {
return Ok(());
@ -398,11 +417,7 @@ pub fn root_source_ref(exec: &Exec, _config: &InstallConfig, state: &StorageStat
}
}
pub fn write_fstab(
exec: &Exec,
config: &InstallConfig,
state: &mut StorageState,
) -> Result<()> {
pub fn write_fstab(exec: &Exec, config: &InstallConfig, state: &mut StorageState) -> Result<()> {
let root = exec.target();
let src = root_source_ref(exec, config, state);
let opts = btrfs_mount_opts(exec, config);
@ -480,19 +495,26 @@ mod tests {
let exec = make_exec(runner.clone());
let cfg = InstallConfig::default();
let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap();
let root = std::path::PathBuf::from(exec.root.clone());
let root = exec.root.clone();
create_layout(&exec, &auth, &cfg, "/dev/mapper/cryptroot", &root).unwrap();
let recorded = runner.recorded();
// Find the first subvolume create and the first subvol=@ mount.
let create_idx = recorded
.iter()
.position(|s| s.program == "btrfs" && s.args.first().map(String::as_str) == Some("subvolume") && s.args.get(1).map(String::as_str) == Some("create"))
.position(|s| {
s.program == "btrfs"
&& s.args.first().map(String::as_str) == Some("subvolume")
&& s.args.get(1).map(String::as_str) == Some("create")
})
.expect("subvolume create");
let mount_idx = recorded
.iter()
.position(|s| s.program == "mount" && s.args.iter().any(|a| a.contains("subvol=@")))
.expect("subvol mount");
assert!(create_idx < mount_idx, "subvolumes must be created before mounting @");
assert!(
create_idx < mount_idx,
"subvolumes must be created before mounting @"
);
}
#[test]

View file

@ -5,7 +5,9 @@
use std::path::{Path, PathBuf};
use phoebus_core::update::{build_args, fetch_args, should_prepare, PowerState, PrepareState, PrepareStatus};
use phoebus_core::update::{
build_args, fetch_args, should_prepare, PowerState, PrepareState, PrepareStatus,
};
use crate::error::{ExecError, Result};
use crate::exec::Exec;
@ -39,7 +41,8 @@ pub fn save_state(exec: &Exec, root: &Path, state: &PrepareState) -> Result<()>
let text = toml::to_string_pretty(state)
.map_err(|e| ExecError::operation("update", "serialize state", e.to_string()))?;
std::fs::write(&path, text).map_err(|e| ExecError::io(path.clone(), e))?;
exec.logger.info(format!("update state -> {}", path.display()));
exec.logger
.info(format!("update state -> {}", path.display()));
Ok(())
}
@ -78,12 +81,7 @@ fn read_load_average() -> f32 {
}
/// Prepare updates: fetch distfiles, then build reusable binary packages.
pub fn prepare(
exec: &Exec,
root: &Path,
cores: u32,
force: bool,
) -> Result<PrepareOutcome> {
pub fn prepare(exec: &Exec, root: &Path, cores: u32, force: bool) -> Result<PrepareOutcome> {
let power = read_power_state();
let load = read_load_average();
if !force && !should_prepare(power, load, cores, false) {
@ -156,7 +154,7 @@ mod tests {
fn prepare_forces_fetch_and_build_without_install() {
let runner = RecordingRunner::new();
let exec = make_exec(runner.clone());
let root = Path::new(&exec.root);
let root = Path::new(&exec.root);
let outcome = prepare(&exec, root, 8, true).unwrap();
assert!(outcome.started);
let specs = runner.recorded();
@ -167,7 +165,9 @@ mod tests {
assert_eq!(emerge_specs.len(), 2);
assert!(emerge_specs[0].args.iter().any(|a| a == "--fetchonly"));
assert!(emerge_specs[1].args.iter().any(|a| a == "--buildpkgonly"));
assert!(!emerge_specs.iter().any(|s| s.args.iter().any(|a| a == "@world" && false)));
assert!(emerge_specs
.iter()
.all(|s| s.args.iter().any(|a| a == "@world")));
let state = load_state(root);
assert_eq!(state.status, PrepareStatus::Ready);
}

View file

@ -122,7 +122,10 @@ pub fn create(
pub fn configure_sudo(exec: &Exec) -> Result<()> {
let target = exec.target();
target.write("etc/sudoers.d/10-wheel", "# Members of the wheel group may run commands as root.\n%wheel ALL=(ALL:ALL) ALL\n")?;
target.write(
"etc/sudoers.d/10-wheel",
"# Members of the wheel group may run commands as root.\n%wheel ALL=(ALL:ALL) ALL\n",
)?;
let path = target.etc("sudoers.d/10-wheel")?;
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o440))

View file

@ -93,7 +93,11 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
manifest.artifacts.sort_by(|a, b| a.name.cmp(&b.name));
let out = output.unwrap_or_else(|| default_manifest_path(&dir));
manifest.save(&out)?;
println!("wrote {} ({} artifacts)", out.display(), manifest.artifacts.len());
println!(
"wrote {} ({} artifacts)",
out.display(),
manifest.artifacts.len()
);
Ok(())
}
Command::Verify { dir, manifest } => {
@ -113,7 +117,9 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
}
if failed > 0 {
return Err(format!("{failed} artifact(s) failed verification; not publishing").into());
return Err(
format!("{failed} artifact(s) failed verification; not publishing").into(),
);
}
println!("all {} artifacts verified", manifest.artifacts.len());
Ok(())

View file

@ -55,10 +55,13 @@ impl Confirmation for SysConfirm {
print!("\nProceed? [y/N] ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("sys", "confirm", e.to_string())
})?;
Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))
std::io::stdin()
.read_line(&mut line)
.map_err(|e| phoebus_executor::ExecError::operation("sys", "confirm", e.to_string()))?;
Ok(matches!(
line.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
}
fn confirm_final(&self, _message: &str) -> Result<bool> {
@ -142,19 +145,18 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
};
// High-risk operations are preceded by a snapshot when the root is Btrfs.
if action.risk() == phoebus_core::action::Risk::High
&& cli.root.join(".snapshots").is_dir()
&& auth.is_some()
{
match phoebus_executor::snapshot::create_and_record(
&exec,
auth.as_ref().unwrap(),
&cli.root,
"/",
&action.describe(),
) {
Ok(record) => println!("created snapshot: {}", record.id),
Err(e) => eprintln!("warning: could not create snapshot: {e}"),
if action.risk() == phoebus_core::action::Risk::High && cli.root.join(".snapshots").is_dir() {
if let Some(auth) = auth.as_ref() {
match phoebus_executor::snapshot::create_and_record(
&exec,
auth,
&cli.root,
"/",
&action.describe(),
) {
Ok(record) => println!("created snapshot: {}", record.id),
Err(e) => eprintln!("warning: could not create snapshot: {e}"),
}
}
}

View file

@ -69,9 +69,9 @@ impl Confirmation for TerminalConfirm {
print!("\nType ERASE to continue: ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.map_err(|e| phoebus_executor::ExecError::operation("confirm", "erase", e.to_string()))?;
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("confirm", "erase", e.to_string())
})?;
Ok(line.trim() == "ERASE")
}
@ -79,10 +79,13 @@ impl Confirmation for TerminalConfirm {
print!("{message} [y/N] ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin()
.read_line(&mut line)
.map_err(|e| phoebus_executor::ExecError::operation("confirm", "final", e.to_string()))?;
Ok(matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes"))
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("confirm", "final", e.to_string())
})?;
Ok(matches!(
line.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
}
}
@ -117,9 +120,21 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
}
// Secrets may come from CLI files or the TUI.
let mut luks = cli.luks_passphrase_file.as_ref().map(read_secret).transpose()?;
let mut user_pw = cli.user_password_file.as_ref().map(read_secret).transpose()?;
let root_pw = cli.root_password_file.as_ref().map(read_secret).transpose()?;
let mut luks = cli
.luks_passphrase_file
.as_ref()
.map(read_secret)
.transpose()?;
let mut user_pw = cli
.user_password_file
.as_ref()
.map(read_secret)
.transpose()?;
let root_pw = cli
.root_password_file
.as_ref()
.map(read_secret)
.transpose()?;
let mut tui_confirmed = false;
let mut do_install = cli.install;
@ -216,7 +231,11 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
print!("{}", installer.render_plan());
let auth: DestructiveAuthorization = if tui_confirmed || installer.config.runtime.assume_yes {
authorize(&AutoConfirm, &installer.destructive_preview(), "Start installation?")?
authorize(
&AutoConfirm,
&installer.destructive_preview(),
"Start installation?",
)?
} else {
let preview = installer.destructive_preview();
authorize(

View file

@ -222,7 +222,9 @@ impl Installer {
self.exec.mount_chroot()?;
let root = PathBuf::from(&self.exec.root);
if let Err(e) = portage::init_machine_id(&self.exec, &root) {
self.exec.logger.warn(format!("could not initialise machine-id: {e}"));
self.exec
.logger
.warn(format!("could not initialise machine-id: {e}"));
}
let result: Result<()> = (|| {
portage::sync(&self.exec, &root)?;
@ -319,9 +321,9 @@ impl Installer {
}
self.exec.mount_chroot()?;
if let Err(e) = boot::install_systemd_boot(&self.exec, &self.config) {
self.exec
.logger
.warn(format!("bootctl install failed; relying on EFI fallback: {e}"));
self.exec.logger.warn(format!(
"bootctl install failed; relying on EFI fallback: {e}"
));
}
if let Err(e) = boot::generate_entries(&self.exec) {
self.exec
@ -336,7 +338,9 @@ impl Installer {
.warn(format!("could not write recovery entry: {e}"));
}
if let Err(e) = boot::install_fallback(&self.exec, &self.config) {
self.exec.logger.warn(format!("EFI fallback not installed: {e}"));
self.exec
.logger
.warn(format!("EFI fallback not installed: {e}"));
}
let _ = boot::random_seed(&self.exec, &self.config);
boot::verify(&self.exec, &self.config)
@ -408,10 +412,16 @@ impl Installer {
}
let _ = self.exec.export_log();
let _ = self.exec.umount_chroot();
storage::unmount_all(&self.exec, &self.config, std::path::Path::new(&self.exec.root))?;
storage::unmount_all(
&self.exec,
&self.config,
std::path::Path::new(&self.exec.root),
)?;
if self.config.is_encrypted() {
if let Err(e) = encryption::luks_close(&self.exec, auth, &self.config) {
self.exec.logger.warn(format!("could not close LUKS device: {e}"));
self.exec
.logger
.warn(format!("could not close LUKS device: {e}"));
}
}
self.exec.logger.info("installation finished");

View file

@ -8,8 +8,7 @@ use std::path::PathBuf;
use std::process::Command;
fn bash_installer() -> Option<PathBuf> {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../installer/bin/ai-installer");
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../installer/bin/ai-installer");
if path.is_file() {
Some(path)
} else {

View file

@ -12,7 +12,10 @@ use crossterm::execute;
use crossterm::terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use phoebus_core::{DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy, SecretString};
use phoebus_core::{
DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy,
SecretString,
};
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
@ -95,10 +98,7 @@ impl App {
("Disk".into(), c.storage.disk.clone()),
("Filesystem".into(), c.storage.filesystem.to_string()),
("Encryption".into(), c.encryption.mode.to_string()),
(
"Kernel profile".into(),
c.kernel.profile.to_string(),
),
("Kernel profile".into(), c.kernel.profile.to_string()),
("Package policy".into(), c.packages.policy.to_string()),
("Desktop".into(), c.desktop.profile.to_string()),
(
@ -107,11 +107,21 @@ impl App {
),
(
"Passphrase".into(),
if self.passphrase.is_some() { "set" } else { "unset" }.into(),
if self.passphrase.is_some() {
"set"
} else {
"unset"
}
.into(),
),
(
"User password".into(),
if self.user_password.is_some() { "set" } else { "unset" }.into(),
if self.user_password.is_some() {
"set"
} else {
"unset"
}
.into(),
),
("Review plan".into(), String::new()),
("Install".into(), String::new()),
@ -122,20 +132,68 @@ impl App {
fn activate(&mut self) {
let idx = self.cursor;
match idx {
0 => self.mode = Mode::Edit(self.edit("Keyboard", &self.config.system.keymap.clone(), EditTarget::Keymap, false)),
1 => self.mode = Mode::Edit(self.edit("Hostname", &self.config.system.hostname.clone(), EditTarget::Hostname, false)),
2 => self.mode = Mode::Edit(self.edit("Locale", &self.config.system.locale.clone(), EditTarget::Locale, false)),
3 => self.mode = Mode::Edit(self.edit("Timezone", &self.config.system.timezone.clone(), EditTarget::Timezone, false)),
4 => self.mode = Mode::Edit(self.edit("User", &self.config.user.username.clone(), EditTarget::Username, false)),
5 => self.mode = Mode::Edit(self.edit("Disk", &self.config.storage.disk.clone(), EditTarget::Disk, false)),
0 => {
self.mode = Mode::Edit(self.edit(
"Keyboard",
&self.config.system.keymap.clone(),
EditTarget::Keymap,
false,
))
}
1 => {
self.mode = Mode::Edit(self.edit(
"Hostname",
&self.config.system.hostname.clone(),
EditTarget::Hostname,
false,
))
}
2 => {
self.mode = Mode::Edit(self.edit(
"Locale",
&self.config.system.locale.clone(),
EditTarget::Locale,
false,
))
}
3 => {
self.mode = Mode::Edit(self.edit(
"Timezone",
&self.config.system.timezone.clone(),
EditTarget::Timezone,
false,
))
}
4 => {
self.mode = Mode::Edit(self.edit(
"User",
&self.config.user.username.clone(),
EditTarget::Username,
false,
))
}
5 => {
self.mode = Mode::Edit(self.edit(
"Disk",
&self.config.storage.disk.clone(),
EditTarget::Disk,
false,
))
}
6 => self.mode = Mode::Choice(Choice::Filesystem, 0),
7 => self.mode = Mode::Choice(Choice::Encryption, 0),
8 => self.mode = Mode::Choice(Choice::KernelProfile, 0),
9 => self.mode = Mode::Choice(Choice::PackagePolicy, 0),
10 => self.mode = Mode::Choice(Choice::DesktopProfile, 0),
11 => self.config.desktop.flatpak = !self.config.desktop.flatpak,
12 => self.mode = Mode::Edit(self.edit("Encryption passphrase", "", EditTarget::Passphrase, true)),
13 => self.mode = Mode::Edit(self.edit("User password", "", EditTarget::UserPassword, true)),
12 => {
self.mode =
Mode::Edit(self.edit("Encryption passphrase", "", EditTarget::Passphrase, true))
}
13 => {
self.mode =
Mode::Edit(self.edit("User password", "", EditTarget::UserPassword, true))
}
14 => self.mode = Mode::Plan(self.render_plan(), 0),
15 => self.mode = Mode::ConfirmErase,
16 => self.mode = Mode::Message("__exit__".into()),
@ -168,7 +226,12 @@ impl App {
out
}
fn commit_edit(state: &EditState, config: &mut InstallConfig, passphrase: &mut Option<SecretString>, user_password: &mut Option<SecretString>) {
fn commit_edit(
state: &EditState,
config: &mut InstallConfig,
passphrase: &mut Option<SecretString>,
user_password: &mut Option<SecretString>,
) {
match state.target {
EditTarget::Keymap => config.system.keymap = state.value.clone(),
EditTarget::Hostname => config.system.hostname = state.value.clone(),
@ -177,7 +240,9 @@ impl App {
EditTarget::Username => config.user.username = state.value.clone(),
EditTarget::Disk => config.storage.disk = state.value.clone(),
EditTarget::Passphrase => *passphrase = Some(SecretString::new(state.value.clone())),
EditTarget::UserPassword => *user_password = Some(SecretString::new(state.value.clone())),
EditTarget::UserPassword => {
*user_password = Some(SecretString::new(state.value.clone()))
}
}
}
}
@ -204,7 +269,11 @@ fn draw(frame: &mut ratatui::Frame, app: &mut App) {
})
.collect();
let list = List::new(items)
.block(Block::default().borders(Borders::ALL).title(" Phoebus OS Installer "))
.block(
Block::default()
.borders(Borders::ALL)
.title(" Phoebus OS Installer "),
)
.highlight_style(Style::default().add_modifier(Modifier::REVERSED))
.highlight_symbol("> ");
let mut state = ListState::default();
@ -265,7 +334,11 @@ fn draw(frame: &mut ratatui::Frame, app: &mut App) {
Paragraph::new(lines)
.scroll((*scroll, 0))
.wrap(Wrap { trim: false })
.block(Block::default().borders(Borders::ALL).title(" Installation plan (q to close) ")),
.block(
Block::default()
.borders(Borders::ALL)
.title(" Installation plan (q to close) "),
),
area,
);
}
@ -288,7 +361,8 @@ fn draw(frame: &mut ratatui::Frame, app: &mut App) {
let area = centered(60, 5, frame.area());
frame.render_widget(Clear, area);
frame.render_widget(
Paragraph::new(msg.clone()).block(Block::default().borders(Borders::ALL).title(" Message ")),
Paragraph::new(msg.clone())
.block(Block::default().borders(Borders::ALL).title(" Message ")),
area,
);
}
@ -298,14 +372,8 @@ fn draw(frame: &mut ratatui::Frame, app: &mut App) {
fn choice_options(choice: Choice, _config: &InstallConfig) -> Vec<String> {
match choice {
Choice::Filesystem => vec![
Filesystem::Btrfs.to_string(),
Filesystem::Ext4.to_string(),
],
Choice::Encryption => vec![
Encryption::Luks2.to_string(),
Encryption::None.to_string(),
],
Choice::Filesystem => vec![Filesystem::Btrfs.to_string(), Filesystem::Ext4.to_string()],
Choice::Encryption => vec![Encryption::Luks2.to_string(), Encryption::None.to_string()],
Choice::KernelProfile => vec![
KernelProfile::Optimized.to_string(),
KernelProfile::Safe.to_string(),
@ -339,19 +407,40 @@ fn centered(width: u16, height: u16, area: Rect) -> Rect {
fn apply_choice(choice: Choice, index: usize, config: &mut InstallConfig) {
match choice {
Choice::Filesystem => {
config.storage.filesystem = if index == 0 { Filesystem::Btrfs } else { Filesystem::Ext4 };
config.storage.filesystem = if index == 0 {
Filesystem::Btrfs
} else {
Filesystem::Ext4
};
}
Choice::Encryption => {
config.encryption.mode = if index == 0 { Encryption::Luks2 } else { Encryption::None };
config.encryption.mode = if index == 0 {
Encryption::Luks2
} else {
Encryption::None
};
}
Choice::KernelProfile => {
config.kernel.profile = [KernelProfile::Optimized, KernelProfile::Safe, KernelProfile::Aggressive][index.min(2)];
config.kernel.profile = [
KernelProfile::Optimized,
KernelProfile::Safe,
KernelProfile::Aggressive,
][index.min(2)];
}
Choice::PackagePolicy => {
config.packages.policy = [PackagePolicy::Balanced, PackagePolicy::SourceFirst, PackagePolicy::BinaryFirst][index.min(2)];
config.packages.policy = [
PackagePolicy::Balanced,
PackagePolicy::SourceFirst,
PackagePolicy::BinaryFirst,
][index.min(2)];
}
Choice::DesktopProfile => {
config.desktop.profile = [DesktopProfile::None, DesktopProfile::Dwl, DesktopProfile::Minimal, DesktopProfile::Full][index.min(3)];
config.desktop.profile = [
DesktopProfile::None,
DesktopProfile::Dwl,
DesktopProfile::Minimal,
DesktopProfile::Full,
][index.min(3)];
}
}
}
@ -393,7 +482,12 @@ pub fn run(mut config: InstallConfig) -> io::Result<TuiOutcome> {
KeyCode::Esc => app.mode = Mode::Browse,
KeyCode::Enter => {
if let Mode::Edit(edit) = std::mem::replace(&mut app.mode, Mode::Browse) {
App::commit_edit(&edit, &mut app.config, &mut app.passphrase, &mut app.user_password);
App::commit_edit(
&edit,
&mut app.config,
&mut app.passphrase,
&mut app.user_password,
);
}
}
KeyCode::Backspace => {
@ -417,7 +511,9 @@ pub fn run(mut config: InstallConfig) -> io::Result<TuiOutcome> {
}
KeyCode::Up | KeyCode::Char('k') => *selected = selected.saturating_sub(1),
KeyCode::Enter => {
if let Mode::Choice(choice, selected) = std::mem::replace(&mut app.mode, Mode::Browse) {
if let Mode::Choice(choice, selected) =
std::mem::replace(&mut app.mode, Mode::Browse)
{
apply_choice(choice, selected, &mut app.config);
}
}