use std::path::{Path, PathBuf}; use std::process::Command; use nostr::prelude::*; use signed_core::RepoAddr; use signed_git::{DiffStatus, GitCache, LocalRepo, Nip34Binding, Nip34Kind, PatchParser, Repo}; #[test] fn blocks_parent_components() { assert_eq!(GitCache::sanitize_path_component(".."), "_"); assert_eq!(GitCache::sanitize_path_component("."), "_"); assert_eq!(GitCache::sanitize_path_component("../.."), ".._.."); assert_eq!(GitCache::sanitize_path_component("a/../b"), "a_.._b"); } #[test] fn concurrent_ensure_clone_succeeds_for_every_caller() { let server = tempfile::tempdir().expect("tempdir"); let server_repo = bare_server(server.path(), "npub1test", "repo"); let (work_dir, work_repo) = fixture(&[("a.txt", b"one")]); commit_all(&work_repo, "initial"); let work_dir = work_dir.path(); let base_url = format!("file://{}", server.path().display()); Repo::open(work_dir) .expect("open") .push_all(&base_url, "npub1test", "repo") .expect("push"); let cache_dir = tempfile::tempdir().expect("tempdir"); let cache = GitCache::new(cache_dir.path().to_path_buf()); let addr = RepoAddr::new(Keys::generate().public_key(), "repo"); let clone_url = format!("file://{}", server_repo.display()); std::thread::scope(|scope| { for _ in 0..4 { scope.spawn(|| { cache .ensure_clone(&addr, &[&clone_url]) .expect("ensure_clone"); }); } }); assert!(cache.open(&addr).expect("open").is_some()); } #[test] fn ensure_clone_recovers_from_a_leftover_directory() { let server = tempfile::tempdir().expect("tempdir"); let server_repo = bare_server(server.path(), "npub1test", "repo"); let (work_dir, work_repo) = fixture(&[("a.txt", b"one")]); commit_all(&work_repo, "initial"); let work_dir = work_dir.path(); let base_url = format!("file://{}", server.path().display()); Repo::open(work_dir) .expect("open") .push_all(&base_url, "npub1test", "repo") .expect("push"); let cache_dir = tempfile::tempdir().expect("tempdir"); let cache = GitCache::new(cache_dir.path().to_path_buf()); let addr = RepoAddr::new(Keys::generate().public_key(), "repo"); let clone_url = format!("file://{}", server_repo.display()); // Simulate the remains of an interrupted clone. let leftover = cache.repo_path(&addr); std::fs::create_dir_all(&leftover).expect("mkdir"); cache .ensure_clone(&addr, &[&clone_url]) .expect("ensure_clone"); assert!(cache.open(&addr).expect("open").is_some()); } #[test] fn root_commit_reports_the_first_ancestor() { let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let dir = dir.path(); let root = repo.root_commit().expect("root").expect("commit"); assert_eq!(root.len(), 40); std::fs::write(dir.join("b.txt"), b"two").expect("write"); commit_all(&repo, "second"); assert_eq!( repo.root_commit().expect("root").as_deref(), Some(root.as_str()) ); } #[test] fn push_all_mirrors_branches_and_tags() { let server = tempfile::tempdir().unwrap(); let server_repo = bare_server(server.path(), "npub1test", "my-repo"); let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let dir = dir.path(); git_run(dir, &["checkout", "-b", "feature"]); std::fs::write(dir.join("b.txt"), b"two").expect("write"); commit_all(&repo, "feature work"); git_run(dir, &["checkout", "-"]); git_run(dir, &["tag", "v1.0"]); let base_url = format!("file://{}", server.path().display()); Repo::open(dir) .expect("open") .push_all(&base_url, "npub1test", "my-repo") .expect("push"); let refs = git_in(&server_repo, &["show-ref"]).expect("server refs"); assert!(refs.contains("refs/heads/main")); assert!(refs.contains("refs/heads/feature")); assert!(refs.contains("refs/tags/v1.0")); } #[test] fn ls_remote_lists_branches_and_tags_only() { let server = tempfile::tempdir().unwrap(); let server_repo = bare_server(server.path(), "npub1test", "my-repo"); let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let dir = dir.path(); git_run(dir, &["branch", "feature"]); git_run(dir, &["tag", "v1"]); git_run(dir, &["tag", "-a", "v2", "-m", "annotated"]); let base_url = format!("file://{}", server.path().display()); let local = Repo::open(dir).expect("open"); local .push_all(&base_url, "npub1test", "my-repo") .expect("push"); // Refs outside heads and tags, and the HEAD symref line, are not listed. let main = git_in(dir, &["rev-parse", "refs/heads/main"]).expect("main oid"); git_run(&server_repo, &["update-ref", "refs/nostr/abc", &main]); let remote = local .ls_remote(&format!("file://{}", server_repo.display())) .expect("ls-remote"); let names: Vec = remote.iter().map(|(name, _)| name.clone()).collect(); assert_eq!( names, vec![ "refs/heads/feature".to_owned(), "refs/heads/main".to_owned(), "refs/tags/v1".to_owned(), "refs/tags/v2".to_owned(), ] ); assert_eq!( remote .iter() .find(|(name, _)| name == "refs/heads/main") .map(|(_, oid)| oid.as_str()), Some(main.as_str()) ); // The annotated tag lists the tag object, matching the local ref state, // without a peeled `^{}` duplicate. let v2 = git_in(dir, &["rev-parse", "refs/tags/v2"]).expect("v2 oid"); assert_eq!( remote .iter() .find(|(name, _)| name == "refs/tags/v2") .map(|(_, oid)| oid.as_str()), Some(v2.as_str()) ); } #[test] fn push_all_force_updates_diverged_remote_branches() { let server = tempfile::tempdir().unwrap(); let server_repo = bare_server(server.path(), "npub1test", "my-repo"); let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); std::fs::write(dir.path().join("b.txt"), b"two").expect("write"); commit_all(&repo, "second"); let dir = dir.path(); let base_url = format!("file://{}", server.path().display()); let local = Repo::open(dir).expect("open"); local .push_all(&base_url, "npub1test", "my-repo") .expect("initial push"); // Diverge local main from the pushed state. git_run(dir, &["reset", "-q", "--hard", "HEAD~1"]); std::fs::write(dir.join("c.txt"), b"three").expect("write"); commit_all(&repo, "diverged"); local .push_all(&base_url, "npub1test", "my-repo") .expect("force push"); assert_eq!( git_in(dir, &["rev-parse", "refs/heads/main"]).expect("local main"), git_in(&server_repo, &["rev-parse", "refs/heads/main"]).expect("server main") ); } #[test] fn push_refspecs_deletes_server_refs_missing_locally() { let server = tempfile::tempdir().unwrap(); let server_repo = bare_server(server.path(), "npub1test", "my-repo"); let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let dir = dir.path(); git_run(dir, &["branch", "feature"]); git_run(dir, &["tag", "v1"]); let base_url = format!("file://{}", server.path().display()); let local = Repo::open(dir).expect("open"); local .push_all(&base_url, "npub1test", "my-repo") .expect("initial push"); git_run(dir, &["branch", "-D", "feature"]); git_run(dir, &["tag", "-d", "v1"]); local .push_refspecs( &base_url, "npub1test", "my-repo", &[ "+refs/heads/*:refs/heads/*", "+refs/tags/*:refs/tags/*", ":refs/heads/feature", ":refs/tags/v1", ], ) .expect("push with deletions"); let refs = git_in(&server_repo, &["show-ref"]).expect("server refs"); assert!(refs.contains("refs/heads/main")); assert!(!refs.contains("refs/heads/feature")); assert!(!refs.contains("refs/tags/v1")); } #[test] fn fetch_refs_brings_server_only_branches_into_local() { let server = tempfile::tempdir().unwrap(); bare_server(server.path(), "npub1test", "my-repo"); let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let dir = dir.path(); git_run(dir, &["branch", "feature"]); let base_url = format!("file://{}", server.path().display()); Repo::open(dir) .expect("open") .push_all(&base_url, "npub1test", "my-repo") .expect("push"); let feature = git_in(dir, &["rev-parse", "refs/heads/feature"]).expect("feature oid"); // A repository that never had the branch fetches it by name. let (other_dir, _other_repo) = fixture(&[("unrelated.txt", b"x")]); let other = Repo::open(other_dir.path()).expect("open other"); let server_url = format!("file://{}/npub1test/my-repo.git", server.path().display()); other .fetch_refs(&[&server_url], "+refs/heads/feature:refs/heads/feature") .expect("fetch ref"); assert_eq!( git_in(other_dir.path(), &["rev-parse", "refs/heads/feature"]).expect("fetched feature"), feature ); } #[test] fn ref_state_matches_the_git_cli_ref_listing() { let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let dir = dir.path(); git_run(dir, &["branch", "browse-group"]); git_run(dir, &["checkout", "-q", "-b", "new-search"]); std::fs::write(dir.join("b.txt"), b"two").expect("write"); commit_all(&repo, "search work"); git_run(dir, &["checkout", "-q", "-"]); git_run(dir, &["tag", "v1"]); let listing = |repo: &Repo| { let mut refs = repo.ref_state().expect("ref state").refs; refs.sort(); refs }; // Loose refs. let loose = listing(&Repo::open(dir).expect("open")); // Packed refs. git_run(dir, &["pack-refs", "--all"]); let packed = listing(&Repo::open(dir).expect("open")); let output = git_run( dir, &[ "for-each-ref", "--format=%(refname) %(objectname)", "refs/heads", "refs/tags", ], ); let mut cli = String::from_utf8_lossy(&output.stdout) .lines() .map(|line| { let (name, oid) = line.split_once(' ').expect("for-each-ref format"); (name.to_owned(), oid.to_owned()) }) .collect::>(); cli.sort(); assert_eq!(loose, cli); assert_eq!(packed, cli); assert!( loose .iter() .any(|(name, _)| name == "refs/heads/new-search") ); assert!( loose .iter() .any(|(name, _)| name == "refs/heads/browse-group") ); } #[test] fn repo_ref_state_lists_branches_tags_and_head() { let (_dir, repo) = fixture(&[("a.txt", b"hello")]); commit_all(&repo, "initial"); let workdir = repo.workdir().expect("workdir").to_path_buf(); let state = repo.ref_state().expect("refs"); let branch = repo.current_branch().expect("on a branch"); assert_eq!(state.head.as_deref(), Some(branch.as_str())); assert_eq!(state.refs.len(), 1); assert_eq!(state.refs[0].0, format!("refs/heads/{branch}")); assert_eq!(state.refs[0].1.len(), 40); git_run(&workdir, &["branch", "feature"]); git_run(&workdir, &["tag", "v1.0"]); let state = repo.ref_state().expect("refs"); let mut expected: Vec = vec![ format!("refs/heads/{branch}"), "refs/heads/feature".to_owned(), "refs/tags/v1.0".to_owned(), ]; expected.sort(); assert_eq!( state .refs .iter() .map(|(name, _)| name.clone()) .collect::>(), expected ); git_run(&workdir, &["checkout", "--detach"]); let state = repo.ref_state().expect("refs"); assert!(state.head.is_none()); assert_eq!(state.refs.len(), 3); } /// Creates a repository fixture with the given files. fn fixture(files: &[(&str, &[u8])]) -> (tempfile::TempDir, Repo) { let dir = tempfile::tempdir().expect("tempdir"); gix::init(&dir).expect("init"); for (rel, bytes) in files { let path = dir.path().join(rel); std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); std::fs::write(&path, bytes).expect("write"); } let repo = Repo::open(dir.path()).expect("open"); (dir, repo) } /// Stages and commits every change in the repository. fn commit_all(repo: &Repo, message: &str) { git_run(repo.workdir().expect("workdir"), &["add", "-A"]); git_run(repo.workdir().expect("workdir"), &["commit", "-m", message]); } #[test] fn merge_base_finds_the_fork_point_and_reports_unrelated_history() { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("repo"); let initial = Repo::init(&path, "My Repo", "desc").expect("init"); let repo = Repo::open(&path).expect("open"); git_run(&path, &["checkout", "-b", "feature"]); std::fs::write(path.join("feature.txt"), "feature\n").expect("write"); commit_all(&repo, "feature commit"); git_run(&path, &["checkout", "main"]); std::fs::write(path.join("main.txt"), "main\n").expect("write"); commit_all(&repo, "mainline commit"); assert_eq!( repo.merge_base("feature", "main") .expect("merge base") .as_deref(), Some(initial.as_str()) ); git_run(&path, &["checkout", "--orphan", "orphan"]); std::fs::write(path.join("orphan.txt"), "orphan\n").expect("write"); commit_all(&repo, "orphan commit"); assert_eq!(repo.merge_base("orphan", "main").expect("ok"), None); assert!(repo.merge_base("orphan", "no-such-ref").is_err()); } #[test] fn sync_status_lists_commits_missing_from_nostr() { let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root"); std::fs::write(dir.path().join("b.txt"), b"two").expect("write"); commit_all(&repo, "second"); let second = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("second"); std::fs::write(dir.path().join("c.txt"), b"three").expect("write"); commit_all(&repo, "third"); let third = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("third"); let branch = repo.current_branch().expect("branch"); let ahead = repo .sync_status(&[(format!("refs/heads/{branch}"), root.clone())]) .expect("status"); assert_eq!(ahead.head.as_deref(), Some(branch.as_str())); assert_eq!(ahead.ahead_total, 2); assert_eq!(ahead.ahead_commits.len(), 2); assert!(ahead.ahead_commits.contains(&second)); assert!(ahead.ahead_commits.contains(&third)); assert!(!ahead.ahead_commits.contains(&root)); let in_sync = repo .sync_status(&[(format!("refs/heads/{branch}"), third)]) .expect("status"); assert!(in_sync.ahead_commits.is_empty()); let missing = repo .sync_status(&[(format!("refs/heads/{branch}"), "0".repeat(40))]) .expect("status"); assert!(missing.ahead_commits.is_empty()); } #[test] fn publishing_a_commit_advances_the_remote_tip() { let server = tempfile::tempdir().expect("tempdir"); let server_repo = bare_server(server.path(), "npub1test", "my-repo"); let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root"); std::fs::write(dir.path().join("b.txt"), b"two").expect("write"); commit_all(&repo, "second"); let second = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("second"); std::fs::write(dir.path().join("c.txt"), b"three").expect("write"); commit_all(&repo, "third"); let third = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("third"); let branch = repo.current_branch().expect("branch"); let refname = format!("refs/heads/{branch}"); let base_url = format!("file://{}", server.path().display()); let root_refspec = format!("+{root}:{refname}"); repo.push_refspecs(&base_url, "npub1test", "my-repo", &[root_refspec.as_str()]) .expect("publish root"); assert_eq!( git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"), root ); let status = repo .sync_status(&[(refname.clone(), root.clone())]) .expect("status"); assert_eq!(status.ahead_commits.len(), 2); assert!(status.ahead_commits.contains(&second)); assert!(status.ahead_commits.contains(&third)); let second_refspec = format!("+{second}:{refname}"); repo.push_refspecs( &base_url, "npub1test", "my-repo", &[second_refspec.as_str()], ) .expect("publish second"); assert_eq!( git_in(&server_repo, &["rev-parse", refname.as_str()]).expect("server tip"), second ); let status = repo .sync_status(&[(refname, second.clone())]) .expect("status"); assert_eq!(status.ahead_commits, vec![third]); } #[test] fn sync_status_skips_a_merged_commit_that_would_rewind_the_branch() { let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root"); let branch = repo.current_branch().expect("branch"); let refname = format!("refs/heads/{branch}"); git_run(dir.path(), &["checkout", "-q", "-b", "side"]); std::fs::write(dir.path().join("side.txt"), b"side").expect("write"); commit_all(&repo, "side work"); let side = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("side"); git_run(dir.path(), &["checkout", "-q", branch.as_str()]); std::fs::write(dir.path().join("main.txt"), b"main").expect("write"); commit_all(&repo, "main work"); let mainline = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("mainline"); assert_ne!(root, mainline); git_run( dir.path(), &["merge", "-q", "--no-ff", "-m", "merge side", "side"], ); let merge = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("merge"); let status = repo.sync_status(&[(refname, mainline)]).expect("status"); assert!(status.ahead_commits.contains(&merge)); assert!(!status.ahead_commits.contains(&root)); // Publishing the side commit would drop the merge and everything after it. assert!(!status.ahead_commits.contains(&side)); } #[test] fn sync_status_skips_a_diverged_history() { let (dir, repo) = fixture(&[("a.txt", b"one")]); commit_all(&repo, "initial"); let root = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("root"); let branch = repo.current_branch().expect("branch"); let refname = format!("refs/heads/{branch}"); std::fs::write(dir.path().join("published.txt"), b"published").expect("write"); commit_all(&repo, "published"); let published = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("published"); git_run(dir.path(), &["reset", "-q", "--hard", root.as_str()]); std::fs::write(dir.path().join("local.txt"), b"local").expect("write"); commit_all(&repo, "local"); let local = git_in(dir.path(), &["rev-parse", "HEAD"]).expect("local"); let status = repo.sync_status(&[(refname, published)]).expect("status"); assert!(status.ahead_commits.is_empty()); assert!(!status.ahead_commits.contains(&local)); } #[test] fn split_patch_series_splits_real_multi_commit_mboxes() { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("repo"); let initial = Repo::init(&path, "My Repo", "desc").expect("init"); let repo = Repo::open(&path).expect("open"); git_run(&path, &["checkout", "-b", "feature"]); std::fs::write(path.join("one.txt"), "one\n").expect("write"); commit_all(&repo, "first commit"); std::fs::write(path.join("two.txt"), "two\n").expect("write"); commit_all(&repo, "second commit"); let series = repo .format_patch_between(&initial, "feature") .expect("series"); let parts = PatchParser::split_patch_series(&series); assert_eq!(parts.len(), 2); assert!(parts[0].contains("Subject: [PATCH 1/2] first commit")); assert!(parts[1].contains("Subject: [PATCH 2/2] second commit")); let first = parts[0].lines().next().expect("first header"); let second = parts[1].lines().next().expect("second header"); assert!(first.starts_with("From ") && first.len() >= 45); assert_ne!(first, second); } #[test] fn head_commit_and_commits_since_track_applied_commits() { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("repo"); let initial = Repo::init(&path, "My Repo", "desc").expect("init"); let repo = Repo::open(&path).expect("open"); assert_eq!(repo.head().as_deref(), Some(initial.as_str())); assert_eq!( repo.commits_since(None).expect("commits"), vec![initial.clone()] ); std::fs::write(path.join("one.txt"), "one\n").expect("write"); commit_all(&repo, "first commit"); let first = repo.head().expect("on a branch"); std::fs::write(path.join("two.txt"), "two\n").expect("write"); commit_all(&repo, "second commit"); let second = repo.head().expect("on a branch"); assert_eq!( repo.commits_since(Some(&initial)).expect("commits"), vec![first.clone(), second.clone()] ); assert_eq!( repo.commits_since(Some(&first)).expect("commits"), vec![second] ); } #[test] fn working_copy_cloned_from_the_mirror_matches_head_and_origin() { let dir = tempfile::tempdir().expect("tempdir"); let mirror = dir.path().join("mirror"); let commit = Repo::init(&mirror, "My Repo", "Does things.").expect("init"); Repo::open(&mirror) .expect("open") .ensure_origin("https://gitnostr.com/npub1test/my-repo.git") .expect("origin"); let destination = dir.path().join("folder").join("My_Repo"); std::fs::create_dir_all(destination.parent().unwrap()).expect("parent"); Repo::clone(&[format!("file://{}", mirror.display())], &destination).expect("clone"); Repo::open(&destination) .expect("open") .set_origin("https://gitnostr.com/npub1test/my-repo.git") .expect("set origin"); let working = Repo::open(&destination).expect("open"); assert_eq!( working.origin_url().expect("url").as_deref(), Some("https://gitnostr.com/npub1test/my-repo.git") ); assert_eq!(working.head().as_deref(), Some(commit.as_str())); assert!(destination.join("README.md").is_file()); } #[test] fn fast_forward_branches_moves_the_mirror_and_keeps_local_work() { let dir = tempfile::tempdir().expect("tempdir"); bare_server(dir.path(), "npub1test", "repo"); let (work_dir, work_repo) = fixture(&[("a.txt", b"one")]); commit_all(&work_repo, "initial"); let work = work_dir.path(); let base_url = format!("file://{}", dir.path().display()); work_repo .push_all(&base_url, "npub1test", "repo") .expect("push"); let mirror = dir.path().join("mirror"); git_run( dir.path(), &[ "clone", "-q", &format!("{base_url}/npub1test/repo.git"), mirror.to_str().unwrap(), ], ); let initial = git_in(&mirror, &["rev-parse", "HEAD"]).expect("initial"); let repo = Repo::open(&mirror).expect("open"); std::fs::write(work.join("new.txt"), b"new\n").expect("write"); commit_all(&work_repo, "new commit"); work_repo .push_all(&base_url, "npub1test", "repo") .expect("push"); git_run(&mirror, &["fetch", "origin"]); let remote = git_in(&mirror, &["rev-parse", "refs/remotes/origin/main"]).expect("remote"); assert_eq!( git_in(&mirror, &["rev-parse", "HEAD"]).expect("local"), initial ); assert_ne!(remote, initial); assert!(repo.fast_forward_branches().expect("ff")); assert_eq!( git_in(&mirror, &["rev-parse", "HEAD"]).expect("local"), remote ); assert!(mirror.join("new.txt").is_file()); assert!(!repo.fast_forward_branches().expect("idle")); git_run(&mirror, &["checkout", "-b", "wip"]); std::fs::write(mirror.join("wip.txt"), b"wip\n").expect("write"); commit_all(&repo, "local wip"); let wip = git_in(&mirror, &["rev-parse", "HEAD"]).expect("wip"); assert!(!repo.fast_forward_branches().expect("wip skipped")); assert_eq!( git_in(&mirror, &["rev-parse", "HEAD"]).expect("wip kept"), wip ); } #[test] fn fetch_repo_refs_imports_heads_under_a_prefix() { let dir = tempfile::tempdir().expect("tempdir"); let base_server = bare_server(dir.path(), "npub1base", "base"); let (upstream_dir, upstream_repo) = fixture(&[("a.txt", b"one")]); commit_all(&upstream_repo, "initial"); let upstream_path = upstream_dir.path(); let initial = git_in(upstream_path, &["rev-parse", "HEAD"]).expect("initial"); upstream_repo .push_all( &format!("file://{}", dir.path().display()), "npub1base", "base", ) .expect("push"); let base_url = format!("file://{}", base_server.display()); let mirror = dir.path().join("mirror"); git_run( dir.path(), &["clone", "-q", &base_url, mirror.to_str().unwrap()], ); let mirror_repo = Repo::open(&mirror).expect("open"); let fork_work = dir.path().join("fork-work"); git_run( dir.path(), &["clone", "-q", &base_url, fork_work.to_str().unwrap()], ); git_run(&fork_work, &["checkout", "-b", "feature"]); std::fs::write(fork_work.join("feature.txt"), "feature\n").expect("write"); commit_all(&Repo::open(&fork_work).expect("open"), "feature commit"); let tip = git_in(&fork_work, &["rev-parse", "HEAD"]).expect("tip"); let fork_server = bare_server(dir.path(), "npub1fork", "fork"); Repo::open(&fork_work) .expect("open") .push_ref( &format!("file://{}", fork_server.display()), &tip, "refs/heads/feature", ) .expect("push"); let dead = format!("file://{}/missing.git", dir.path().display()); mirror_repo .fetch_refs( &[dead, format!("file://{}", fork_server.display())], "+refs/heads/*:refs/fork/npub1fork/fork/*", ) .expect("fetch"); assert_eq!( mirror_repo .refs_with_prefix("refs/fork/npub1fork/fork") .expect("refs"), vec!["refs/fork/npub1fork/fork/feature"] ); assert_eq!( mirror_repo .refs_with_prefix("refs/heads/fork") .expect("refs"), Vec::::new() ); assert_eq!( mirror_repo .merge_base( "refs/remotes/origin/main", "refs/fork/npub1fork/fork/feature", ) .expect("merge base") .as_deref(), Some(initial.as_str()) ); let patch = mirror_repo .format_patch_between(&initial, "refs/fork/npub1fork/fork/feature") .expect("patch"); assert!(patch.contains("Subject: [PATCH] feature commit")); assert!(patch.contains("feature.txt")); mirror_repo .delete_refs_with_prefix("refs/fork/npub1fork/fork") .expect("delete"); assert_eq!( mirror_repo .refs_with_prefix("refs/fork/npub1fork/fork") .expect("refs"), Vec::::new() ); } /// Runs `git` in `dir`, failing the test on a non-zero exit. fn git_run(dir: &Path, args: &[&str]) -> std::process::Output { let output = Command::new("git") .current_dir(dir) .env("GIT_AUTHOR_NAME", "Test Author") .env("GIT_AUTHOR_EMAIL", "test@example.com") .env("GIT_COMMITTER_NAME", "Test Author") .env("GIT_COMMITTER_EMAIL", "test@example.com") .env("GIT_EDITOR", "true") .args(args) .output() .expect("spawn git"); assert!(output.status.success(), "git {args:?} failed"); output } fn git_in(dir: &Path, args: &[&str]) -> anyhow::Result { let output = git_run(dir, args); Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned()) } #[test] fn find_git_repos_reports_the_outermost_repository() { let root = tempfile::tempdir().expect("tempdir"); let repo_dir = root.path().join("project").join("sub"); std::fs::create_dir_all(&repo_dir).expect("mkdir"); git_run(&repo_dir, &["init", "-q"]); let plain_dir = root.path().join("plain").join("deep"); std::fs::create_dir_all(&plain_dir).expect("mkdir"); let repos = LocalRepo::find_all(root.path()); assert_eq!(repos.len(), 1); assert_eq!(repos[0].path, repo_dir.canonicalize().expect("canonical")); assert!(repos[0].nip34.is_none()); } #[test] fn find_git_repos_skips_repositories_nested_in_repositories() { let root = tempfile::tempdir().expect("tempdir"); let outer = root.path().join("outer"); std::fs::create_dir_all(&outer).expect("mkdir"); git_run(&outer, &["init", "-q"]); let nested = outer.join("nested"); std::fs::create_dir_all(&nested).expect("mkdir"); git_run(&nested, &["init", "-q"]); let repos = LocalRepo::find_all(root.path()); assert_eq!(repos.len(), 1); assert_eq!(repos[0].path, outer.canonicalize().expect("canonical")); } #[test] fn find_git_repos_ignores_a_repository_above_the_scan_root() { let outer = tempfile::tempdir().expect("tempdir"); git_run(outer.path(), &["init", "-q"]); let root = outer.path().join("scan"); std::fs::create_dir_all(&root).expect("mkdir"); assert!(LocalRepo::find_all(&root).is_empty()); } /// Creates an empty bare server repository for push tests. fn bare_server(base: &Path, owner: &str, name: &str) -> PathBuf { let repo = base.join(owner).join(format!("{name}.git")); std::fs::create_dir_all(repo.parent().expect("parent")).expect("mkdir"); git_run( base, &["init", "--bare", "-q", repo.to_str().expect("utf8 path")], ); repo } #[test] fn patch_commits_lists_every_patch_in_order() { let patch = r#"From 1111111111111111111111111111111111111111 Mon Sep 17 00:00:00 2001 From: Alice Date: Tue, 1 Aug 2023 10:00:00 +0200 Subject: [PATCH 1/2] first body one --- a.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/a.txt b/a.txt @@ -1 +1,2 @@ a +b From 2222222222222222222222222222222222222222 Mon Sep 17 00:00:00 2001 From: Bob Date: Wed, 2 Aug 2023 11:30:00 +0000 Subject: [PATCH 2/2] second body two --- b.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/b.txt b/b.txt @@ -1 +1,2 @@ x +y "#; let commits = PatchParser::patch_commits(patch); assert_eq!(commits.len(), 2); assert_eq!(commits[0].id, "1111111111111111111111111111111111111111"); assert_eq!(commits[0].summary, "first"); assert_eq!(commits[0].author, "Alice"); assert_eq!(commits[0].time, 1690876800); assert_eq!(commits[1].id, "2222222222222222222222222222222222222222"); assert_eq!(commits[1].summary, "second"); assert_eq!(commits[1].author, "Bob"); assert_eq!(commits[1].time, 1690975800); let stats = PatchParser::patch_commits_with_stats(patch); assert_eq!(stats.len(), 2); assert_eq!((stats[0].1, stats[0].2), (1, 0)); assert_eq!((stats[1].1, stats[1].2), (1, 0)); } #[test] fn parses_real_format_patch_output() { let (dir, repo) = fixture(&[ ("src/main.rs", b"fn main() {\n println!(\"one\");\n}\n"), ("my file.txt", b"hello\n"), ("\u{8bf4}\u{660e}.md", "# \u{8bf4}\u{660e}\n".as_bytes()), ("img.png", b"\x89PNG\r\n\x1a\n\x00binary"), ]); commit_all(&repo, "initial"); std::fs::write( dir.path().join("src/main.rs"), b"fn main() {\n println!(\"two\");\n println!(\"three\");\n}\n", ) .expect("write"); std::fs::write(dir.path().join("my file.txt"), b"hello world\n").expect("write"); std::fs::write( dir.path().join("\u{8bf4}\u{660e}.md"), "# \u{8bf4}\u{660e}\nupdated\n", ) .expect("write"); std::fs::remove_file(dir.path().join("img.png")).expect("remove"); std::fs::write(dir.path().join("new file.md"), b"# new\n").expect("write"); commit_all(&repo, "changes"); let output = git_run(dir.path(), &["format-patch", "-1", "--stdout"]); let patch = String::from_utf8(output.stdout).expect("patch is utf-8"); let diff = PatchParser::patch_diffs(&patch).expect("parse real format-patch output"); let by_path = |path: &str| { diff.files .iter() .find(|file| file.path == path) .unwrap_or_else(|| panic!("missing file {path:?}")) }; let file = by_path("my file.txt"); assert_eq!(file.status, DiffStatus::Modified); assert_eq!(file.insertions, 1); let file = by_path("\u{8bf4}\u{660e}.md"); assert_eq!(file.status, DiffStatus::Modified); assert_eq!(file.insertions, 1); let file = by_path("src/main.rs"); assert_eq!(file.status, DiffStatus::Modified); assert_eq!(file.insertions, 2); assert_eq!(file.deletions, 1); assert!(!file.hunks.is_empty()); let file = by_path("new file.md"); assert_eq!(file.status, DiffStatus::Added); assert_eq!(file.insertions, 1); let file = by_path("img.png"); assert_eq!(file.status, DiffStatus::Deleted); assert!(file.binary); assert!(file.hunks.is_empty()); assert_eq!(file.insertions, 0); assert_eq!(file.deletions, 0); } #[test] fn entries_at_lists_a_commits_files_directories_first() { let (_dir, repo) = fixture(&[ ("README", b"plain"), ("docs/README.md", b"# Docs"), ("notes.txt", b"one"), ("readme.md", b"# Title"), ("src/lib.rs", b"fn old() {}"), ]); commit_all(&repo, "initial"); let first = repo.head_commit().expect("head").expect("commit").id; let expected = vec![ PathBuf::from("docs"), PathBuf::from("src"), PathBuf::from("README"), PathBuf::from("docs/README.md"), PathBuf::from("notes.txt"), PathBuf::from("readme.md"), PathBuf::from("src/lib.rs"), ]; let entries = repo.entries_at(&first).expect("entries"); assert_eq!(entries, expected); assert_eq!(repo.entries().expect("entries"), expected); assert_eq!( Repo::pick_readme(&entries).as_deref(), Some(Path::new("readme.md")) ); assert_eq!( repo.find_readme().expect("readme").as_deref(), Some(Path::new("readme.md")) ); } #[test] fn read_at_reads_the_files_of_that_commit() { let (dir, repo) = fixture(&[("notes.txt", b"one"), ("src/lib.rs", b"fn old() {}")]); commit_all(&repo, "initial"); let first = repo.head_commit().expect("head").expect("commit").id; std::fs::write(dir.path().join("src/lib.rs"), b"fn new() {}").expect("write"); std::fs::remove_file(dir.path().join("notes.txt")).expect("remove"); commit_all(&repo, "second"); let second = repo.head_commit().expect("head").expect("commit").id; assert_eq!( repo.read_at(&first, Path::new("src/lib.rs")) .expect("read") .as_deref(), Some(b"fn old() {}".as_slice()) ); assert_eq!( repo.read_at(&second, Path::new("src/lib.rs")) .expect("read") .as_deref(), Some(b"fn new() {}".as_slice()) ); assert_eq!( repo.read_at(&second, Path::new("notes.txt")).expect("read"), None ); assert_eq!(repo.read_at(&second, Path::new("src")).expect("read"), None); assert!( repo.read_at("0000000000000000000000000000000000000000", Path::new("src")) .is_err() ); } /// Creates a fresh repository in a temp directory. fn init_repo() -> (tempfile::TempDir, std::path::PathBuf) { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("repo"); std::fs::create_dir_all(&path).expect("mkdir"); git(&path, &["init", "-q"]); (dir, path) } /// Runs `git` in `dir`, failing the test on a non-zero exit. fn git(dir: &Path, args: &[&str]) { let status = Command::new("git") .current_dir(dir) .env("GIT_AUTHOR_NAME", "Test Author") .env("GIT_AUTHOR_EMAIL", "test@example.com") .env("GIT_COMMITTER_NAME", "Test Author") .env("GIT_COMMITTER_EMAIL", "test@example.com") .env("GIT_EDITOR", "true") .args(args) .status() .expect("spawn git"); assert!(status.success(), "git {args:?} failed"); } /// Generates a fresh public key. fn key() -> PublicKey { Keys::generate().public_key() } /// Encodes a NIP-34 coordinate as an `naddr` string. fn naddr(kind: Kind, owner: PublicKey, identifier: &str) -> String { let coordinate = Coordinate::new(kind, owner).identifier(identifier); Nip19Coordinate::new(coordinate, Vec::::new()) .to_bech32() .expect("naddr") } /// Opens the repository at `path` and returns its NIP-34 binding. fn binding_of(path: &Path) -> Option { Repo::open(path).ok()?.nip34_binding() } #[test] fn plain_repository_has_no_binding() { let (_dir, path) = init_repo(); assert!(binding_of(&path).is_none()); } #[test] fn nip34_json_marks_a_repository_initialized() { let (_dir, path) = init_repo(); let owner = key(); let npub = owner.to_bech32().expect("npub"); std::fs::write( path.join("nip34.json"), format!(r#"{{"identifier":"my-repo","owner":"{npub}"}}"#), ) .expect("write"); let binding = binding_of(&path).expect("binding"); assert_eq!(binding.kind, Nip34Kind::Initialized); assert!(binding.signals.nip34_json); assert_eq!(binding.owner, Some(owner)); assert_eq!(binding.identifier.as_deref(), Some("my-repo")); } #[test] fn malformed_nip34_json_is_ignored() { let (_dir, path) = init_repo(); std::fs::write(path.join("nip34.json"), b"not json").expect("write"); assert!(binding_of(&path).is_none()); } #[test] fn commit_patch_applies_cleanly_to_parent() { let (dir, path) = init_repo(); git(&path, &["config", "user.name", "Test Author"]); git(&path, &["config", "user.email", "test@example.com"]); std::fs::write(path.join("file.txt"), "one\n").expect("write"); git(&path, &["add", "."]); git(&path, &["commit", "-q", "-m", "first"]); std::fs::write(path.join("file.txt"), "two\n").expect("write"); std::fs::write(path.join("file2.txt"), "added\n").expect("write"); git(&path, &["add", "."]); git(&path, &["commit", "-q", "-m", "second"]); let patch = Repo::open(&path) .expect("open repo") .commit_patch("HEAD") .expect("commit patch"); assert!(patch.contains("diff --git a/file.txt b/file.txt")); assert!(patch.contains("diff --git a/file2.txt b/file2.txt")); assert!(patch.contains("--- /dev/null")); assert!(patch.contains("+added")); let patch_path = dir.path().join("head.patch"); std::fs::write(&patch_path, &patch).expect("write patch"); git(&path, &["checkout", "-q", "--detach", "HEAD~1"]); git( &path, &["apply", patch_path.to_str().expect("utf8 patch path")], ); let applied = std::fs::read_to_string(path.join("file.txt")).expect("read"); assert_eq!(applied, "two\n"); assert_eq!( std::fs::read_to_string(path.join("file2.txt")).expect("read"), "added\n" ); } #[test] fn nak_exclude_and_state_refs_are_detected() { let (_dir, path) = init_repo(); std::fs::create_dir_all(path.join(".git/info")).expect("mkdir"); std::fs::write(path.join(".git/info/exclude"), "nip34.json\n").expect("write"); git(&path, &["commit", "-q", "--allow-empty", "-m", "initial"]); git( &path, &["update-ref", "refs/heads/nip34/state/HEAD", "HEAD"], ); let binding = binding_of(&path).expect("binding"); assert_eq!(binding.kind, Nip34Kind::Initialized); assert!(binding.signals.nip34_excluded); assert!(binding.signals.nip34_state_refs); } #[test] fn nostr_repo_config_marks_a_repository_initialized() { let (_dir, path) = init_repo(); let owner = key(); let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo"); git(&path, &["config", "nostr.repo", &naddr]); let binding = binding_of(&path).expect("binding"); assert_eq!(binding.kind, Nip34Kind::Initialized); assert!(binding.signals.nostr_repo_config); assert_eq!(binding.owner, Some(owner)); assert_eq!(binding.identifier.as_deref(), Some("my-repo")); } #[test] fn the_written_nostr_repo_marker_is_detected() { let (_dir, path) = init_repo(); let owner = key(); let naddr = naddr(Kind::GitRepoAnnouncement, owner, "my-repo"); Repo::open(&path) .expect("open") .set_nostr_repo(&naddr) .expect("write marker"); let binding = binding_of(&path).expect("binding"); assert_eq!(binding.kind, Nip34Kind::Initialized); assert!(binding.signals.nostr_repo_config); assert_eq!(binding.owner, Some(owner)); assert_eq!(binding.identifier.as_deref(), Some("my-repo")); } #[test] fn nostr_remote_is_a_nip34_clone() { let (_dir, path) = init_repo(); let owner = key(); let npub = owner.to_bech32().expect("npub"); let url = format!("nostr://{npub}/relay.ngit.dev/my-repo"); git(&path, &["remote", "add", "origin", &url]); let binding = binding_of(&path).expect("binding"); assert_eq!(binding.kind, Nip34Kind::Cloned); assert!(binding.signals.nostr_remote); assert_eq!(binding.owner, Some(owner)); assert_eq!(binding.identifier.as_deref(), Some("my-repo")); } #[test] fn nak_grasp_remote_marks_a_repository_initialized() { let (_dir, path) = init_repo(); let owner = key(); let npub = owner.to_bech32().expect("npub"); let url = format!("https://gitnostr.com/{npub}/my-repo.git"); git( &path, &["config", "remote.nip34/grasp/gitnostr.com.url", &url], ); let binding = binding_of(&path).expect("binding"); assert_eq!(binding.kind, Nip34Kind::Initialized); assert!(binding.signals.nip34_grasp_remote); assert!(binding.signals.grasp_remote); assert_eq!(binding.grasp_urls, vec![url]); assert_eq!(binding.owner, Some(owner)); assert_eq!(binding.identifier.as_deref(), Some("my-repo")); } #[test] fn nostr_cache_alone_is_tooling_only() { let (_dir, path) = init_repo(); std::fs::write(path.join(".git/nostr-cache.lmdb"), b"cache").expect("write"); let binding = binding_of(&path).expect("binding"); assert_eq!(binding.kind, Nip34Kind::ToolingOnly); assert!(binding.signals.nostr_cache); } #[test] fn grasp_urls_are_recognised_by_shape() { let owner = key(); let npub = owner.to_bech32().expect("npub"); assert!(Repo::is_grasp_url(&format!( "https://gitnostr.com/{npub}/my-repo.git" ))); assert!(Repo::is_grasp_url(&format!( "grasp://gitnostr.com/{npub}/my-repo.git" ))); assert!(!Repo::is_grasp_url("https://gitnostr.com/my-repo.git")); assert!(!Repo::is_grasp_url( "https://gitnostr.com/not-a-pubkey/my-repo.git" )); assert!(!Repo::is_grasp_url(&format!( "ssh://gitnostr.com/{npub}/my-repo.git" ))); }