forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

history.rs417 lines, 12.8 KiBHistoryRawDownload
1use std::io::Write;
2use std::path::{Path, PathBuf};
3use std::process::{Command, Stdio};
4
5use forge_git::history::{
6 ArchiveFormat, CommitDiff, DiffLimits, DiffStatus, FileDiff, LineKind, archive_command,
7 commit_diff, count, last_commits, log,
8};
9use forge_git::{Error, GitEnv};
10
11use crate::common::{BIG, git_env};
12
13struct Fixture {
14 _dir: tempfile::TempDir,
15 work: PathBuf,
16 git_dir: PathBuf,
17 env: GitEnv,
18}
19
20fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String {
21 let out = Command::new("/usr/bin/git")
22 .arg("-C")
23 .arg(dir)
24 .args([
25 "-c",
26 "user.name=Tester",
27 "-c",
28 "user.email=tester@example.com",
29 "-c",
30 "commit.gpgsign=false",
31 ])
32 .args(args)
33 .env_clear()
34 .env("PATH", "/usr/bin:/bin")
35 .env("HOME", home)
36 .env("GIT_CONFIG_NOSYSTEM", "1")
37 .env("GIT_CONFIG_GLOBAL", "/dev/null")
38 .output()
39 .unwrap();
40 assert!(
41 out.status.success(),
42 "git {args:?} failed: {}",
43 String::from_utf8_lossy(&out.stderr)
44 );
45 String::from_utf8_lossy(&out.stdout).into_owned()
46}
47
48fn fixture() -> Fixture {
49 let dir = tempfile::tempdir().unwrap();
50 let work = dir.path().join("work");
51 std::fs::create_dir(&work).unwrap();
52 git_in(&work, dir.path(), &["init", "-q", "-b", "main"]);
53 let env = git_env(dir.path());
54 let git_dir = work.join(".git");
55 Fixture {
56 _dir: dir,
57 work,
58 git_dir,
59 env,
60 }
61}
62
63impl Fixture {
64 fn git(&self, args: &[&str]) -> String {
65 git_in(&self.work, self._dir.path(), args)
66 }
67
68 fn write(&self, name: &str, content: impl AsRef<[u8]>) {
69 let p = self.work.join(name);
70 if let Some(parent) = p.parent() {
71 std::fs::create_dir_all(parent).unwrap();
72 }
73 std::fs::write(p, content).unwrap();
74 }
75
76 /// Stages everything, commits, and returns the new full oid.
77 fn commit(&self, msg: &str) -> String {
78 self.git(&["add", "-A"]);
79 self.git(&["commit", "-q", "--allow-empty", "-m", msg]);
80 self.git(&["rev-parse", "HEAD"]).trim().to_owned()
81 }
82}
83
84fn find<'a>(diff: &'a CommitDiff, path: &str) -> &'a FileDiff {
85 diff.files
86 .iter()
87 .find(|f| f.new_path.as_deref() == Some(path) || f.old_path.as_deref() == Some(path))
88 .unwrap_or_else(|| panic!("no file {path} in diff"))
89}
90
91fn summaries(commits: &[forge_git::browse::CommitInfo]) -> Vec<&str> {
92 commits.iter().map(|c| c.summary.as_str()).collect()
93}
94
95#[tokio::test]
96async fn log_path_filter_and_pagination() {
97 let f = fixture();
98 f.write("a.txt", "1\n");
99 f.commit("add a");
100 f.write("b.txt", "1\n");
101 f.commit("add b");
102 f.write("a.txt", "2\n");
103 f.commit("change a");
104 f.write("b.txt", "2\n");
105 let head = f.commit("change b\n\nbody with \"quotes\"\n");
106
107 let all = log(&f.env, &f.git_dir, &head, None, 0, 10).await.unwrap();
108 assert_eq!(summaries(&all), ["change b", "change a", "add b", "add a"]);
109 assert!(all[0].message.contains("body with \"quotes\""));
110 assert_eq!(all[0].parents, vec![all[1].oid.clone()]);
111 assert!(all[3].parents.is_empty());
112
113 let only_a = log(&f.env, &f.git_dir, &head, Some("a.txt"), 0, 10)
114 .await
115 .unwrap();
116 assert_eq!(summaries(&only_a), ["change a", "add a"]);
117
118 let page = log(&f.env, &f.git_dir, &head, None, 1, 2).await.unwrap();
119 assert_eq!(summaries(&page), ["change a", "add b"]);
120
121 let page_a = log(&f.env, &f.git_dir, &head, Some("a.txt"), 1, 1)
122 .await
123 .unwrap();
124 assert_eq!(summaries(&page_a), ["add a"]);
125}
126
127#[tokio::test]
128async fn commit_diff_modify_add_delete_rename_binary() {
129 let f = fixture();
130 f.write("a.txt", "one\ntwo\n");
131 f.write("gone.txt", "bye\n");
132 f.write("old.txt", "alpha\nbeta\ngamma\ndelta\nepsilon\n");
133 f.commit("base");
134
135 f.write("a.txt", "one\n2\n");
136 f.write("new.txt", "fresh\n");
137 f.write("bin.dat", b"\0\x01\x02binary");
138 f.git(&["rm", "-q", "gone.txt"]);
139 f.git(&["mv", "old.txt", "moved.txt"]);
140 let oid = f.commit("mixed");
141
142 let diff = commit_diff(&f.env, &f.git_dir, &oid, BIG).await.unwrap();
143 assert!(!diff.truncated_files);
144 assert_eq!(diff.files.len(), 5);
145
146 let a = find(&diff, "a.txt");
147 assert_eq!(a.status, DiffStatus::Modified);
148 assert_eq!((a.additions, a.deletions), (1, 1));
149 assert!(!a.is_binary);
150 assert_eq!(a.hunks.len(), 1);
151 assert!(!a.truncated);
152
153 let new = find(&diff, "new.txt");
154 assert_eq!(new.status, DiffStatus::Added);
155 assert_eq!(new.old_path, None);
156 assert_eq!(new.additions, 1);
157
158 let gone = find(&diff, "gone.txt");
159 assert_eq!(gone.status, DiffStatus::Deleted);
160 assert_eq!(gone.new_path, None);
161 assert_eq!(gone.deletions, 1);
162
163 let moved = find(&diff, "moved.txt");
164 assert_eq!(moved.status, DiffStatus::Renamed);
165 assert_eq!(moved.old_path.as_deref(), Some("old.txt"));
166 assert_eq!(moved.new_path.as_deref(), Some("moved.txt"));
167 assert!(moved.hunks.is_empty());
168
169 let bin = find(&diff, "bin.dat");
170 assert_eq!(bin.status, DiffStatus::Added);
171 assert!(bin.is_binary);
172 assert!(bin.hunks.is_empty());
173}
174
175#[tokio::test]
176async fn commit_diff_line_numbers_on_known_hunk() {
177 let f = fixture();
178 f.write("n.txt", "l1\nl2\nl3\nl4\nl5\n");
179 f.commit("base");
180 f.write("n.txt", "l1\nl2\nX3\nl4\nl5\nl6\n");
181 let oid = f.commit("edit");
182
183 let diff = commit_diff(&f.env, &f.git_dir, &oid, BIG).await.unwrap();
184 let file = find(&diff, "n.txt");
185 assert_eq!(file.hunks.len(), 1);
186 assert!(file.hunks[0].header.starts_with("@@ -1,5 +1,6 @@"));
187
188 let got: Vec<(LineKind, Option<u32>, Option<u32>, &str)> = file.hunks[0]
189 .lines
190 .iter()
191 .map(|l| (l.kind, l.old_no, l.new_no, l.text.as_str()))
192 .collect();
193 assert_eq!(
194 got,
195 vec![
196 (LineKind::Context, Some(1), Some(1), "l1"),
197 (LineKind::Context, Some(2), Some(2), "l2"),
198 (LineKind::Del, Some(3), None, "l3"),
199 (LineKind::Add, None, Some(3), "X3"),
200 (LineKind::Context, Some(4), Some(4), "l4"),
201 (LineKind::Context, Some(5), Some(5), "l5"),
202 (LineKind::Add, None, Some(6), "l6"),
203 ]
204 );
205 assert_eq!((file.additions, file.deletions), (2, 1));
206}
207
208#[tokio::test]
209async fn commit_diff_root_commit_uses_empty_tree() {
210 let f = fixture();
211 f.write("a.txt", "x\ny\n");
212 f.write("d/b.txt", "z\n");
213 let oid = f.commit("root");
214
215 let diff = commit_diff(&f.env, &f.git_dir, &oid, BIG).await.unwrap();
216 assert_eq!(diff.files.len(), 2);
217 for file in &diff.files {
218 assert_eq!(file.status, DiffStatus::Added);
219 assert_eq!(file.deletions, 0);
220 }
221 let a = find(&diff, "a.txt");
222 assert_eq!(a.additions, 2);
223 assert_eq!(a.hunks[0].header, "@@ -0,0 +1,2 @@");
224}
225
226#[tokio::test]
227async fn commit_diff_limits_truncate() {
228 let f = fixture();
229 let old: String = (0..10).map(|i| format!("old{i}\n")).collect();
230 f.write("big.txt", &old);
231 f.commit("base");
232 let new: String = (0..10).map(|i| format!("new{i}\n")).collect();
233 f.write("big.txt", &new);
234 f.write("f1.txt", "x\n");
235 f.write("f2.txt", "x\n");
236 f.write("f3.txt", "x\n");
237 let oid = f.commit("rewrite");
238
239 let limits = DiffLimits {
240 max_files: 2,
241 max_lines_per_file: 3,
242 max_total_lines: 100_000,
243 };
244 let diff = commit_diff(&f.env, &f.git_dir, &oid, limits).await.unwrap();
245 assert!(diff.truncated_files);
246 assert_eq!(diff.files.len(), 2);
247 let big = find(&diff, "big.txt");
248 assert!(big.truncated);
249 assert_eq!((big.additions, big.deletions), (10, 10));
250 let kept: usize = big.hunks.iter().map(|h| h.lines.len()).sum();
251 assert_eq!(kept, 3);
252
253 let limits = DiffLimits {
254 max_files: 10,
255 max_lines_per_file: 100,
256 max_total_lines: 4,
257 };
258 let diff = commit_diff(&f.env, &f.git_dir, &oid, limits).await.unwrap();
259 assert!(!diff.truncated_files);
260 let total: usize = diff
261 .files
262 .iter()
263 .flat_map(|f| f.hunks.iter())
264 .map(|h| h.lines.len())
265 .sum();
266 assert_eq!(total, 4);
267 let last = find(&diff, "f3.txt");
268 assert!(last.truncated);
269 assert!(last.hunks.is_empty());
270 assert_eq!(last.additions, 1);
271}
272
273#[tokio::test]
274async fn last_commits_finds_newest_touch_per_child() {
275 let f = fixture();
276 f.write("d/x.txt", "1\n");
277 f.commit("c1 add x");
278 f.write("d/y.txt", "1\n");
279 let c2 = f.commit("c2 add y");
280 f.write("d/z.txt", "1\n");
281 let c3 = f.commit("c3 add z");
282 f.write("d/x.txt", "2\n");
283 let c4 = f.commit("c4 change x");
284 f.write("d/sub/w.txt", "1\n");
285 let c5 = f.commit("c5 add sub/w");
286 f.write("other.txt", "1\n");
287 let c6 = f.commit("c6 other");
288
289 let names: Vec<String> = ["x.txt", "y.txt", "z.txt", "sub", "missing"]
290 .iter()
291 .map(|s| s.to_string())
292 .collect();
293 let map = last_commits(&f.env, &f.git_dir, &c6, "d", &names, 100)
294 .await
295 .unwrap();
296 assert_eq!(map.len(), 4);
297 assert_eq!(map["x.txt"].oid, c4);
298 assert_eq!(map["y.txt"].oid, c2);
299 assert_eq!(map["z.txt"].oid, c3);
300 assert_eq!(map["sub"].oid, c5);
301 assert!(!map.contains_key("missing"));
302
303 let root_names: Vec<String> = vec!["d".into(), "other.txt".into()];
304 let root = last_commits(&f.env, &f.git_dir, &c6, "", &root_names, 100)
305 .await
306 .unwrap();
307 assert_eq!(root["d"].oid, c5);
308 assert_eq!(root["other.txt"].oid, c6);
309
310 // max_walk counts commits in the pathspec-limited walk: c5 then c4.
311 let short = last_commits(&f.env, &f.git_dir, &c6, "d", &names, 1)
312 .await
313 .unwrap();
314 assert_eq!(short.len(), 1);
315 assert_eq!(short["sub"].oid, c5);
316}
317
318#[tokio::test]
319async fn count_counts_all_commits_or_those_touching_a_path() {
320 let f = fixture();
321 f.write("d/x.txt", "1\n");
322 f.commit("c1 add x");
323 f.write("d/y.txt", "1\n");
324 let c2 = f.commit("c2 add y");
325 f.write("d/x.txt", "2\n");
326 f.commit("c3 change x");
327 f.write("other.txt", "1\n");
328 let c4 = f.commit("c4 other");
329
330 let all = count(&f.env, &f.git_dir, &c4, None).await.unwrap();
331 assert_eq!(all, 4);
332 let dir = count(&f.env, &f.git_dir, &c4, Some("d")).await.unwrap();
333 assert_eq!(dir, 3);
334 let file = count(&f.env, &f.git_dir, &c4, Some("other.txt"))
335 .await
336 .unwrap();
337 assert_eq!(file, 1);
338 let at_c2 = count(&f.env, &f.git_dir, &c2, Some("d/x.txt"))
339 .await
340 .unwrap();
341 assert_eq!(at_c2, 1);
342 let untouched = count(&f.env, &f.git_dir, &c4, Some("missing"))
343 .await
344 .unwrap();
345 assert_eq!(untouched, 0);
346
347 assert!(count(&f.env, &f.git_dir, "not-an-oid", None).await.is_err());
348 assert!(
349 count(&f.env, &f.git_dir, &c4, Some("../escape"))
350 .await
351 .is_err()
352 );
353}
354
355#[tokio::test]
356async fn archive_command_produces_listable_tar_gz() {
357 let f = fixture();
358 f.write("a.txt", "hello\n");
359 f.write("d/b.txt", "world\n");
360 let oid = f.commit("archive me");
361
362 let cmd = archive_command(&f.env, &f.git_dir, &oid, ArchiveFormat::TarGz, "proj-1").unwrap();
363 let out = cmd.into_tokio().output().await.unwrap();
364 assert!(out.status.success());
365
366 let mut tar = Command::new("tar")
367 .arg("-tz")
368 .stdin(Stdio::piped())
369 .stdout(Stdio::piped())
370 .spawn()
371 .unwrap();
372 if let Some(mut stdin) = tar.stdin.take() {
373 stdin.write_all(&out.stdout).unwrap();
374 }
375 let listing = tar.wait_with_output().unwrap();
376 assert!(listing.status.success());
377 let names = String::from_utf8_lossy(&listing.stdout);
378 assert!(names.lines().any(|l| l == "proj-1/a.txt"), "{names}");
379 assert!(names.lines().any(|l| l == "proj-1/d/b.txt"), "{names}");
380}
381
382#[tokio::test]
383async fn non_hex_commit_arguments_are_rejected() {
384 let f = fixture();
385 f.write("a.txt", "1\n");
386 let oid = f.commit("one");
387
388 let bad_oid = "--output=/tmp/pwned";
389 assert!(matches!(
390 log(&f.env, &f.git_dir, bad_oid, None, 0, 10).await,
391 Err(Error::InvalidInput(_))
392 ));
393 assert!(matches!(
394 log(&f.env, &f.git_dir, "HEAD", None, 0, 10).await,
395 Err(Error::InvalidInput(_))
396 ));
397 assert!(matches!(
398 commit_diff(&f.env, &f.git_dir, "main", BIG).await,
399 Err(Error::InvalidInput(_))
400 ));
401 assert!(matches!(
402 last_commits(&f.env, &f.git_dir, "g".repeat(40).as_str(), "", &[], 10).await,
403 Err(Error::InvalidInput(_))
404 ));
405 assert!(matches!(
406 archive_command(&f.env, &f.git_dir, bad_oid, ArchiveFormat::Zip, "p"),
407 Err(Error::InvalidInput(_))
408 ));
409 assert!(matches!(
410 archive_command(&f.env, &f.git_dir, &oid, ArchiveFormat::TarGz, "../evil"),
411 Err(Error::InvalidInput(_))
412 ));
413 assert!(matches!(
414 log(&f.env, &f.git_dir, &oid, Some("../escape"), 0, 10).await,
415 Err(Error::InvalidInput(_))
416 ));
417}