use std::fs;
use std::path::{Path, PathBuf};
use anyhow::Result;
use openmoat_hosts::OwnedFile;
use super::{HOOK_BACKUP, HookState, HostConfig, Outcome};
use crate::home::{Home, KeepMode, write_like};
pub fn text(config: &HostConfig, file: &OwnedFile, binary: &Path) -> Result<String> {
let guard = config.guard(binary);
let home = guard.home.unwrap_or_default();
Ok(file.text(&guard.binary, &home)?)
}
fn paths(config: &HostConfig) -> Vec<PathBuf> {
std::iter::once(config.settings_path.clone())
.chain(config.extra_files())
.collect()
}
pub fn install(
home: &Home,
config: &HostConfig,
file: &OwnedFile,
binary: &Path,
dry_run: bool,
) -> Result<Outcome> {
let wanted = text(config, file, binary)?;
let mut outcome = Outcome::Unchanged;
for path in paths(config) {
let current = fs::read_to_string(&path).ok();
let this = match ¤t {
Some(text) if *text == wanted => Outcome::Unchanged,
Some(text) if file.is_ours(text) => Outcome::Updated,
_ => Outcome::Installed,
};
outcome = outcome.max(this);
if this == Outcome::Unchanged || dry_run {
continue;
}
if current.as_deref().is_some_and(|text| !file.is_ours(text)) {
super::back_up(home, &path, HOOK_BACKUP)?;
}
write_like(
&path,
wanted.as_bytes(),
&path,
KeepMode::NotWritableByOthers,
)?;
}
Ok(outcome)
}
pub fn persons_file(config: &HostConfig, file: &OwnedFile) -> Option<std::path::PathBuf> {
let current = fs::read_to_string(&config.settings_path).ok()?;
(!file.is_ours(¤t)).then(|| super::backup_path(&config.settings_path, HOOK_BACKUP))
}
pub fn render(
config: &HostConfig,
file: &OwnedFile,
binary: &Path,
current: &str,
) -> Result<Option<String>> {
let wanted = text(config, file, binary)?;
Ok((wanted != current).then_some(wanted))
}
pub fn state(config: &HostConfig, file: &OwnedFile, binary: &Path) -> HookState {
let state = state_at(config, &config.settings_path, file, binary);
if state != HookState::Installed {
return state;
}
let extra_missing = config
.extra_files()
.iter()
.any(|path| state_at(config, path, file, binary) != HookState::Installed);
if extra_missing {
return HookState::Stale {
command: binary.to_string_lossy().into_owned(),
};
}
state
}
fn state_at(config: &HostConfig, path: &Path, file: &OwnedFile, binary: &Path) -> HookState {
let current = match fs::read_to_string(path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return HookState::Missing,
Err(e) => {
return HookState::Unreadable(format!("reading {}: {e}", path.display()));
}
};
if text(config, file, binary).is_ok_and(|wanted| wanted == current) {
return HookState::Installed;
}
if !file.is_ours(¤t) {
return HookState::Missing;
}
HookState::Stale {
command: file.binary(¤t).unwrap_or_else(|| "?".to_owned()),
}
}
#[cfg(test)]
mod tests;