80 lines
2.4 KiB
Rust
80 lines
2.4 KiB
Rust
use nix::{unistd::Uid, unistd::getuid};
|
|
use std::{io::Write, os::unix::fs::PermissionsExt};
|
|
|
|
use crate::print_status;
|
|
|
|
pub fn is_root() -> bool {
|
|
getuid() == Uid::from_raw(0)
|
|
}
|
|
|
|
pub fn run_command(cmd: &[&str], input: Option<&str>, inherit: bool) -> (String, String) {
|
|
print_status(&cmd.join(" "));
|
|
|
|
let mut cmd_setup = std::process::Command::new(cmd[0]);
|
|
let mut cmd_setup = cmd_setup.args(cmd.iter().skip(1).collect::<Vec<_>>());
|
|
|
|
if inherit {
|
|
assert!(input.is_none());
|
|
cmd_setup = cmd_setup
|
|
.stdout(std::process::Stdio::inherit())
|
|
.stdin(std::process::Stdio::inherit());
|
|
} else {
|
|
cmd_setup = cmd_setup.stdout(std::process::Stdio::piped());
|
|
}
|
|
|
|
if input.is_some() {
|
|
cmd_setup = cmd_setup.stdin(std::process::Stdio::piped());
|
|
}
|
|
|
|
let mut child = cmd_setup.spawn().unwrap();
|
|
|
|
if let Some(input) = input {
|
|
let stdin = child.stdin.as_mut().unwrap();
|
|
stdin.write_all(input.as_bytes()).unwrap();
|
|
stdin.flush().unwrap();
|
|
}
|
|
|
|
let status = child.wait_with_output().unwrap();
|
|
assert!(status.status.success());
|
|
|
|
let output = String::from_utf8(status.stdout).unwrap();
|
|
let stderr = String::from_utf8(status.stderr).unwrap();
|
|
|
|
if !stderr.trim().is_empty() && !inherit {
|
|
eprintln!("{stderr}");
|
|
}
|
|
|
|
if !inherit {
|
|
println!("{output}");
|
|
}
|
|
|
|
(output, stderr)
|
|
}
|
|
|
|
/// Runs a command in the chroot environment at `/mnt`
|
|
pub fn arch_chroot(cmd: &[&str], input: Option<&str>, inherit: bool) -> (String, String) {
|
|
let mut chroot_cmd = vec!["arch-chroot", "/mnt"];
|
|
chroot_cmd.extend_from_slice(cmd);
|
|
run_command(&chroot_cmd, input, inherit)
|
|
}
|
|
|
|
/// Enable a systemd `.service` in the chroot environment at `/mnt`
|
|
pub fn systemd_service_enable(unit: &str) {
|
|
arch_chroot(&["systemctl", "enable", unit], None, false);
|
|
}
|
|
|
|
/// Installs a file at `path` with `content` and `permissions`
|
|
pub fn install_file(path: &str, content: &str, permissions: u32) {
|
|
let mut file = std::fs::OpenOptions::new()
|
|
.write(true)
|
|
.create(true)
|
|
.truncate(true)
|
|
.open(path)
|
|
.unwrap();
|
|
|
|
file.write_all(content.as_bytes()).unwrap();
|
|
|
|
let permissions = std::fs::Permissions::from_mode(permissions);
|
|
print_status(&format!("Wrote file {path} [{:o}]", permissions.mode()));
|
|
std::fs::set_permissions(path, permissions).unwrap();
|
|
}
|