nixpkgs mirror (for testing)
github.com/NixOS/nixpkgs
nix
1use std::{io::Write, path::PathBuf, process::Command};
2
3use anyhow::{Context, Result, bail};
4
5use crate::SYSROOT_PATH;
6
7/// Switch root from initrd.
8///
9/// If the provided init is `None`, systemd is used as the next init.
10pub fn switch_root(init: Option<PathBuf>) -> Result<()> {
11 log::info!("Switching root to {SYSROOT_PATH}...");
12
13 let mut cmd = Command::new("systemctl");
14 cmd.arg("--no-block").arg("switch-root").arg(SYSROOT_PATH);
15
16 if let Some(init) = init {
17 log::info!("Using init {}.", init.display());
18 cmd.arg(init);
19 } else {
20 log::info!("Using built-in systemd as init.");
21 cmd.arg("");
22 }
23
24 let output = cmd
25 .output()
26 .context("Failed to run systemctl switch-root. Most likely the binary is not on PATH")?;
27
28 let _ = std::io::stderr().write_all(&output.stderr);
29
30 if !output.status.success() {
31 bail!("systemctl switch-root exited unsuccessfully");
32 }
33
34 Ok(())
35}