//! Runaway guard (S6): a burst that removes or rewrites a big part of the vault is held for the owner. use anyhow::Result; use git2::{DiffFindOptions, Patch, Repository, Tree, TreeWalkMode, TreeWalkResult}; use serde::{Deserialize, Serialize}; use std::path::Path; /// A saved burst that isn't shared until the owner says so. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HeldBurst { pub id: String, pub message: String, pub removed: usize, pub rewritten: usize, pub total: usize, pub at: i64, } #[derive(Debug, Clone, Copy, Default)] pub struct Damage { pub removed: usize, pub rewritten: usize, /// Notes in the vault before the burst. pub total: usize, } impl Damage { pub fn is_runaway(&self) -> bool { let n = self.removed + self.rewritten; n >= 50 || (n >= 5 && n * 5 >= self.total) } } /// Counts notes removed and heavily rewritten (more than half their lines gone). Renames don't count. pub fn assess(repo: &Repository, old: &Tree, new: &Tree) -> Result { let mut diff = repo.diff_tree_to_tree(Some(old), Some(new), None)?; diff.find_similar(Some(DiffFindOptions::new().renames(true)))?; let mut d = Damage::default(); old.walk(TreeWalkMode::PreOrder, |_, e| { if e.kind() == Some(git2::ObjectType::Blob) { d.total += 1; } TreeWalkResult::Ok })?; for delta in diff.deltas() { match delta.status() { git2::Delta::Deleted => d.removed += 1, git2::Delta::Modified => { let before = repo.find_blob(delta.old_file().id())?; let after = repo.find_blob(delta.new_file().id())?; if before.is_binary() || after.is_binary() { d.rewritten += 1; continue; } let lines = before.content().split(|&b| b == b'\n').filter(|l| !l.is_empty()).count(); let patch = Patch::from_blobs(&before, None, &after, None, None)?; let (_, _, gone) = patch.line_stats()?; if lines > 0 && gone * 2 > lines { d.rewritten += 1; } } _ => {} } } Ok(d) } fn path(git_dir: &Path) -> std::path::PathBuf { crate::state::lune_dir(git_dir).join("held.json") } pub fn load(git_dir: &Path) -> Vec { std::fs::read_to_string(path(git_dir)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default() } pub fn save(git_dir: &Path, held: &[HeldBurst]) -> Result<()> { let p = path(git_dir); std::fs::create_dir_all(p.parent().unwrap())?; let tmp = p.with_extension("json.tmp"); std::fs::write(&tmp, serde_json::to_vec_pretty(held)?)?; std::fs::rename(tmp, p)?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn thresholds() { let d = |removed, rewritten, total| Damage { removed, rewritten, total }; assert!(d(50, 0, 10_000).is_runaway()); assert!(d(10, 10, 100).is_runaway()); assert!(!d(19, 0, 100).is_runaway()); assert!(!d(4, 0, 10).is_runaway(), "tiny vaults need at least 5 notes touched"); assert!(d(5, 0, 10).is_runaway()); } }