//! Pull request plumbing: PR head refs, merge checks, merge commits and compare-and-swap ref //! updates. Every object id is validated as a full hex id and every ref name against a strict //! allowlist before it reaches git. User values follow `--end-of-options` where git allows it. use std::path::Path; use std::process::{Output, Stdio}; use tokio::io::AsyncWriteExt; use crate::browse::{CommitInfo, validate_repo_path}; use crate::command::{GitCommand, GitEnv, ObjectSource}; use crate::error::{Error, Result}; use crate::history::{ CommitDiff, DiffLimits, diff_between, empty_tree_for, git, new_commits_with, validate_oid, }; /// Outcome of a merge check between a base tip and a head commit. #[derive(Debug, Clone, PartialEq, Eq)] pub enum MergeCheck { /// The merge would be clean; `tree` is the id of the resulting tree. Clean { tree: String }, /// The merge would conflict; `files` are the conflicted paths, deduplicated. Conflict { files: Vec }, /// The head is already contained in the base. UpToDate, } /// Author or committer identity for [`commit_tree`]. `time_unix` is written as ` +0000`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Signature { pub name: String, pub email: String, pub time_unix: i64, } /// Runs a command without turning a non-zero exit into an error, optionally feeding stdin. async fn run_raw(cmd: GitCommand, stdin: Option<&[u8]>) -> Result { let mut command = cmd.into_tokio(); command.stdout(Stdio::piped()).stderr(Stdio::piped()); if stdin.is_some() { command.stdin(Stdio::piped()); } let mut child = command.spawn()?; if let (Some(data), Some(mut pipe)) = (stdin, child.stdin.take()) { pipe.write_all(data).await?; // `pipe` is dropped here, which closes git's stdin. } Ok(child.wait_with_output().await?) } fn failed(subcommand: &str, out: &Output) -> Error { Error::Failed(format!( "git {subcommand} exited with {}: {}", out.status, String::from_utf8_lossy(&out.stderr).trim() )) } fn stdout_trimmed(out: &Output) -> String { String::from_utf8_lossy(&out.stdout).trim().to_owned() } /// Accepts `refs/heads/` and `refs/pull//head`, with a conservative character set. fn validate_ref(refname: &str) -> Result<()> { let heads_ok = refname .strip_prefix("refs/heads/") .is_some_and(valid_branch_rest); let pull_ok = refname .strip_prefix("refs/pull/") .and_then(|r| r.strip_suffix("/head")) .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())); if heads_ok || pull_ok { Ok(()) } else { Err(Error::InvalidInput(format!( "invalid ref name: {refname:?}" ))) } } fn valid_branch_rest(rest: &str) -> bool { !rest.is_empty() && !rest.contains("..") && !rest.contains("@{") && !rest.contains("//") && !rest.ends_with(['/', '.']) && !rest.ends_with(".lock") && rest .split('/') .all(|c| !c.is_empty() && !c.starts_with(['.', '-'])) && rest .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-' | b'+')) } /// Rejects identity fields git would refuse or misparse. fn validate_signature(sig: &Signature) -> Result<()> { let bad = |s: &str| s.is_empty() || s.contains(['<', '>', '\n', '\0']); if bad(&sig.name) || bad(&sig.email) { return Err(Error::InvalidInput("invalid identity name or email".into())); } Ok(()) } /// True when both paths name the same repository (equal, or equal after canonicalization). fn same_repo(a: &Path, b: &Path) -> bool { if a == b { return true; } match (std::fs::canonicalize(a), std::fs::canonicalize(b)) { (Ok(x), Ok(y)) => x == y, _ => false, } } /// Fetches `oid` from `head_repo` into `base_repo`'s object store. The first attempt uses a plain /// fetch of the raw id. If git refuses it, the one call is retried with /// `uploadpack.allowAnySHA1InWant=true` for the local upload-pack process. async fn fetch_object(env: &GitEnv, base_repo: &Path, head_repo: &Path, oid: &str) -> Result<()> { let head_path = head_repo .to_str() .ok_or_else(|| Error::InvalidInput("repo path is not valid UTF-8".into()))?; let build = |allow_any: bool| -> Result { // `head_repo` is a fork repo from repo_path(), so the local transport is allowed here only. let cmd = git(env, "fetch") .allow_local_transport() .git_dir(base_repo) .arg("--no-tags") .arg("--no-write-fetch-head"); let cmd = if allow_any { cmd.env("GIT_CONFIG_COUNT", "2") .env("GIT_CONFIG_KEY_1", "uploadpack.allowAnySHA1InWant") .env("GIT_CONFIG_VALUE_1", "true") } else { cmd }; cmd.user_revs(&[head_path, oid]) }; match build(false)?.status().await { Ok(()) => Ok(()), Err(Error::Failed(_)) => build(true)?.status().await, Err(e) => Err(e), } } /// Points `refs/pull//head` at `head_oid` in `base_repo`. When the head lives in another /// repository, the object is fetched into `base_repo` first. pub async fn fetch_into_pull_ref( env: &GitEnv, base_repo: &Path, head_repo: &Path, head_oid: &str, number: i64, ) -> Result<()> { validate_oid(head_oid)?; if number < 1 { return Err(Error::InvalidInput(format!( "invalid pull number: {number}" ))); } let refname = format!("refs/pull/{number}/head"); validate_ref(&refname)?; if !same_repo(base_repo, head_repo) { fetch_object(env, base_repo, head_repo, head_oid).await?; } git(env, "update-ref") .git_dir(base_repo) .user_arg(&refname)? .user_arg(head_oid)? .status() .await } /// Best common ancestor of `a` and `b`, or `None` when they share no history. pub async fn merge_base(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result> { merge_base_with(env, repo, ObjectSource::default(), a, b).await } /// [`merge_base`], reading objects missing from `repo` (such as a fork's head commit) from `src`. /// Nothing is written to `repo`. pub async fn merge_base_with( env: &GitEnv, repo: &Path, src: ObjectSource<'_>, a: &str, b: &str, ) -> Result> { validate_oid(a)?; validate_oid(b)?; let cmd = git(env, "merge-base") .git_dir(repo) .objects(src)? .user_revs(&[a, b])?; let out = run_raw(cmd, None).await?; match out.status.code() { Some(0) => { let oid = stdout_trimmed(&out); validate_oid(&oid)?; Ok(Some(oid)) } Some(1) => Ok(None), _ => Err(failed("merge-base", &out)), } } /// Blob id of `path` in `commit`, or `None` when the path is absent or is not a blob (a tree or a /// submodule). `commit` must be a full object id. `path` is a relative `/`-separated repo path. pub async fn blob_at( env: &GitEnv, repo: &Path, commit: &str, path: &str, ) -> Result> { blob_at_with(env, repo, ObjectSource::default(), commit, path).await } /// [`blob_at`], reading objects missing from `repo` (such as a fork's commit) from `src`. /// Nothing is written to `repo`. pub async fn blob_at_with( env: &GitEnv, repo: &Path, src: ObjectSource<'_>, commit: &str, path: &str, ) -> Result> { validate_oid(commit)?; validate_blob_path(path)?; // `ls-tree` rather than `rev-parse :`: the path is a pathspec after `--`, so it is // never read as a revision. `:(literal)` stops globs and magic such as `:x` from matching // other entries. Output is NUL-terminated and unquoted, so any name is safe to parse. let spec = format!(":(literal){path}"); let out = git(env, "ls-tree") .git_dir(repo) .objects(src)? .arg("-z") .arg("--full-tree") .user_arg(commit)? .paths(&[spec.as_str()]) .output() .await?; // Pathspecs can match more than one entry, so keep only the exact path. let entry = out.split(|&b| b == 0).find_map(|rec| { let text = std::str::from_utf8(rec).ok()?; let (meta, name) = text.split_once('\t')?; if name != path { return None; } let mut fields = meta.split(' '); let _mode = fields.next()?; let kind = fields.next()?; let oid = fields.next()?; Some((kind.to_owned(), oid.to_owned())) }); match entry { Some((kind, oid)) if kind == "blob" => { validate_oid(&oid)?; Ok(Some(oid)) } _ => Ok(None), } } /// Rules for the path argument of [`blob_at`]: non-empty, relative, no newline, and the segment /// rules of [`validate_repo_path`]. fn validate_blob_path(path: &str) -> Result<()> { if path.is_empty() { return Err(Error::InvalidInput("empty path".into())); } if path.starts_with('/') { return Err(Error::InvalidInput(format!("absolute path: {path:?}"))); } if path.contains('\n') { return Err(Error::InvalidInput("path contains newline".into())); } validate_repo_path(path) } /// True when `a` is an ancestor of `b` (or equal to it). pub async fn is_ancestor(env: &GitEnv, repo: &Path, a: &str, b: &str) -> Result { validate_oid(a)?; validate_oid(b)?; let cmd = git(env, "merge-base") .git_dir(repo) .arg("--is-ancestor") .user_revs(&[a, b])?; let out = run_raw(cmd, None).await?; match out.status.code() { Some(0) => Ok(true), Some(1) => Ok(false), _ => Err(failed("merge-base --is-ancestor", &out)), } } /// Checks whether `head` merges cleanly into `base`, without touching any ref. pub async fn check_merge( env: &GitEnv, repo: &Path, base_oid: &str, head_oid: &str, ) -> Result { validate_oid(base_oid)?; validate_oid(head_oid)?; if is_ancestor(env, repo, head_oid, base_oid).await? { return Ok(MergeCheck::UpToDate); } let cmd = git(env, "merge-tree") .git_dir(repo) .arg("--write-tree") .arg("--name-only") .arg("--no-messages") .user_revs(&[base_oid, head_oid])?; let out = run_raw(cmd, None).await?; let text = String::from_utf8_lossy(&out.stdout).into_owned(); match out.status.code() { Some(0) => { let tree = text.lines().next().unwrap_or_default().trim().to_owned(); validate_oid(&tree)?; Ok(MergeCheck::Clean { tree }) } Some(1) => { let mut lines = text.lines(); let tree = lines.next().unwrap_or_default().trim().to_owned(); validate_oid(&tree)?; let mut files: Vec = Vec::new(); for line in lines.map(str::trim).filter(|l| !l.is_empty()) { if !files.iter().any(|f| f == line) { files.push(line.to_owned()); } } Ok(MergeCheck::Conflict { files }) } _ => Err(failed("merge-tree", &out)), } } /// Creates a commit for `tree` with the given parents and returns its id. The message is written /// to stdin. Author and committer come from `GIT_AUTHOR_*` and `GIT_COMMITTER_*`. pub async fn commit_tree( env: &GitEnv, repo: &Path, tree: &str, parents: &[&str], message: &str, author: &Signature, committer: &Signature, ) -> Result { validate_oid(tree)?; for p in parents { validate_oid(p)?; } validate_signature(author)?; validate_signature(committer)?; if message.contains('\0') { return Err(Error::InvalidInput("commit message contains NUL".into())); } let mut cmd = git(env, "commit-tree").git_dir(repo); for p in parents { cmd = cmd.arg("-p").user_arg(p)?; } let cmd = cmd .user_revs(&[tree])? .env("GIT_AUTHOR_NAME", author.name.as_str()) .env("GIT_AUTHOR_EMAIL", author.email.as_str()) .env("GIT_AUTHOR_DATE", format!("{} +0000", author.time_unix)) .env("GIT_COMMITTER_NAME", committer.name.as_str()) .env("GIT_COMMITTER_EMAIL", committer.email.as_str()) .env( "GIT_COMMITTER_DATE", format!("{} +0000", committer.time_unix), ); let out = run_raw(cmd, Some(message.as_bytes())).await?; if !out.status.success() { return Err(failed("commit-tree", &out)); } let oid = stdout_trimmed(&out); validate_oid(&oid)?; Ok(oid) } /// Moves `refname` from `old` to `new` only if it still points at `old`. A stale `old` gives /// `Error::RefMoved`. Use the zero id as `old` to require that the ref does not exist yet. pub async fn update_ref_cas( env: &GitEnv, repo: &Path, refname: &str, new: &str, old: &str, ) -> Result<()> { validate_ref(refname)?; validate_oid(new)?; validate_oid(old)?; let cmd = git(env, "update-ref") .git_dir(repo) .user_arg(refname)? .user_arg(new)? .user_arg(old)?; let out = run_raw(cmd, None).await?; if out.status.success() { return Ok(()); } let stderr = String::from_utf8_lossy(&out.stderr); if stderr.contains("but expected") || stderr.contains("unable to resolve reference") { return Err(Error::RefMoved(refname.to_owned())); } Err(failed("update-ref", &out)) } /// Deletes `refname` only if it still points at `old`. `git update-ref -d ` checks the /// old value itself, so a ref that moved, or one that is already gone, gives `Error::RefMoved` /// and is left alone. The zero id is not accepted as `old`: a deletion needs a real value to /// compare against. pub async fn delete_ref_cas(env: &GitEnv, repo: &Path, refname: &str, old: &str) -> Result<()> { validate_ref(refname)?; validate_oid(old)?; let cmd = git(env, "update-ref") .git_dir(repo) .arg("-d") .user_arg(refname)? .user_arg(old)?; let out = run_raw(cmd, None).await?; if out.status.success() { return Ok(()); } let stderr = String::from_utf8_lossy(&out.stderr); if stderr.contains("but expected") || stderr.contains("unable to resolve reference") { return Err(Error::RefMoved(refname.to_owned())); } Err(failed("update-ref", &out)) } /// The diff of the head side of a three-dot range: `merge-base(base, head)..head`. Parsed the same /// way as [`crate::history::commit_diff`]. With no common ancestor it is the diff from the empty tree. pub async fn range_diff_files( env: &GitEnv, repo: &Path, base_oid: &str, head_oid: &str, limits: DiffLimits, ) -> Result { range_diff_files_with( env, repo, ObjectSource::default(), base_oid, head_oid, limits, ) .await } /// [`range_diff_files`], reading objects missing from `repo` from `src`. Nothing is written. pub async fn range_diff_files_with( env: &GitEnv, repo: &Path, src: ObjectSource<'_>, base_oid: &str, head_oid: &str, limits: DiffLimits, ) -> Result { validate_oid(base_oid)?; validate_oid(head_oid)?; let from = match merge_base_with(env, repo, src, base_oid, head_oid).await? { Some(b) => b, None => empty_tree_for(head_oid).to_owned(), }; diff_between(env, repo, src, &from, head_oid, limits).await } /// Commits reachable from `head` but not from `base` (`log ^`), oldest first. /// At most `max` of the newest such commits are returned. pub async fn range_log( env: &GitEnv, repo: &Path, base_oid: &str, head_oid: &str, max: usize, ) -> Result> { range_log_with(env, repo, ObjectSource::default(), base_oid, head_oid, max).await } /// [`range_log`], reading objects missing from `repo` from `src`. Nothing is written. pub async fn range_log_with( env: &GitEnv, repo: &Path, src: ObjectSource<'_>, base_oid: &str, head_oid: &str, max: usize, ) -> Result> { validate_oid(base_oid)?; validate_oid(head_oid)?; new_commits_with(env, repo, src, Some(base_oid), head_oid, max).await } #[cfg(test)] mod tests { use super::*; use crate::history::DiffStatus; use std::path::PathBuf; use std::process::Command; const LIMITS: DiffLimits = DiffLimits { max_files: 100, max_lines_per_file: 1000, max_total_lines: 10_000, }; /// Runs git in `dir` with a cleared environment and fixed identities. fn git_in(dir: &Path, home: &Path, args: &[&str]) -> String { let out = Command::new("/usr/bin/git") .arg("-C") .arg(dir) .args(["-c", "commit.gpgsign=false"]) .args(args) .env_clear() .env("PATH", "/usr/bin:/bin") .env("HOME", home) .env("GIT_CONFIG_NOSYSTEM", "1") .env("GIT_CONFIG_GLOBAL", "/dev/null") .env("GIT_AUTHOR_NAME", "Tester") .env("GIT_AUTHOR_EMAIL", "tester@example.com") .env("GIT_COMMITTER_NAME", "Tester") .env("GIT_COMMITTER_EMAIL", "tester@example.com") .output() .expect("git runs"); assert!( out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).trim().to_owned() } struct Sandbox { _dir: tempfile::TempDir, home: PathBuf, } impl Sandbox { /// The data dir holds the real managed gitconfig, as written at boot, so these tests see /// the same `protocol.file.allow = never` setting that the server runs with. fn new() -> Self { let dir = tempfile::tempdir().expect("tempdir"); let home = dir.path().join("home"); std::fs::create_dir(&home).expect("home dir"); crate::setup::write_managed_gitconfig(&home).expect("managed gitconfig"); Self { _dir: dir, home } } fn env(&self) -> GitEnv { GitEnv { git_bin: PathBuf::from("/usr/bin/git"), data_dir: self.home.clone(), } } /// A non-bare repo named `name` with `main` checked out. fn repo(&self, name: &str) -> Work { let work = self._dir.path().join(name); std::fs::create_dir(&work).expect("work dir"); git_in(&work, &self.home, &["init", "-q", "-b", "main"]); Work { work, home: self.home.clone(), } } } struct Work { work: PathBuf, home: PathBuf, } impl Work { fn git_dir(&self) -> PathBuf { self.work.join(".git") } fn git(&self, args: &[&str]) -> String { git_in(&self.work, &self.home, args) } fn write(&self, name: &str, content: &str) { std::fs::write(self.work.join(name), content).expect("write file"); } /// Stages everything, commits, and returns the new full id. fn commit(&self, msg: &str) -> String { self.git(&["add", "-A"]); self.git(&["commit", "-q", "--allow-empty", "-m", msg]); self.git(&["rev-parse", "HEAD"]) } } #[tokio::test] async fn clean_merge_builds_merge_commit_with_author() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("a.txt", "1\n"); let c0 = w.commit("c0"); w.git(&["switch", "-q", "-c", "feature"]); w.write("b.txt", "feature\n"); let head = w.commit("feature work"); w.git(&["switch", "-q", "main"]); w.write("c.txt", "main\n"); let base = w.commit("main work"); let gd = w.git_dir(); assert_eq!( merge_base(&env, &gd, &base, &head) .await .expect("merge-base"), Some(c0) ); let tree = match check_merge(&env, &gd, &base, &head).await.expect("check") { MergeCheck::Clean { tree } => tree, other => panic!("expected clean merge, got {other:?}"), }; assert_eq!(tree.len(), 40); let author = Signature { name: "Alice Author".into(), email: "alice@example.com".into(), time_unix: 1_700_000_000, }; let committer = Signature { name: "Carol Committer".into(), email: "carol@example.com".into(), time_unix: 1_700_000_100, }; let merge = commit_tree( &env, &gd, &tree, &[base.as_str(), head.as_str()], "Merge pull request #1 from owner/feature\n\nFeature", &author, &committer, ) .await .expect("commit-tree"); assert_eq!( w.git(&["rev-list", "--parents", "-n1", merge.as_str()]), format!("{merge} {base} {head}") ); assert_eq!( w.git(&[ "log", "-1", "--format=%T|%an|%ae|%at|%cn|%ce|%ct|%s", merge.as_str() ]), format!( "{tree}|Alice Author|alice@example.com|1700000000|Carol Committer|carol@example.com|1700000100|Merge pull request #1 from owner/feature" ) ); assert!( is_ancestor(&env, &gd, &head, &merge) .await .expect("ancestor") ); } #[tokio::test] async fn conflicting_merge_lists_the_file() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("f.txt", "base\n"); w.commit("c0"); w.git(&["switch", "-q", "-c", "feature"]); w.write("f.txt", "head\n"); let head = w.commit("feature edits f"); w.git(&["switch", "-q", "main"]); w.write("f.txt", "other\n"); let base = w.commit("main edits f"); let check = check_merge(&env, &w.git_dir(), &base, &head) .await .expect("check"); assert_eq!( check, MergeCheck::Conflict { files: vec!["f.txt".to_owned()] } ); } #[tokio::test] async fn head_contained_in_base_is_up_to_date() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("a.txt", "1\n"); let c0 = w.commit("c0"); w.write("a.txt", "2\n"); let c1 = w.commit("c1"); let gd = w.git_dir(); assert_eq!( check_merge(&env, &gd, &c1, &c0).await.expect("check"), MergeCheck::UpToDate ); assert!(is_ancestor(&env, &gd, &c0, &c1).await.expect("ancestor")); assert!(!is_ancestor(&env, &gd, &c1, &c0).await.expect("ancestor")); } #[tokio::test] async fn update_ref_cas_succeeds_then_refuses_stale_old() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("a.txt", "1\n"); let c0 = w.commit("c0"); w.write("a.txt", "2\n"); let c1 = w.commit("c1"); w.write("a.txt", "3\n"); let c2 = w.commit("c2"); let gd = w.git_dir(); // The base is at c2, so a CAS expecting c0 must fail and leave the ref alone. let stale = update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c0).await; assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}"); assert_eq!(w.git(&["rev-parse", "main"]), c2); update_ref_cas(&env, &gd, "refs/heads/main", &c1, &c2) .await .expect("cas with current old"); assert_eq!(w.git(&["rev-parse", "main"]), c1); } #[tokio::test] async fn delete_ref_cas_deletes_only_at_expected_value() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("a.txt", "1\n"); let c0 = w.commit("c0"); w.git(&["branch", "topic"]); w.write("a.txt", "2\n"); let c1 = w.commit("c1"); let gd = w.git_dir(); // topic is at c0, so a deletion expecting c1 must fail and leave the ref alone. let stale = delete_ref_cas(&env, &gd, "refs/heads/topic", &c1).await; assert!(matches!(stale, Err(Error::RefMoved(_))), "{stale:?}"); assert_eq!(w.git(&["rev-parse", "topic"]), c0); delete_ref_cas(&env, &gd, "refs/heads/topic", &c0) .await .expect("delete at current value"); let gone = w.git(&["for-each-ref", "refs/heads/topic"]); assert!(gone.is_empty(), "{gone:?}"); // Deleting a ref that is already gone is a refusal, not a silent success. let missing = delete_ref_cas(&env, &gd, "refs/heads/topic", &c0).await; assert!(matches!(missing, Err(Error::RefMoved(_))), "{missing:?}"); } #[tokio::test] async fn range_log_returns_head_side_commits_oldest_first() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("a.txt", "1\n"); w.commit("c0"); w.git(&["switch", "-q", "-c", "feature"]); w.write("f1.txt", "1\n"); w.commit("f1"); w.write("f2.txt", "1\n"); let head = w.commit("f2"); w.git(&["switch", "-q", "main"]); w.write("m.txt", "1\n"); let base = w.commit("m1"); let log = range_log(&env, &w.git_dir(), &base, &head, 100) .await .expect("range log"); let summaries: Vec<&str> = log.iter().map(|c| c.summary.as_str()).collect(); assert_eq!(summaries, vec!["f1", "f2"]); } #[tokio::test] async fn range_diff_shows_only_head_side_after_base_moved() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("a.txt", "1\n"); w.commit("c0"); w.git(&["switch", "-q", "-c", "feature"]); w.write("feat.txt", "feature\n"); let head = w.commit("feature"); w.git(&["switch", "-q", "main"]); w.write("base.txt", "base\n"); let base = w.commit("base moves"); let diff = range_diff_files(&env, &w.git_dir(), &base, &head, LIMITS) .await .expect("range diff"); let paths: Vec = diff .files .iter() .map(|f| f.new_path.clone().unwrap_or_default()) .collect(); assert_eq!(paths, vec!["feat.txt".to_owned()]); assert_eq!(diff.files[0].status, DiffStatus::Added); } /// True when the repo at `git_dir` has `oid` in its object store. fn has_object(git_dir: &Path, oid: &str) -> bool { Command::new("/usr/bin/git") .arg("--git-dir") .arg(git_dir) .args(["cat-file", "-e", oid]) .env_clear() .env("PATH", "/usr/bin:/bin") .env("GIT_CONFIG_NOSYSTEM", "1") .env("GIT_CONFIG_GLOBAL", "/dev/null") .status() .expect("git runs") .success() } #[tokio::test] async fn alternate_objects_read_fork_commit_without_copying_it() { let sb = Sandbox::new(); let env = sb.env(); let base = sb.repo("base"); base.write("a.txt", "1\n"); let base_tip = base.commit("base"); // The fork is a clone, so both histories share `base_tip`. let fork_dir = sb._dir.path().join("fork"); git_in( sb._dir.path(), &sb.home, &["clone", "-q", base.work.to_str().expect("utf8"), "fork"], ); let fork = Work { work: fork_dir, home: sb.home.clone(), }; fork.write("b.txt", "fork\n"); let fork_head = fork.commit("fork work"); let base_git = base.git_dir(); let fork_objects = fork.git_dir().join("objects"); assert!(!has_object(&base_git, &fork_head)); // Without the alternate the base cannot see the fork's commit. assert!( range_log(&env, &base_git, &base_tip, &fork_head, 10) .await .is_err() ); let src = ObjectSource { extra: Some(fork_objects.as_path()), }; let log = range_log_with(&env, &base_git, src, &base_tip, &fork_head, 10) .await .expect("range log through alternate"); let summaries: Vec<&str> = log.iter().map(|c| c.summary.as_str()).collect(); assert_eq!(summaries, vec!["fork work"]); let merge = merge_base_with(&env, &base_git, src, &base_tip, &fork_head) .await .expect("merge base through alternate"); assert_eq!(merge.as_deref(), Some(base_tip.as_str())); let diff = range_diff_files_with(&env, &base_git, src, &base_tip, &fork_head, LIMITS) .await .expect("range diff through alternate"); let paths: Vec = diff .files .iter() .map(|f| f.new_path.clone().unwrap_or_default()) .collect(); assert_eq!(paths, vec!["b.txt".to_owned()]); // Reading through the alternate wrote nothing into the base repo. assert!(!has_object(&base_git, &fork_head)); } #[tokio::test] async fn fetch_into_pull_ref_from_fork_and_same_repo() { let sb = Sandbox::new(); let env = sb.env(); let base = sb.repo("base"); base.write("a.txt", "1\n"); let base_tip = base.commit("base"); let fork = sb.repo("fork"); fork.write("x.txt", "fork\n"); let fork_tip = fork.commit("fork work"); fetch_into_pull_ref(&env, &base.git_dir(), &fork.git_dir(), &fork_tip, 1) .await .expect("fork fetch"); assert_eq!(base.git(&["rev-parse", "refs/pull/1/head"]), fork_tip); fetch_into_pull_ref(&env, &base.git_dir(), &base.git_dir(), &base_tip, 2) .await .expect("same-repo update"); assert_eq!(base.git(&["rev-parse", "refs/pull/2/head"]), base_tip); } #[tokio::test] async fn fetch_into_pull_ref_handles_unadvertised_fork_commit() { let sb = Sandbox::new(); let env = sb.env(); let base = sb.repo("base"); base.write("a.txt", "1\n"); base.commit("base"); let fork = sb.repo("fork"); fork.write("x.txt", "fork\n"); fork.commit("main work"); fork.git(&["switch", "-q", "-c", "topic"]); fork.write("y.txt", "topic\n"); let topic_tip = fork.commit("topic work"); fork.git(&["switch", "-q", "main"]); fork.git(&["branch", "-q", "-D", "topic"]); fetch_into_pull_ref(&env, &base.git_dir(), &fork.git_dir(), &topic_tip, 3) .await .expect("unadvertised fetch"); assert_eq!(base.git(&["rev-parse", "refs/pull/3/head"]), topic_tip); } #[tokio::test] async fn blob_at_returns_blob_ids_for_files_only() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); let gd = w.git_dir(); w.write("a.txt", "1\n"); std::fs::create_dir(w.work.join("dir")).expect("dir"); w.write("dir/x.txt", "x\n"); let c0 = w.commit("c0"); let a0 = w.git(&["hash-object", "a.txt"]); assert_eq!( blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"), Some(a0.clone()) ); assert_eq!( blob_at(&env, &gd, &c0, "dir/x.txt").await.expect("ok"), Some(w.git(&["hash-object", "dir/x.txt"])) ); assert_eq!( blob_at(&env, &gd, &c0, "missing.txt").await.expect("ok"), None ); assert_eq!(blob_at(&env, &gd, &c0, "dir").await.expect("ok"), None); w.write("a.txt", "2\n"); let c1 = w.commit("c1"); let a1 = blob_at(&env, &gd, &c1, "a.txt").await.expect("ok"); assert_eq!(a1, Some(w.git(&["hash-object", "a.txt"]))); assert_ne!(a1, Some(a0)); // The older commit still maps to the older blob. let old_spec = format!("{c0}:a.txt"); assert_eq!( blob_at(&env, &gd, &c0, "a.txt").await.expect("ok"), Some(w.git(&["rev-parse", old_spec.as_str()])) ); } #[tokio::test] async fn blob_at_handles_literal_special_and_unicode_names() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); let gd = w.git_dir(); std::fs::create_dir(w.work.join("dir with space")).expect("dir"); w.write("dir with space/füß ü.txt", "u\n"); w.write("star*", "s\n"); w.write(":colon", "c\n"); w.write("other", "o\n"); let c0 = w.commit("c0"); assert_eq!( blob_at(&env, &gd, &c0, "dir with space/füß ü.txt") .await .expect("ok"), Some(w.git(&["hash-object", "dir with space/füß ü.txt"])) ); assert_eq!( blob_at(&env, &gd, &c0, "star*").await.expect("ok"), Some(w.git(&["hash-object", "star*"])) ); assert_eq!( blob_at(&env, &gd, &c0, ":colon").await.expect("ok"), Some(w.git(&["hash-object", ":colon"])) ); // A glob must not match other entries. assert_eq!(blob_at(&env, &gd, &c0, "st*").await.expect("ok"), None); assert_eq!(blob_at(&env, &gd, &c0, "*").await.expect("ok"), None); } #[tokio::test] async fn blob_at_rejects_invalid_paths_and_commits() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("a.txt", "1\n"); let c0 = w.commit("c0"); let gd = w.git_dir(); for bad in [ "", "../x", "a/../x", "/a", "a//b", "a/", "./a", "a/./b", "a\nb", "a\0b", ] { let r = blob_at(&env, &gd, &c0, bad).await; assert!(matches!(r, Err(Error::InvalidInput(_))), "{bad:?}: {r:?}"); } let r = blob_at(&env, &gd, "not-hex", "a.txt").await; assert!(matches!(r, Err(Error::InvalidInput(_))), "{r:?}"); } #[tokio::test] async fn invalid_inputs_are_rejected_before_git() { let sb = Sandbox::new(); let env = sb.env(); let w = sb.repo("repo"); w.write("a.txt", "1\n"); let c0 = w.commit("c0"); let gd = w.git_dir(); let short = "a".repeat(39); let bad_oid = |r: Result<()>| assert!(matches!(r, Err(Error::InvalidInput(_))), "{r:?}"); bad_oid(check_merge(&env, &gd, "not-hex", &c0).await.map(|_| ())); bad_oid(merge_base(&env, &gd, &short, &c0).await.map(|_| ())); bad_oid( commit_tree( &env, &gd, "--output=/tmp/x", &[], "m", &Signature { name: "a".into(), email: "a@example.com".into(), time_unix: 0, }, &Signature { name: "a".into(), email: "a@example.com".into(), time_unix: 0, }, ) .await .map(|_| ()), ); bad_oid(update_ref_cas(&env, &gd, "refs/heads/main", "HEAD", &c0).await); bad_oid(update_ref_cas(&env, &gd, "refs/heads/../x", &c0, &c0).await); bad_oid(update_ref_cas(&env, &gd, "refs/heads/-x", &c0, &c0).await); bad_oid(fetch_into_pull_ref(&env, &gd, &gd, "--upload-pack=x", 1).await); bad_oid(fetch_into_pull_ref(&env, &gd, &gd, &c0, 0).await); bad_oid(range_log(&env, &gd, "main", &c0, 10).await.map(|_| ())); bad_oid( range_diff_files(&env, &gd, &c0, &short, LIMITS) .await .map(|_| ()), ); let bad_name = Signature { name: "Eve ".into(), email: "eve@example.com".into(), time_unix: 0, }; bad_oid( commit_tree(&env, &gd, &c0, &[], "m", &bad_name, &bad_name) .await .map(|_| ()), ); } }