From 7f0954e6e0fb52eba4543fe90614df3cc02240de Mon Sep 17 00:00:00 2001 From: Swayam Gupta Date: Sat, 28 Nov 2026 18:41:47 +0530 Subject: [PATCH] feat(review): add --base to review local changes against a named revision --- README.md | 2 + src/git.rs | 57 ++++++++++- src/hooks.rs | 2 +- src/lib.rs | 16 ++- tests/local_patch.rs | 233 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 302 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index eea0165..7eeac2b 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,8 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight. You cannot combine `--path` with pushed-commit, range, or pull-request review. +`proofline review --base main` reviews the local changes against the merge-base of `HEAD` and `main` instead of the upstream or default branch, including commits you already pushed. Name the branch you build on: after a push, the upstream alone would leave the pushed commits out, and on a branch stacked on another, naming the parent reviews only the stacked branch's commits. GitHub must have the merge-base, so the command refuses one that no remote-tracking branch contains before it sends anything. Combine it with `--staged`, `--include-untracked`, `--path`, `--verify`, or `--allow-path`; you cannot combine it with pushed-commit, range, file, or pull-request review. + `proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. Both commands send the API the name without its owner, and use the response only when its repository choices list `owner/name`, or the Git remote's owner and name, among the organization's reviewed repositories. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches. None of these commands reads the organization's review list. `proofline rerun REVIEW_ID` requests the original immutable subject and waits, while `--no-wait` returns its link. Reruns require `reviews:rerun`. `proofline guidance --repo owner/name` requires `guidance:read`, and `proofline fix-prompt FINDING_ID` requires `findings:read`. History, guidance, and fix prompts print JSON; prompt text remains untrusted. diff --git a/src/git.rs b/src/git.rs index da409a7..2e9c213 100644 --- a/src/git.rs +++ b/src/git.rs @@ -23,6 +23,12 @@ pub enum GitError { "the checkout has no base to review against: set an upstream branch with `git branch --set-upstream-to`, or run `git remote set-head {0} --auto`" )] NoBase(String), + #[error( + "the merge-base {base} of HEAD and {revision:?} is on no remote-tracking branch, so GitHub may not have it; push {revision:?}, or pass --base a revision that is already pushed" + )] + UnpushedBase { base: String, revision: String }, + #[error("HEAD and {0:?} have no commit in common, so there is no base to review against")] + NoCommonBase(String), #[error("the local changes include text that is not UTF-8, which Proofline cannot review")] NotUtf8, #[error("the local changes make a {0} MiB patch; Proofline reviews patches up to 5 MiB")] @@ -239,6 +245,40 @@ async fn base(dir: &Path, remote: &str) -> Result { merge_base(dir, remote, "HEAD", &["@{upstream}", default.as_str()]).await } +/// The merge-base of `HEAD` with the commit `revision` names, the base a +/// pull request from `HEAD` into it would have. GitHub must have the base, +/// so one that no remote-tracking branch contains is refused here, before +/// anything is sent. +async fn named_base(dir: &Path, revision: &str) -> Result { + let commit = resolve(dir, revision).await?; + let base = line_in(dir, &["merge-base", "HEAD", &commit]) + .await + .map_err(|error| match error { + GitError::Failed { .. } => GitError::NoCommonBase(revision.to_owned()), + error => error, + })?; + let base = commit_sha(&base)?; + let pushed = line_in( + dir, + &[ + "for-each-ref", + "--count=1", + "--format=%(refname)", + "--contains", + &base, + "refs/remotes/", + ], + ) + .await?; + if pushed.is_empty() { + return Err(GitError::UnpushedBase { + base, + revision: revision.to_owned(), + }); + } + Ok(base) +} + /// Which local bytes contribute to the patch against its pinned base. #[derive(Debug, Clone, Copy)] pub enum LocalSelection { @@ -250,17 +290,22 @@ pub enum LocalSelection { IncludeUntracked, } -/// Local changes against one merge-base. A copied index collects the selected -/// bytes, so the person's index is untouched. +/// Local changes against one merge-base: with `base_revision` when the person +/// names one, otherwise with the upstream or default branch. A copied index +/// collects the selected bytes, so the person's index is untouched. pub async fn local_changes( dir: &Path, remote: &str, + base_revision: Option<&str>, selection: LocalSelection, path: Option<&str>, ) -> Result { let root = line_in(dir, &["rev-parse", "--show-toplevel"]).await?; let root = Path::new(&root); - let base_commit_sha = base(root, remote).await?; + let base_commit_sha = match base_revision { + Some(revision) => named_base(root, revision).await?, + None => base(root, remote).await?, + }; let scratch = tempfile::tempdir() .map_err(|error| GitError::Unavailable(format!("no temporary directory: {error}")))?; let index = scratch.path().join("index"); @@ -705,7 +750,7 @@ mod tests { ], ); - let unchanged = local_changes(dir, "origin", LocalSelection::Tracked, None) + let unchanged = local_changes(dir, "origin", None, LocalSelection::Tracked, None) .await .unwrap(); assert_eq!( @@ -749,7 +794,9 @@ mod tests { ], ), ] { - let changes = local_changes(dir, "origin", selection, None).await.unwrap(); + let changes = local_changes(dir, "origin", None, selection, None) + .await + .unwrap(); assert_eq!(changes.base_commit_sha, base); let mut expected = vec![ "diff --git a/committed.txt b/committed.txt", diff --git a/src/hooks.rs b/src/hooks.rs index 1de7d43..3cb01a1 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -377,7 +377,7 @@ async fn subjects(hook: Hook, here: &Path, remote: &str) -> anyhow::Result<(Vec< Hook::PreCommit => Ok(( vec![Subject { label: "the staged changes".to_owned(), - changes: git::local_changes(here, remote, LocalSelection::Staged, None).await, + changes: git::local_changes(here, remote, None, LocalSelection::Staged, None).await, }], 0, )), diff --git a/src/lib.rs b/src/lib.rs index 8c6f1d6..6eab1d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -313,6 +313,16 @@ struct ReviewArgs { pr: Option, #[command(flatten)] local_selection: LocalSelectionArgs, + /// Review the local changes against the merge-base of HEAD and this + /// revision instead of the upstream or default branch, including commits + /// already pushed. The name is resolved once in the checkout; a + /// remote-tracking branch must contain the merge-base, so GitHub has it. + #[arg( + long, + value_name = "REVISION", + conflicts_with_all = ["pr", "commit", "range", "files"] + )] + base: Option, /// Review the change this pushed commit makes against its first parent. /// The name is resolved once in the checkout; GitHub must have both commits. /// With --files, review complete selected files at that commit instead. @@ -1068,8 +1078,9 @@ async fn review(api: &Api, args: &ReviewArgs) -> anyhow::Result { finish(api, requested.review_id, args).await } -/// Reviews the checkout's local changes against the commit they build on. -/// Nothing is pushed: GitHub needs only the base commit. +/// Reviews the checkout's local changes against the commit they build on, or +/// against the merge-base with `--base`. Nothing is pushed: GitHub needs only +/// the base commit. async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { let selection = if args.local_selection.staged { git::LocalSelection::Staged @@ -1081,6 +1092,7 @@ async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { let changes = git::local_changes( std::path::Path::new("."), &args.repository.remote, + args.base.as_deref(), selection, args.path.as_deref(), ) diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 6da45f8..b61db8e 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -300,6 +300,21 @@ impl Checkout { .unwrap() } + async fn sha(&self, revision: &str) -> String { + String::from_utf8(self.git(&["rev-parse", "--verify", revision]).await) + .unwrap() + .trim() + .to_owned() + } + + /// Commits `text` at `path` and returns the new commit. + async fn commit(&self, path: &str, text: &str) -> String { + self.write(path, text).await; + self.git(&["add", path]).await; + self.git(&["commit", "-qm", path]).await; + self.sha("HEAD").await + } + async fn review(&self, server: &Server, allowed: &[&str], flags: &[&str]) -> Output { let mut flags = flags.to_vec(); flags.push("--no-wait"); @@ -361,6 +376,37 @@ impl Checkout { } } +/// Reviews with `flags` and checks the one upload: its base, and which +/// texts its patch has and lacks. +async fn assert_upload( + checkout: &Checkout, + flags: &[&str], + base: &str, + included: &[&str], + excluded: &[&str], +) { + let server = Server::start(true).await; + let output = checkout.review(&server, &[], flags).await; + assert!( + output.status.success(), + "{flags:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + { + let uploads = server.fixture.uploads.lock().unwrap(); + assert_eq!(uploads.len(), 1, "{flags:?}"); + assert_eq!(uploads[0]["base_commit_sha"], base, "{flags:?}"); + let patch = uploads[0]["patch"].as_str().unwrap(); + for text in included { + assert!(patch.contains(text), "{flags:?}: {patch}"); + } + for text in excluded { + assert!(!patch.contains(text), "{flags:?}: {patch}"); + } + } + server.close().await; +} + fn assert_refusal(output: &Output, diagnostic: &str, secret: &str) { assert_eq!(output.status.code(), Some(1)); assert!(output.stdout.is_empty()); @@ -978,3 +1024,190 @@ async fn local_path_never_expands_a_file_replaced_by_a_directory() { assert_eq!(checkout.index().await, index); server.close().await; } + +/// Once a branch is pushed its upstream is its head, so the default base +/// leaves its pushed commits out. `--base` names the branch it builds on and +/// reviews those commits with the selected local changes. +#[tokio::test] +async fn a_named_base_reviews_the_pushed_commits_an_upstream_leaves_out() { + let checkout = Checkout::new(&[("kept.txt", "base\n")]).await; + checkout.git(&["switch", "-qc", "feature"]).await; + let pushed = checkout.commit("pushed.txt", "pushed commit\n").await; + checkout + .git(&["update-ref", "refs/remotes/origin/feature", &pushed]) + .await; + checkout + .git(&["remote", "add", "origin", "https://github.com/acme/web.git"]) + .await; + checkout + .git(&["branch", "--set-upstream-to=origin/feature"]) + .await; + checkout.write("kept.txt", "staged\n").await; + checkout.git(&["add", "kept.txt"]).await; + checkout.write("kept.txt", "working tree\n").await; + let index = checkout.index().await; + + assert_upload(&checkout, &[], &pushed, &["+working tree"], &["pushed.txt"]).await; + for (flags, included, excluded) in [ + ( + vec!["--base", "main"], + vec!["+pushed commit", "+working tree"], + vec!["+staged"], + ), + ( + vec!["--base", "origin/main", "--verify", FINDING], + vec!["+pushed commit", "+working tree"], + vec!["+staged"], + ), + ( + vec!["--base", "main", "--staged"], + vec!["+pushed commit", "+staged"], + vec!["+working tree"], + ), + ( + vec!["--base", "main", "--path", "pushed.txt"], + vec!["+pushed commit"], + vec!["kept.txt"], + ), + ] { + assert_upload(&checkout, &flags, &checkout.base, &included, &excluded).await; + } + assert_eq!(checkout.index().await, index); +} + +/// A branch stacked on another names its parent, and only its own commits +/// are reviewed: against the merge-base, so later parent commits do not +/// show up as reverted. +#[tokio::test] +async fn a_stacked_branch_reviews_only_its_own_commits_against_its_parent() { + let checkout = Checkout::new(&[("kept.txt", "base\n")]).await; + checkout.git(&["switch", "-qc", "parent"]).await; + let fork = checkout.commit("parent.txt", "parent commit\n").await; + checkout.git(&["switch", "-qc", "child"]).await; + checkout.commit("child.txt", "child commit\n").await; + checkout.git(&["switch", "-q", "parent"]).await; + let moved = checkout.commit("later.txt", "later parent commit\n").await; + checkout + .git(&["update-ref", "refs/remotes/origin/parent", &moved]) + .await; + checkout.git(&["switch", "-q", "child"]).await; + + // Without an upstream, the default branch is the base and the parent's + // commit is reviewed again. + assert_upload( + &checkout, + &[], + &checkout.base, + &["+parent commit", "+child commit"], + &["later.txt"], + ) + .await; + for base in ["parent", "origin/parent"] { + assert_upload( + &checkout, + &["--base", base], + &fork, + &["+child commit"], + &["parent.txt", "later.txt"], + ) + .await; + } +} + +/// GitHub must have the base, so a merge-base that no remote-tracking branch +/// contains, or none at all, is refused before any request. +#[tokio::test] +async fn a_named_base_github_may_not_have_is_refused_before_http() { + let checkout = Checkout::new(&[("kept.txt", "base\n")]).await; + checkout.git(&["switch", "-qc", "parent"]).await; + let unpushed = checkout.commit("parent.txt", "parent commit\n").await; + checkout.git(&["switch", "-qc", "child"]).await; + checkout.commit("child.txt", "child commit\n").await; + let unrelated = String::from_utf8( + checkout + .git(&["commit-tree", "HEAD^{tree}", "-m", "unrelated"]) + .await, + ) + .unwrap() + .trim() + .to_owned(); + let index = checkout.index().await; + let server = Server::start(true).await; + for (base, diagnostic) in [ + ( + "parent", + format!( + "the merge-base {unpushed} of HEAD and \"parent\" is on no remote-tracking branch, so GitHub may not have it; push \"parent\"" + ), + ), + ( + unrelated.as_str(), + format!("HEAD and \"{unrelated}\" have no commit in common"), + ), + ] { + let output = checkout.review(&server, &[], &["--base", base]).await; + assert_eq!(output.status.code(), Some(1), "{base}"); + assert!(output.stdout.is_empty(), "{base}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains(&diagnostic), "{stderr}"); + server.assert_no_requests(); + assert_eq!(checkout.index().await, index); + } + server.close().await; + + checkout + .git(&["update-ref", "refs/remotes/origin/parent", &unpushed]) + .await; + assert_upload( + &checkout, + &["--base", "parent"], + &unpushed, + &["+child commit"], + &["parent.txt"], + ) + .await; +} + +/// `--base` names one commit for a local review: a name the checkout cannot +/// resolve, one Git would read as an option, or another review selection is +/// refused before any request. +#[tokio::test] +async fn a_named_base_refuses_unknown_names_options_and_other_selections() { + let checkout = Checkout::new(&[("kept.txt", "base\n")]).await; + checkout.write("kept.txt", "changed\n").await; + let server = Server::start(true).await; + for (flags, diagnostic) in [ + ( + vec!["--base", "no-such-branch"], + "\"no-such-branch\" names no commit in this checkout", + ), + ( + vec!["--base=--all"], + "\"--all\" names no commit in this checkout", + ), + ( + vec!["--base", "main", "--pr", "7"], + "'--base ' cannot be used with '--pr", + ), + ( + vec!["--base", "main", "--commit", "HEAD"], + "'--base ' cannot be used with '--commit", + ), + ( + vec!["--base", "main", "--range", "main..main"], + "'--base ' cannot be used with '--range", + ), + ( + vec!["--base", "main", "--files", "kept.txt"], + "'--base ' cannot be used with '--files", + ), + ] { + let output = checkout.review(&server, &[], &flags).await; + assert_eq!(output.status.code(), Some(1), "{flags:?}"); + assert!(output.stdout.is_empty(), "{flags:?}"); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains(diagnostic), "{flags:?}: {stderr}"); + server.assert_no_requests(); + } + server.close().await; +}