Skip to content

Commit

Permalink
Merge branch 'main' of github.com:FyraLabs/readymade
Browse files Browse the repository at this point in the history
  • Loading branch information
madonuko committed Jan 24, 2025
2 parents c0f16e7 + 3a1c527 commit f373834
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 185 deletions.
10 changes: 2 additions & 8 deletions src/backend/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@ pub struct MountTarget {
impl MountTarget {
fn mount(&self, root: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(root)?;
let target = self
.mountpoint
.strip_prefix("/")
.unwrap_or(&self.mountpoint);
let target = (self.mountpoint.strip_prefix("/")).unwrap_or(&self.mountpoint);
tracing::info!(?root, "Mounting {:?} to {target:?}", self.partition);
let target = root.join(target);
std::fs::create_dir_all(&target)?;
Expand All @@ -32,10 +29,7 @@ impl MountTarget {

pub fn umount(&self, root: &Path) -> std::io::Result<()> {
// sanitize target path
let target = self
.mountpoint
.strip_prefix("/")
.unwrap_or(&self.mountpoint);
let target = (self.mountpoint.strip_prefix("/")).unwrap_or(&self.mountpoint);
let target = root.join(target);

nix::mount::umount(&target)?;
Expand Down
55 changes: 14 additions & 41 deletions src/backend/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,11 @@ impl InstallationState {
let res = std::thread::scope(|s| {
s.spawn(|| {
let reader = BufReader::new(tee_stdout);
reader
.lines()
.for_each(|line| println!("| {}", line.unwrap()));
(reader.lines()).for_each(|line| println!("| {}", line.unwrap()));
});
s.spawn(|| {
let reader = BufReader::new(tee_stderr);
reader
.lines()
.for_each(|line| eprintln!("| {}", line.unwrap()));
(reader.lines()).for_each(|line| eprintln!("| {}", line.unwrap()));
});
s.spawn(|| -> Result<()> {
let (receiver, _) = server.accept()?;
Expand Down Expand Up @@ -185,18 +181,14 @@ impl InstallationState {
#[allow(clippy::unwrap_in_result)]
#[tracing::instrument]
pub fn install(&self) -> Result<()> {
let inst_type = self
.installation_type
.as_ref()
let inst_type = (self.installation_type.as_ref())
.expect("A valid installation type should be set before calling install()");

if let InstallationType::Custom = inst_type {
let mut mounttags = self.mounttags.clone().unwrap();
return crate::backend::custom::install_custom(self, &mut mounttags);
}
let blockdev = &self
.destination_disk
.as_ref()
let blockdev = &(self.destination_disk.as_ref())
.expect("A valid destination device should be set before calling install()")
.devpath;
let cfgdir = inst_type.cfgdir();
Expand Down Expand Up @@ -224,17 +216,14 @@ impl InstallationState {
let fstab = output.generate_fstab()?;

// todo: Also handle custom installs? Needs more information
let esp_node = if check_uefi() {
output.get_esp_partition()
} else {
None
};
let esp_node = check_uefi().then(|| output.get_esp_partition()).flatten();

container.run(|| self._inner_sys_setup(fstab, esp_node))??;

Ok(())
}

#[allow(clippy::unwrap_in_result)]
#[tracing::instrument]
pub fn _inner_sys_setup(&self, fstab: String, esp_node: Option<String>) -> Result<()> {
// We will run the specified postinstall modules now
Expand Down Expand Up @@ -345,7 +334,7 @@ impl InstallationState {
std::env::var("READYMADE_DRY_RUN").map_or(cfg!(debug_assertions), |v| v == "1");
let dry_run = if dry_run { "yes" } else { "no" };

let mut args = vec![
let args = [
"--dry-run",
dry_run,
"--definitions",
Expand All @@ -358,15 +347,9 @@ impl InstallationState {
&copy_source,
"--json",
"pretty",
blockdev.to_str().unwrap(),
];

// if systemd_version()? >= 256 {
// args.push("--generate-fstab");
// args.push("/dev/stdout");
// }

args.push(blockdev.to_str().unwrap());

tracing::debug!(?dry_run, ?args, "Running systemd-repart");

let repart_cmd = Command::new("systemd-repart")
Expand Down Expand Up @@ -406,22 +389,12 @@ impl InstallationType {
let blockdev_str = blockdev
.to_str()
.ok_or_else(|| eyre!("Invalid block device path"))?;
let status = Command::new("cgpt")
.args([
"add",
"-i",
"2",
"-t",
"kernel",
"-P",
"15",
"-T",
"1",
"-S",
"1",
blockdev_str,
])
.status()?;
let args = [
["add", "-i", "2", "-t"],
["kernel", "-P", "15", "-T"],
["1", "-S", "1", blockdev_str],
];
let status = Command::new("cgpt").args(args.concat()).status()?;

if !status.success() {
bail!("cgpt command failed with exit code {:?}", status.code());
Expand Down
30 changes: 1 addition & 29 deletions src/backend/repart_output.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use bytesize::ByteSize;
use color_eyre::eyre::eyre;
use std::fmt::Write;
use std::path::PathBuf;
use sys_mount::MountFlags;
Expand All @@ -11,21 +10,6 @@ use crate::{
};

/// Gets the systemd version
pub fn systemd_version() -> color_eyre::Result<usize> {
let output = std::process::Command::new("systemctl")
.arg("--version")
.output()?;
let version_str = std::str::from_utf8(&output.stdout)?;
let version = version_str
.split_whitespace()
.nth(1)
.ok_or_else(|| eyre!("Could not parse systemd version"))?
.split('.')
.next()
.ok_or_else(|| eyre!("Could not parse systemd version"))?
.parse()?;
Ok(version)
}
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
// type should be just an array of partitions
Expand All @@ -39,15 +23,10 @@ impl RepartOutput {
/// Generate a `BTreeMap` of mountpoint -> node name for generating /etc/fstab
/// from DDI partition types
pub fn mountpoints(&self) -> impl Iterator<Item = (&'static str, String)> + '_ {
self.partitions
.iter()
(self.partitions.iter())
.filter_map(|part| part.ddi_mountpoint().map(|mp| (mp, part.node.clone())))
}

pub fn find_by_node(&self, node: &str) -> Option<&RepartPartition> {
self.partitions.iter().find(|part| part.node == node)
}

/// Generate a /etc/fstab file from the DDI partition types
///
/// This function may be deprecated when systemd 256 hits f40, or when
Expand Down Expand Up @@ -367,11 +346,4 @@ mod tests {

println!("{mountpoints}");
}

#[test]
fn get_systemd_version() -> color_eyre::Result<()> {
let version = systemd_version()?;
println!("{version}");
Ok(())
}
}
3 changes: 1 addition & 2 deletions src/disks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ mod osprobe;

use std::{collections::HashMap, path::PathBuf};

use itertools::Itertools;
use osprobe::OSProbe;

use crate::pages::destination::DiskInit;
Expand Down Expand Up @@ -51,7 +50,7 @@ pub fn detect_os() -> Vec<DiskInit> {
.iter()
.filter_map(|(path, osname)| path.to_str().zip(Some(osname)))
.find_map(|(path, osname)| {
path.starts_with(&disk.fullname.to_str().unwrap())
path.starts_with(disk.fullname.to_str().unwrap())
.then_some(osname)
})
.map_or(OSNAME_PLACEHOLDER.to_owned(), ToOwned::to_owned),
Expand Down
45 changes: 16 additions & 29 deletions src/disks/osprobe.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::{path::PathBuf, process::Command};

use itertools::Itertools;

#[derive(Debug, Clone)]
pub struct OSProbe {
pub part: PathBuf,
Expand All @@ -14,8 +16,8 @@ pub struct OSProbe {
impl OSProbe {
#[tracing::instrument]
pub fn from_entry(entry: &str) -> Self {
let parts: Vec<&str> =
tracing::debug_span!("OS Probe Entry", ?entry).in_scope(|| entry.split(':').collect());
let parts = tracing::debug_span!("OS Probe Entry", ?entry)
.in_scope(|| entry.split(':').collect_vec());

// Minimum 4 parts, Part 5, 6 and 7 are optional

Expand All @@ -34,38 +36,23 @@ impl OSProbe {
})
}

// #[tracing::instrument]
pub fn scan() -> Option<Vec<Self>> {
// check if root already

const ERROR: &str = "os-prober failed to run! Are we root? Is it installed? Continuing without OS detection.";

let scan = tracing::info_span!("Scanning for OS").in_scope(|| {
let ret = tracing::info_span!("Scanning for OS").in_scope(|| {
tracing::info!("Scanning for OS with os-prober");
Command::new("pkexec")
.arg("os-prober")
.output()
.ok()
.map(|x| {
String::from_utf8(x.stdout)
.expect("os-prober should return valid utf8")
.trim()
.to_owned()
})
.filter(|x| !x.is_empty())
});

// let scan: Option<String> = Some("".to_string()); // test case for failure

scan.map(|strout| {
let x = Command::new("pkexec").arg("os-prober").output().ok()?;
let strout = String::from_utf8(x.stdout).inspect_err(|e| {
tracing::error!(?e, "os-prober should return valid utf8");
});
let strout = strout.ok()?;
tracing::info!(?strout, "OS Probe Output");

(strout.split('\n').map(str::trim))
.filter(|l| !l.is_empty())
.map(Self::from_entry)
.collect()
})
.or_else(|| {
let v = strout.lines().map(str::trim);
let v = v.filter(|l| !l.is_empty()).map(Self::from_entry);
let v = v.collect_vec();
(!v.is_empty()).then_some(v)
});
ret.or_else(|| {
tracing::error!("{ERROR}");
None
})
Expand Down
3 changes: 1 addition & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ use tracing_subscriber::{fmt, EnvFilter};
/// State related to the user's installation configuration
static INSTALLATION_STATE: SharedState<InstallationState> = SharedState::new();
static CONFIG: SharedState<cfg::ReadymadeConfig> = SharedState::new();
static ROOT_WINDOW_ID: SharedState<u32> = SharedState::new();

// todo: lazy_static const variables for the setup params

Expand Down Expand Up @@ -208,7 +207,7 @@ fn main() -> Result<()> {

let channel = IpcSender::connect(
std::env::args()
.nth(i + 1)
.nth(i.wrapping_add(1))
.context("No IPC channel ID passed")?,
)?;

Expand Down
Loading

0 comments on commit f373834

Please sign in to comment.