forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli2 hours ago363 commits

maintenance.rs211 lines, 7.1 KiBHistoryRawDownload
1use std::fs;
2use std::path::Path;
3use std::time::{Duration, SystemTime};
4
5use crate::command::{GitCommand, GitEnv};
6use crate::error::{Error, Result};
7
8const STEP_TIMEOUT: Duration = Duration::from_secs(120);
9const PRUNE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
10const PRUNE_MARK: &str = "forge-prune-due";
11const PRUNE_STAMP: &str = "forge-pruned";
12const STANDBY_PRUNE_MARK: &str = "forge-standby-prune-due";
13const PRUNE_GRACE: Duration = Duration::from_secs(15 * 60);
14pub const PRUNE_AFTER_GRACE: &str = "--prune=900.seconds.ago";
15const PRUNE_EVERY: Duration = Duration::from_secs(7 * 24 * 60 * 60);
16
17pub async fn after_push(env: &GitEnv, repo: &Path) -> Result<()> {
18 let graph = GitCommand::new(env, "commit-graph")
19 .git_dir(repo)
20 .arg("write")
21 .arg("--reachable")
22 .arg("--changed-paths");
23 run_bounded(graph).await?;
24
25 let maintenance = GitCommand::new(env, "maintenance")
26 .git_dir(repo)
27 .arg("run")
28 .arg("--auto")
29 .arg("--quiet");
30 run_bounded(maintenance).await
31}
32
33pub fn mark_prune_due(repo: &Path) {
34 let _ = fs::write(repo.join(PRUNE_MARK), b"");
35}
36
37pub fn prune_due(repo: &Path, now: SystemTime) -> bool {
38 let age = |name: &str| {
39 let modified = fs::metadata(repo.join(name))
40 .and_then(|m| m.modified())
41 .ok()?;
42 Some(now.duration_since(modified).unwrap_or_default())
43 };
44 age(PRUNE_MARK).is_some_and(|mark| mark >= PRUNE_GRACE)
45 || age(PRUNE_STAMP).is_none_or(|stamp| stamp >= PRUNE_EVERY)
46}
47
48pub async fn prune_unreachable(env: &GitEnv, repo: &Path, prune: &'static str) -> Result<()> {
49 let marked = fs::metadata(repo.join(PRUNE_MARK)).and_then(|m| m.modified());
50 let gc = GitCommand::new(env, "gc")
51 .git_dir(repo)
52 .arg("--quiet")
53 .arg(prune);
54 match tokio::time::timeout(PRUNE_TIMEOUT, gc.status()).await {
55 Ok(result) => result?,
56 Err(_) => {
57 return Err(Error::Failed(format!(
58 "timed out after {}s",
59 PRUNE_TIMEOUT.as_secs()
60 )));
61 }
62 }
63 fs::write(repo.join(PRUNE_STAMP), b"")?;
64 fs::write(repo.join(STANDBY_PRUNE_MARK), b"")?;
65 if let Ok(marked) = marked
66 && fs::metadata(repo.join(PRUNE_MARK))
67 .and_then(|m| m.modified())
68 .ok()
69 == Some(marked)
70 {
71 let _ = fs::remove_file(repo.join(PRUNE_MARK));
72 }
73 Ok(())
74}
75
76pub fn standby_prune_due(repo: &Path) -> bool {
77 repo.join(STANDBY_PRUNE_MARK).is_file()
78}
79
80pub fn clear_standby_prune(repo: &Path) {
81 let _ = fs::remove_file(repo.join(STANDBY_PRUNE_MARK));
82}
83
84async fn run_bounded(cmd: GitCommand) -> Result<()> {
85 match tokio::time::timeout(STEP_TIMEOUT, cmd.status()).await {
86 Ok(result) => result,
87 Err(_) => Err(Error::Failed(format!(
88 "timed out after {}s",
89 STEP_TIMEOUT.as_secs()
90 ))),
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97 use crate::repo::init_bare;
98 use std::path::PathBuf;
99
100 fn git(dir: &Path, args: &[&str]) {
101 let out = std::process::Command::new("git")
102 .arg("-C")
103 .arg(dir)
104 .args(args)
105 .env("GIT_AUTHOR_NAME", "test")
106 .env("GIT_AUTHOR_EMAIL", "test@example.com")
107 .env("GIT_COMMITTER_NAME", "test")
108 .env("GIT_COMMITTER_EMAIL", "test@example.com")
109 .output()
110 .expect("git runs");
111 assert!(
112 out.status.success(),
113 "git {args:?} failed: {}",
114 String::from_utf8_lossy(&out.stderr)
115 );
116 }
117
118 fn env_for(tmp: &Path) -> GitEnv {
119 GitEnv {
120 git_bin: PathBuf::from("git"),
121 data_dir: tmp.to_path_buf(),
122 }
123 }
124
125 #[tokio::test]
126 async fn after_push_writes_commit_graph() {
127 let tmp = tempfile::tempdir().expect("tempdir");
128 let env = env_for(tmp.path());
129 let bare = tmp.path().join("repo.git");
130 init_bare(&env, &bare, "main").await.expect("init bare");
131
132 let work = tmp.path().join("work");
133 std::fs::create_dir(&work).expect("mkdir work");
134 git(&work, &["init", "-b", "main"]);
135 let bare_str = bare.to_str().expect("utf8 path");
136 for text in ["one", "two"] {
137 std::fs::write(work.join("file.txt"), text).expect("write");
138 git(&work, &["add", "file.txt"]);
139 git(&work, &["commit", "-m", text]);
140 }
141 git(&work, &["push", bare_str, "main"]);
142
143 after_push(&env, &bare).await.expect("after_push");
144
145 let single = bare.join("objects/info/commit-graph");
146 let split = bare.join("objects/info/commit-graphs");
147 assert!(
148 single.is_file() || split.is_dir(),
149 "no commit-graph written under {}",
150 bare.display()
151 );
152
153 after_push(&env, &bare).await.expect("second after_push");
154 }
155
156 #[tokio::test]
157 async fn overwritten_commits_stop_resolving_then_are_removed() {
158 use crate::browse::{commit_reachable, resolve_commit};
159
160 let tmp = tempfile::tempdir().expect("tempdir");
161 let env = env_for(tmp.path());
162 let bare = tmp.path().join("repo.git");
163 init_bare(&env, &bare, "main").await.expect("init bare");
164 let work = tmp.path().join("work");
165 std::fs::create_dir(&work).expect("mkdir work");
166 git(&work, &["init", "-b", "main"]);
167 let bare_str = bare.to_str().expect("utf8 path");
168 for text in ["one", "two"] {
169 std::fs::write(work.join("file.txt"), text).expect("write");
170 git(&work, &["add", "file.txt"]);
171 git(&work, &["commit", "-m", text]);
172 }
173 git(&work, &["push", bare_str, "main"]);
174 let rev = |name: &str| {
175 let out = std::process::Command::new("git")
176 .arg("-C")
177 .arg(&work)
178 .args(["rev-parse", name])
179 .output()
180 .expect("rev-parse");
181 String::from_utf8_lossy(&out.stdout).trim().to_owned()
182 };
183 let old = rev("HEAD");
184 assert_eq!(resolve_commit(&bare, &old[..8]).unwrap(), Some(old.clone()));
185
186 git(&work, &["reset", "--hard", "HEAD~1"]);
187 git(&work, &["push", "--force", bare_str, "main"]);
188 assert_eq!(resolve_commit(&bare, &old).unwrap(), None);
189 assert!(!commit_reachable(&bare, &old).unwrap());
190
191 git(&bare, &["update-ref", "refs/pull/1/head", &old]);
192 assert_eq!(resolve_commit(&bare, &old).unwrap(), Some(old.clone()));
193 git(&bare, &["update-ref", "-d", "refs/pull/1/head"]);
194
195 mark_prune_due(&bare);
196 assert!(prune_due(&bare, SystemTime::now() + PRUNE_GRACE));
197 prune_unreachable(&env, &bare, "--prune=now")
198 .await
199 .expect("prune");
200 assert!(!prune_due(&bare, SystemTime::now() + PRUNE_GRACE));
201
202 let gone = std::process::Command::new("git")
203 .arg("-C")
204 .arg(&bare)
205 .args(["cat-file", "-e", &old])
206 .status()
207 .expect("cat-file");
208 assert!(!gone.success(), "the overwritten commit is still on disk");
209 assert_eq!(resolve_commit(&bare, "main").unwrap(), Some(rev("HEAD")));
210 }
211}