feat: move install commands from xtask into clap subcommands

This commit is contained in:
Willem Vanhulle committed 2026-10-25 12:03:39 +01:00
1 parent 4dad85473b
commit 3acc577aac
15 files changed
+463 -381

No files matched your search

+1
View File
@@ -3,4 +3,5 @@ pub mod boot_view;
pub mod console_session;
pub mod demo_script;
pub mod screen_settings;
pub mod system_install;
pub mod systemd_link;
+61 -31
View File
@@ -1,9 +1,5 @@
use std::{
error::Error,
io::ErrorKind,
path::{Path, PathBuf},
process::ExitCode,
time::Duration,
error::Error, fmt::Display, io::ErrorKind, path::PathBuf, process::ExitCode, time::Duration,
};
use bootvine::{
@@ -11,9 +7,12 @@ use bootvine::{
screen_settings::config_file::{
Config, ConfigError, Timing, default_config_table, read_config_file,
},
system_install::install_files::{
InstallOptions, UninstallOptions, install_files, uninstall_files,
},
systemd_link::{boot_feed::RootRequest, systemd_bus::Scope},
};
use clap::{Parser, Subcommand, ValueEnum};
use clap::{Args, Parser, Subcommand, ValueEnum};
use jiff::fmt::friendly::SpanParser;
#[derive(Parser)]
@@ -25,6 +24,12 @@ use jiff::fmt::friendly::SpanParser;
struct Cli {
#[command(subcommand)]
command: Option<Command>,
#[command(flatten)]
watch: WatchOptions,
}
#[derive(Args)]
struct WatchOptions {
#[arg(long, help = "Watch the user service manager instead of PID 1")]
user: bool,
#[arg(
@@ -55,12 +60,27 @@ struct Cli {
#[derive(Subcommand)]
enum Command {
#[command(about = "Print every setting with its default value")]
Defaults {
#[arg(long, value_enum, default_value_t = DefaultsFormat::Toml)]
format: DefaultsFormat,
},
Defaults(DefaultsOptions),
#[command(about = "Exit with an error if a config file is unreadable or invalid")]
Check { path: PathBuf },
Check(CheckOptions),
#[command(
about = "Install this binary and the systemd units, and enable them; asks sudo when needed"
)]
Install(InstallOptions),
#[command(about = "Disable and remove what install put in place")]
Uninstall(UninstallOptions),
}
#[derive(Args)]
struct DefaultsOptions {
#[arg(long, value_enum, default_value_t = DefaultsFormat::Toml)]
format: DefaultsFormat,
}
#[derive(Args)]
struct CheckOptions {
#[arg(help = "Config file to check, such as /etc/bootvine.toml")]
path: PathBuf,
}
#[derive(Clone, Copy, ValueEnum)]
@@ -72,9 +92,21 @@ enum DefaultsFormat {
fn main() -> ExitCode {
let cli = Cli::parse();
match cli.command {
Some(Command::Defaults { format }) => print_defaults(format),
Some(Command::Check { ref path }) => check_config_file(path),
None => watch_boot(cli),
Some(Command::Defaults(options)) => print_defaults(options.format),
Some(Command::Check(options)) => check_config_file(&options),
Some(Command::Install(options)) => report_outcome(install_files(&options)),
Some(Command::Uninstall(options)) => report_outcome(uninstall_files(&options)),
None => watch_boot(cli.watch),
}
}
fn report_outcome(outcome: Result<(), impl Display>) -> ExitCode {
match outcome {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bootvine: {error}");
ExitCode::FAILURE
}
}
}
@@ -99,44 +131,42 @@ fn print_defaults(format: DefaultsFormat) -> ExitCode {
}
}
fn check_config_file(path: &Path) -> ExitCode {
match read_config_file(path) {
fn check_config_file(options: &CheckOptions) -> ExitCode {
match read_config_file(&options.path) {
Ok(_) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bootvine: {}: {error}", path.display());
eprintln!("bootvine: {}: {error}", options.path.display());
ExitCode::FAILURE
}
}
}
fn watch_boot(cli: Cli) -> ExitCode {
let config = match read_config_file(&cli.config) {
fn watch_boot(options: WatchOptions) -> ExitCode {
let config = match read_config_file(&options.config) {
Ok(config) => config,
Err(ConfigError::Unreadable(error)) if error.kind() == ErrorKind::NotFound => {
Config::default()
}
Err(error) => {
eprintln!("bootvine: ignoring {}: {error}", cli.config.display());
eprintln!("bootvine: ignoring {}: {error}", options.config.display());
Config::default()
}
};
let settings = Settings {
scope: if cli.user { Scope::User } else { Scope::System },
shutdown: cli.shutdown,
target: cli
scope: if options.user {
Scope::User
} else {
Scope::System
},
shutdown: options.shutdown,
target: options
.target
.map_or(RootRequest::ManagerDefault, RootRequest::Named),
timing: Timing {
keep_final_frame_for: cli.hold.unwrap_or(config.timing.keep_final_frame_for),
keep_final_frame_for: options.hold.unwrap_or(config.timing.keep_final_frame_for),
..config.timing
},
colors: config.colors,
};
match run(&settings) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bootvine: {error}");
ExitCode::FAILURE
}
}
report_outcome(run(&settings))
}
+2
View File
@@ -0,0 +1,2 @@
pub mod install_error;
pub mod install_files;
+11
View File
@@ -0,0 +1,11 @@
use std::{io, path::PathBuf, process::ExitStatus};
#[derive(Debug, thiserror::Error)]
pub enum InstallError {
#[error("{}: {source}", path.display())]
File { path: PathBuf, source: io::Error },
#[error("could not run {program}: {source}")]
Spawn { program: String, source: io::Error },
#[error("{program} failed: {status}")]
Failed { program: String, status: ExitStatus },
}
+309
View File
@@ -0,0 +1,309 @@
use std::{
env,
ffi::OsString,
fs::{self, Permissions},
io::ErrorKind,
iter::once,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
process::Command,
};
use clap::{Args, ValueEnum};
use rustix::process::geteuid;
use crate::system_install::install_error::InstallError;
const DRACUT_MODULE_DIR: &str = "/usr/lib/dracut/modules.d/90bootvine";
const DRACUT_CONF: &str = "/etc/dracut.conf.d/bootvine.conf";
const MKINITCPIO_HOOK: &str = "/usr/lib/initcpio/install/sd-bootvine";
const PACKAGED_BINARY_PATH: &str = "/usr/bin/bootvine";
struct PackagedUnit {
name: &'static str,
contents: &'static str,
}
const PACKAGED_UNITS: [PackagedUnit; 2] = [
PackagedUnit {
name: "bootvine.service",
contents: include_str!("../../system-files/systemd/bootvine.service"),
},
PackagedUnit {
name: "bootvine-shutdown.service",
contents: include_str!("../../system-files/systemd/bootvine-shutdown.service"),
},
];
const DRACUT_MODULE_SETUP: &str =
include_str!("../../system-files/dracut/90bootvine/module-setup.sh");
const MKINITCPIO_INSTALL_HOOK: &str =
include_str!("../../system-files/mkinitcpio/install/sd-bootvine");
#[derive(Args)]
pub struct InstallTarget {
#[arg(
long,
default_value = "/usr",
help = "Prefix for bin/bootvine and lib/systemd/system"
)]
prefix: PathBuf,
#[arg(
long,
help = "Stage the files under this directory instead of /; skips sudo and systemctl"
)]
destdir: Option<PathBuf>,
}
#[derive(Args)]
pub struct InstallOptions {
#[command(flatten)]
target: InstallTarget,
#[arg(
long,
value_enum,
default_value_t = InitrdGenerator::None,
help = "Also install the hook that adds bootvine to this initramfs generator"
)]
initrd: InitrdGenerator,
#[arg(long, help = "Leave the units disabled")]
no_enable: bool,
}
#[derive(Args)]
pub struct UninstallOptions {
#[command(flatten)]
target: InstallTarget,
}
#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum InitrdGenerator {
None,
Dracut,
Mkinitcpio,
}
struct InstalledFile {
destination: PathBuf,
contents: Vec<u8>,
mode: u32,
}
impl InstallTarget {
fn staged(&self, path: &Path) -> PathBuf {
match &self.destdir {
Some(root) => root.join(path.strip_prefix("/").unwrap_or(path)),
None => path.to_owned(),
}
}
fn changes_live_system(&self) -> bool {
self.destdir.is_none()
}
fn needs_sudo(&self) -> bool {
self.changes_live_system() && !geteuid().is_root()
}
fn binary_path(&self) -> PathBuf {
self.prefix.join("bin/bootvine")
}
fn unit_path(&self, unit: &str) -> PathBuf {
self.prefix.join("lib/systemd/system").join(unit)
}
fn every_installed_path(&self) -> Vec<PathBuf> {
once(self.binary_path())
.chain(unit_names().map(|unit| self.unit_path(unit)))
.chain([
Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"),
PathBuf::from(DRACUT_CONF),
PathBuf::from(MKINITCPIO_HOOK),
])
.collect()
}
}
fn running_binary() -> Result<PathBuf, InstallError> {
env::current_exe().map_err(|source| InstallError::File {
path: PathBuf::from("/proc/self/exe"),
source,
})
}
fn is_running_binary(path: &Path, running: &Path) -> bool {
fs::canonicalize(path).is_ok_and(|resolved| resolved == running)
}
fn binary_file(target: &InstallTarget) -> Result<Option<InstalledFile>, InstallError> {
let running = running_binary()?;
let destination = target.binary_path();
if is_running_binary(&target.staged(&destination), &running) {
return Ok(None);
}
let contents = fs::read(&running).map_err(|source| InstallError::File {
path: running,
source,
})?;
Ok(Some(InstalledFile {
destination,
contents,
mode: 0o755,
}))
}
fn unit_files(target: &InstallTarget) -> impl Iterator<Item = InstalledFile> {
let binary_path = target.binary_path();
PACKAGED_UNITS.iter().map(move |unit| InstalledFile {
destination: target.unit_path(unit.name),
contents: unit
.contents
.replace(PACKAGED_BINARY_PATH, &binary_path.to_string_lossy())
.into_bytes(),
mode: 0o644,
})
}
fn initrd_hook_files(initrd: InitrdGenerator) -> Vec<InstalledFile> {
match initrd {
InitrdGenerator::None => Vec::new(),
InitrdGenerator::Dracut => vec![
InstalledFile {
destination: Path::new(DRACUT_MODULE_DIR).join("module-setup.sh"),
contents: DRACUT_MODULE_SETUP.as_bytes().to_vec(),
mode: 0o755,
},
InstalledFile {
destination: PathBuf::from(DRACUT_CONF),
contents: b"add_dracutmodules+=\" bootvine \"\n".to_vec(),
mode: 0o644,
},
],
InitrdGenerator::Mkinitcpio => vec![InstalledFile {
destination: PathBuf::from(MKINITCPIO_HOOK),
contents: MKINITCPIO_INSTALL_HOOK.as_bytes().to_vec(),
mode: 0o644,
}],
}
}
fn sibling_for_replacement(path: &Path) -> PathBuf {
let mut file_name = OsString::from(".");
file_name.push(path.file_name().unwrap_or_default());
file_name.push(".bootvine-new");
path.with_file_name(file_name)
}
fn write_installed_file(target: &InstallTarget, file: &InstalledFile) -> Result<(), InstallError> {
let path = target.staged(&file.destination);
let replacement = sibling_for_replacement(&path);
path.parent()
.map_or(Ok(()), fs::create_dir_all)
.and_then(|()| fs::write(&replacement, &file.contents))
.and_then(|()| fs::set_permissions(&replacement, Permissions::from_mode(file.mode)))
.and_then(|()| fs::rename(&replacement, &path))
.map_err(|source| InstallError::File { path, source })
}
fn remove_if_present(path: PathBuf) -> Result<(), InstallError> {
match fs::remove_file(&path) {
Err(error) if error.kind() != ErrorKind::NotFound => Err(InstallError::File {
path,
source: error,
}),
_ => Ok(()),
}
}
fn run_command(command: &mut Command) -> Result<(), InstallError> {
let program = command.get_program().to_string_lossy().into_owned();
let status = command.status().map_err(|source| InstallError::Spawn {
program: program.clone(),
source,
})?;
if status.success() {
Ok(())
} else {
Err(InstallError::Failed { program, status })
}
}
fn systemctl<'a>(arguments: impl IntoIterator<Item = &'a str>) -> Result<(), InstallError> {
run_command(Command::new("systemctl").args(arguments))
}
fn unit_names() -> impl Iterator<Item = &'static str> {
PACKAGED_UNITS.iter().map(|unit| unit.name)
}
fn rerun_with_sudo() -> Result<(), InstallError> {
run_command(
Command::new("sudo")
.arg(running_binary()?)
.args(env::args_os().skip(1)),
)
}
fn print_initramfs_hint(initrd: InitrdGenerator) {
match initrd {
InitrdGenerator::None => {}
InitrdGenerator::Dracut => println!("rebuild the initramfs: sudo dracut --force"),
InitrdGenerator::Mkinitcpio => println!(
"add sd-bootvine after systemd in HOOKS in /etc/mkinitcpio.conf, then run: sudo \
mkinitcpio -P"
),
}
}
pub fn install_files(options: &InstallOptions) -> Result<(), InstallError> {
let target = &options.target;
if target.needs_sudo() {
return rerun_with_sudo();
}
binary_file(target)?
.into_iter()
.chain(unit_files(target))
.chain(initrd_hook_files(options.initrd))
.try_for_each(|file| write_installed_file(target, &file))?;
if target.changes_live_system() {
systemctl(["daemon-reload"])?;
if !options.no_enable {
systemctl(once("enable").chain(unit_names()))?;
}
print_initramfs_hint(options.initrd);
}
Ok(())
}
pub fn uninstall_files(options: &UninstallOptions) -> Result<(), InstallError> {
let target = &options.target;
if target.needs_sudo() {
return rerun_with_sudo();
}
if target.changes_live_system() {
let installed_units: Vec<&str> = unit_names()
.filter(|unit| target.unit_path(unit).exists())
.collect();
if !installed_units.is_empty() {
systemctl(once("disable").chain(installed_units))?;
}
}
target
.every_installed_path()
.into_iter()
.try_for_each(|path| remove_if_present(target.staged(&path)))?;
let dracut_module_dir = target.staged(Path::new(DRACUT_MODULE_DIR));
match fs::remove_dir(&dracut_module_dir) {
Err(error) if error.kind() == ErrorKind::DirectoryNotEmpty => {
return Err(InstallError::File {
path: dracut_module_dir,
source: error,
});
}
_ => {}
}
if target.changes_live_system() {
systemctl(["daemon-reload"])?;
}
Ok(())
}
+4 -6
View File
@@ -214,12 +214,10 @@ impl BusFeed {
return Ok(Vec::new());
}
self.gave_origin = true;
let origin = if connection.boot_in_progress().await? {
Duration::ZERO
} else {
monotonic_now()
};
Ok(once(BootChange::SetOrigin(origin))
if connection.boot_in_progress().await? {
return Ok(vec![BootChange::SetOrigin(Duration::ZERO)]);
}
Ok(once(BootChange::SetOrigin(monotonic_now()))
.chain(self.boot_finished())
.collect())
}