返回 CodeWhale
delta.rs
根目录 / crates / snapshot / src / delta.rs
1 //! Read-only views over two snapshots: what changed between them.
2 //!
3 //! The engine is the only snapshot writer. These methods only read the side
4 //! repo (`diff-tree`, `ls-tree`, `cat-file`), so a host can learn what a turn
5 //! changed from the `pre-turn`/`post-turn` pair the engine already took,
6 //! without a second snapshot or a second store.
7
8 use std::collections::HashSet;
9 use std::io::{self, BufRead, BufReader, Write};
10 use std::path::{Component, Path};
11 use std::process::{Command, Stdio};
12 use std::sync::atomic::{AtomicBool, Ordering};
13 use std::sync::{Arc, mpsc};
14 use std::time::Duration;
15
16 use sha2::{Digest, Sha256};
17
18 use super::{SnapshotId, SnapshotRepo};
19 use crate::repo::GIT_COMMAND_TIMEOUT;
20 use codewhale_dependencies::{ExternalTool, run_bounded_git_with_timeout};
21
22 /// Blobs above this size are reported by size only: hashing them for a
23 /// Preview list is not worth the I/O, and the read route refuses them anyway.
24 pub const DELTA_HASH_MAX_BYTES: u64 = 16 * 1024 * 1024;
25
26 /// How one path changed between two snapshots.
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 pub enum DeltaChange {
29 Created,
30 Updated,
31 Deleted,
32 Renamed,
33 }
34
35 /// One changed path. `size`/`sha256` describe the content in the *newer*
36 /// snapshot; both are `None` for a deletion, and `sha256` is `None` above
37 /// [`DELTA_HASH_MAX_BYTES`].
38 #[derive(Debug, Clone, PartialEq, Eq)]
39 pub struct DeltaEntry {
40 /// Workspace-relative, `/`-separated.
41 pub path: String,
42 pub previous_path: Option<String>,
43 pub change: DeltaChange,
44 pub size: Option<u64>,
45 pub sha256: Option<String>,
46 }
47
48 /// Every regular-file change between two snapshots, bounded.
49 #[derive(Debug, Clone, Default, PartialEq, Eq)]
50 pub struct SnapshotDelta {
51 pub entries: Vec<DeltaEntry>,
52 /// Entries were cut at the limit.
53 pub truncated: bool,
54 /// Changes not listed: past the limit, a non-UTF-8 or unsafe path, or
55 /// not a regular file (symlink, submodule).
56 pub omitted: u64,
57 }
58
59 struct RawChange {
60 dst_mode: String,
61 dst_blob: String,
62 status: u8,
63 path: Vec<u8>,
64 previous_path: Option<Vec<u8>>,
65 }
66
67 fn git(repo: &SnapshotRepo) -> io::Result<Command> {
68 let mut command = codewhale_dependencies::Git::command()
69 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "git not found on PATH"))?;
70 command
71 .arg("--git-dir")
72 .arg(repo.git_dir())
73 .arg("--work-tree")
74 .arg(repo.work_tree());
75 Ok(command)
76 }
77
78 fn git_output(repo: &SnapshotRepo, args: &[&str]) -> io::Result<Vec<u8>> {
79 let mut command = git(repo)?;
80 command.args(args);
81 let output = run_bounded_git_with_timeout(
82 &mut command,
83 args.first().copied().unwrap_or_default(),
84 GIT_COMMAND_TIMEOUT,
85 )?;
86 if !output.status.success() {
87 return Err(io::Error::other(format!(
88 "git {} failed: {}",
89 args.first().copied().unwrap_or_default(),
90 String::from_utf8_lossy(&output.stderr).trim()
91 )));
92 }
93 Ok(output.stdout)
94 }
95
96 /// A workspace-relative display path, or `None` when the bytes are not
97 /// UTF-8, the path is not plainly relative, or it names `.git`.
98 fn safe_display(path: &[u8]) -> Option<String> {
99 let text = std::str::from_utf8(path).ok()?;
100 let mut parts = Vec::new();
101 for component in Path::new(text).components() {
102 match component {
103 Component::Normal(name)
104 if !codewhale_util::git_metadata::is_git_metadata_name(name) =>
105 {
106 parts.push(name.to_str()?)
107 }
108 _ => return None,
109 }
110 }
111 (!parts.is_empty()).then(|| parts.join("/"))
112 }
113
114 /// Parse `diff-tree -r -z --raw -M` output: `:<src mode> <dst mode> <src oid>
115 /// <dst oid> <status>\0<path>\0` and, for a rename or copy, a second path.
116 fn parse_raw(bytes: &[u8]) -> io::Result<Vec<RawChange>> {
117 let invalid = || io::Error::new(io::ErrorKind::InvalidData, "unexpected diff-tree output");
118 let mut fields = bytes.split(|byte| *byte == 0).filter(|f| !f.is_empty());
119 let mut changes = Vec::new();
120 while let Some(header) = fields.next() {
121 let header = std::str::from_utf8(header).map_err(|_| invalid())?;
122 let header = header.strip_prefix(':').ok_or_else(invalid)?;
123 let parts: Vec<&str> = header.split(' ').collect();
124 let [_, dst_mode, _, dst_blob, status] = parts.as_slice() else {
125 return Err(invalid());
126 };
127 let status = status.bytes().next().ok_or_else(invalid)?;
128 let first = fields.next().ok_or_else(invalid)?.to_vec();
129 let (path, previous_path) = if matches!(status, b'R' | b'C') {
130 let second = fields.next().ok_or_else(invalid)?.to_vec();
131 (second, Some(first))
132 } else {
133 (first, None)
134 };
135 changes.push(RawChange {
136 dst_mode: (*dst_mode).to_string(),
137 dst_blob: (*dst_blob).to_string(),
138 status,
139 path,
140 previous_path,
141 });
142 }
143 Ok(changes)
144 }
145
146 impl SnapshotRepo {
147 /// Every regular-file change from snapshot `from` to snapshot `to`,
148 /// with the size and SHA-256 of each new blob, bounded to `limit`
149 /// entries. Renames are detected (`-M`). Reads the side repo only.
150 ///
151 /// What the snapshots cannot see is not here either: paths excluded by
152 /// the built-in excludes or the workspace's `.gitignore` never enter a
153 /// snapshot, so a change to them never appears in a delta.
154 pub fn diff_snapshots(
155 &self,
156 from: &SnapshotId,
157 to: &SnapshotId,
158 limit: usize,
159 ) -> io::Result<SnapshotDelta> {
160 let raw = git_output(
161 self,
162 &[
163 "diff-tree",
164 "-r",
165 "-z",
166 "-M",
167 "--raw",
168 "--no-commit-id",
169 "--end-of-options",
170 from.as_str(),
171 to.as_str(),
172 ],
173 )?;
174 let mut delta = SnapshotDelta::default();
175 let mut pending_blobs = Vec::new();
176 for change in parse_raw(&raw)? {
177 let kind = match change.status {
178 b'A' | b'C' => DeltaChange::Created,
179 b'D' => DeltaChange::Deleted,
180 b'M' | b'T' => DeltaChange::Updated,
181 b'R' => DeltaChange::Renamed,
182 _ => {
183 delta.omitted += 1;
184 continue;
185 }
186 };
187 let regular = matches!(change.dst_mode.as_str(), "100644" | "100755");
188 if kind != DeltaChange::Deleted && !regular {
189 delta.omitted += 1;
190 continue;
191 }
192 let Some(path) = safe_display(&change.path) else {
193 delta.omitted += 1;
194 continue;
195 };
196 let previous_path = match change.previous_path.as_deref() {
197 Some(previous) => match safe_display(previous) {
198 Some(previous) => Some(previous),
199 None => {
200 delta.omitted += 1;
201 continue;
202 }
203 },
204 None => None,
205 };
206 if delta.entries.len() >= limit {
207 delta.truncated = true;
208 delta.omitted += 1;
209 continue;
210 }
211 if kind != DeltaChange::Deleted {
212 pending_blobs.push((delta.entries.len(), change.dst_blob));
213 }
214 delta.entries.push(DeltaEntry {
215 path,
216 previous_path,
217 // A copy (`C`) only appears with `-C`; treat it as a creation
218 // so its source is never reported as touched.
219 change: kind,
220 size: None,
221 sha256: None,
222 });
223 }
224 for (index, size, sha256) in self.blob_facts(&pending_blobs)? {
225 let entry = &mut delta.entries[index];
226 entry.size = Some(size);
227 entry.sha256 = sha256;
228 }
229 Ok(delta)
230 }
231
232 /// Size and SHA-256 of each blob in one `cat-file --batch` pass. Blobs
233 /// above [`DELTA_HASH_MAX_BYTES`] are streamed past without hashing.
234 fn blob_facts(
235 &self,
236 blobs: &[(usize, String)],
237 ) -> io::Result<Vec<(usize, u64, Option<String>)>> {
238 if blobs.is_empty() {
239 return Ok(Vec::new());
240 }
241 let mut command = git(self)?;
242 command.args(["cat-file", "--batch"]);
243 run_blob_facts(&mut command, blobs, GIT_COMMAND_TIMEOUT)
244 }
245
246 /// The bytes of regular file `rel` in snapshot `id`, or `None` when the
247 /// snapshot does not hold a regular file there. A blob larger than
248 /// `max_bytes` is refused with `FileTooLarge` before it is read.
249 pub fn read_blob(
250 &self,
251 id: &SnapshotId,
252 rel: &str,
253 max_bytes: u64,
254 ) -> io::Result<Option<Vec<u8>>> {
255 if safe_display(rel.as_bytes()).as_deref() != Some(rel) {
256 return Err(io::Error::new(
257 io::ErrorKind::InvalidInput,
258 "snapshot path must be a plain workspace-relative path",
259 ));
260 }
261 let entry = git_output(
262 self,
263 &[
264 "--literal-pathspecs",
265 "ls-tree",
266 "-z",
267 "--long",
268 "--end-of-options",
269 id.as_str(),
270 "--",
271 rel,
272 ],
273 )?;
274 // `<mode> blob <oid> <size>\t<path>\0`
275 let Some(line) = entry.split(|byte| *byte == 0).find(|line| !line.is_empty()) else {
276 return Ok(None);
277 };
278 let header = std::str::from_utf8(line)
279 .ok()
280 .and_then(|line| line.split('\t').next())
281 .unwrap_or_default();
282 let fields: Vec<&str> = header.split_whitespace().collect();
283 let [mode, "blob", oid, size] = fields.as_slice() else {
284 return Ok(None);
285 };
286 if !matches!(*mode, "100644" | "100755") {
287 return Ok(None);
288 }
289 let size: u64 = size
290 .parse()
291 .map_err(|_| io::Error::other("ls-tree returned an invalid size"))?;
292 if size > max_bytes {
293 return Err(io::Error::new(
294 io::ErrorKind::FileTooLarge,
295 "snapshot blob exceeds the read limit",
296 ));
297 }
298 git_output(self, &["cat-file", "blob", oid]).map(Some)
299 }
300
301 /// Which of `paths` snapshot `id` contains. A path absent from both
302 /// snapshots of a pair is one the snapshots cannot see (excluded or
303 /// ignored), which is different from one that did not change.
304 pub fn tracked_paths(&self, id: &SnapshotId, paths: &[String]) -> io::Result<HashSet<String>> {
305 if paths.is_empty() {
306 return Ok(HashSet::new());
307 }
308 let mut args = vec![
309 "--literal-pathspecs",
310 "ls-tree",
311 "-r",
312 "-z",
313 "--name-only",
314 "--end-of-options",
315 id.as_str(),
316 "--",
317 ];
318 args.extend(paths.iter().map(String::as_str));
319 let listed = git_output(self, &args)?;
320 Ok(listed
321 .split(|byte| *byte == 0)
322 .filter_map(safe_display)
323 .collect())
324 }
325 }
326
327 fn run_blob_facts(
328 command: &mut Command,
329 blobs: &[(usize, String)],
330 timeout: Duration,
331 ) -> io::Result<Vec<(usize, u64, Option<String>)>> {
332 command
333 .stdin(Stdio::piped())
334 .stdout(Stdio::piped())
335 .stderr(Stdio::null());
336 let (mut child, tree) = codewhale_runtime::process_tree::spawn_contained_std(command)?;
337 let (Some(mut stdin), Some(stdout)) = (child.stdin.take(), child.stdout.take()) else {
338 let _ = tree.kill();
339 let _ = child.kill();
340 let _ = child.wait();
341 tree.disarm();
342 return Err(io::Error::other("cat-file stdio unavailable"));
343 };
344 let request: String = blobs.iter().map(|(_, oid)| format!("{oid}\n")).collect();
345 // Feed requests from another thread: git blocks on a full stdout pipe.
346 let writer = std::thread::spawn(move || stdin.write_all(request.as_bytes()));
347 let mut reader = BufReader::new(stdout);
348 let tree = Arc::new(tree);
349 let timed_out = Arc::new(AtomicBool::new(false));
350 let (done_tx, done_rx) = mpsc::channel::<()>();
351 let watchdog = {
352 let tree = Arc::clone(&tree);
353 let timed_out = Arc::clone(&timed_out);
354 std::thread::spawn(move || {
355 if done_rx.recv_timeout(timeout) == Err(mpsc::RecvTimeoutError::Timeout) {
356 timed_out.store(true, Ordering::SeqCst);
357 let _ = tree.kill();
358 }
359 })
360 };
361
362 let read = read_blob_facts(&mut reader, blobs);
363 drop(reader);
364
365 let outcome = match read {
366 Ok(facts) => match writer.join() {
367 Ok(Ok(())) => match child.wait() {
368 Ok(status) if status.success() => Ok(facts),
369 Ok(status) => Err(io::Error::other(format!(
370 "git cat-file exited with {status}"
371 ))),
372 Err(error) => Err(error),
373 },
374 Ok(Err(error)) => {
375 let _ = tree.kill();
376 let _ = child.kill();
377 let _ = child.wait();
378 Err(error)
379 }
380 Err(_) => {
381 let _ = tree.kill();
382 let _ = child.kill();
383 let _ = child.wait();
384 Err(io::Error::other("cat-file writer panicked"))
385 }
386 },
387 Err(error) => {
388 let _ = tree.kill();
389 let _ = child.kill();
390 if timed_out.load(Ordering::SeqCst) {
391 drop(done_tx);
392 std::thread::spawn(move || {
393 let _ = watchdog.join();
394 let _ = writer.join();
395 let _ = child.wait();
396 tree.disarm();
397 drop(tree);
398 });
399 return Err(io::Error::new(
400 io::ErrorKind::TimedOut,
401 format!("git cat-file timed out after {}s", timeout.as_secs()),
402 ));
403 }
404 let _ = writer.join();
405 let _ = child.wait();
406 Err(error)
407 }
408 };
409
410 drop(done_tx);
411 let _ = watchdog.join();
412 if let Ok(tree) = Arc::try_unwrap(tree) {
413 tree.release();
414 }
415 match outcome {
416 Ok(facts) => Ok(facts),
417 Err(_) if timed_out.load(Ordering::SeqCst) => Err(io::Error::new(
418 io::ErrorKind::TimedOut,
419 format!("git cat-file timed out after {}s", timeout.as_secs()),
420 )),
421 Err(error) => Err(error),
422 }
423 }
424
425 fn read_blob_facts(
426 reader: &mut impl BufRead,
427 blobs: &[(usize, String)],
428 ) -> io::Result<Vec<(usize, u64, Option<String>)>> {
429 let mut facts = Vec::with_capacity(blobs.len());
430 let mut header = String::new();
431 let mut buffer = vec![0_u8; 64 * 1024];
432 for (index, _) in blobs {
433 header.clear();
434 reader.read_line(&mut header)?;
435 let mut parts = header.split_whitespace();
436 let (Some(_), Some("blob"), Some(size)) = (parts.next(), parts.next(), parts.next()) else {
437 return Err(io::Error::other(format!(
438 "cat-file returned an unexpected header: {}",
439 header.trim()
440 )));
441 };
442 let size: u64 = size
443 .parse()
444 .map_err(|_| io::Error::other("cat-file returned an invalid size"))?;
445 let mut hasher = (size <= DELTA_HASH_MAX_BYTES).then(Sha256::new);
446 let mut remaining = size;
447 while remaining > 0 {
448 let want = usize::try_from(remaining.min(buffer.len() as u64)).unwrap_or(0);
449 let read = reader.read(&mut buffer[..want])?;
450 if read == 0 {
451 return Err(io::Error::new(
452 io::ErrorKind::UnexpectedEof,
453 "cat-file ended inside a blob",
454 ));
455 }
456 if let Some(hasher) = hasher.as_mut() {
457 hasher.update(&buffer[..read]);
458 }
459 remaining -= read as u64;
460 }
461 let mut newline = [0_u8; 1];
462 reader.read_exact(&mut newline)?;
463 facts.push((
464 *index,
465 size,
466 hasher.map(|hasher| codewhale_runtime::hashing::hex_bytes(hasher.finalize())),
467 ));
468 }
469 Ok(facts)
470 }
471
472 #[cfg(test)]
473 mod tests {
474 use super::*;
475 use codewhale_runtime::test_support::{EnvVarGuard, TestEnvLock, lock_test_env};
476 use std::fs;
477
478 struct Home {
479 _vars: Vec<EnvVarGuard>,
480 _lock: TestEnvLock,
481 }
482
483 fn repo(root: &Path) -> (SnapshotRepo, Home) {
484 let lock = lock_test_env();
485 let vars = vec![
486 EnvVarGuard::set("HOME", root),
487 EnvVarGuard::set("USERPROFILE", root),
488 EnvVarGuard::set("CODEWHALE_HOME", root.join(".codewhale")),
489 ];
490 let workspace = root.join("workspace");
491 fs::create_dir_all(&workspace).unwrap();
492 let repo = SnapshotRepo::open_or_init_with_cap(&workspace, 0).expect("snapshot repo");
493 (
494 repo,
495 Home {
496 _vars: vars,
497 _lock: lock,
498 },
499 )
500 }
501
502 fn sha(bytes: &[u8]) -> Option<String> {
503 Some(codewhale_runtime::hashing::sha256_hex(bytes))
504 }
505
506 #[test]
507 fn delta_reports_created_updated_deleted_and_renamed_with_facts() {
508 let root = tempfile::tempdir().unwrap();
509 let (repo, _home) = repo(root.path());
510 let work = repo.work_tree().to_path_buf();
511 fs::write(work.join("keep.txt"), "same\n").unwrap();
512 fs::write(work.join("edit.txt"), "before\n").unwrap();
513 fs::write(work.join("gone.txt"), "bye\n").unwrap();
514 fs::write(
515 work.join("move-me.txt"),
516 "a long enough body to be detected as a rename\n",
517 )
518 .unwrap();
519 let pre = repo.snapshot("pre-turn:1").unwrap();
520
521 // What a shell command does: plain filesystem writes, no receipts.
522 fs::create_dir(work.join("site")).unwrap();
523 fs::write(work.join("site/index.html"), "<h1>hi</h1>\n").unwrap();
524 fs::write(work.join("edit.txt"), "after\n").unwrap();
525 fs::remove_file(work.join("gone.txt")).unwrap();
526 fs::rename(work.join("move-me.txt"), work.join("moved.txt")).unwrap();
527 let post = repo.snapshot("post-turn:1").unwrap();
528
529 let delta = repo.diff_snapshots(&pre, &post, 100).unwrap();
530 assert!(!delta.truncated);
531 assert_eq!(delta.omitted, 0);
532 let mut entries = delta.entries.clone();
533 entries.sort_by(|a, b| a.path.cmp(&b.path));
534 assert_eq!(
535 entries,
536 vec![
537 DeltaEntry {
538 path: "edit.txt".into(),
539 previous_path: None,
540 change: DeltaChange::Updated,
541 size: Some(6),
542 sha256: sha(b"after\n"),
543 },
544 DeltaEntry {
545 path: "gone.txt".into(),
546 previous_path: None,
547 change: DeltaChange::Deleted,
548 size: None,
549 sha256: None,
550 },
551 DeltaEntry {
552 path: "moved.txt".into(),
553 previous_path: Some("move-me.txt".into()),
554 change: DeltaChange::Renamed,
555 size: Some(46),
556 sha256: sha(b"a long enough body to be detected as a rename\n"),
557 },
558 DeltaEntry {
559 path: "site/index.html".into(),
560 previous_path: None,
561 change: DeltaChange::Created,
562 size: Some(12),
563 sha256: sha(b"<h1>hi</h1>\n"),
564 },
565 ]
566 );
567
568 // The pair is diffable in either direction and bounded.
569 let bounded = repo.diff_snapshots(&pre, &post, 2).unwrap();
570 assert_eq!(bounded.entries.len(), 2);
571 assert!(bounded.truncated);
572 assert_eq!(bounded.omitted, 2);
573
574 // Tracked probes distinguish "unchanged" from "invisible".
575 let probes = ["keep.txt", "gone.txt", "never.txt"].map(String::from);
576 assert_eq!(
577 repo.tracked_paths(&pre, &probes).unwrap(),
578 HashSet::from(["keep.txt".to_string(), "gone.txt".to_string()])
579 );
580 }
581
582 #[test]
583 fn oversized_blobs_report_size_without_a_revision() {
584 let root = tempfile::tempdir().unwrap();
585 let (repo, _home) = repo(root.path());
586 let work = repo.work_tree().to_path_buf();
587 fs::write(work.join("seed.txt"), "seed\n").unwrap();
588 let pre = repo.snapshot("pre-turn:1").unwrap();
589 let big = vec![b'z'; (DELTA_HASH_MAX_BYTES + 1) as usize];
590 fs::write(work.join("big.txt"), &big).unwrap();
591 fs::write(work.join("small.txt"), "small\n").unwrap();
592 let post = repo.snapshot("post-turn:1").unwrap();
593 let delta = repo.diff_snapshots(&pre, &post, 100).unwrap();
594 let big_entry = delta.entries.iter().find(|e| e.path == "big.txt").unwrap();
595 assert_eq!(big_entry.size, Some(DELTA_HASH_MAX_BYTES + 1));
596 assert_eq!(big_entry.sha256, None);
597 // A later blob in the same batch is still read correctly.
598 let small = delta
599 .entries
600 .iter()
601 .find(|e| e.path == "small.txt")
602 .unwrap();
603 assert_eq!(small.sha256, sha(b"small\n"));
604 }
605
606 #[test]
607 fn read_blob_returns_exact_snapshot_bytes_and_refuses_unsafe_paths() {
608 let root = tempfile::tempdir().unwrap();
609 let (repo, _home) = repo(root.path());
610 let work = repo.work_tree().to_path_buf();
611 fs::create_dir(work.join("dir")).unwrap();
612 fs::write(work.join("dir/a.txt"), b"exact \x00 bytes").unwrap();
613 let id = repo.snapshot("post-turn:1").unwrap();
614 fs::write(work.join("dir/a.txt"), b"changed later").unwrap();
615 assert_eq!(
616 repo.read_blob(&id, "dir/a.txt", 1024).unwrap().as_deref(),
617 Some(&b"exact \x00 bytes"[..])
618 );
619 assert_eq!(repo.read_blob(&id, "dir/missing.txt", 1024).unwrap(), None);
620 assert_eq!(
621 repo.read_blob(&id, "dir", 1024).unwrap(),
622 None,
623 "a tree is not a file"
624 );
625 assert_eq!(
626 repo.read_blob(&id, "dir/a.txt", 3).unwrap_err().kind(),
627 io::ErrorKind::FileTooLarge
628 );
629 for unsafe_path in [
630 "../escape",
631 "/etc/passwd",
632 "dir/../dir/a.txt",
633 ".git/config",
634 "",
635 ] {
636 assert_eq!(
637 repo.read_blob(&id, unsafe_path, 1024).unwrap_err().kind(),
638 io::ErrorKind::InvalidInput,
639 "{unsafe_path:?}"
640 );
641 }
642 }
643
644 #[test]
645 fn unsafe_and_non_utf8_paths_are_not_displayed() {
646 assert_eq!(safe_display(b"a/b.txt").as_deref(), Some("a/b.txt"));
647 assert_eq!(safe_display(b"../x"), None);
648 assert_eq!(safe_display(b"/abs"), None);
649 assert_eq!(safe_display(b".git/config"), None);
650 assert_eq!(safe_display(b"bad\xff.txt"), None);
651 assert_eq!(safe_display(b""), None);
652 }
653
654 #[test]
655 fn blob_facts_returns_an_error_for_a_missing_object() {
656 let root = tempfile::tempdir().unwrap();
657 let (repo, _home) = repo(root.path());
658 let missing = "1".repeat(40);
659 let err = repo
660 .blob_facts(&[(0, missing.clone()), (1, missing)])
661 .unwrap_err();
662 assert!(err.to_string().contains("unexpected header"), "{err}");
663 }
664
665 #[cfg(unix)]
666 #[test]
667 fn blob_facts_times_out_a_stalled_cat_file() {
668 let started = std::time::Instant::now();
669 let mut wedged = Command::new("sh");
670 wedged.args(["-c", "sleep 30"]);
671 let blobs = [(0, "1".repeat(40))];
672 let err = run_blob_facts(&mut wedged, &blobs, Duration::from_millis(250))
673 .expect_err("a stalled cat-file must time out");
674 assert_eq!(err.kind(), io::ErrorKind::TimedOut);
675 assert!(err.to_string().contains("timed out after"), "{err}");
676 assert!(started.elapsed() < Duration::from_secs(15));
677 }
678
679 #[cfg(unix)]
680 #[test]
681 fn blob_facts_times_out_a_cat_file_that_stalls_on_exit() {
682 let started = std::time::Instant::now();
683 let oid = "1".repeat(40);
684 let mut wedged = Command::new("sh");
685 wedged.args([
686 "-c",
687 &format!("cat >/dev/null; printf '{oid} blob 3\\nabc\\n'; sleep 30"),
688 ]);
689 let blobs = [(0, oid)];
690 let err = run_blob_facts(&mut wedged, &blobs, Duration::from_millis(250))
691 .expect_err("a cat-file that stalls after output must still time out");
692 assert_eq!(err.kind(), io::ErrorKind::TimedOut);
693 assert!(started.elapsed() < Duration::from_secs(15));
694 }
695 }
696
696 lines RUST