use std::fs; use std::path::Path; use std::time::{Duration, SystemTime}; use crate::command::{GitCommand, GitEnv}; use crate::error::{Error, Result}; const STEP_TIMEOUT: Duration = Duration::from_secs(120); const PRUNE_TIMEOUT: Duration = Duration::from_secs(30 * 60); const PRUNE_MARK: &str = "forge-prune-due"; const PRUNE_STAMP: &str = "forge-pruned"; const STANDBY_PRUNE_MARK: &str = "forge-standby-prune-due"; const PRUNE_GRACE: Duration = Duration::from_secs(15 * 60); pub const PRUNE_AFTER_GRACE: &str = "--prune=900.seconds.ago"; const PRUNE_EVERY: Duration = Duration::from_secs(7 * 24 * 60 * 60); pub async fn after_push(env: &GitEnv, repo: &Path) -> Result<()> { let graph = GitCommand::new(env, "commit-graph") .git_dir(repo) .arg("write") .arg("--reachable") .arg("--changed-paths"); run_bounded(graph).await?; let maintenance = GitCommand::new(env, "maintenance") .git_dir(repo) .arg("run") .arg("--auto") .arg("--quiet"); run_bounded(maintenance).await } pub fn mark_prune_due(repo: &Path) { let _ = fs::write(repo.join(PRUNE_MARK), b""); } pub fn prune_due(repo: &Path, now: SystemTime) -> bool { let age = |name: &str| { let modified = fs::metadata(repo.join(name)) .and_then(|m| m.modified()) .ok()?; Some(now.duration_since(modified).unwrap_or_default()) }; age(PRUNE_MARK).is_some_and(|mark| mark >= PRUNE_GRACE) || age(PRUNE_STAMP).is_none_or(|stamp| stamp >= PRUNE_EVERY) } pub async fn prune_unreachable(env: &GitEnv, repo: &Path, prune: &'static str) -> Result<()> { let marked = fs::metadata(repo.join(PRUNE_MARK)).and_then(|m| m.modified()); let gc = GitCommand::new(env, "gc") .git_dir(repo) .arg("--quiet") .arg(prune); match tokio::time::timeout(PRUNE_TIMEOUT, gc.status()).await { Ok(result) => result?, Err(_) => { return Err(Error::Failed(format!( "timed out after {}s", PRUNE_TIMEOUT.as_secs() ))); } } fs::write(repo.join(PRUNE_STAMP), b"")?; fs::write(repo.join(STANDBY_PRUNE_MARK), b"")?; if let Ok(marked) = marked && fs::metadata(repo.join(PRUNE_MARK)) .and_then(|m| m.modified()) .ok() == Some(marked) { let _ = fs::remove_file(repo.join(PRUNE_MARK)); } Ok(()) } pub fn standby_prune_due(repo: &Path) -> bool { repo.join(STANDBY_PRUNE_MARK).is_file() } pub fn clear_standby_prune(repo: &Path) { let _ = fs::remove_file(repo.join(STANDBY_PRUNE_MARK)); } async fn run_bounded(cmd: GitCommand) -> Result<()> { match tokio::time::timeout(STEP_TIMEOUT, cmd.status()).await { Ok(result) => result, Err(_) => Err(Error::Failed(format!( "timed out after {}s", STEP_TIMEOUT.as_secs() ))), } } #[cfg(test)] mod tests { use super::*; use crate::repo::init_bare; use std::path::PathBuf; fn git(dir: &Path, args: &[&str]) { let out = std::process::Command::new("git") .arg("-C") .arg(dir) .args(args) .env("GIT_AUTHOR_NAME", "test") .env("GIT_AUTHOR_EMAIL", "test@example.com") .env("GIT_COMMITTER_NAME", "test") .env("GIT_COMMITTER_EMAIL", "test@example.com") .output() .expect("git runs"); assert!( out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr) ); } fn env_for(tmp: &Path) -> GitEnv { GitEnv { git_bin: PathBuf::from("git"), data_dir: tmp.to_path_buf(), } } #[tokio::test] async fn after_push_writes_commit_graph() { let tmp = tempfile::tempdir().expect("tempdir"); let env = env_for(tmp.path()); let bare = tmp.path().join("repo.git"); init_bare(&env, &bare, "main").await.expect("init bare"); let work = tmp.path().join("work"); std::fs::create_dir(&work).expect("mkdir work"); git(&work, &["init", "-b", "main"]); let bare_str = bare.to_str().expect("utf8 path"); for text in ["one", "two"] { std::fs::write(work.join("file.txt"), text).expect("write"); git(&work, &["add", "file.txt"]); git(&work, &["commit", "-m", text]); } git(&work, &["push", bare_str, "main"]); after_push(&env, &bare).await.expect("after_push"); let single = bare.join("objects/info/commit-graph"); let split = bare.join("objects/info/commit-graphs"); assert!( single.is_file() || split.is_dir(), "no commit-graph written under {}", bare.display() ); after_push(&env, &bare).await.expect("second after_push"); } #[tokio::test] async fn overwritten_commits_stop_resolving_then_are_removed() { use crate::browse::{commit_reachable, resolve_commit}; let tmp = tempfile::tempdir().expect("tempdir"); let env = env_for(tmp.path()); let bare = tmp.path().join("repo.git"); init_bare(&env, &bare, "main").await.expect("init bare"); let work = tmp.path().join("work"); std::fs::create_dir(&work).expect("mkdir work"); git(&work, &["init", "-b", "main"]); let bare_str = bare.to_str().expect("utf8 path"); for text in ["one", "two"] { std::fs::write(work.join("file.txt"), text).expect("write"); git(&work, &["add", "file.txt"]); git(&work, &["commit", "-m", text]); } git(&work, &["push", bare_str, "main"]); let rev = |name: &str| { let out = std::process::Command::new("git") .arg("-C") .arg(&work) .args(["rev-parse", name]) .output() .expect("rev-parse"); String::from_utf8_lossy(&out.stdout).trim().to_owned() }; let old = rev("HEAD"); assert_eq!(resolve_commit(&bare, &old[..8]).unwrap(), Some(old.clone())); git(&work, &["reset", "--hard", "HEAD~1"]); git(&work, &["push", "--force", bare_str, "main"]); assert_eq!(resolve_commit(&bare, &old).unwrap(), None); assert!(!commit_reachable(&bare, &old).unwrap()); git(&bare, &["update-ref", "refs/pull/1/head", &old]); assert_eq!(resolve_commit(&bare, &old).unwrap(), Some(old.clone())); git(&bare, &["update-ref", "-d", "refs/pull/1/head"]); mark_prune_due(&bare); assert!(prune_due(&bare, SystemTime::now() + PRUNE_GRACE)); prune_unreachable(&env, &bare, "--prune=now") .await .expect("prune"); assert!(!prune_due(&bare, SystemTime::now() + PRUNE_GRACE)); let gone = std::process::Command::new("git") .arg("-C") .arg(&bare) .args(["cat-file", "-e", &old]) .status() .expect("cat-file"); assert!(!gone.success(), "the overwritten commit is still on disk"); assert_eq!(resolve_commit(&bare, "main").unwrap(), Some(rev("HEAD"))); } }