use std::io::Write;
pub fn log_installed(names: &[String]) -> std::io::Result<()> {
let mut path = crate::theme::logs_dir();
path.push("install_log.log");
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.and_then(|d| i64::try_from(d.as_secs()).ok());
let when = crate::util::ts_to_date(now);
for n in names {
writeln!(f, "{when} {n}")?;
}
Ok(())
}
pub fn log_removed(names: &[String]) -> std::io::Result<()> {
let mut path = crate::theme::logs_dir();
path.push("remove_log.log");
let mut f = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)?;
for n in names {
writeln!(f, "{n}")?;
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn logging_writes_install_and_remove_logs_under_logs_dir() {
use std::fs;
use std::path::PathBuf;
let orig_home = std::env::var_os("HOME");
let mut home: PathBuf = std::env::temp_dir();
home.push(format!(
"pacsea_test_logs_{}_{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("System time is before UNIX epoch")
.as_nanos()
));
let _ = fs::create_dir_all(&home);
unsafe { std::env::set_var("HOME", home.display().to_string()) };
let names = vec!["a".to_string(), "b".to_string()];
super::log_installed(&names).expect("Failed to write install log in test");
let mut p = crate::theme::logs_dir();
p.push("install_log.log");
let body = fs::read_to_string(&p).expect("Failed to read install log in test");
assert!(body.contains(" a\n") || body.contains(" a\r\n"));
super::log_removed(&names).expect("Failed to write remove log in test");
let mut pr = crate::theme::logs_dir();
pr.push("remove_log.log");
let body_r = fs::read_to_string(&pr).expect("Failed to read remove log in test");
assert!(body_r.contains("a\n") || body_r.contains("a\r\n"));
unsafe {
if let Some(v) = orig_home {
std::env::set_var("HOME", v);
} else {
std::env::remove_var("HOME");
}
}
}
}