mod common;
use std::collections::HashSet;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use common::{TmpDir, ostree_available};
use ostrya::{
Checksum, CreateOptions, DiffChange, DiffEntry, FsckOptions, LockKind, ObjectName, ObjectType,
Ref, Repo, RepoMode,
};
use ostrya_rt::block_on;
fn ostree(args: &[&str]) -> String {
let output = Command::new("ostree")
.args(args)
.output()
.expect("run ostree");
assert!(
output.status.success(),
"ostree {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout).unwrap().trim().to_owned()
}
fn ostree_output(args: &[&str]) -> String {
let output = Command::new("ostree")
.args(args)
.output()
.expect("run ostree");
let mut s = String::from_utf8_lossy(&output.stdout).into_owned();
s.push_str(&String::from_utf8_lossy(&output.stderr));
s
}
fn write_tree(dir: &Path, name: &str, content: &[u8]) {
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join(name), content).unwrap();
std::fs::set_permissions(dir.join(name), std::fs::Permissions::from_mode(0o644)).unwrap();
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755)).unwrap();
}
fn tool_commit(repo: &Path, branch: &str, src: &Path) -> Checksum {
let repo_arg = format!("--repo={}", repo.display());
let hex = ostree(&[
&repo_arg,
"commit",
"-b",
branch,
"-s",
"c",
"--owner-uid=0",
"--owner-gid=0",
"--no-xattrs",
"--timestamp=@1700000000",
src.to_str().unwrap(),
]);
Checksum::from_hex(&hex).unwrap()
}
fn tool_init(repo: &Path) {
ostree(&[
&format!("--repo={}", repo.display()),
"init",
"--mode=archive-z2",
]);
}
fn copy_tree(from: &Path, to: &Path) {
let status = Command::new("cp")
.args(["-a"])
.arg(from)
.arg(to)
.status()
.expect("run cp");
assert!(status.success(), "cp -a {from:?} {to:?} failed");
}
fn disk_object_paths(repo: &Path) -> HashSet<String> {
let mut out = HashSet::new();
let objects = repo.join("objects");
for fanout in std::fs::read_dir(&objects).unwrap() {
let fanout = fanout.unwrap().path();
if !fanout.is_dir() {
continue;
}
let prefix = fanout.file_name().unwrap().to_string_lossy().into_owned();
for entry in std::fs::read_dir(&fanout).unwrap() {
let name = entry.unwrap().file_name().to_string_lossy().into_owned();
out.insert(format!("{prefix}/{name}"));
}
}
out
}
fn build_three_commit_repo(base: &Path, repo: &Path) -> [Checksum; 3] {
tool_init(repo);
let mut commits = Vec::new();
for (i, content) in ["one\n", "two\n", "three\n"].iter().enumerate() {
let src = base.join(format!("tree{i}"));
write_tree(&src.join("sub"), "nested.txt", b"nested\n");
write_tree(&src, "a.txt", content.as_bytes());
commits.push(tool_commit(repo, "m", &src));
}
[commits[0], commits[1], commits[2]]
}
#[test]
fn list_objects_matches_the_disk() {
if !ostree_available() {
eprintln!("skipping list_objects_matches_the_disk: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-list");
let repo = tmp.path().join("repo");
build_three_commit_repo(tmp.path(), &repo);
block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let listed = handle.list_objects().await.unwrap();
let listed_paths: HashSet<String> = listed
.iter()
.map(|o| o.loose_path(RepoMode::Archive))
.collect();
assert_eq!(
listed_paths,
disk_object_paths(&repo),
"list_objects matches the loose objects on disk"
);
});
}
#[test]
fn traverse_commit_honors_depth() {
if !ostree_available() {
eprintln!("skipping traverse_commit_honors_depth: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-traverse");
let repo = tmp.path().join("repo");
let [c1, c2, c3] = build_three_commit_repo(tmp.path(), &repo);
block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let full = handle.traverse_commit(&c3, -1).await.unwrap();
for c in [c1, c2, c3] {
assert!(
full.contains(&ObjectName::new(c, ObjectType::Commit)),
"depth -1 reaches commit {c}"
);
}
let head_only = handle.traverse_commit(&c3, 0).await.unwrap();
assert!(head_only.contains(&ObjectName::new(c3, ObjectType::Commit)));
assert!(!head_only.contains(&ObjectName::new(c2, ObjectType::Commit)));
assert!(!head_only.contains(&ObjectName::new(c1, ObjectType::Commit)));
let one = handle.traverse_commit(&c3, 1).await.unwrap();
assert!(one.contains(&ObjectName::new(c3, ObjectType::Commit)));
assert!(one.contains(&ObjectName::new(c2, ObjectType::Commit)));
assert!(!one.contains(&ObjectName::new(c1, ObjectType::Commit)));
let bogus = Checksum::from_hex(&"ab".repeat(32)).unwrap();
assert!(handle.traverse_commit(&bogus, -1).await.is_err());
});
}
#[test]
fn traverse_reachable_depth_is_order_independent() {
let tmp = TmpDir::new("maint-traverse-order");
block_on(async {
let base = tmp.path();
write_tree(&base.join("t0"), "a.txt", b"zero\n");
write_tree(&base.join("t1"), "a.txt", b"one\n");
write_tree(&base.join("t2"), "a.txt", b"two\n");
write_tree(&base.join("t3"), "a.txt", b"three\n");
let repo_dir = base.join("repo");
let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let c0 = library_commit(&repo, base, "t0", None).await;
let c1 = library_commit(&repo, base, "t1", Some(c0)).await;
let c2 = library_commit(&repo, base, "t2", Some(c1)).await;
let c3 = library_commit(&repo, base, "t3", Some(c2)).await;
let forward = repo.traverse_reachable([c3, c2], 1).await.unwrap();
let reverse = repo.traverse_reachable([c2, c3], 1).await.unwrap();
assert_eq!(
forward, reverse,
"the reachable set must not depend on root order"
);
assert!(
forward.contains(&ObjectName::new(c1, ObjectType::Commit)),
"c1 is within depth 1 of the c2 root, so it is reachable"
);
assert!(
!forward.contains(&ObjectName::new(c0, ObjectType::Commit)),
"c0 is beyond depth 1 from every root"
);
});
}
fn parse_prune_counts(output: &str) -> (usize, u64) {
let line = output
.lines()
.find(|l| l.contains("Deleted") || l.contains("Would delete"))
.expect("a deletion line in prune output");
let tokens: Vec<&str> = line.split_whitespace().collect();
let objects = tokens
.iter()
.position(|t| t.starts_with("object"))
.map(|i| tokens[i - 1].parse().unwrap())
.expect("object count in prune output");
let bytes = tokens
.iter()
.position(|t| t.starts_with("byte"))
.map(|i| tokens[i - 1].parse().unwrap())
.expect("byte count in prune output");
(objects, bytes)
}
#[test]
fn prune_matches_the_tool_refs_only_depth_zero() {
if !ostree_available() {
eprintln!("skipping prune_matches_the_tool_refs_only_depth_zero: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-prune");
let tool_repo = tmp.path().join("tool");
build_three_commit_repo(tmp.path(), &tool_repo);
let port_repo = tmp.path().join("port");
copy_tree(&tool_repo, &port_repo);
let out = ostree_output(&[
&format!("--repo={}", tool_repo.display()),
"prune",
"--refs-only",
"--depth=0",
]);
let (tool_objects, tool_bytes) = parse_prune_counts(&out);
assert!(tool_objects > 0, "the tool prunes history at depth 0");
let stats = block_on(async {
let handle = Repo::open(&port_repo).await.unwrap();
let opts = ostrya::PruneOptions {
refs_only: true,
depth: 0,
..ostrya::PruneOptions::new()
};
handle.prune(&opts).await.unwrap()
});
assert_eq!(
stats.pruned_objects, tool_objects,
"port and tool prune the same number of objects"
);
assert_eq!(
stats.freed_bytes, tool_bytes,
"port and tool free the same number of bytes"
);
assert_eq!(
disk_object_paths(&port_repo),
disk_object_paths(&tool_repo),
"the surviving object sets are identical"
);
let fsck = ostree_output(&[&format!("--repo={}", port_repo.display()), "fsck"]);
assert!(
fsck.contains("no errors found"),
"tool fsck accepts the port-pruned repo: {fsck}"
);
}
#[test]
fn prune_default_keeps_everything() {
if !ostree_available() {
eprintln!("skipping prune_default_keeps_everything: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-prune-default");
let repo = tmp.path().join("repo");
build_three_commit_repo(tmp.path(), &repo);
let before = disk_object_paths(&repo);
let stats = block_on(async {
let handle = Repo::open(&repo).await.unwrap();
handle.prune(&ostrya::PruneOptions::new()).await.unwrap()
});
assert_eq!(stats.pruned_objects, 0, "default prune removes nothing");
assert_eq!(stats.total_objects, before.len());
assert_eq!(disk_object_paths(&repo), before, "no objects removed");
}
#[test]
fn prune_no_prune_is_a_dry_run() {
if !ostree_available() {
eprintln!("skipping prune_no_prune_is_a_dry_run: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-prune-dry");
let repo = tmp.path().join("repo");
build_three_commit_repo(tmp.path(), &repo);
let before = disk_object_paths(&repo);
let stats = block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let opts = ostrya::PruneOptions {
refs_only: true,
depth: 0,
no_prune: true,
..ostrya::PruneOptions::new()
};
handle.prune(&opts).await.unwrap()
});
assert!(
stats.pruned_objects > 0,
"the dry run reports would-be deletions"
);
assert_eq!(
disk_object_paths(&repo),
before,
"no_prune deletes nothing on disk"
);
}
#[test]
fn prune_delete_commit_removes_it_and_orphans() {
if !ostree_available() {
eprintln!("skipping prune_delete_commit_removes_it_and_orphans: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-delete-commit");
let repo = tmp.path().join("repo");
let [c1, _c2, _c3] = build_three_commit_repo(tmp.path(), &repo);
block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let opts = ostrya::PruneOptions {
delete_commit: Some(c1),
..ostrya::PruneOptions::new()
};
handle.prune(&opts).await.unwrap();
assert!(
!handle.has_object(ObjectType::Commit, &c1).await.unwrap(),
"the deleted commit object is removed"
);
});
let fsck = ostree_output(&[&format!("--repo={}", repo.display()), "fsck"]);
assert!(
fsck.contains("no errors found"),
"tool fsck accepts the repo after delete-commit: {fsck}"
);
}
#[test]
fn prune_refuses_to_delete_a_referenced_commit() {
if !ostree_available() {
eprintln!("skipping prune_refuses_to_delete_a_referenced_commit: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-delete-ref");
let repo = tmp.path().join("repo");
let [_c1, _c2, c3] = build_three_commit_repo(tmp.path(), &repo);
block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let opts = ostrya::PruneOptions {
delete_commit: Some(c3), ..ostrya::PruneOptions::new()
};
assert!(
handle.prune(&opts).await.is_err(),
"deleting a ref's target is refused"
);
});
}
const FOREIGN_LOCK_REPO: &str = "OSTRYA_FOREIGN_LOCK_REPO";
const LOCK_TIMEOUT_SECS: u64 = 1;
const READY_TIMEOUT: Duration = Duration::from_secs(10);
const READY_POLL: Duration = Duration::from_millis(20);
struct ChildGuard(std::process::Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn set_lock_timeout(repo: &Path, secs: u64) {
let config = repo.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(&format!("lock-timeout-secs={secs}\n"));
std::fs::write(&config, text).unwrap();
}
fn wait_for_marker(marker: &Path) -> bool {
wait_until(|| marker.exists())
}
fn wait_for_tool_staging(repo: &Path) -> bool {
wait_until(|| {
let Ok(entries) = std::fs::read_dir(repo.join("tmp")) else {
return false;
};
entries.flatten().any(|entry| {
entry
.file_name()
.to_string_lossy()
.starts_with(TOOL_STAGING_PREFIX)
})
})
}
const TOOL_STAGING_PREFIX: &str = "staging-";
fn wait_until(mut ready: impl FnMut() -> bool) -> bool {
let deadline = Instant::now() + READY_TIMEOUT;
loop {
if ready() {
return true;
}
if Instant::now() >= deadline {
return false;
}
std::thread::sleep(READY_POLL);
}
}
#[test]
fn the_tool_prune_waits_on_a_lock_the_port_holds() {
if !ostree_available() {
eprintln!("skipping the_tool_prune_waits_on_a_lock_the_port_holds: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-lock-tool");
let repo = tmp.path().join("repo");
build_three_commit_repo(tmp.path(), &repo);
set_lock_timeout(&repo, LOCK_TIMEOUT_SECS);
let before = disk_object_paths(&repo);
block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let txn = handle
.transaction_with_lock(LockKind::Exclusive)
.await
.unwrap();
let started = Instant::now();
let out = Command::new("ostree")
.args([
&format!("--repo={}", repo.display()),
"prune",
"--refs-only",
"--depth=0",
])
.output()
.expect("run ostree");
let waited = started.elapsed();
assert!(
!out.status.success(),
"the tool's prune fails while the port holds the lock"
);
assert!(
waited >= Duration::from_secs(LOCK_TIMEOUT_SECS),
"the tool ran for {waited:?}, short of the configured timeout, so it \
did not wait on the lock"
);
txn.abort().await.unwrap();
});
assert_eq!(
disk_object_paths(&repo),
before,
"the refused tool prune removed no object"
);
}
#[test]
fn prune_waits_while_the_tool_holds_the_repository() {
if !ostree_available() {
eprintln!("skipping prune_waits_while_the_tool_holds_the_repository: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-lock-port");
let repo = tmp.path().join("repo");
build_three_commit_repo(tmp.path(), &repo);
set_lock_timeout(&repo, LOCK_TIMEOUT_SECS);
let before = disk_object_paths(&repo);
let holder = ChildGuard(
Command::new("ostree")
.args([
&format!("--repo={}", repo.display()),
"commit",
"-b",
"held",
"-s",
"held",
"--tree=tar=-",
])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn the tool"),
);
assert!(
wait_for_tool_staging(&repo),
"the tool never took the repository"
);
let (err, waited) = block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let started = Instant::now();
let err = handle
.prune(&ostrya::PruneOptions::new())
.await
.expect_err("a prune fails while the tool holds the repository");
(err, started.elapsed())
});
assert!(
matches!(err, ostrya::Error::LockTimeout { secs: 1 }),
"the contended prune reports the configured timeout: {err:?}"
);
assert!(
waited >= Duration::from_secs(LOCK_TIMEOUT_SECS),
"the prune returned after {waited:?}, short of the configured timeout"
);
drop(holder);
assert_eq!(
disk_object_paths(&repo),
before,
"the refused prune removed no object"
);
}
#[test]
fn prune_waits_on_a_foreign_lock_holder() {
let tmp = TmpDir::new("maint-lock-foreign");
let repo = tmp.path().join("repo");
block_on(Repo::create(
&repo,
ostrya::CreateOptions::new(RepoMode::Archive),
))
.unwrap();
set_lock_timeout(&repo, LOCK_TIMEOUT_SECS);
let marker = repo.join(FOREIGN_LOCK_MARKER);
let holder = ChildGuard(
Command::new(std::env::current_exe().unwrap())
.args([
"foreign_lock_holder_subprocess",
"--exact",
"--ignored",
"--nocapture",
])
.env(FOREIGN_LOCK_REPO, &repo)
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.expect("spawn the foreign lock holder"),
);
assert!(wait_for_marker(&marker), "the holder never took the lock");
let (err, waited) = block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let started = Instant::now();
let err = handle
.prune(&ostrya::PruneOptions::new())
.await
.expect_err("a prune under a foreign lock fails");
(err, started.elapsed())
});
assert!(
matches!(err, ostrya::Error::LockTimeout { secs: 1 }),
"the contended prune reports the configured timeout: {err:?}"
);
assert!(
waited >= Duration::from_secs(LOCK_TIMEOUT_SECS),
"the prune returned after {waited:?}, short of the configured timeout"
);
drop(holder);
}
const FOREIGN_LOCK_MARKER: &str = ".foreign-held";
#[test]
#[ignore = "helper process for prune_waits_on_a_foreign_lock_holder"]
fn foreign_lock_holder_subprocess() {
use rustix::fs::{FlockOperation, Mode, OFlags};
use std::io::Read;
let Ok(repo) = std::env::var(FOREIGN_LOCK_REPO) else {
return;
};
let repo = Path::new(&repo);
let fd = rustix::fs::open(
repo.join(".lock"),
OFlags::RDWR | OFlags::CREATE,
Mode::from_raw_mode(0o660),
)
.expect("open the lock file");
rustix::fs::fcntl_lock(&fd, FlockOperation::LockExclusive).expect("take the record lock");
std::fs::write(repo.join(FOREIGN_LOCK_MARKER), b"1").expect("write the readiness marker");
let mut sink = Vec::new();
let _ = std::io::stdin().read_to_end(&mut sink);
}
async fn build_library_repo(base: &Path) -> (Repo, Checksum) {
use ostrya::{CommitModifier, CommitModifierFlags, CommitOptions, MutableTree};
use std::os::fd::AsFd;
let src = base.join("src");
write_tree(&src.join("sub"), "nested.txt", b"nested\n");
write_tree(&src, "hello.txt", b"hello ostree\n");
std::os::unix::fs::symlink("hello.txt", src.join("link")).unwrap();
let repo_dir = base.join("repo");
let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
let mut modifier = CommitModifier::new(
CommitModifierFlags::CANONICAL_PERMISSIONS | CommitModifierFlags::SKIP_XATTRS,
);
let mut mtree = MutableTree::new();
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(
dfd.as_fd(),
Path::new("src"),
&mut mtree,
Some(&mut modifier),
)
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
subject: Some("c".to_owned()),
timestamp: Some(1_700_000_000),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref(&Ref::local("main"), Some(&commit));
txn.commit().await.unwrap();
(repo, commit)
}
async fn library_commit(repo: &Repo, base: &Path, rel: &str, parent: Option<Checksum>) -> Checksum {
use ostrya::{CommitModifier, CommitModifierFlags, CommitOptions, MutableTree};
use std::os::fd::AsFd;
let txn = repo.transaction().await.unwrap();
let mut modifier = CommitModifier::new(
CommitModifierFlags::CANONICAL_PERMISSIONS | CommitModifierFlags::SKIP_XATTRS,
);
let mut mtree = MutableTree::new();
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(rel), &mut mtree, Some(&mut modifier))
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
parent,
subject: Some("c".to_owned()),
timestamp: Some(1_700_000_000),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref(&Ref::local("main"), Some(&commit));
txn.commit().await.unwrap();
commit
}
#[test]
fn fsck_passes_on_a_healthy_repo() {
let tmp = TmpDir::new("maint-fsck-ok");
block_on(async {
let (repo, commit) = build_library_repo(tmp.path()).await;
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "healthy fsck: {:?}", report.errors);
assert_eq!(report.commits_checked, 1);
let reachable = repo.traverse_commit(&commit, -1).await.unwrap();
assert_eq!(report.objects_checked, reachable.len());
let detached = tmp
.path()
.join("repo/objects")
.join(ObjectName::new(commit, ObjectType::CommitMeta).loose_path(RepoMode::Archive));
std::fs::write(&detached, [0x61, 0x7b, 0x73, 0x76, 0x7d, 0x00]).unwrap();
let again = repo.fsck(&FsckOptions::new()).await.unwrap();
assert!(again.is_ok(), "healthy fsck: {:?}", again.errors);
assert_eq!(again.objects_checked, reachable.len());
});
}
#[test]
fn fsck_and_prune_refuse_a_symlinked_remote_or_mirror_directory() {
for (link, rel) in [
("refs/remotes/o", "../stash/o"),
("refs/mirrors/org.example.X", "../stash/org.example.X"),
] {
let tmp = TmpDir::new("maint-top-link");
block_on(async {
let (repo, commit) = build_library_repo(tmp.path()).await;
let objects = repo.list_objects().await.unwrap().len();
let dir = tmp.path().join("repo");
let parent = dir.join(link).parent().unwrap().to_owned();
let stashed = parent.join(rel);
std::fs::create_dir_all(&parent).unwrap();
std::fs::create_dir_all(&stashed).unwrap();
std::fs::rename(dir.join("refs/heads/main"), stashed.join("main")).unwrap();
std::os::unix::fs::symlink(rel, dir.join(link)).unwrap();
let expected = format!("{link} passes through a symlink");
let err = repo.fsck(&FsckOptions::new()).await.unwrap_err();
assert!(
matches!(&err, ostrya::Error::InvalidFormat(m) if m.starts_with(&expected)),
"{link}: fsck gave {err:?}"
);
for no_prune in [true, false] {
let mut opts = ostrya::PruneOptions::new();
opts.no_prune = no_prune;
let err = repo.prune(&opts).await.unwrap_err();
assert!(
matches!(&err, ostrya::Error::InvalidFormat(m) if m.starts_with(&expected)),
"{link}: prune gave {err:?}"
);
}
assert!(repo.load_commit(&commit).await.is_ok(), "{link}");
assert!(stashed.join("main").is_file(), "{link}");
assert_eq!(repo.list_objects().await.unwrap().len(), objects, "{link}");
});
}
}
#[test]
fn fsck_and_prune_skip_a_ref_symlink_naming_a_directory() {
let tmp = TmpDir::new("maint-fsck-dirlink");
block_on(async {
let (repo, commit) = build_library_repo(tmp.path()).await;
let heads = tmp.path().join("repo/refs/heads");
std::os::unix::fs::symlink(".", heads.join("selfdir")).unwrap();
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert!(report.errors.is_empty(), "{report:?}");
repo.prune(&ostrya::PruneOptions::new()).await.unwrap();
assert!(repo.load_commit(&commit).await.is_ok());
});
}
#[test]
fn fsck_and_prune_skip_a_ref_entry_that_is_a_fifo() {
let tmp = TmpDir::new("maint-fsck-fifo");
let (repo, commit) = block_on(build_library_repo(tmp.path()));
let fifos: Vec<_> = [
"refs/heads/fifo",
"refs/remotes/o/fifo",
"refs/mirrors/org.example.Other/fifo",
]
.iter()
.map(|rel| {
let fifo = tmp.path().join("repo").join(rel);
std::fs::create_dir_all(fifo.parent().unwrap()).unwrap();
rustix::fs::mknodat(
rustix::fs::CWD,
&fifo,
rustix::fs::FileType::Fifo,
rustix::fs::Mode::from_raw_mode(0o644),
0,
)
.unwrap();
fifo
})
.collect();
let (tx, rx) = std::sync::mpsc::channel();
let handle = repo.clone();
std::thread::spawn(move || {
let _ = tx.send(block_on(async {
let opts = ostrya::PruneOptions {
refs_only: true,
..ostrya::PruneOptions::new()
};
let pruned = handle.prune(&opts).await;
let report = handle.fsck(&FsckOptions::new()).await;
(pruned, report)
}));
});
let timeout = Duration::from_secs(10);
let Ok((pruned, report)) = rx.recv_timeout(timeout) else {
for fifo in &fifos {
let _ = rustix::fs::open(
fifo,
rustix::fs::OFlags::WRONLY
| rustix::fs::OFlags::NONBLOCK
| rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
);
}
let _ = rx.recv_timeout(timeout);
panic!("the open waits on a FIFO");
};
assert_eq!(pruned.unwrap().pruned_objects, 0);
let report = report.unwrap();
assert!(report.is_ok(), "fsck: {:?}", report.errors);
assert_eq!(report.commits_checked, 1);
assert!(block_on(repo.has_object(ObjectType::Commit, &commit)).unwrap());
}
#[test]
fn fsck_detects_content_corruption() {
let tmp = TmpDir::new("maint-fsck-content");
block_on(async {
let (repo, _commit) = build_library_repo(tmp.path()).await;
let repo_dir = tmp.path().join("repo");
let filez = find_object(&repo_dir, "filez").expect("a .filez object");
std::fs::write(&filez, b"corrupted payload bytes").unwrap();
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert!(!report.is_ok(), "corruption is detected");
assert!(
report
.errors
.iter()
.any(|e| e.object.ty == ObjectType::File),
"a content-object fault is reported: {:?}",
report.errors
);
});
}
#[test]
fn fsck_detects_metadata_corruption() {
let tmp = TmpDir::new("maint-fsck-meta");
block_on(async {
let (repo, _commit) = build_library_repo(tmp.path()).await;
let repo_dir = tmp.path().join("repo");
let dirtree = find_object(&repo_dir, "dirtree").expect("a .dirtree object");
let mut bytes = std::fs::read(&dirtree).unwrap();
bytes.push(0);
std::fs::write(&dirtree, &bytes).unwrap();
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert!(
report.errors.iter().any(|e| matches!(
e.kind,
ostrya::FsckErrorKind::ChecksumMismatch { .. }
) && e.object.ty == ObjectType::DirTree),
"a dirtree checksum mismatch is reported: {:?}",
report.errors
);
});
}
#[test]
fn fsck_detects_missing_object_and_marks_partial() {
let tmp = TmpDir::new("maint-fsck-missing");
block_on(async {
let (repo, commit) = build_library_repo(tmp.path()).await;
let repo_dir = tmp.path().join("repo");
let filez = find_object(&repo_dir, "filez").expect("a .filez object");
std::fs::remove_file(&filez).unwrap();
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert!(
report
.errors
.iter()
.any(|e| matches!(e.kind, ostrya::FsckErrorKind::Missing)),
"a missing object is reported: {:?}",
report.errors
);
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
ostrya::CommitState::Partial,
"the commit is marked partial after a missing object"
);
let marker = repo_dir.join(format!("state/{}.commitpartial", commit.to_hex()));
assert_eq!(std::fs::read(&marker).unwrap(), vec![0x66]);
});
}
#[test]
fn fsck_mark_partial_can_be_disabled() {
let tmp = TmpDir::new("maint-fsck-nomark");
block_on(async {
let (repo, commit) = build_library_repo(tmp.path()).await;
let repo_dir = tmp.path().join("repo");
std::fs::remove_file(find_object(&repo_dir, "filez").unwrap()).unwrap();
let report = repo
.fsck(&FsckOptions {
mark_partial: false,
..FsckOptions::new()
})
.await
.unwrap();
assert!(!report.is_ok());
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
ostrya::CommitState::Normal,
"no marker is written when mark_partial is off"
);
});
}
#[test]
fn fsck_marks_every_commit_sharing_a_missing_subtree() {
let tmp = TmpDir::new("maint-fsck-shared");
block_on(async {
let base = tmp.path();
write_tree(&base.join("one/sub"), "nested.txt", b"nested\n");
write_tree(&base.join("one"), "a.txt", b"one\n");
write_tree(&base.join("two/sub"), "nested.txt", b"nested\n");
write_tree(&base.join("two"), "a.txt", b"two\n");
let repo_dir = base.join("repo");
let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let c1 = library_commit(&repo, base, "one", None).await;
let c2 = library_commit(&repo, base, "two", Some(c1)).await;
let r1 = repo.traverse_commit(&c1, 0).await.unwrap();
let r2 = repo.traverse_commit(&c2, 0).await.unwrap();
let shared = r1
.intersection(&r2)
.find(|o| o.ty == ObjectType::File)
.copied()
.expect("a file object shared by both commits");
std::fs::remove_file(
repo_dir
.join("objects")
.join(shared.loose_path(RepoMode::Archive)),
)
.unwrap();
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert!(!report.is_ok(), "the missing shared object is detected");
assert_eq!(
repo.commit_state(&c1).await.unwrap(),
ostrya::CommitState::Partial,
"the first commit is marked partial"
);
assert_eq!(
repo.commit_state(&c2).await.unwrap(),
ostrya::CommitState::Partial,
"the second commit is marked partial"
);
});
}
#[test]
fn fsck_marks_commits_sharing_a_missing_file_via_distinct_dirs() {
let tmp = TmpDir::new("maint-fsck-shared-file");
block_on(async {
let base = tmp.path();
write_tree(&base.join("one/dir"), "shared.txt", b"data\n");
write_tree(&base.join("one/dir"), "other.txt", b"a\n");
write_tree(&base.join("two/dir"), "shared.txt", b"data\n");
write_tree(&base.join("two/dir"), "other.txt", b"b\n");
let repo_dir = base.join("repo");
let repo = Repo::create(&repo_dir, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let c1 = library_commit(&repo, base, "one", None).await;
let c2 = library_commit(&repo, base, "two", Some(c1)).await;
let r1 = repo.traverse_commit(&c1, 0).await.unwrap();
let r2 = repo.traverse_commit(&c2, 0).await.unwrap();
let shared = r1
.intersection(&r2)
.find(|o| o.ty == ObjectType::File)
.copied()
.expect("a file object shared by both commits");
std::fs::remove_file(
repo_dir
.join("objects")
.join(shared.loose_path(RepoMode::Archive)),
)
.unwrap();
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert_eq!(
report
.errors
.iter()
.filter(|e| matches!(e.kind, ostrya::FsckErrorKind::Missing))
.count(),
1,
"the missing file is reported once: {:?}",
report.errors
);
assert_eq!(
repo.commit_state(&c1).await.unwrap(),
ostrya::CommitState::Partial,
"the first commit is marked partial"
);
assert_eq!(
repo.commit_state(&c2).await.unwrap(),
ostrya::CommitState::Partial,
"the second commit is marked partial"
);
});
}
async fn build_two_commit_repo(base: &Path, mode: RepoMode) -> (Repo, Checksum, Checksum) {
write_tree(&base.join("one"), "a.txt", b"one\n");
write_tree(&base.join("two"), "a.txt", b"two\n");
let repo = Repo::create(&base.join("repo"), CreateOptions::new(mode))
.await
.unwrap();
let c1 = library_commit(&repo, base, "one", None).await;
let c2 = library_commit(&repo, base, "two", Some(c1)).await;
(repo, c1, c2)
}
async fn commit_with_metadata(
repo: &Repo,
base: &Path,
rel: &str,
metadata: ostrya::Value,
) -> Checksum {
use ostrya::{CommitModifier, CommitModifierFlags, CommitOptions, MutableTree};
use std::os::fd::AsFd;
let txn = repo.transaction().await.unwrap();
let mut modifier = CommitModifier::new(
CommitModifierFlags::CANONICAL_PERMISSIONS | CommitModifierFlags::SKIP_XATTRS,
);
let mut mtree = MutableTree::new();
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(rel), &mut mtree, Some(&mut modifier))
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
subject: Some("c".to_owned()),
timestamp: Some(1_700_000_000),
metadata: Some(metadata),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.commit().await.unwrap();
commit
}
fn binding_metadata(refs: &[&str], collection: Option<&str>) -> ostrya::Value {
let names: Vec<String> = refs.iter().map(|r| (*r).to_owned()).collect();
let mut builder = ostrya::DictBuilder::new();
builder.insert_strv("ostree.ref-binding", &names);
if let Some(collection) = collection {
builder.insert_str("ostree.collection-binding", collection);
}
builder.build()
}
#[test]
fn fsck_skips_a_commit_already_marked_partial() {
let tmp = TmpDir::new("maint-fsck-skip-partial");
block_on(async {
let base = tmp.path();
let (repo, _c1, c2) = build_two_commit_repo(base, RepoMode::Archive).await;
let both = repo.fsck(&FsckOptions::new()).await.unwrap();
assert_eq!(both.commits_checked, 2);
assert_eq!(both.commits_partial, 0);
assert!(both.is_ok());
let marker = base.join(format!("repo/state/{}.commitpartial", c2.to_hex()));
std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
std::fs::write(&marker, [0x66]).unwrap();
let skipped = repo.fsck(&FsckOptions::new()).await.unwrap();
assert_eq!(skipped.commits_checked, 1, "the partial commit is skipped");
assert_eq!(skipped.commits_partial, 1);
assert!(
skipped.objects_checked < both.objects_checked,
"the skipped commit's objects leave the denominator: {} against {}",
skipped.objects_checked,
both.objects_checked
);
assert!(!skipped.is_ok(), "a skipped commit is not a clean run");
});
}
#[test]
fn fsck_delete_unlinks_and_marks() {
let tmp = TmpDir::new("maint-fsck-delete");
block_on(async {
let base = tmp.path();
let (repo, c1, c2) = build_two_commit_repo(base, RepoMode::Archive).await;
let repo_dir = base.join("repo");
let mut corrupted = Vec::new();
for name in [c1, c2] {
let reachable = repo.traverse_commit(&name, 0).await.unwrap();
let object = reachable
.iter()
.find(|o| o.ty == ObjectType::File)
.copied()
.expect("a content object");
let path = repo_dir
.join("objects")
.join(object.loose_path(RepoMode::Archive));
std::fs::write(&path, b"not the object these bytes are named for").unwrap();
corrupted.push(object);
}
let plain = repo.fsck(&FsckOptions::new()).await.unwrap();
assert_eq!(
plain.errors.len(),
2,
"the walk carries past the first fault: {:?}",
plain.errors
);
assert!(plain.deleted.is_empty() && plain.marked_partial.is_empty());
let report = repo
.fsck(&FsckOptions {
delete: true,
..FsckOptions::new()
})
.await
.unwrap();
assert_eq!(
report.errors.len(),
2,
"`delete` continues past the first fault: {:?}",
report.errors
);
for object in &corrupted {
assert!(report.deleted.contains(object), "{object} was unlinked");
assert!(
!repo_dir
.join("objects")
.join(object.loose_path(RepoMode::Archive))
.exists(),
"{object} is gone from the store"
);
}
assert_eq!(report.marked_partial, {
let mut expected = vec![c1, c2];
expected.sort();
expected
});
for commit in [c1, c2] {
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
ostrya::CommitState::Partial
);
}
});
}
fn is_root() -> bool {
rustix::process::geteuid().is_root()
}
#[test]
fn fsck_stops_at_an_unreadable_object() {
use std::os::unix::fs::PermissionsExt;
if is_root() {
eprintln!("skipping: root reads a file of mode 0000");
return;
}
let tmp = TmpDir::new("maint-fsck-unreadable");
block_on(async {
let base = tmp.path();
let (repo, c1, c2) = build_two_commit_repo(base, RepoMode::BareUser).await;
let repo_dir = base.join("repo");
let reachable = repo.traverse_commit(&c2, 0).await.unwrap();
let mut objects: Vec<ObjectName> =
[ObjectType::File, ObjectType::DirMeta, ObjectType::DirTree]
.into_iter()
.map(|ty| reachable.iter().find(|o| o.ty == ty).copied().unwrap())
.collect();
objects.push(ObjectName::new(c2, ObjectType::Commit));
for object in objects {
let ty = object.ty;
let relative = Path::new("objects").join(object.loose_path(RepoMode::BareUser));
let path = repo_dir.join(&relative);
let permissions = std::fs::metadata(&path).unwrap().permissions();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
for delete in [false, true] {
let opts = FsckOptions {
delete,
..FsckOptions::new()
};
match repo.fsck(&opts).await {
Err(ostrya::Error::Io(e)) => {
assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(
e.to_string(),
format!("{}: Permission denied", relative.display())
);
}
other => panic!("{ty:?}, delete {delete}: {other:?}"),
}
assert!(path.exists(), "{ty:?}, delete {delete}: the object stays");
for commit in [c1, c2] {
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
ostrya::CommitState::Normal,
"{ty:?}, delete {delete}"
);
}
}
std::fs::set_permissions(&path, permissions).unwrap();
}
});
}
#[test]
fn fsck_add_tombstones_replaces_the_commit() {
for mode in [
RepoMode::BareUser,
RepoMode::BareUserOnly,
RepoMode::Archive,
] {
let tmp = TmpDir::new("maint-fsck-tombstone");
block_on(async {
let base = tmp.path();
let (repo, c1, c2) = build_two_commit_repo(base, mode).await;
let repo_dir = base.join("repo");
let parent = repo_dir
.join("objects")
.join(ObjectName::new(c1, ObjectType::Commit).loose_path(mode));
std::fs::remove_file(&parent).unwrap();
let report = repo
.fsck(&FsckOptions {
add_tombstones: true,
..FsckOptions::new()
})
.await
.unwrap();
assert_eq!(report.tombstoned, vec![c2], "the child is tombstoned");
let commit_path = repo_dir
.join("objects")
.join(ObjectName::new(c2, ObjectType::Commit).loose_path(mode));
assert!(!commit_path.exists(), "the child commit object is gone");
let tombstone = repo_dir
.join("objects")
.join(ObjectName::new(c2, ObjectType::TombstoneCommit).loose_path(mode));
let bytes = std::fs::read(&tombstone).unwrap();
assert_eq!(bytes.len(), 78, "the marker is 78 bytes in {mode:?}");
let mut expected = b"commit\0\0".to_vec();
expected.extend_from_slice(c2.to_hex().as_bytes());
assert!(
bytes.starts_with(&expected),
"the marker names the commit in {mode:?}"
);
let meta = std::fs::metadata(&tombstone).unwrap();
assert_eq!(
std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o777,
0o644,
"the marker's permission bits in {mode:?}"
);
});
}
}
#[test]
fn a_symlink_at_tmp_fails_each_detached_metadata_write() {
let tmp = TmpDir::new("maint-tmp-symlink");
block_on(async {
let base = tmp.path();
let mode = RepoMode::BareUser;
let (repo, c1, c2) = build_two_commit_repo(base, mode).await;
repo.write_commit_detached_metadata(&c2, None)
.await
.unwrap();
drop(repo);
let repo_dir = base.join("repo");
let objects = repo_dir.join("objects");
let meta = objects.join(ObjectName::new(c2, ObjectType::CommitMeta).loose_path(mode));
let outside = base.join("outside");
std::fs::create_dir(&outside).unwrap();
std::fs::remove_dir_all(repo_dir.join("tmp")).unwrap();
std::os::unix::fs::symlink(&outside, repo_dir.join("tmp")).unwrap();
std::fs::remove_file(
objects.join(ObjectName::new(c1, ObjectType::Commit).loose_path(mode)),
)
.unwrap();
let repo = Repo::open(&repo_dir).await.unwrap();
let dict = ostrya::Value::Array(Vec::new());
let results = [
repo.write_commit_detached_metadata(&c2, Some(&dict)).await,
repo.sign_commit(&c2, &ostrya::DummySigner::new(b"key".to_vec()))
.await,
repo.fsck(&FsckOptions {
add_tombstones: true,
..FsckOptions::new()
})
.await
.map(drop),
];
let expected = "tmp passes through a symlink; ostrya refuses a symlink in the repository";
for (index, result) in results.into_iter().enumerate() {
match result {
Err(ostrya::Error::InvalidFormat(m)) => assert_eq!(m, expected, "write {index}"),
other => panic!("write {index}: {other:?}"),
}
}
assert_eq!(std::fs::metadata(&meta).unwrap().len(), 0);
let tombstone =
objects.join(ObjectName::new(c2, ObjectType::TombstoneCommit).loose_path(mode));
assert!(!tombstone.exists(), "no tombstone is written");
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
});
}
#[test]
fn fsck_add_tombstones_needs_a_walk_that_found_no_corruption() {
let arm = |name: &str, corrupt: bool, opts: FsckOptions| {
let tmp = TmpDir::new(name);
block_on(async {
let base = tmp.path();
let (repo, c1, c2) = build_two_commit_repo(base, RepoMode::Archive).await;
let objects = base.join("repo").join("objects");
std::fs::remove_file(
objects.join(ObjectName::new(c1, ObjectType::Commit).loose_path(RepoMode::Archive)),
)
.unwrap();
let reachable = repo.traverse_commit(&c2, 0).await.unwrap();
let object = reachable
.iter()
.find(|o| o.ty == ObjectType::File)
.copied()
.expect("a content object");
let path = objects.join(object.loose_path(RepoMode::Archive));
if corrupt {
std::fs::write(&path, b"not the object these bytes are named for").unwrap();
} else {
std::fs::remove_file(&path).unwrap();
}
let report = repo.fsck(&opts).await.unwrap();
assert_eq!(report.errors.len(), 1, "the walk reports the one fault");
let commit =
objects.join(ObjectName::new(c2, ObjectType::Commit).loose_path(RepoMode::Archive));
let tombstone = objects.join(
ObjectName::new(c2, ObjectType::TombstoneCommit).loose_path(RepoMode::Archive),
);
(report.tombstoned, commit.exists(), tombstone.exists())
})
};
let tombstones = |opts: FsckOptions| FsckOptions {
add_tombstones: true,
..opts
};
let (tombstoned, commit, tombstone) =
arm("maint-fsck-tomb-held", true, tombstones(FsckOptions::new()));
assert!(tombstoned.is_empty(), "no commit is tombstoned");
assert!(commit, "the child commit object stands");
assert!(!tombstone, "no tombstone is written");
for (name, opts) in [
(
"maint-fsck-tomb-all",
FsckOptions {
all: true,
..FsckOptions::new()
},
),
(
"maint-fsck-tomb-delete",
FsckOptions {
delete: true,
..FsckOptions::new()
},
),
] {
let (tombstoned, commit, tombstone) = arm(name, true, tombstones(opts));
assert_eq!(tombstoned.len(), 1, "{name}: the child is tombstoned");
assert!(!commit, "{name}: the child commit object is gone");
assert!(tombstone, "{name}: the tombstone is written");
}
let (tombstoned, commit, tombstone) = arm(
"maint-fsck-tomb-absent",
false,
tombstones(FsckOptions::new()),
);
assert_eq!(tombstoned.len(), 1, "the child is tombstoned");
assert!(!commit, "the child commit object is gone");
assert!(tombstone, "the tombstone is written");
}
#[test]
fn fsck_binding_checks_report_each_kind() {
use ostrya::{FsckBindingErrorKind, FsckFailure};
let tmp = TmpDir::new("maint-fsck-bindings");
block_on(async {
let base = tmp.path();
write_tree(&base.join("one"), "a.txt", b"one\n");
write_tree(&base.join("two"), "a.txt", b"two\n");
let bindings = |back: bool| {
let mut opts = FsckOptions::new();
opts.verify_bindings = !back;
opts.verify_back_refs = back;
opts
};
let kind = |failure: Option<FsckFailure>| match failure {
Some(FsckFailure::Binding(error)) => error.kind,
other => panic!("a binding finding, got {other:?}"),
};
let repo = Repo::create(
&base.join("not-bound"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let commit =
commit_with_metadata(&repo, base, "one", binding_metadata(&["alpha"], None)).await;
repo.set_ref_immediate(&Ref::local("alpha"), Some(&commit))
.await
.unwrap();
repo.set_ref_immediate(&Ref::local("beta"), Some(&commit))
.await
.unwrap();
let report = repo.fsck(&bindings(false)).await.unwrap();
match kind(report.failure) {
FsckBindingErrorKind::RefNotBound { ref_name, bindings } => {
assert_eq!(ref_name, "beta");
assert_eq!(bindings, vec!["alpha".to_owned()]);
}
other => panic!("RefNotBound, got {other:?}"),
}
let repo = Repo::create(
&base.join("collection"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let commit = commit_with_metadata(
&repo,
base,
"one",
binding_metadata(&["main"], Some("org.test.Coll")),
)
.await;
let cref = ostrya::Ref::collection("org.test.Other", "main");
repo.set_ref_immediate(&cref, Some(&commit)).await.unwrap();
let report = repo.fsck(&bindings(false)).await.unwrap();
match kind(report.failure) {
FsckBindingErrorKind::CollectionMismatch { bound, found_under } => {
assert_eq!(bound, "org.test.Coll");
assert_eq!(found_under, "org.test.Other");
}
other => panic!("CollectionMismatch, got {other:?}"),
}
let repo = Repo::create(&base.join("no-ref"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let commit = commit_with_metadata(
&repo,
base,
"one",
binding_metadata(&["alpha", "delta"], None),
)
.await;
repo.set_ref_immediate(&Ref::local("alpha"), Some(&commit))
.await
.unwrap();
let report = repo.fsck(&bindings(true)).await.unwrap();
match kind(report.failure) {
FsckBindingErrorKind::BackRefMissing { ref_name } => assert_eq!(ref_name, "delta"),
other => panic!("BackRefMissing, got {other:?}"),
}
let repo = Repo::create(&base.join("moved"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let first =
commit_with_metadata(&repo, base, "one", binding_metadata(&["alpha"], None)).await;
let second =
commit_with_metadata(&repo, base, "two", binding_metadata(&["alpha"], None)).await;
repo.set_ref_immediate(&Ref::local("alpha"), Some(&second))
.await
.unwrap();
let report = repo.fsck(&bindings(true)).await.unwrap();
match kind(report.failure) {
FsckBindingErrorKind::BackRefMismatch { ref_name } => assert_eq!(ref_name, "alpha"),
other => panic!("BackRefMismatch, got {other:?}"),
}
assert_ne!(first, second);
let repo = Repo::create(
&base.join("no-collection-ref"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let commit = commit_with_metadata(
&repo,
base,
"one",
binding_metadata(&["main"], Some("org.test.Coll")),
)
.await;
repo.set_ref_immediate(&Ref::local("main"), Some(&commit))
.await
.unwrap();
let report = repo.fsck(&bindings(true)).await.unwrap();
match kind(report.failure) {
FsckBindingErrorKind::BackCollectionRefMissing {
collection_id,
ref_name,
} => {
assert_eq!(collection_id, "org.test.Coll");
assert_eq!(ref_name, "main");
}
other => panic!("BackCollectionRefMissing, got {other:?}"),
}
let repo = Repo::create(
&base.join("moved-collection-ref"),
CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let first = commit_with_metadata(&repo, base, "one", binding_metadata(&[], None)).await;
let second = commit_with_metadata(
&repo,
base,
"two",
binding_metadata(&["main"], Some("org.test.Coll")),
)
.await;
repo.set_ref_immediate(&Ref::local("main"), Some(&second))
.await
.unwrap();
let cref = ostrya::Ref::collection("org.test.Coll", "main");
repo.set_ref_immediate(&cref, Some(&first)).await.unwrap();
let report = repo.fsck(&bindings(true)).await.unwrap();
match kind(report.failure) {
FsckBindingErrorKind::BackCollectionRefMismatch {
collection_id,
ref_name,
} => {
assert_eq!(collection_id, "org.test.Coll");
assert_eq!(ref_name, "main");
}
other => panic!("BackCollectionRefMismatch, got {other:?}"),
}
});
}
async fn attachment_commit(
repo: &Repo,
base: &Path,
rel: &str,
branch: Option<&str>,
related: &[(&str, Checksum)],
) -> Checksum {
use ostrya::{CommitModifier, CommitModifierFlags, CommitOptions, MutableTree};
use std::os::fd::AsFd;
let txn = repo.transaction().await.unwrap();
let mut modifier = CommitModifier::new(
CommitModifierFlags::CANONICAL_PERMISSIONS | CommitModifierFlags::SKIP_XATTRS,
);
let mut mtree = MutableTree::new();
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(rel), &mut mtree, Some(&mut modifier))
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
subject: Some("c".to_owned()),
timestamp: Some(1_700_000_000),
attachments: related
.iter()
.map(|(name, checksum)| ((*name).to_owned(), *checksum))
.collect(),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
if let Some(branch) = branch {
txn.set_ref(&Ref::local(branch), Some(&commit));
}
txn.commit().await.unwrap();
commit
}
async fn build_attachment_repo(base: &Path) -> (Repo, Checksum, Checksum) {
write_tree(&base.join("uki"), "uki.txt", b"uki\n");
write_tree(&base.join("main"), "main.txt", b"main\n");
let repo = Repo::create(&base.join("repo"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let att = attachment_commit(&repo, base, "uki", None, &[]).await;
let tip = attachment_commit(&repo, base, "main", Some("main"), &[("boot/uki", att)]).await;
(repo, tip, att)
}
fn remove_object(repo: &Repo, name: ObjectName) {
std::fs::remove_file(
repo.path()
.join("objects")
.join(name.loose_path(RepoMode::Archive)),
)
.unwrap();
}
fn attachment_finding(
commit: Checksum,
name: &str,
attachment: Option<Checksum>,
kind: ostrya::FsckAttachmentErrorKind,
) -> ostrya::FsckAttachmentError {
ostrya::FsckAttachmentError {
commit,
name: name.to_owned(),
attachment,
kind,
}
}
#[test]
fn fsck_passes_with_complete_attachments() {
let tmp = TmpDir::new("maint-fsck-dep-ok");
block_on(async {
let (repo, _tip, _att) = build_attachment_repo(tmp.path()).await;
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "{report:?}");
assert_eq!(report.commits_checked, 2);
assert!(report.attachment_errors.is_empty());
assert!(report.marked_partial.is_empty());
});
}
#[test]
fn fsck_marks_the_commit_of_an_absent_attachment_and_a_pull_repairs_it() {
let tmp = TmpDir::new("maint-fsck-dep-absent");
block_on(async {
let base = tmp.path();
let (src, tip, att) = build_attachment_repo(base).await;
let dst = Repo::create(&base.join("dst"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let main = || ostrya::PullOptions {
refs: vec!["main".to_owned()],
..ostrya::PullOptions::default()
};
dst.pull_local(&src, main()).await.unwrap();
remove_object(&dst, ObjectName::new(att, ObjectType::Commit));
let report = dst.fsck(&FsckOptions::new()).await.unwrap();
let finding = attachment_finding(
tip,
"boot/uki",
Some(att),
ostrya::FsckAttachmentErrorKind::Absent,
);
assert_eq!(report.attachment_errors, std::slice::from_ref(&finding));
assert_eq!(
finding.to_string(),
format!(
"related commits in field 2 of commit {tip}: attachment boot/uki names commit \
{att}, which the repository does not hold"
)
);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert!(!report.is_ok());
assert_eq!(report.marked_partial, [tip]);
assert_eq!(
dst.commit_state(&tip).await.unwrap(),
ostrya::CommitState::Partial
);
dst.pull_local(&src, main()).await.unwrap();
assert!(dst.has_object(ObjectType::Commit, &att).await.unwrap());
let again = dst.fsck(&FsckOptions::new()).await.unwrap();
assert!(again.is_ok(), "{again:?}");
});
}
#[test]
fn fsck_reports_an_absent_attachment_without_a_marker() {
let tmp = TmpDir::new("maint-fsck-dep-nomark");
block_on(async {
let base = tmp.path();
let (repo, first, att) = build_attachment_repo(base).await;
let tip = attachment_commit(
&repo,
base,
"main",
Some("main"),
&[("boot/a", att), ("boot/b", att)],
)
.await;
remove_object(&repo, ObjectName::new(att, ObjectType::Commit));
let report = repo
.fsck(&FsckOptions {
mark_partial: false,
..FsckOptions::new()
})
.await
.unwrap();
let absent = |commit, name| {
attachment_finding(
commit,
name,
Some(att),
ostrya::FsckAttachmentErrorKind::Absent,
)
};
let mut expected = vec![
absent(first, "boot/uki"),
absent(tip, "boot/a"),
absent(tip, "boot/b"),
];
expected.sort_by_key(|error| error.commit);
assert_eq!(report.attachment_errors, expected);
assert!(report.marked_partial.is_empty());
for commit in [first, tip] {
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
ostrya::CommitState::Normal
);
}
});
}
#[test]
fn fsck_without_attachment_marks_reports_an_absent_attachment_and_marks_nothing() {
let tmp = TmpDir::new("maint-fsck-dep-nodepmark");
block_on(async {
let (repo, tip, att) = build_attachment_repo(tmp.path()).await;
remove_object(&repo, ObjectName::new(att, ObjectType::Commit));
let opts = FsckOptions {
mark_attachments: false,
..FsckOptions::new()
};
let finding = attachment_finding(
tip,
"boot/uki",
Some(att),
ostrya::FsckAttachmentErrorKind::Absent,
);
for _ in 0..2 {
let report = repo.fsck(&opts).await.unwrap();
assert_eq!(report.attachment_errors, std::slice::from_ref(&finding));
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert!(report.marked_partial.is_empty());
assert!(!report.is_ok());
assert_eq!(
repo.commit_state(&tip).await.unwrap(),
ostrya::CommitState::Normal
);
}
});
}
#[test]
fn fsck_without_attachment_marks_still_marks_the_commit_of_an_absent_object() {
let tmp = TmpDir::new("maint-fsck-dep-objmark");
block_on(async {
let (repo, tip, att) = build_attachment_repo(tmp.path()).await;
let shared: HashSet<ObjectName> = repo.traverse_commit(&att, 0).await.unwrap();
let file = repo
.traverse_commit(&tip, 0)
.await
.unwrap()
.into_iter()
.find(|name| name.ty == ObjectType::File && !shared.contains(name))
.expect("a file of the tip alone");
remove_object(&repo, file);
remove_object(&repo, ObjectName::new(att, ObjectType::Commit));
let report = repo
.fsck(&FsckOptions {
mark_attachments: false,
..FsckOptions::new()
})
.await
.unwrap();
assert_eq!(report.errors.len(), 1, "{:?}", report.errors);
assert_eq!(report.errors[0].in_commits, [tip]);
assert_eq!(
report.attachment_errors,
[attachment_finding(
tip,
"boot/uki",
Some(att),
ostrya::FsckAttachmentErrorKind::Absent,
)]
);
assert_eq!(report.marked_partial, [tip]);
assert_eq!(
repo.commit_state(&tip).await.unwrap(),
ostrya::CommitState::Partial
);
});
}
#[test]
fn fsck_reports_a_partial_attachment() {
let tmp = TmpDir::new("maint-fsck-dep-partial");
block_on(async {
let (repo, tip, att) = build_attachment_repo(tmp.path()).await;
common::mark_partial(&repo, &att);
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
let partial = attachment_finding(
tip,
"boot/uki",
Some(att),
ostrya::FsckAttachmentErrorKind::Partial,
);
assert_eq!(report.attachment_errors, std::slice::from_ref(&partial));
assert!(
partial
.to_string()
.ends_with(&format!("names commit {att}, which is partial")),
"{partial}"
);
assert_eq!(report.commits_partial, 1);
assert_eq!(report.marked_partial, [tip]);
std::fs::remove_file(repo.path().join(format!("state/{att}.commitpartial"))).unwrap();
std::fs::remove_file(repo.path().join(format!("state/{tip}.commitpartial"))).unwrap();
let shared: HashSet<ObjectName> = repo.traverse_commit(&tip, 0).await.unwrap();
let file = repo
.traverse_commit(&att, 0)
.await
.unwrap()
.into_iter()
.find(|name| name.ty == ObjectType::File && !shared.contains(name))
.expect("a file of the attachment alone");
remove_object(&repo, file);
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert_eq!(report.errors.len(), 1, "{:?}", report.errors);
assert_eq!(report.errors[0].in_commits, [att]);
assert_eq!(report.attachment_errors, [partial]);
let mut marked = vec![att, tip];
marked.sort();
assert_eq!(report.marked_partial, marked);
});
}
#[test]
fn fsck_reports_defective_attachments_without_a_marker() {
let tmp = TmpDir::new("maint-fsck-dep-defective");
block_on(async {
let base = tmp.path();
let (repo, tip, att) = build_attachment_repo(base).await;
let defective =
common::store_with_field2(&repo, &att, &[("", att.as_bytes()), ("lib/a", &[7; 31])])
.await;
let nested = common::store_with_field2(&repo, &att, &[("lib/b", tip.as_bytes())]).await;
let above =
common::store_with_field2(&repo, &att, &[("lib/c", defective.as_bytes())]).await;
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
let kind = |reason: &str| ostrya::FsckAttachmentErrorKind::Defective(reason.to_owned());
let expected = vec![
attachment_finding(defective, "", Some(att), kind("entry 0 has an empty name")),
attachment_finding(
defective,
"lib/a",
None,
kind("entry 1 (lib/a) has a checksum of 31 bytes, not 32"),
),
];
assert_eq!(report.attachment_errors, expected);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert!(report.marked_partial.is_empty());
assert!(!report.is_ok());
for commit in [defective, nested, above] {
assert_eq!(
repo.commit_state(&commit).await.unwrap(),
ostrya::CommitState::Normal
);
}
});
}
async fn build_chain_repo(base: &Path) -> (Repo, common::Chain) {
let repo = Repo::create(&base.join("repo"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let chain = common::write_chain(&repo, base, "chain").await;
(repo, chain)
}
fn sorted(commits: &[Checksum]) -> Vec<Checksum> {
let mut commits = commits.to_vec();
commits.sort();
commits
}
async fn assert_states(repo: &Repo, commits: &[Checksum], state: ostrya::CommitState) {
for commit in commits {
assert_eq!(repo.commit_state(commit).await.unwrap(), state, "{commit}");
}
}
#[test]
fn fsck_marks_each_commit_above_an_absent_attachment_in_a_chain() {
use ostrya::FsckAttachmentErrorKind::{Absent, Partial};
let tmp = TmpDir::new("maint-fsck-att-chain");
block_on(async {
let (repo, common::Chain { r, c, d }) = build_chain_repo(tmp.path()).await;
remove_object(&repo, ObjectName::new(d, ObjectType::Commit));
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
let top = attachment_finding(r, common::CHAIN_C, Some(c), Partial);
let mut expected = vec![
attachment_finding(c, common::CHAIN_D, Some(d), Absent),
top.clone(),
];
expected.sort_by_key(|error| error.commit);
assert_eq!(report.attachment_errors, expected);
assert!(
top.to_string()
.ends_with(&format!("names commit {c}, which is partial")),
"{top}"
);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert_eq!(report.commits_checked, 2);
assert_eq!(report.marked_partial, sorted(&[c, r]));
assert_states(&repo, &[c, r], ostrya::CommitState::Partial).await;
});
}
#[test]
fn fsck_without_attachment_marks_reports_the_chain_and_marks_nothing() {
use ostrya::FsckAttachmentErrorKind::{Absent, Partial};
let tmp = TmpDir::new("maint-fsck-att-chain-nomark");
block_on(async {
let (repo, common::Chain { r, c, d }) = build_chain_repo(tmp.path()).await;
remove_object(&repo, ObjectName::new(d, ObjectType::Commit));
let opts = FsckOptions {
mark_attachments: false,
..FsckOptions::new()
};
let mut expected = vec![
attachment_finding(c, common::CHAIN_D, Some(d), Absent),
attachment_finding(r, common::CHAIN_C, Some(c), Partial),
];
expected.sort_by_key(|error| error.commit);
for _ in 0..2 {
let report = repo.fsck(&opts).await.unwrap();
assert_eq!(report.attachment_errors, expected);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert!(report.marked_partial.is_empty());
assert!(!report.is_ok());
assert_states(&repo, &[c, r], ostrya::CommitState::Normal).await;
}
});
}
#[test]
fn fsck_marks_each_commit_above_an_absent_attachment_in_a_diamond() {
use ostrya::FsckAttachmentErrorKind::{Absent, Partial};
let tmp = TmpDir::new("maint-fsck-att-diamond");
block_on(async {
let base = tmp.path();
let repo = Repo::create(&base.join("repo"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let common::Diamond { r, a, b, d } = common::write_diamond(&repo, base, "diamond").await;
remove_object(&repo, ObjectName::new(d, ObjectType::Commit));
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
let mut expected = vec![
attachment_finding(a, common::DIAMOND_D, Some(d), Absent),
attachment_finding(b, common::DIAMOND_D, Some(d), Absent),
attachment_finding(r, common::DIAMOND_A, Some(a), Partial),
attachment_finding(r, common::DIAMOND_B, Some(b), Partial),
];
expected.sort_by_key(|error| error.commit);
assert_eq!(report.attachment_errors, expected);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert_eq!(report.marked_partial, sorted(&[a, b, r]));
assert_states(&repo, &[a, b, r], ostrya::CommitState::Partial).await;
});
}
#[test]
fn fsck_marks_each_commit_above_an_absent_attachment_at_depth_three() {
use ostrya::FsckAttachmentErrorKind::{Absent, Partial};
let tmp = TmpDir::new("maint-fsck-att-depth3");
block_on(async {
let base = tmp.path();
let (repo, common::Chain { r, c, d }) = build_chain_repo(base).await;
write_tree(&base.join("top"), "top.txt", b"top\n");
let t = attachment_commit(&repo, base, "top", Some("top"), &[("rootfs", r)]).await;
remove_object(&repo, ObjectName::new(d, ObjectType::Commit));
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
let mut expected = vec![
attachment_finding(c, common::CHAIN_D, Some(d), Absent),
attachment_finding(r, common::CHAIN_C, Some(c), Partial),
attachment_finding(t, "rootfs", Some(r), Partial),
];
expected.sort_by_key(|error| error.commit);
assert_eq!(report.attachment_errors, expected);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert_eq!(report.marked_partial, sorted(&[c, r, t]));
assert_states(&repo, &[c, r, t], ostrya::CommitState::Partial).await;
});
}
#[test]
fn fsck_marks_the_chain_above_an_absent_attachment_and_a_pull_of_the_top_repairs_it() {
let tmp = TmpDir::new("maint-fsck-att-chain-pull");
block_on(async {
let base = tmp.path();
let src = Repo::create(&base.join("src"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let common::Chain { r, c, d } = common::write_chain(&src, base, "chain").await;
let dst = Repo::create(&base.join("dst"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let chain = || ostrya::PullOptions {
refs: vec!["chain".to_owned()],
..ostrya::PullOptions::default()
};
dst.pull_local(&src, chain()).await.unwrap();
remove_object(&dst, ObjectName::new(d, ObjectType::Commit));
let report = dst.fsck(&FsckOptions::new()).await.unwrap();
assert_eq!(report.attachment_errors.len(), 2, "{report:?}");
assert_eq!(report.marked_partial, sorted(&[c, r]));
dst.pull_local(&src, chain()).await.unwrap();
assert!(dst.has_object(ObjectType::Commit, &d).await.unwrap());
assert_states(&dst, &[r, c, d], ostrya::CommitState::Normal).await;
let again = dst.fsck(&FsckOptions::new()).await.unwrap();
assert!(again.is_ok(), "{again:?}");
});
}
#[test]
fn fsck_marks_each_commit_above_a_partial_attachment_in_a_chain() {
use ostrya::FsckAttachmentErrorKind::Partial;
let tmp = TmpDir::new("maint-fsck-att-chain-partial");
block_on(async {
let (repo, common::Chain { r, c, d }) = build_chain_repo(tmp.path()).await;
common::mark_partial(&repo, &d);
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
let mut expected = vec![
attachment_finding(c, common::CHAIN_D, Some(d), Partial),
attachment_finding(r, common::CHAIN_C, Some(c), Partial),
];
expected.sort_by_key(|error| error.commit);
assert_eq!(report.attachment_errors, expected);
assert!(report.errors.is_empty(), "{:?}", report.errors);
assert_eq!(report.commits_checked, 2);
assert_eq!(report.commits_partial, 1);
assert_eq!(report.marked_partial, sorted(&[c, r]));
assert_states(&repo, &[c, r], ostrya::CommitState::Partial).await;
});
}
fn object_file(repo: &Repo, name: ObjectName) -> std::path::PathBuf {
repo.path()
.join("objects")
.join(name.loose_path(RepoMode::Archive))
}
#[test]
fn fsck_delete_removes_a_bad_attachment_commit_and_reports_it_absent() {
let tmp = TmpDir::new("maint-fsck-dep-delete-commit");
block_on(async {
let base = tmp.path();
let (repo, tip, att) = build_attachment_repo(base).await;
let other = attachment_commit(&repo, base, "main", None, &[]).await;
let att_name = ObjectName::new(att, ObjectType::Commit);
let bytes = std::fs::read(object_file(
&repo,
ObjectName::new(other, ObjectType::Commit),
))
.unwrap();
std::fs::write(object_file(&repo, att_name), bytes).unwrap();
let report = repo
.fsck(&FsckOptions {
delete: true,
..FsckOptions::new()
})
.await
.unwrap();
assert_eq!(report.deleted, [att_name]);
assert!(!object_file(&repo, att_name).exists());
assert_eq!(
report.attachment_errors,
[attachment_finding(
tip,
"boot/uki",
Some(att),
ostrya::FsckAttachmentErrorKind::Absent,
)]
);
assert!(report.marked_partial.contains(&tip), "{report:?}");
});
}
#[test]
fn fsck_delete_of_a_bad_object_makes_its_attachment_partial() {
let tmp = TmpDir::new("maint-fsck-dep-delete-object");
block_on(async {
let (repo, tip, att) = build_attachment_repo(tmp.path()).await;
let shared: HashSet<ObjectName> = repo.traverse_commit(&tip, 0).await.unwrap();
let file = repo
.traverse_commit(&att, 0)
.await
.unwrap()
.into_iter()
.find(|name| name.ty == ObjectType::File && !shared.contains(name))
.expect("a file of the attachment alone");
std::fs::write(object_file(&repo, file), b"not the object of this name").unwrap();
let report = repo.fsck(&FsckOptions::new()).await.unwrap();
assert_eq!(report.errors.len(), 1, "{:?}", report.errors);
assert!(report.attachment_errors.is_empty(), "{report:?}");
assert!(report.marked_partial.is_empty());
let report = repo
.fsck(&FsckOptions {
delete: true,
..FsckOptions::new()
})
.await
.unwrap();
assert_eq!(report.deleted, [file]);
assert_eq!(
report.attachment_errors,
[attachment_finding(
tip,
"boot/uki",
Some(att),
ostrya::FsckAttachmentErrorKind::Partial,
)]
);
let mut marked = vec![att, tip];
marked.sort();
assert_eq!(report.marked_partial, marked);
});
}
#[test]
fn fsck_options_and_report_are_send_sync() {
fn assert_send<T: Send>() {}
fn assert_send_sync<T: Send + Sync>() {}
assert_send::<FsckOptions>();
assert_send_sync::<ostrya::FsckReport>();
assert_send_sync::<ostrya::FsckError>();
assert_send_sync::<ostrya::FsckBindingError>();
assert_send_sync::<ostrya::FsckFailure>();
assert_send_sync::<ostrya::FsckAttachmentError>();
assert_send_sync::<ostrya::FsckAttachmentErrorKind>();
}
fn find_object(repo: &Path, ext: &str) -> Option<std::path::PathBuf> {
for fanout in std::fs::read_dir(repo.join("objects")).unwrap() {
let fanout = fanout.unwrap().path();
if !fanout.is_dir() {
continue;
}
for entry in std::fs::read_dir(&fanout).unwrap() {
let p = entry.unwrap().path();
if p.extension().and_then(|e| e.to_str()) == Some(ext) {
return Some(p);
}
}
}
None
}
fn parse_tool_diff(output: &str) -> HashSet<(char, String)> {
output
.lines()
.filter_map(|line| {
let code = line.chars().next()?;
let path = line[1..].trim_start().to_owned();
if matches!(code, 'A' | 'D' | 'M') && !path.is_empty() {
Some((code, path))
} else {
None
}
})
.collect()
}
fn port_diff_set(entries: &[DiffEntry]) -> HashSet<(char, String)> {
entries
.iter()
.map(|e| {
let code = match e.change {
DiffChange::Added => 'A',
DiffChange::Removed => 'D',
DiffChange::Modified => 'M',
};
(code, e.path.clone())
})
.collect()
}
#[test]
fn diff_matches_the_tool() {
if !ostree_available() {
eprintln!("skipping diff_matches_the_tool: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-diff");
let base = tmp.path();
let repo = base.join("repo");
tool_init(&repo);
let t1 = base.join("t1");
write_tree(&t1, "keep.txt", b"one\n");
write_tree(&t1.join("gone"), "x.txt", b"g\n");
write_tree(&t1.join("meta"), "f.txt", b"m\n");
write_tree(&t1, "thing", b"file-form\n");
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(t1.join("meta"), std::fs::Permissions::from_mode(0o755)).unwrap();
}
let t2 = base.join("t2");
write_tree(&t2, "keep.txt", b"two\n");
write_tree(&t2.join("meta"), "f.txt", b"m\n");
write_tree(&t2.join("added"), "y.txt", b"new\n");
write_tree(&t2.join("thing"), "inner.txt", b"dir-form\n");
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(t2.join("meta"), std::fs::Permissions::from_mode(0o700)).unwrap();
}
let a = tool_commit(&repo, "b", &t1);
let b = tool_commit(&repo, "b", &t2);
let tool_out = ostree(&[
&format!("--repo={}", repo.display()),
"diff",
&a.to_hex(),
&b.to_hex(),
]);
let tool_set = parse_tool_diff(&tool_out);
let port_set = block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let entries = handle.diff_commits(&a, &b).await.unwrap();
port_diff_set(&entries)
});
assert_eq!(
port_set, tool_set,
"the port's diff matches the tool's:\n tool={tool_set:?}\n port={port_set:?}"
);
}
#[test]
fn diff_print_order_is_the_walk_order() {
let tmp = TmpDir::new("maint-diff-order");
let base = tmp.path();
let repo_path = base.join("repo");
let one = base.join("t1");
write_tree(&one.join("M1/s"), "x", b"x\n");
write_tree(&one.join("M1"), "y", b"y\n");
write_tree(&one.join("M2"), "w", b"w\n");
write_tree(&one.join("D1"), "keep", b"k\n");
write_tree(&one, "aa", b"a\n");
write_tree(&one, "gone", b"g\n");
write_tree(&one.join("gonedir"), "inner", b"i\n");
let two = base.join("t2");
write_tree(&two.join("M1/s"), "x", b"x2\n");
write_tree(&two.join("M1"), "y", b"y2\n");
write_tree(&two.join("M2"), "w", b"w2\n");
write_tree(&two.join("D1"), "keep", b"k\n");
write_tree(&two.join("D1"), "new1", b"n\n");
write_tree(&two, "aa", b"a2\n");
write_tree(&two, "zz_added", b"z\n");
write_tree(&two.join("N/b1/deep"), "g", b"g\n");
write_tree(&two.join("N/b1"), "f", b"f\n");
write_tree(&two.join("N"), "a", b"a\n");
let ordered = block_on(async {
let repo = Repo::create(&repo_path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let a = library_commit(&repo, base, "t1", None).await;
let b = library_commit(&repo, base, "t2", Some(a)).await;
let entries = repo.diff_commits(&a, &b).await.unwrap();
entries
.iter()
.map(|entry| {
let code = match entry.change {
DiffChange::Added => 'A',
DiffChange::Removed => 'D',
DiffChange::Modified => 'M',
};
format!("{code} {}", entry.path)
})
.collect::<Vec<_>>()
});
assert_eq!(
ordered,
vec![
"M /aa",
"M /M1/y",
"M /M1/s/x",
"M /M2/w",
"D /gone",
"D /gonedir",
"A /D1/new1",
"A /zz_added",
"A /N",
"A /N/a",
"A /N/b1",
"A /N/b1/f",
"A /N/b1/deep",
"A /N/b1/deep/g",
],
"the walk order"
);
}
#[test]
fn diff_of_identical_commits_is_empty() {
if !ostree_available() {
eprintln!("skipping diff_of_identical_commits_is_empty: no ostree tool");
return;
}
let tmp = TmpDir::new("maint-diff-empty");
let base = tmp.path();
let repo = base.join("repo");
tool_init(&repo);
let t = base.join("t");
write_tree(&t, "a.txt", b"same\n");
let c = tool_commit(&repo, "b", &t);
block_on(async {
let handle = Repo::open(&repo).await.unwrap();
let entries = handle.diff_commits(&c, &c).await.unwrap();
assert!(entries.is_empty(), "a commit differs from itself nowhere");
});
}