use std::collections::HashSet;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
pub fn get_session_file(pid: u32) -> PathBuf {
PathBuf::from(format!("/tmp/whi_session_{pid}.log"))
}
pub fn read_session_paths(pid: u32) -> Result<(HashSet<String>, Vec<String>), String> {
let session_file = get_session_file(pid);
if !session_file.exists() {
return Ok((HashSet::new(), Vec::new()));
}
let content = fs::read_to_string(&session_file)
.map_err(|e| format!("Failed to read session log: {e}"))?;
let mut affected = HashSet::new();
let mut deleted = Vec::new();
for line in content.lines() {
if let Some((op_type, path)) = line.split_once(' ') {
match op_type {
"deleted" | "delete" => {
deleted.push(path.to_string());
}
_ => {
affected.insert(path.to_string());
}
}
}
}
Ok((affected, deleted))
}
pub fn write_operation(pid: u32, op_type: &str, paths: &[String]) -> Result<(), String> {
if paths.is_empty() {
return Ok(());
}
let session_file = get_session_file(pid);
let mut file = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&session_file)
.map_err(|e| format!("Failed to open session log: {e}"))?;
for path in paths {
writeln!(file, "{} {}", op_type, path)
.map_err(|e| format!("Failed to write to session log: {e}"))?;
}
Ok(())
}
pub fn clear_session(pid: u32) -> Result<(), String> {
let session_file = get_session_file(pid);
if session_file.exists() {
fs::remove_file(&session_file).map_err(|e| format!("Failed to remove session log: {e}"))?;
}
Ok(())
}
fn get_all_session_files() -> Result<Vec<(PathBuf, std::time::SystemTime)>, String> {
let tmp_dir = Path::new("/tmp");
let entries =
fs::read_dir(tmp_dir).map_err(|e| format!("Failed to read /tmp directory: {e}"))?;
let mut session_files = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with("whi_session_") && name.ends_with(".log") {
if let Ok(metadata) = entry.metadata() {
if let Ok(modified) = metadata.modified() {
session_files.push((path, modified));
}
}
}
}
}
Ok(session_files)
}
pub fn cleanup_old_sessions() -> Result<(), String> {
let mut session_files = get_all_session_files()?;
if session_files.len() <= 30 {
return Ok(());
}
session_files.sort_by(|a, b| a.1.cmp(&b.1));
let files_to_delete = session_files.len() - 30;
for (path, _) in session_files.iter().take(files_to_delete) {
let _ = fs::remove_file(path); }
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_session_file_path() {
let path = get_session_file(12345);
assert_eq!(path, PathBuf::from("/tmp/whi_session_12345.log"));
}
}