Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

Explain actual partial-clone failures without rejecting usable sources

xerj-orgf82859444104
diff --cc engine/crates/xerj-autoindex/src/xc.rs
index fc1c248fe,2e1d879d6..4aac2a118
--- a/engine/crates/xerj-autoindex/src/xc.rs
+++ b/engine/crates/xerj-autoindex/src/xc.rs
@@@ -452,6 -444,11 +452,10 @@@ the list is written back into corpus.js
a local checkout's root .xerjignore is copied into the clone when it differs
from the committed file (git clone drops an untracked or uncommitted one);
a pinned --from rebuild stays exact and does not copy it, and says so;
-a local partial clone (git clone --filter=blob:none) is refused with its
-reason instead of being reported as corruption: its blobs are fetched on
-demand, so cloning from it fails inside upload-pack; index that checkout in
-place with 'xerj autoindex <path> --prefix <name>', or re-clone without
---filter and add that;
++if cloning a local partial clone fails, its promisor configuration is
++reported as a possible source of missing-object errors. Hydrated partial
++clones remain accepted. Index only already-present working-tree files with
++'xerj autoindex <path>', or use a complete clone as the corpus source;
--from takes the corpus name from the manifest's 'corpus' field (or the
pack's 'pack' field) unless <name> or --as overrides it; a harvested pack
also checksum-verifies and materializes records per source; --verify-sig
@@@ -986,6 -795,59 +990,58 @@@ fn local_checkout_root(url: &str) -> Op
path.is_dir().then_some(path)
}
-/// Why `src` is a partial clone, if it is one (#2576).
-///
-/// `git clone --filter=blob:none` leaves the blobs outside the checked-out
-/// paths unfetched and records a promisor remote to fetch them on demand. The
-/// working tree reads normally — which is why `xerj autoindex <that path>`
-/// works — but the checkout cannot serve as a clone *source*: upload-pack has
-/// to materialize every object at the tip, cannot, and dies with
-/// `unable to read sha1 file of …` or, on newer git, "repository corruption".
-/// Neither wording says "partial clone", so a valid checkout gets reported as
-/// a damaged one.
-///
-/// Detected from the config the filter writes, not by probing for absent
-/// objects: `extensions.partialClone` on current git, `remote.origin.promisor`
-/// on older ones. Both are written at clone time, so this costs two
-/// `git config` reads and no object walk.
++/// Partial-clone configuration is context for an observed clone failure,
++/// not proof that objects are missing. A hydrated source remains cloneable.
++/// Git supports multiple named promisor remotes, not only `origin`.
+ fn partial_clone_cause(src: &Path) -> Option<String> {
- let read = |key: &str| {
- git(Some(src), &["config", "--get", key])
- .ok()
- .filter(|(rc, _)| *rc == 0)
- .map(|(_, out)| out.trim().to_string())
- .filter(|v| !v.is_empty())
++ let concise = |value: &str| {
++ value
++ .chars()
++ .filter(|c| !c.is_control())
++ .take(120)
++ .collect::<String>()
+ };
- if let Some(v) = read("extensions.partialclone") {
- return Some(format!("extensions.partialClone={v}"));
++ if let Ok((0, out, _)) = git_stdout(src, &["config", "--get", "extensions.partialclone"]) {
++ if !out.is_empty() {
++ return Some(format!("extensions.partialClone={}", concise(&out)));
++ }
+ }
- match read("remote.origin.promisor") {
- Some(v) if v == "true" => Some("remote.origin.promisor=true".to_string()),
- _ => None,
++ if let Ok((0, out, _)) = git_stdout(
++ src,
++ &[
++ "config",
++ "--type=bool",
++ "--get-regexp",
++ r"^remote\..*\.promisor$",
++ ],
++ ) {
++ for line in out.lines() {
++ if let Some(key) = line.strip_suffix(" true") {
++ return Some(format!("{}=true", concise(key)));
++ }
++ }
+ }
++ None
+ }
+
-/// The lines `corpus add` prints when it refuses a partial clone (#2576).
-///
-/// Split out from the loop so the wording is testable — the whole point of the
-/// issue is the message, and `eprintln!` cannot be captured in-process.
-fn partial_clone_refusal(repo_name: &str, src: &Path, cause: &str) -> Vec<String> {
++/// Advice is conditional and follows Git's actual failure. Quote the source
++/// path for the named shell; the partial working tree may cover only a subset.
++fn partial_clone_failure_hint(repo_name: &str, src: &Path, cause: &str) -> Vec<String> {
++ let path = src.to_string_lossy();
++ #[cfg(not(windows))]
++ let (shell, quoted) = (
++ "POSIX shell",
++ format!("'{}'", path.replace('\'', "'\"'\"'")),
++ );
++ #[cfg(windows)]
++ let (shell, quoted) = ("PowerShell", format!("'{}'", path.replace('\'', "''")));
+ vec![
- format!(
- " [FAIL] {repo_name}: {} is a partial clone ({cause}) — its blobs are fetched on \
- demand, so cloning from it fails with a misleading \"repository corruption\"; \
- continuing",
- src.display()
- ),
- format!(
- "xerj corpus add: index the working tree in place: \
- xerj autoindex {} --prefix {repo_name}",
- src.display()
- ),
- "xerj corpus add: or re-clone it without --filter and add that checkout".to_string(),
++ format!("xerj corpus add: the source has partial-clone configuration ({cause}); missing promised objects may explain this Git failure"),
++ format!("xerj corpus add: to index only files already present in its working tree ({shell}): xerj autoindex {quoted} --prefix {repo_name}"),
++ "xerj corpus add: for a complete corpus, restore access to the promisor remote or use a new clone made without --filter, then retry".to_string(),
+ ]
+ }
+
/// `file:///abs/path` → `/abs/path`. `file://localhost/abs/path` → `/abs/path`.
fn file_url_path(rest: &str) -> Option<PathBuf> {
let path = if rest.starts_with('/') {
@@@ -1501,29 -1339,45 +1557,37 @@@ fn run_corpus_add(args: &[String]) -> i
);
continue;
}
- // #2576: a partial clone has no blobs outside its checked-out paths,
- // so cloning FROM it fails inside upload-pack — with git's "repository
- // corruption" wording, which names the wrong problem. Refuse with the
- // reason and the two ways forward, before git prints anything at all.
- if let Some(src) = local_checkout_root(&url) {
- if let Some(cause) = partial_clone_cause(&src) {
- for line in partial_clone_refusal(&repo_name, &src, &cause) {
- eprintln!("{line}");
- }
- skipped.push(repo_name);
- continue;
- }
- }
println!(" [clone] {repo_name}");
- if sha.is_empty() {
- if let Some(parent) = target.parent() {
- let _ = std::fs::create_dir_all(parent);
- }
- // Never a shell string: the URL and target are single argv
- // elements, so a hostile URL cannot smuggle flags.
- let target_s = target.to_string_lossy().to_string();
- let (rc, _) = git(None, &["clone", "--depth", "1", "--quiet", &url, &target_s])
- .unwrap_or((-1, String::new()));
- if rc != 0 {
- let (rc2, _) = git(None, &["clone", "--depth", "1", &url, &target_s])
- .unwrap_or((-1, String::new()));
- if rc2 != 0 {
- eprintln!(" [FAIL] {repo_name} — could not clone; continuing");
- skipped.push(repo_name);
- continue;
+ let cloned = stage_new_checkout(&target, |checkout| {
+ if sha.is_empty() {
+ let target_s = checkout.to_string_lossy().to_string();
+ let (rc, output) = git(None, &["clone", "--depth", "1", "--", &url, &target_s])?;
+ if rc != 0 {
+ let shown: String = output
+ .replace(&url, "[source]")
+ .chars()
+ .take(GIT_FETCH_OUTPUT_CAP)
+ .collect();
- anyhow::bail!("git clone failed (exit {rc}): {shown}");
++ let hint = local_checkout_root(&url)
++ .and_then(|src| {
++ partial_clone_cause(&src).map(|cause| {
++ partial_clone_failure_hint(&repo_name, &src, &cause).join("\n")
++ })
++ })
++ .map(|lines| format!("\n{lines}"))
++ .unwrap_or_default();
++ anyhow::bail!("git clone failed (exit {rc}): {shown}{hint}");
}
+ Ok(())
+ } else {
+ println!(" [pin] {repo_name} -> {}{note}", &sha[..12.min(sha.len())]);
+ checkout_at_sha_paths(checkout, &url, &sha, &paths)
}
- } else {
- println!(" [pin] {repo_name} -> {}{note}", &sha[..12.min(sha.len())]);
- if let Err(e) = checkout_at_sha_paths(&target, &url, &sha, &paths) {
- eprintln!(" [FAIL] {repo_name}: {e:#}; continuing");
- skipped.push(repo_name);
- continue;
- }
+ });
+ if let Err(e) = cloned {
+ eprintln!(" [FAIL] {repo_name}: {e:#}; continuing");
+ skipped.push(repo_name);
+ continue;
}
carry_ignore(&target);
record(
@@@ -5711,433 -5518,201 +5775,574 @@@ precedence = ["a", "b"
let home = tempfile::tempdir().unwrap();
let _h = code_home(home.path());
let origin = home.path().join("widget");
- init_committed_repo(&origin, &[("src/lib.rs", "fn mine() {}\n")]);
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let clone = home.path().join("corpora/partial/widget");
+ std::fs::create_dir_all(&clone).unwrap();
+ let (rc, out) = git(Some(&clone), &["init", "--quiet"]).unwrap();
+ assert_eq!(rc, 0, "git init: {out}");
+ std::fs::remove_dir_all(clone.join(".git/objects")).unwrap();
+ std::fs::write(clone.join(".git/config.lock"), "").unwrap();
assert_eq!(
- run_corpus_add(&["plain".into(), origin.display().to_string()]),
- 0
+ run_corpus_add(&["partial".into(), origin.display().to_string()]),
+ 1
);
- let plain =
- manifest::read_corpus_manifest(&home.path().join("corpora/plain/corpus.json")).unwrap();
- assert!(!plain.own, "a local path is not own unless --own is passed");
- assert_eq!(plain.repos[0].licence, "NONE-FOUND");
-
+ let backup = preserve_incomplete_for_retry(&clone);
+ assert!(backup.join(".git/HEAD").is_file());
assert_eq!(
- run_corpus_add(&["--own".into(), "mine".into(), origin.display().to_string()]),
+ run_corpus_add(&["partial".into(), origin.display().to_string()]),
0
);
- let mine_path = home.path().join("corpora/mine/corpus.json");
- let mine = manifest::read_corpus_manifest(&mine_path).unwrap();
- assert!(mine.own);
- assert_eq!(mine.repos[0].licence, "NONE-FOUND");
- let text = std::fs::read_to_string(&mine_path).unwrap();
- assert!(text.contains("\"own\":true"), "{text}");
-
assert_eq!(
- run_corpus_add(&["mine".into(), origin.display().to_string()]),
- 0,
- "re-add without --own keeps the marker"
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "tracked\n"
);
- assert!(manifest::read_corpus_manifest(&mine_path).unwrap().own);
+ }
- let sha = head_sha(&origin);
- let pin = home.path().join("hostile.json");
- std::fs::write(
- &pin,
- format!(
- r#"{{"corpus":"from-file","own":true,"repos":[{{"repo":"widget","url":"{}","sha":"{sha}","licence":"UNKNOWN"}}]}}"#,
- origin.display()
- ),
- )
- .unwrap();
- assert_eq!(
- run_corpus_add(&["--from".into(), pin.display().to_string()]),
- 0
- );
- let from_path = home.path().join("corpora/from-file/corpus.json");
- let from = manifest::read_corpus_manifest(&from_path).unwrap();
+ /// A finished checkout is reused, but a missing index is preserved and
+ /// refused even when the remote is offline. Recovery keeps local notes.
+ #[test]
+ fn corpus_add_preserves_an_ambiguous_checkout_when_remote_is_offline() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
+ let add = || run_corpus_add(&["mid".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/mid/widget");
+ assert_eq!(add(), 0);
+
+ std::fs::write(clone.join("marker"), "kept\n").unwrap();
+ assert_eq!(add(), 0);
assert!(
- !from.own,
- "a --from manifest must not be able to set own: {}",
- std::fs::read_to_string(&from_path).unwrap()
+ clone.join("marker").exists(),
+ "a finished clone is not touched"
);
- assert_eq!(run_corpus_own(&["from-file".into()]), 0);
- assert!(manifest::read_corpus_manifest(&from_path).unwrap().own);
+ kill_mid_checkout(&clone, "b.txt");
+ std::fs::rename(&origin, home.path().join("gone")).unwrap();
assert_eq!(
- manifest::read_corpus_manifest(&from_path).unwrap().repos[0].licence,
- "NONE-FOUND"
+ add(),
+ 1,
+ "missing index is ambiguous even when the remote is unavailable"
);
- assert_eq!(run_corpus_own(&["from-file".into(), "--off".into()]), 0);
- let cleared = std::fs::read_to_string(&from_path).unwrap();
- assert!(!cleared.contains("own"), "{cleared}");
- assert!(!manifest::read_corpus_manifest(&from_path).unwrap().own);
-
- assert_eq!(run_corpus_own(&["missing".into()]), 2);
- assert_eq!(run_corpus_own(&[]), 2);
- assert!(CORPUS_USAGE.contains("xerj corpus own"));
- assert!(CORPUS_USAGE.contains("--own"));
- assert!(CORPUS_USAGE.contains("file classes") || CORPUS_USAGE.contains("per-file-class"));
+ assert!(!clone.join("b.txt").exists());
+ assert_eq!(
+ std::fs::read_to_string(clone.join("marker")).unwrap(),
+ "kept\n"
+ );
+ let backup = preserve_incomplete_for_retry(&clone);
+ std::fs::rename(home.path().join("gone"), &origin).unwrap();
+ assert_eq!(add(), 0);
+ assert_eq!(std::fs::read_to_string(clone.join("b.txt")).unwrap(), "b\n");
+ assert!(
+ backup.join("marker").exists(),
+ "local files remain in the saved directory"
+ );
+ let recorded =
+ manifest::read_corpus_manifest(&home.path().join("corpora/mid/corpus.json")).unwrap();
+ // Only the committed a.txt and b.txt are in the new checkout.
+ assert_eq!(recorded.repos[0].files, Some(2));
}
- /// #2576: both spellings the filter writes are recognised, and a complete
- /// checkout — even one with a remote — is not a partial clone.
+ /// A leftover `.git/index.lock` may belong to a git that is still
+ /// running, so the run fails and touches nothing. Removing a lock alone
+ /// does not authorize overwriting files when the index is still absent.
#[test]
- fn partial_clone_cause_reads_both_config_spellings() {
- let dir = tempfile::tempdir().unwrap();
+ fn corpus_add_refuses_a_checkout_left_with_index_lock() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
+ let add = || run_corpus_add(&["locked".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/locked/widget");
+ assert_eq!(add(), 0);
+
+ kill_mid_checkout(&clone, "b.txt");
+ std::fs::write(clone.join(".git/index.lock"), "").unwrap();
+ assert_eq!(add(), 1);
+ assert!(
+ clone.join(".git/index.lock").exists(),
+ "the lock is not deleted"
+ );
+ assert!(!clone.join("b.txt").exists());
+
+ std::fs::remove_file(clone.join(".git/index.lock")).unwrap();
+ assert_eq!(
+ add(),
+ 1,
+ "removing a lock does not authorize resetting local files"
+ );
+ let backup = preserve_incomplete_for_retry(&clone);
+ assert!(backup.join("a.txt").exists());
+ assert_eq!(add(), 0);
+ assert_eq!(std::fs::read_to_string(clone.join("b.txt")).unwrap(), "b\n");
+ }
+
+ /// When the files cannot be restored the run fails and the checkout,
+ /// with every object in it, is kept for the next try.
+ #[cfg(unix)]
+ #[test]
+ fn corpus_add_keeps_a_checkout_it_cannot_restore() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("a.txt", "a\n"), ("b.txt", "b\n")]);
+ let add = || run_corpus_add(&["stuck".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/stuck/widget");
+ assert_eq!(add(), 0);
+ kill_mid_checkout(&clone, "b.txt");
+ assert_eq!(add(), 1);
+ assert!(clone.join(".git").is_dir(), "the checkout is kept");
+ assert_eq!(std::fs::read_to_string(clone.join("a.txt")).unwrap(), "a\n");
+ assert!(!clone.join("b.txt").exists());
+ }
+
+ /// A pinned checkout without HEAD is kept, not silently republished.
+ /// Moving it aside permits a fresh checkout at the declared pin.
+ #[test]
+ fn corpus_add_from_preserves_a_pin_without_head_before_recovery() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(
+ &origin,
+ &[("LICENSE", "bsd\n"), ("src/a.rs", "fn a() {}\n")],
+ );
+ let manifest = home.path().join("pin.json");
+ write_pin(
+ &manifest,
+ &origin.display().to_string(),
+ &head_sha(&origin),
+ None,
+ );
+ let add = || run_corpus_add(&["--from".into(), manifest.display().to_string()]);
+ let checkout = home.path().join("corpora/sparse-demo/vulndb");
+ assert_eq!(add(), 0);
+
+ kill_mid_checkout(&checkout, "src/a.rs");
+ std::fs::write(checkout.join(".git/HEAD"), "ref: refs/heads/unborn\n").unwrap();
+ assert_eq!(add(), 1);
+ assert!(checkout.join("LICENSE").is_file());
+ let backup = preserve_incomplete_for_retry(&checkout);
+ assert!(backup.join("LICENSE").is_file());
+ assert_eq!(add(), 0);
+ assert_eq!(
+ worktree_files(&checkout),
+ vec!["LICENSE".to_string(), "src/a.rs".to_string()]
+ );
+ assert!(!checkout.join(".git/index.lock").exists());
+ }
+
+ /// HEAD at the pin does not make a missing index safe to reset.
+ #[test]
+ fn corpus_add_from_preserves_a_pin_without_index_before_recovery() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(
+ &origin,
+ &[("LICENSE", "bsd\n"), ("src/a.rs", "fn a() {}\n")],
+ );
+ let manifest = home.path().join("pin.json");
+ write_pin(
+ &manifest,
+ &origin.display().to_string(),
+ &head_sha(&origin),
+ None,
+ );
+ let add = || run_corpus_add(&["--from".into(), manifest.display().to_string()]);
+ let checkout = home.path().join("corpora/sparse-demo/vulndb");
+ assert_eq!(add(), 0);
+
+ kill_mid_checkout(&checkout, "src/a.rs");
+ assert_eq!(add(), 1);
+ assert!(checkout.join("LICENSE").is_file());
+ let backup = preserve_incomplete_for_retry(&checkout);
+ assert!(backup.join("LICENSE").is_file());
+ assert_eq!(add(), 0);
+ assert_eq!(
+ worktree_files(&checkout),
+ vec!["LICENSE".to_string(), "src/a.rs".to_string()]
+ );
+ }
+
+ /// A checkout git cannot read at all (exit 128, not "no commit") is not
+ /// proof of a killed clone: the run fails and leaves it exactly as it is,
+ /// instead of recording it as already cloned. Moving it aside, as the
+ /// diagnostic advises, permits a new clone while retaining local files.
+ #[test]
+ fn corpus_add_fails_on_a_checkout_git_cannot_read() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let add = || run_corpus_add(&["odd".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/odd/widget");
+ assert_eq!(add(), 0);
+ std::fs::write(clone.join(".git/HEAD"), "garbage\n").unwrap();
+ std::fs::write(clone.join("marker"), "kept\n").unwrap();
+ assert_eq!(add(), 1);
+ assert!(
+ clone.join("marker").exists(),
+ "an unreadable checkout is not deleted"
+ );
+ assert_eq!(
+ std::fs::read_to_string(clone.join(".git/HEAD")).unwrap(),
+ "garbage\n"
+ );
+
+ // The recovery keeps the old directory and all local files.
+ let backup = preserve_incomplete_for_retry(&clone);
+ assert!(backup.join("marker").exists());
+ assert_eq!(add(), 0);
+ assert_eq!(
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "tracked\n"
+ );
+ }
+
+ /// A finished clone that lost its HEAD commit object still has its
+ /// files and index: git cannot read it, so the run fails and keeps it
+ /// instead of deleting it as a clone that never got a commit.
+ #[test]
+ fn corpus_add_fails_on_a_clone_missing_its_head_commit() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let add = || run_corpus_add(&["lost".into(), origin.display().to_string()]);
+ let clone = home.path().join("corpora/lost/widget");
+ assert_eq!(add(), 0);
+ std::fs::remove_dir_all(clone.join(".git/objects")).unwrap();
+ std::fs::create_dir(clone.join(".git/objects")).unwrap();
+ assert_eq!(add(), 1);
+ assert_eq!(
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "tracked\n"
+ );
+ }
+
+ /// A `.git` file (a linked worktree) has no `.git/index` of its own and
+ /// is never ours: it is left alone, not taken for an unfinished clone.
+ #[test]
+ fn corpus_add_leaves_a_linked_worktree_alone() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let clone = home.path().join("corpora/linked/widget");
+ let clone_s = clone.display().to_string();
+ let (rc, out) = git(Some(&origin), &["worktree", "add", "--quiet", &clone_s]).unwrap();
+ assert_eq!(rc, 0, "git worktree add: {out}");
+ std::fs::write(clone.join("keep.txt"), "edited\n").unwrap();
+
+ assert_eq!(
+ run_corpus_add(&["linked".into(), origin.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ std::fs::read_to_string(clone.join("keep.txt")).unwrap(),
+ "edited\n"
+ );
+ assert!(clone.join(".git").is_file());
+ }
+
+ /// A second `corpus add` of the same corpus refuses while the first holds
+ /// the lock, and touches nothing.
+ #[test]
+ fn corpus_add_refuses_while_another_run_holds_the_corpus() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "tracked\n")]);
+ let held = lock_corpus_add(home.path(), "busy").unwrap();
+ assert_eq!(
+ run_corpus_add(&["busy".into(), origin.display().to_string()]),
+ 1
+ );
+ assert!(!home.path().join("corpora/busy/widget").exists());
+ drop(held);
+ assert_eq!(
+ run_corpus_add(&["busy".into(), origin.display().to_string()]),
+ 0
+ );
+ }
+
+ /// `corpus add --from <pack>` takes the same lock.
+ #[test]
+ fn corpus_add_from_pack_refuses_while_another_run_holds_the_corpus() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let pack = build_demo_pack(home.path());
+ let add = || run_corpus_add(&["--from".to_string(), pack.display().to_string()]);
+ let held = lock_corpus_add(home.path(), "demo").unwrap();
+ assert_eq!(add(), 1);
+ assert!(!home.path().join("corpora/demo").exists());
+ drop(held);
+ assert_eq!(add(), 0);
+ }
+
+ #[test]
+ fn local_checkout_root_is_a_directory_or_a_file_url() {
+ assert!(local_checkout_root("https://github.com/xerj-org/xerj").is_none());
+ assert!(local_checkout_root("ssh://[email protected]/xerj-org/xerj.git").is_none());
+ assert!(local_checkout_root("[email protected]:xerj-org/xerj.git").is_none());
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().display().to_string();
+ assert_eq!(local_checkout_root(&path).as_deref(), Some(dir.path()));
+ assert_eq!(
+ local_checkout_root(&format!("file://{path}")).as_deref(),
+ Some(dir.path())
+ );
+ assert_eq!(
+ local_checkout_root(&format!("file://localhost{path}")).as_deref(),
+ Some(dir.path())
+ );
+ assert!(local_checkout_root("file://localhost/no/such/xerj-path-2199").is_none());
+ }
+
+ /// #2472: a Windows drive or UNC path names its repo by the last
+ /// `\`-separated segment, as a URL or a Unix path does by its last `/` one.
+ #[test]
+ fn repo_name_from_source_splits_windows_paths() {
+ for (source, repo) in [
+ (r"F:\Projects\Roblox\LunarGame", "LunarGame"),
+ (r"F:\Projects\Roblox\LunarGame\", "LunarGame"),
+ (r"F:\src\widget.git", "widget"),
+ (r"\\server\share\widget", "widget"),
+ ("C:/src/widget/", "widget"),
+ ("/home/me/widget", "widget"),
+ ("https://github.com/xerj-org/xerj.git", "xerj"),
+ ("[email protected]:xerj-org/xerj.git", "xerj"),
+ ] {
+ let name = repo_name_from_source(source);
+ assert_eq!(name, repo, "{source}");
+ assert!(
+ xccode::pathgate::valid_repo_name(&name).is_ok(),
+ "{source} -> {name}"
+ );
+ }
+ }
+
+ /// #2339: `--own` is explicit. A local path with no LICENSE is not marked
+ /// own by itself. The marker persists across a re-add, a `--from` file
+ /// cannot set it, and `xerj corpus own` sets and clears it.
+ #[test]
+ fn corpus_add_own_is_explicit_and_corpus_own_sets_an_existing_corpus() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("src/lib.rs", "fn mine() {}\n")]);
+
+ assert_eq!(
+ run_corpus_add(&["plain".into(), origin.display().to_string()]),
+ 0
+ );
+ let plain =
+ manifest::read_corpus_manifest(&home.path().join("corpora/plain/corpus.json")).unwrap();
+ assert!(!plain.own, "a local path is not own unless --own is passed");
+ assert_eq!(plain.repos[0].licence, "NONE-FOUND");
+
+ assert_eq!(
+ run_corpus_add(&["--own".into(), "mine".into(), origin.display().to_string()]),
+ 0
+ );
+ let mine_path = home.path().join("corpora/mine/corpus.json");
+ let mine = manifest::read_corpus_manifest(&mine_path).unwrap();
+ assert!(mine.own);
+ assert_eq!(mine.repos[0].licence, "NONE-FOUND");
+ let text = std::fs::read_to_string(&mine_path).unwrap();
+ assert!(text.contains("\"own\":true"), "{text}");
+
+ assert_eq!(
+ run_corpus_add(&["mine".into(), origin.display().to_string()]),
+ 0,
+ "re-add without --own keeps the marker"
+ );
+ assert!(manifest::read_corpus_manifest(&mine_path).unwrap().own);
+
+ let sha = head_sha(&origin);
+ let pin = home.path().join("hostile.json");
+ std::fs::write(
+ &pin,
+ format!(
+ r#"{{"corpus":"from-file","own":true,"repos":[{{"repo":"widget","url":"{}","sha":"{sha}","licence":"UNKNOWN"}}]}}"#,
+ origin.display()
+ ),
+ )
+ .unwrap();
+ assert_eq!(
+ run_corpus_add(&["--from".into(), pin.display().to_string()]),
+ 0
+ );
+ let from_path = home.path().join("corpora/from-file/corpus.json");
+ let from = manifest::read_corpus_manifest(&from_path).unwrap();
+ assert!(
+ !from.own,
+ "a --from manifest must not be able to set own: {}",
+ std::fs::read_to_string(&from_path).unwrap()
+ );
+
+ assert_eq!(run_corpus_own(&["from-file".into()]), 0);
+ assert!(manifest::read_corpus_manifest(&from_path).unwrap().own);
+ assert_eq!(
+ manifest::read_corpus_manifest(&from_path).unwrap().repos[0].licence,
+ "NONE-FOUND"
+ );
+ assert_eq!(run_corpus_own(&["from-file".into(), "--off".into()]), 0);
+ let cleared = std::fs::read_to_string(&from_path).unwrap();
+ assert!(!cleared.contains("own"), "{cleared}");
+ assert!(!manifest::read_corpus_manifest(&from_path).unwrap().own);
+
+ assert_eq!(run_corpus_own(&["missing".into()]), 2);
+ assert_eq!(run_corpus_own(&[]), 2);
+ assert!(CORPUS_USAGE.contains("xerj corpus own"));
+ assert!(CORPUS_USAGE.contains("--own"));
+ assert!(CORPUS_USAGE.contains("file classes") || CORPUS_USAGE.contains("per-file-class"));
+ }
+
- /// #2199: `git clone` of a local path checks out committed files only.
++ /// #2576: both spellings the filter writes are recognised, and a complete
++ /// checkout — even one with a remote — is not a partial clone.
++ #[test]
++ fn partial_clone_cause_reads_both_config_spellings() {
++ let dir = tempfile::tempdir().unwrap();
+ let repo = dir.path().join("complete");
+ init_committed_repo(&repo, &[("keep.txt", "tracked\n")]);
+ let (rc, _) = git(
+ Some(&repo),
+ &["remote", "add", "origin", "https://example.com/x.git"],
+ )
+ .unwrap();
+ assert_eq!(rc, 0);
+ assert_eq!(
+ partial_clone_cause(&repo),
+ None,
+ "a full clone has no promisor"
+ );
+
+ let (rc, _) = git(Some(&repo), &["config", "remote.origin.promisor", "true"]).unwrap();
+ assert_eq!(rc, 0);
+ assert_eq!(
+ partial_clone_cause(&repo).as_deref(),
+ Some("remote.origin.promisor=true"),
- "older git records the filter on the remote"
++ "Git records the promisor property on a named remote"
+ );
+
+ let (rc, _) = git(
+ Some(&repo),
+ &["config", "extensions.partialClone", "origin"],
+ )
+ .unwrap();
+ assert_eq!(rc, 0);
+ assert_eq!(
+ partial_clone_cause(&repo).as_deref(),
+ Some("extensions.partialClone=origin"),
- "current git records it in extensions, and that is the one reported"
++ "the optional extension records a promisor remote name"
+ );
+ }
+
- /// #2576: `git clone --filter=blob:none` leaves the blobs outside the
- /// checked-out paths unfetched, so a clone *from* that checkout fails inside
- /// upload-pack — with git's "repository corruption" wording, which names
- /// the wrong problem and sends the reader looking for a damaged repo. The
- /// checkout is valid: `xerj autoindex` reads it. Refuse it by name and
- /// point at the command that works.
++ /// Real missing objects plus an unavailable promisor remote cause a
++ /// clone failure. Restoring and hydrating the source makes a retry work.
+ #[test]
- fn corpus_add_refuses_a_partial_clone_by_name_instead_of_calling_it_corrupt() {
++ fn corpus_add_partial_clone_failure_preserves_retry_and_names_the_context() {
+ let home = tempfile::tempdir().unwrap();
+ let _h = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(&origin, &[("src/keep.txt", "tracked\n")]);
- let (rc, out) = git(Some(&origin), &["config", "uploadpack.allowFilter", "true"]).unwrap();
- assert_eq!(rc, 0, "{out}");
-
++ assert_eq!(
++ git(Some(&origin), &["config", "uploadpack.allowFilter", "true"])
++ .unwrap()
++ .0,
++ 0
++ );
+ let partial = home.path().join("partial");
+ let (rc, out) = git(
+ None,
+ &[
+ "clone",
- "--quiet",
+ "--filter=blob:none",
- "--sparse",
++ "--no-checkout",
+ &format!("file://{}", origin.display()),
+ &partial.display().to_string(),
+ ],
+ )
+ .unwrap();
- assert_eq!(rc, 0, "the fixture must clone: {out}");
- let (rc, promisor) = git(
- Some(&partial),
- &["config", "--get", "remote.origin.promisor"],
- )
- .unwrap();
- assert_eq!(rc, 0, "the fixture must be a partial clone: {promisor}");
-
- // The premise, not the fix: cloning FROM it is what fails, and with a
- // message that never says "partial".
- let (clone_rc, clone_out) = git(
- None,
- &[
- "clone",
- "--depth",
- "1",
- "--quiet",
- &partial.display().to_string(),
- &home.path().join("would-be-clone").display().to_string(),
- ],
++ assert_eq!(rc, 0, "{out}");
++ let (rc, missing, err) = git_stdout(
++ &partial,
++ &["rev-list", "--objects", "--all", "--missing=print"],
+ )
+ .unwrap();
- assert_ne!(
- clone_rc, 0,
- "if this ever succeeds, the guard is unnecessary: {clone_out}"
++ assert_eq!(rc, 0, "{err}");
++ assert!(
++ missing.lines().any(|line| line.starts_with('?')),
++ "fixture needs missing objects: {missing}"
+ );
-
++ std::fs::rename(&origin, home.path().join("offline-origin")).unwrap();
++ let args = vec!["partial-corpus".into(), partial.display().to_string()];
++ assert_eq!(run_corpus_add(&args), 1);
+ assert_eq!(
- run_corpus_add(&["partial-corpus".into(), partial.display().to_string()]),
- 1,
- "a corpus whose only source was refused has nothing cloned"
- );
- assert!(
- !home.path().join("corpora/partial-corpus/partial").exists(),
- "the refused source must not leave a half-clone behind"
++ std::fs::read_dir(home.path().join("corpora/partial-corpus"))
++ .unwrap()
++ .count(),
++ 0,
++ "failed clone cannot publish a partial target"
+ );
-
- // The message is the fix: it has to name the partial clone, name the
- // config that proves it, and hand over a command that works. It must
- // not repeat the two misdirections the issue was filed about.
- let cause = partial_clone_cause(&partial).expect("the fixture is a partial clone");
- let lines = partial_clone_refusal("partial", &partial, &cause).join("\n");
- assert!(lines.contains("is a partial clone"), "{lines}");
++ let cause = partial_clone_cause(&partial).unwrap();
++ let lines = partial_clone_failure_hint("partial", &partial, &cause).join("\n");
++ assert!(lines.contains("partial-clone configuration"), "{lines}");
++ assert!(lines.contains("may explain"), "{lines}");
++ assert!(lines.contains("only files already present"), "{lines}");
+ assert!(lines.contains(&cause), "{lines}");
- assert!(
- lines.contains(&format!(
- "xerj autoindex {} --prefix partial",
- partial.display()
- )),
- "the refusal must hand over the command that works: {lines}"
- );
- assert!(!lines.contains("could not clone"), "{lines}");
- assert!(
- lines.contains("misleading \"repository corruption\""),
- "the old wording is quoted only to say it is wrong: {lines}"
++ std::fs::rename(home.path().join("offline-origin"), &origin).unwrap();
++ let (rc, out) = git(Some(&partial), &["checkout", "HEAD", "--", "."]).unwrap();
++ assert_eq!(rc, 0, "hydrate after restoring the remote: {out}");
++ assert_eq!(run_corpus_add(&args), 0);
++ assert!(home
++ .path()
++ .join("corpora/partial-corpus/partial/src/keep.txt")
++ .is_file());
++ }
++
++ #[test]
++ fn partial_clone_cause_accepts_non_origin_promisors_and_git_boolean_spellings() {
++ let home = tempfile::tempdir().unwrap();
++ let repo = home.path().join("repo");
++ init_committed_repo(&repo, &[("keep.txt", "keep\n")]);
++ for value in ["yes", "1", "true"] {
++ assert_eq!(
++ git(Some(&repo), &["config", "remote.cache.promisor", value])
++ .unwrap()
++ .0,
++ 0
++ );
++ assert_eq!(
++ partial_clone_cause(&repo).as_deref(),
++ Some("remote.cache.promisor=true")
++ );
++ }
++ assert_eq!(
++ git(Some(&repo), &["config", "remote.cache.promisor", "false"])
++ .unwrap()
++ .0,
++ 0
+ );
++ assert!(partial_clone_cause(&repo).is_none());
++ }
++
++ #[cfg(unix)]
++ #[test]
++ fn partial_clone_hint_quotes_source_paths_for_the_named_shell() {
++ let lines = partial_clone_failure_hint(
++ "sample",
++ Path::new("/tmp/a'b $(cmd)"),
++ "remote.origin.promisor=true",
++ )
++ .join("\n");
++ assert!(lines.contains("POSIX shell"));
++ assert!(lines.contains("'/tmp/a'\"'\"'b $(cmd)'"), "{lines}");
+ }
+
/// An untracked root `.xerjignore` has to be copied or the index sees
/// built-in rules alone. Re-adding refreshes it; `file://` is the same
/// local checkout; a source with no ignore file does not gain one.
@@@ -6928,385 -6503,4 +7133,438 @@@
"an escaping paths entry is refused before any directory is created"
);
}
+
+ /// #2486: a `paths` entry may name a file. The pandas time-series pack
+ /// needs `pandas/core/resample.py` without the rest of `pandas/core`, and
+ /// naming the parent directory crowds the documentation out of the top
+ /// hits. A file entry checks out that file and nothing beside it: not a
+ /// sibling whose name starts the same way, and not a file of the same
+ /// name deeper in the tree (the pattern is anchored at the root).
+ #[test]
+ fn corpus_add_from_paths_harvests_a_named_file() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(
+ &origin,
+ &[
+ ("LICENSE", "bsd\n"),
+ ("pkg/core/resample.py", "def resample(): pass\n"),
+ ("pkg/core/resample.pyx", "cdef int x\n"),
+ ("pkg/core/frame.py", "class DataFrame: pass\n"),
+ ("other/pkg/core/resample.py", "def other(): pass\n"),
+ ("doc/timeseries.rst", "Time series\n"),
+ ],
+ );
+ let sha = head_sha(&origin);
+ let url = origin.display().to_string();
+ let manifest = home.path().join("pin.json");
+ let checkout = home.path().join("corpora/sparse-demo/vulndb");
+
+ write_pin(
+ &manifest,
+ &url,
+ &sha,
+ Some(&["pkg/core/resample.py", "doc"]),
+ );
+ assert_eq!(
+ run_corpus_add(&["--from".into(), manifest.display().to_string()]),
+ 0,
+ "a paths entry naming a file must be harvested"
+ );
+ assert_eq!(
+ worktree_files(&checkout),
+ vec![
+ "doc/timeseries.rst".to_string(),
+ "pkg/core/resample.py".to_string(),
+ ]
+ );
+ let recorded =
+ manifest::read_corpus_manifest(&home.path().join("corpora/sparse-demo/corpus.json"))
+ .unwrap();
+ assert_eq!(
+ recorded.repos[0].paths,
+ vec!["pkg/core/resample.py".to_string(), "doc".to_string()]
+ );
+ assert_eq!(recorded.repos[0].files, Some(2));
+
+ // Re-adding over the existing checkout narrows and widens it too.
+ write_pin(&manifest, &url, &sha, Some(&["doc"]));
+ assert_eq!(
+ run_corpus_add(&["--from".into(), manifest.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ worktree_files(&checkout),
+ vec!["doc/timeseries.rst".to_string()]
+ );
+ write_pin(&manifest, &url, &sha, Some(&["pkg/core/frame.py"]));
+ assert_eq!(
+ run_corpus_add(&["--from".into(), manifest.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ worktree_files(&checkout),
+ vec!["pkg/core/frame.py".to_string()]
+ );
+ }
+
+ /// Each tree entry kind gets its own answer, read from the mode, so a
+ /// submodule is not reported as a missing path.
+ #[test]
+ fn confirm_paths_exist_classifies_each_entry_kind() {
+ let home = tempfile::tempdir().unwrap();
+ let repo = home.path().join("repo");
+ init_committed_repo(&repo, &[("doc/a.rst", "a\n"), ("pkg/m.py", "x = 1\n")]);
+ let first = head_sha(&repo);
+ let gitlink = format!("160000,{first},vendor/sub");
+ let (rc, out) = git(
+ Some(&repo),
+ &["update-index", "--add", "--cacheinfo", &gitlink],
+ )
+ .unwrap();
+ assert_eq!(rc, 0, "git update-index: {out}");
+ let (rc, out) = git(
+ Some(&repo),
+ &[
+ "-c",
+ "-c",
+ "user.name=xerj-test",
+ "commit",
+ "--quiet",
+ "-m",
+ "gitlink",
+ ],
+ )
+ .unwrap();
+ assert_eq!(rc, 0, "git commit: {out}");
+ let sha = head_sha(&repo);
+ let paths = |list: &[&str]| list.iter().map(|p| p.to_string()).collect::<Vec<_>>();
+
+ assert_eq!(
+ confirm_paths_exist(&repo, &sha, &paths(&["pkg/m.py", "doc"])).unwrap(),
+ vec![PathKind::File, PathKind::Dir]
+ );
+ let err = confirm_paths_exist(&repo, &sha, &paths(&["vendor/sub"]))
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("is a submodule"), "{err}");
+ let err = confirm_paths_exist(&repo, &sha, &paths(&["doc/nope.rst"]))
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("has no such path"), "{err}");
+ }
+
+ /// A symlink entry is refused end to end. Naming one would hand
+ /// `corpus index` a link the manifest author chose, possibly pointing out
+ /// of the checkout, so it is refused and no corpus is recorded.
+ #[cfg(unix)]
+ #[test]
+ fn corpus_add_from_paths_refuses_a_symlink_entry() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(&origin, &[("LICENSE", "bsd\n")]);
+ std::os::unix::fs::symlink("/etc/hostname", origin.join("link")).unwrap();
+ let (rc, out) = git(Some(&origin), &["add", "--", "link"]).unwrap();
+ assert_eq!(rc, 0, "git add link: {out}");
+ let (rc, out) = git(
+ Some(&origin),
+ &[
+ "-c",
+ "-c",
+ "user.name=xerj-test",
+ "commit",
+ "--quiet",
+ "-m",
+ "link",
+ ],
+ )
+ .unwrap();
+ assert_eq!(rc, 0, "git commit: {out}");
+ let sha = head_sha(&origin);
+ let manifest = home.path().join("pin.json");
+ write_pin(
+ &manifest,
+ &origin.display().to_string(),
+ &sha,
+ Some(&["link"]),
+ );
+ assert_eq!(
+ run_corpus_add(&["--from".into(), manifest.display().to_string()]),
+ 1
+ );
+ assert!(
+ !home.path().join("corpora/sparse-demo/corpus.json").exists(),
+ "a refused symlink entry must not record a corpus"
+ );
+ assert!(!home
+ .path()
+ .join("corpora/sparse-demo/vulndb/LICENSE")
+ .exists());
+ }
+ #[test]
+ fn corpus_bad_sparse_path_preserves_existing_checkout_and_manifest() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("origin");
+ init_committed_repo(
+ &origin,
+ &[
+ ("doc/keep.txt", "retained content\n"),
+ ("pkg/code.rs", "fn f() {}\n"),
+ ],
+ );
+ let sha = head_sha(&origin);
+ let pin = home.path().join("pin.json");
+ let url = origin.display().to_string();
+ write_pin(&pin, &url, &sha, Some(&["doc"]));
+ let args = vec!["--from".to_string(), pin.display().to_string()];
+ assert_eq!(run_corpus_add(&args), 0);
+ let checkout = home.path().join("corpora/sparse-demo/vulndb");
+ let manifest = home.path().join("corpora/sparse-demo/corpus.json");
+ let before = std::fs::read(&manifest).unwrap();
+ let index_before = std::fs::read(checkout.join(".git/index")).unwrap();
+ let sparse_before = std::fs::read(checkout.join(".git/info/sparse-checkout")).unwrap();
+ std::fs::write(checkout.join("local-note.txt"), "uncommitted local note").unwrap();
+ write_pin(&pin, &url, &sha, Some(&["pkg/code.rs", "missing.txt"]));
+ assert_eq!(run_corpus_add(&args), 1);
+ assert_eq!(std::fs::read(&manifest).unwrap(), before);
+ assert_eq!(
+ std::fs::read(checkout.join(".git/index")).unwrap(),
+ index_before
+ );
+ assert_eq!(
+ std::fs::read(checkout.join(".git/info/sparse-checkout")).unwrap(),
+ sparse_before
+ );
+ assert_eq!(
+ std::fs::read_to_string(checkout.join("doc/keep.txt")).unwrap(),
+ "retained content\n"
+ );
+ assert_eq!(
+ std::fs::read_to_string(checkout.join("local-note.txt")).unwrap(),
+ "uncommitted local note"
+ );
+ assert!(!checkout.join("pkg/code.rs").exists());
+ assert_eq!(head_sha(&checkout), sha);
+ // Correcting the path performs the requested narrower harvest.
+ write_pin(&pin, &url, &sha, Some(&["pkg/code.rs"]));
+ assert_eq!(run_corpus_add(&args), 0);
+ assert!(checkout.join("pkg/code.rs").is_file());
+ assert!(!checkout.join("doc/keep.txt").exists());
+ }
+ #[test]
+ fn corpus_add_does_not_delete_an_unborn_repo_with_user_files() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "remote content\n")]);
+ let target = home.path().join("corpora/preserve/widget");
+ std::fs::create_dir_all(&target).unwrap();
+ assert_eq!(git(Some(&target), &["init", "--quiet"]).unwrap().0, 0);
+ std::fs::write(target.join("local-note.txt"), "irreplaceable local content").unwrap();
+ let code = run_corpus_add(&["preserve".into(), origin.display().to_string()]);
+ assert_eq!(
+ std::fs::read_to_string(target.join("local-note.txt"))
+ .ok()
+ .as_deref(),
+ Some("irreplaceable local content"),
+ "an unborn repo is not proof of disposable state"
+ );
+ assert_eq!(code, 1, "an ambiguous existing checkout must be refused");
+ assert!(!home.path().join("corpora/preserve/corpus.json").exists());
+ // Keeping the old directory separately makes a normal retry safe.
+ let backup = home.path().join("saved-incomplete-widget");
+ std::fs::rename(&target, &backup).unwrap();
+ assert_eq!(
+ run_corpus_add(&["preserve".into(), origin.display().to_string()]),
+ 0
+ );
+ assert_eq!(
+ std::fs::read_to_string(backup.join("local-note.txt")).unwrap(),
+ "irreplaceable local content"
+ );
+ assert_eq!(
+ std::fs::read_to_string(target.join("keep.txt")).unwrap(),
+ "remote content\n"
+ );
+ }
+
+ #[test]
+ fn corpus_add_does_not_reset_user_edits_when_index_is_missing() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("widget");
+ init_committed_repo(&origin, &[("keep.txt", "remote content\n")]);
+ let args = vec!["preserve".into(), origin.display().to_string()];
+ assert_eq!(run_corpus_add(&args), 0);
+ let target = home.path().join("corpora/preserve/widget");
+ let manifest = home.path().join("corpora/preserve/corpus.json");
+ let before = std::fs::read(&manifest).unwrap();
+ std::fs::write(target.join("keep.txt"), "irreplaceable local edit").unwrap();
+ std::fs::remove_file(target.join(".git/index")).unwrap();
+ let code = run_corpus_add(&args);
+ assert_eq!(
+ std::fs::read_to_string(target.join("keep.txt")).unwrap(),
+ "irreplaceable local edit",
+ "missing index does not authorize reset --hard"
+ );
+ assert_eq!(code, 1);
+ assert_eq!(std::fs::read(&manifest).unwrap(), before);
+ }
+
+ fn preserve_incomplete_for_retry(checkout: &Path) -> PathBuf {
+ let backup = checkout.with_extension("saved");
+ assert!(!backup.exists());
+ std::fs::rename(checkout, &backup).unwrap();
+ backup
+ }
+
+ #[test]
+ fn staged_clone_failure_never_publishes_a_partial_checkout() {
+ let home = tempfile::tempdir().unwrap();
+ let target = home.path().join("repo");
+ let error = stage_new_checkout(&target, |stage| {
+ assert!(!target.exists());
+ std::fs::create_dir_all(stage)?;
+ std::fs::write(stage.join("partial.txt"), "partial")?;
+ anyhow::bail!("injected clone failure")
+ })
+ .unwrap_err();
+ assert!(error.to_string().contains("injected clone failure"));
+ assert!(!target.exists());
+ assert_eq!(std::fs::read_dir(home.path()).unwrap().count(), 0);
+ stage_new_checkout(&target, |stage| {
+ assert!(!target.exists());
+ init_committed_repo(stage, &[("complete.txt", "complete\n")]);
+ Ok(())
+ })
+ .unwrap();
+ assert!(existing_checkout_is_complete(&target));
+ assert_eq!(std::fs::read_dir(home.path()).unwrap().count(), 1);
+ }
+
+ #[test]
+ fn staged_clone_does_not_replace_a_destination_created_during_clone() {
+ let home = tempfile::tempdir().unwrap();
+ let target = home.path().join("repo");
+ let error = stage_new_checkout(&target, |stage| {
+ init_committed_repo(stage, &[("remote.txt", "remote\n")]);
+ std::fs::create_dir(&target)?;
+ std::fs::write(target.join("local.txt"), "local content")?;
+ Ok(())
+ })
+ .unwrap_err();
+ assert!(error.to_string().contains("already exists"));
+ assert_eq!(
+ std::fs::read_to_string(target.join("local.txt")).unwrap(),
+ "local content"
+ );
+ assert!(!target.join("remote.txt").exists());
+ assert_eq!(std::fs::read_dir(home.path()).unwrap().count(), 1);
+ let error = stage_new_checkout(&target, |_| {
+ panic!("existing destination must be refused before cloning")
+ })
+ .unwrap_err();
+ assert!(error.to_string().contains("already exists"));
+ }
+
+ #[test]
+ fn corpus_failed_new_clone_can_be_retried_without_deleting_anything() {
+ let home = tempfile::tempdir().unwrap();
+ let _hold = code_home(home.path());
+ let origin = home.path().join("widget");
+ let args = vec!["retry".into(), origin.display().to_string()];
+ assert_eq!(run_corpus_add(&args), 1);
+ let corpus = home.path().join("corpora/retry");
+ assert_eq!(std::fs::read_dir(&corpus).unwrap().count(), 0);
+ init_committed_repo(&origin, &[("complete.txt", "complete\n")]);
+ assert_eq!(run_corpus_add(&args), 0);
+ assert!(corpus.join("widget/complete.txt").is_file());
+ assert!(corpus.join("corpus.json").is_file());
+ }
+
+ #[test]
+ fn a_committed_empty_tree_is_a_reusable_checkout() {
+ let home = tempfile::tempdir().unwrap();
+ let repo = home.path().join("empty");
+ std::fs::create_dir(&repo).unwrap();
+ assert_eq!(git(Some(&repo), &["init", "--quiet"]).unwrap().0, 0);
+ assert_eq!(
+ git(
+ Some(&repo),
+ &[
+ "-c",
+ "user.name=xerj-test",
+ "-c",
+ "commit",
+ "--allow-empty",
+ "--quiet",
+ "-m",
+ "empty"
+ ]
+ )
+ .unwrap()
+ .0,
+ 0
+ );
+ assert!(existing_checkout_is_complete(&repo));
+ }
++ #[test]
++ fn corpus_add_accepts_a_hydrated_partial_clone_source() {
++ let home = tempfile::tempdir().unwrap();
++ let _hold = code_home(home.path());
++ let origin = home.path().join("origin");
++ init_committed_repo(
++ &origin,
++ &[
++ ("src/a.txt", "source content\n"),
++ ("docs/b.txt", "documentation\n"),
++ ],
++ );
++ assert_eq!(
++ git(Some(&origin), &["config", "uploadpack.allowFilter", "true"])
++ .unwrap()
++ .0,
++ 0
++ );
++ let partial = home.path().join("partial");
++ let url = format!("file://{}", origin.display());
++ let (rc, out) = git(
++ None,
++ &[
++ "clone",
++ "--filter=blob:none",
++ "--no-checkout",
++ &url,
++ &partial.display().to_string(),
++ ],
++ )
++ .unwrap();
++ assert_eq!(rc, 0, "{out}");
++ let (rc, out) = git(Some(&partial), &["checkout", "HEAD", "--", "."]).unwrap();
++ assert_eq!(rc, 0, "hydration: {out}");
++ assert!(
++ partial_clone_cause(&partial).is_some(),
++ "config remains after hydration"
++ );
++ assert_eq!(
++ run_corpus_add(&["hydrated".into(), partial.display().to_string()]),
++ 0,
++ "promisor configuration is not proof that cloning will fail"
++ );
++ let target = home.path().join("corpora/hydrated/partial");
++ assert_eq!(
++ std::fs::read_to_string(target.join("src/a.txt")).unwrap(),
++ "source content\n"
++ );
++ assert_eq!(
++ std::fs::read_to_string(target.join("docs/b.txt")).unwrap(),
++ "documentation\n"
++ );
++ }
}