use crate::debate;
use crate::prompts::{ReviewScope, RunTask};
use crate::review;
use eyre::{Result, WrapErr};
use nitpicker_agent::config::Config;
use serde::Deserialize;
use sha2::Digest;
use std::path::{Path, PathBuf};
use std::process::Command;
fn lock_path(repo: &Path) -> PathBuf {
let identity = git_common_dir(repo)
.or_else(|| repo.canonicalize().ok())
.unwrap_or_else(|| repo.to_path_buf());
let hash = sha2::Sha256::digest(identity.as_os_str().as_encoded_bytes());
let hash_hex: String = hash.iter().map(|b| format!("{b:02x}")).collect();
std::env::temp_dir().join(format!("nitpicker-pr-review-{hash_hex}.lock"))
}
fn git_common_dir(repo: &Path) -> Option<PathBuf> {
let output = Command::new("git")
.args(["rev-parse", "--git-common-dir"])
.current_dir(repo)
.output()
.ok()?;
if !output.status.success() {
return None;
}
let path = PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
let path = if path.is_absolute() {
path
} else {
repo.join(path)
};
path.canonicalize().ok()
}
struct PrLock {
#[cfg(unix)]
_file: std::fs::File,
#[cfg(not(unix))]
path: PathBuf,
}
impl PrLock {
#[cfg(unix)]
fn acquire(repo: &Path) -> Result<Self> {
use std::os::unix::io::AsRawFd;
let path = lock_path(repo);
let file = std::fs::OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(&path)
.wrap_err("failed to open PR review lock file")?;
let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if rc != 0 {
let err = std::io::Error::last_os_error();
match err.raw_os_error() {
Some(code) if code == libc::EWOULDBLOCK => eyre::bail!(
"Another PR review is already running for this repo (lock file: {}). Wait for it to finish.",
path.display()
),
_ => return Err(err).wrap_err("failed to acquire PR review lock"),
}
}
Ok(Self { _file: file })
}
#[cfg(not(unix))]
fn acquire(repo: &Path) -> Result<Self> {
let path = lock_path(repo);
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(_) => Ok(Self { path }),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => eyre::bail!(
"Another PR review is already running for this repo (lock file: {}). Remove it if it crashed.",
path.display()
),
Err(e) => Err(e).wrap_err("failed to create lock file"),
}
}
}
impl Drop for PrLock {
fn drop(&mut self) {
#[cfg(not(unix))]
let _ = std::fs::remove_file(&self.path);
}
}
#[derive(Debug, clap::Args)]
pub struct PrArgs {
pub url: Option<String>,
#[command(flatten)]
pub context: crate::ContextFileArgs,
#[command(flatten)]
pub presets: crate::PresetArgs,
#[arg(long)]
pub prompt: Option<String>,
#[arg(long)]
pub no_debate: bool,
#[arg(long)]
pub alloy: bool,
#[arg(long, default_value = "5")]
pub rounds: usize,
#[arg(long, value_parser = crate::parse_positive_usize)]
pub max_turns: Option<usize>,
#[arg(long)]
pub no_comment: bool,
#[arg(long)]
pub clone: bool,
#[arg(long)]
pub json: bool,
}
impl PrArgs {
fn output_format(&self) -> crate::output::OutputFormat {
match self.json {
true => crate::output::OutputFormat::Json,
false => crate::output::OutputFormat::Text,
}
}
}
#[derive(Deserialize)]
struct PrMeta {
title: String,
body: String,
#[serde(rename = "headRefOid")]
head_ref_oid: String,
#[serde(rename = "baseRefName")]
base_ref_name: String,
}
#[derive(Deserialize)]
struct PrComment {
author: Option<PrCommentAuthor>,
body: String,
}
#[derive(Deserialize)]
struct PrCommentAuthor {
login: String,
}
pub fn check_gh() -> Result<()> {
let status = Command::new("gh").arg("--version").output();
match status {
Ok(o) if o.status.success() => Ok(()),
_ => eyre::bail!(
"`gh` CLI not found or not working. Install it from https://cli.github.com/ and run `gh auth login`."
),
}
}
fn fetch_pr_meta(url: Option<&str>, repo: &Path) -> Result<PrMeta> {
let mut cmd = Command::new("gh");
cmd.args(["pr", "view", "--json", "title,body,headRefOid,baseRefName"])
.current_dir(repo);
if let Some(u) = url {
cmd.arg(u);
}
let out = cmd.output().wrap_err("failed to run gh pr view")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("gh pr view failed: {}", stderr.trim());
}
serde_json::from_slice(&out.stdout).wrap_err("failed to parse gh pr view output")
}
fn fetch_pr_comments(url: Option<&str>, repo: &Path) -> Result<Vec<PrComment>> {
let mut cmd = Command::new("gh");
cmd.args(["pr", "view", "--json", "comments"])
.current_dir(repo);
if let Some(u) = url {
cmd.arg(u);
}
let out = cmd
.output()
.wrap_err("failed to run gh pr view --json comments")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("gh pr view comments failed: {}", stderr.trim());
}
#[derive(Deserialize)]
struct CommentsWrapper {
comments: Vec<PrComment>,
}
let wrapper: CommentsWrapper =
serde_json::from_slice(&out.stdout).wrap_err("failed to parse gh pr comments output")?;
Ok(wrapper.comments)
}
pub fn parse_pr_url(url: &str) -> Result<(String, u32)> {
let url_obj = url::Url::parse(url).wrap_err("invalid URL")?;
match url_obj.host_str() {
Some("github.com") => {}
Some(host) => eyre::bail!("only GitHub PRs are supported (got host: {host})"),
None => eyre::bail!("URL has no host"),
}
let segments: Vec<&str> = url_obj
.path_segments()
.ok_or_else(|| eyre::eyre!("URL has no path"))?
.filter(|s| !s.is_empty())
.collect();
match segments.as_slice() {
[owner, repo, "pull", n, ..] => {
let pr_number: u32 = n
.parse()
.wrap_err_with(|| format!("PR number `{n}` is not a valid integer"))?;
Ok((format!("{owner}/{repo}"), pr_number))
}
_ => eyre::bail!("expected a URL like https://github.com/owner/repo/pull/N, got: {url}"),
}
}
fn slug_from_remote_url(url: &str) -> Option<String> {
let url = url.trim().trim_end_matches(".git");
if url.contains("://") {
let parsed = url::Url::parse(url).ok()?;
let path = parsed.path().trim_start_matches('/');
let parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
if parts.len() >= 2 {
return Some(format!("{}/{}", parts[0], parts[1]));
}
} else if let Some(colon) = url.find(':') {
let after = &url[colon + 1..];
let parts: Vec<&str> = after.split('/').filter(|s| !s.is_empty()).collect();
if parts.len() >= 2 {
return Some(format!("{}/{}", parts[0], parts[1]));
}
}
None
}
fn get_origin_slug(repo: &Path) -> Option<String> {
let out = Command::new("git")
.args(["remote", "get-url", "origin"])
.current_dir(repo)
.output()
.ok()?;
if !out.status.success() {
return None;
}
slug_from_remote_url(&String::from_utf8_lossy(&out.stdout))
}
fn get_head_commit(repo: &Path) -> Result<String> {
let out = Command::new("git")
.args(["rev-parse", "HEAD"])
.current_dir(repo)
.output()
.wrap_err("failed to get HEAD commit")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("git rev-parse HEAD failed: {}", stderr.trim());
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
enum HeadState {
Branch(String),
Detached(String),
}
fn get_head_state(repo: &Path) -> Result<HeadState> {
let out = Command::new("git")
.args(["symbolic-ref", "-q", "--short", "HEAD"])
.current_dir(repo)
.output()
.wrap_err("failed to get current branch")?;
if out.status.success() {
return Ok(HeadState::Branch(
String::from_utf8_lossy(&out.stdout).trim().to_string(),
));
}
let out = Command::new("git")
.args(["rev-parse", "HEAD"])
.current_dir(repo)
.output()
.wrap_err("failed to get current commit")?;
if !out.status.success() {
eyre::bail!("failed to get current branch or commit");
}
Ok(HeadState::Detached(
String::from_utf8_lossy(&out.stdout).trim().to_string(),
))
}
fn restore_head(repo: &Path, head: &HeadState) {
let (args, recover): (Vec<&str>, String) = match head {
HeadState::Branch(b) => (vec!["switch", "--", b], format!("git switch -- {b}")),
HeadState::Detached(sha) => (
vec!["switch", "--detach", sha],
format!("git switch --detach {sha}"),
),
};
let result = Command::new("git").args(&args).current_dir(repo).output();
let detail = match result {
Ok(out) if out.status.success() => return,
Ok(out) => String::from_utf8_lossy(&out.stderr).trim().to_string(),
Err(e) => e.to_string(),
};
eprintln!(
"warning: could not restore HEAD in {repo}; run `{recover}` to recover ({detail})",
repo = repo.display(),
);
}
struct BranchRestoreGuard {
repo: PathBuf,
head: HeadState,
}
impl Drop for BranchRestoreGuard {
fn drop(&mut self) {
restore_head(&self.repo, &self.head);
}
}
fn assert_clean_working_tree(repo: &Path) -> Result<()> {
let out = Command::new("git")
.args(["status", "--porcelain"])
.current_dir(repo)
.output()
.wrap_err("failed to run git status")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("git status failed: {}", stderr.trim());
}
let porcelain = String::from_utf8_lossy(&out.stdout);
if !porcelain.trim().is_empty() {
eyre::bail!(
"working tree has uncommitted changes; commit or stash before running `nitpicker pr` against a different PR:\n{}",
porcelain.trim_end()
);
}
Ok(())
}
fn refresh_remote_branches(repo: &Path) -> Result<()> {
let out = Command::new("git")
.args(["fetch", "origin", "--prune"])
.current_dir(repo)
.output()
.wrap_err("failed to refresh remote branches")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!(
"git fetch origin failed: {}\nReview would run against a stale base branch. Fix the remote or pass `--clone` to review in a fresh temp clone.",
stderr.trim()
);
}
Ok(())
}
fn checkout_pr_branch(repo: &Path, pr_number: u32) -> Result<()> {
assert_clean_working_tree(repo)?;
let fetch_ref = format!("refs/nitpicker/pr-{pr_number}-head");
let refspec = format!("+refs/pull/{pr_number}/head:{fetch_ref}");
let out = Command::new("git")
.args(["fetch", "origin", &refspec])
.current_dir(repo)
.output()
.wrap_err("failed to fetch PR branch")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("git fetch failed: {}", stderr.trim());
}
let branch = format!("nitpicker/pr-{pr_number}");
if matches!(get_head_state(repo), Ok(HeadState::Branch(b)) if b == branch) {
let out = Command::new("git")
.args(["merge", "--ff-only", &fetch_ref])
.current_dir(repo)
.output()
.wrap_err("failed to fast-forward PR branch")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("could not fast-forward to PR head: {}", stderr.trim());
}
return Ok(());
}
let _ = Command::new("git")
.args(["branch", "-D", &branch])
.current_dir(repo)
.output();
let out = Command::new("git")
.args(["switch", "-c", &branch, "--no-track", &fetch_ref])
.current_dir(repo)
.output()
.wrap_err("failed to checkout PR branch")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("git switch failed: {}", stderr.trim());
}
Ok(())
}
fn clone_pr(repo_slug: &str, pr_number: u32, dir: &Path) -> Result<()> {
let clone_url = format!("https://github.com/{repo_slug}.git");
let out = Command::new("git")
.args(["clone", "--filter=blob:none", &clone_url, "."])
.current_dir(dir)
.output()
.wrap_err("failed to run git clone")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("git clone failed: {}", stderr.trim());
}
checkout_pr_branch(dir, pr_number)
}
fn create_temp_clone_repo_dir(temp_root: &Path, repo_slug: &str) -> Result<PathBuf> {
let repo_name = repo_slug
.rsplit('/')
.next()
.filter(|name| !name.is_empty() && *name != "." && *name != ".." && !name.contains('\\'))
.ok_or_else(|| eyre::eyre!("invalid GitHub repository slug: {repo_slug}"))?;
let path = temp_root.join(repo_name);
std::fs::create_dir(&path).wrap_err_with(|| {
format!(
"failed to create temporary clone directory {}",
path.display()
)
})?;
path.canonicalize()
.wrap_err("failed to canonicalize temporary clone directory")
}
fn post_comment(url: Option<&str>, repo: &Path, body: &str) -> Result<()> {
let mut cmd = Command::new("gh");
cmd.args(["pr", "comment", "--body", body])
.current_dir(repo);
if let Some(u) = url {
cmd.arg(u);
}
let out = cmd.output().wrap_err("failed to run gh pr comment")?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
eyre::bail!("gh pr comment failed: {}", stderr.trim());
}
Ok(())
}
fn build_pr_prompt(
meta: &PrMeta,
comments: &[PrComment],
diff_context: &str,
extra: Option<&str>,
) -> String {
let mut parts = vec![format!("## PR: {}", meta.title)];
if !meta.body.trim().is_empty() {
parts.push(meta.body.trim().to_string());
}
if !comments.is_empty() {
let mut comments_section = String::from("## PR Comments\n");
for comment in comments {
let login = comment
.author
.as_ref()
.map(|a| a.login.as_str())
.unwrap_or("[deleted]");
comments_section.push_str(&format!("**{}**: {}\n\n", login, comment.body));
}
parts.push(comments_section);
}
parts.push(diff_context.to_string());
if let Some(p) = extra {
if !p.trim().is_empty() {
parts.push(format!("Additional instructions: {p}"));
}
}
parts.join("\n\n")
}
enum PrFlow {
CurrentBranch { repo: PathBuf },
InPlace {
repo: PathBuf,
url: String,
pr_number: u32,
},
TempClone {
url: String,
slug: String,
pr_number: u32,
},
}
impl PrFlow {
fn user_repo(&self) -> Option<&Path> {
match self {
Self::CurrentBranch { repo } | Self::InPlace { repo, .. } => Some(repo),
Self::TempClone { .. } => None,
}
}
}
pub async fn run_pr(
args: PrArgs,
common: crate::CommonArgs,
context_files: Vec<PathBuf>,
preset_names: Vec<String>,
) -> Result<crate::Exit> {
let start = std::time::Instant::now();
let format = args.output_format();
match run_pr_inner(args, common, context_files, preset_names, start).await {
Ok(degraded) => Ok(crate::Exit::from_degraded(degraded)),
Err(e) => pr_failure_exit(
format,
e,
start.elapsed().as_millis() as u64,
&mut std::io::stdout().lock(),
),
}
}
fn pr_failure_exit(
format: crate::output::OutputFormat,
err: eyre::Report,
elapsed_ms: u64,
stdout: &mut impl std::io::Write,
) -> Result<crate::Exit> {
match format {
crate::output::OutputFormat::Text => Err(err),
crate::output::OutputFormat::Json => {
let env = crate::output::PrReviewOutput::error(format!("{err:#}"), elapsed_ms);
let _ = crate::output::write_json(stdout, &env);
Ok(crate::Exit::Failed)
}
}
}
async fn run_pr_inner(
args: PrArgs,
common: crate::CommonArgs,
context_files: Vec<PathBuf>,
preset_names: Vec<String>,
start: std::time::Instant,
) -> Result<bool> {
check_gh()?;
let prepared = prepare_pr(&args, &common.repo)?;
if let Some(number) = prepared.pr_number {
tracing::Span::current().record("nitpicker.pr.number", u64::from(number));
}
let mut config = load_pr_config(common.config.as_deref(), &prepared)?;
let presets = crate::presets::resolve(&preset_names, &config)?;
let (alloy, fallback) = crate::resolve_routing_modes(&config, args.alloy, common.fallback)?;
let execution = PrReviewExecution {
verbose: common.verbose,
alloy,
fallback,
};
crate::finalize_routing_config(&mut config, fallback).await?;
let config = config;
run_review_inner(
&prepared,
&args,
&context_files,
&presets,
&config,
execution,
start,
)
.await
}
#[derive(Clone, Copy)]
struct PrReviewExecution {
verbose: bool,
alloy: bool,
fallback: bool,
}
fn load_pr_config(explicit: Option<&Path>, prepared: &PreparedPr) -> Result<Config> {
if explicit.is_some() {
return crate::load_config(explicit, &prepared.repo);
}
let base_blob = match origin_is_github(&prepared.repo) {
true => read_base_branch_config(&prepared.repo, &prepared.meta.base_ref_name),
false => {
tracing::warn!(
"`origin` is not a github.com remote; ignoring its nitpicker.toml and using \
the global config"
);
None
}
};
let (repo_config, warning) = choose_repo_config(
base_blob,
head_config_state(&prepared.repo, &prepared.meta.base_ref_name),
);
if let Some(warning) = warning {
tracing::warn!("{warning}");
}
match repo_config {
Some(content) => {
let config: Config = toml::from_str(&content)
.map_err(|e| eyre::eyre!("invalid nitpicker.toml on the PR base branch: {e}"))?;
config.validate_structure()?;
Ok(config)
}
None => crate::load_global_config(),
}
}
fn origin_is_github(repo: &Path) -> bool {
let out = Command::new("git")
.args(["remote", "get-url", "origin"])
.current_dir(repo)
.output();
let url = match out {
Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_string(),
_ => return false,
};
is_trusted_github_remote(&url)
}
fn is_trusted_github_remote(url: &str) -> bool {
let url = url.trim();
if url.contains("::") {
return false;
}
let host = match url.contains("://") {
true => match url::Url::parse(url) {
Ok(parsed) => match parsed.scheme() {
"https" | "ssh" => parsed.host_str().map(str::to_string),
_ => None,
},
Err(_) => None,
},
false => remote_host(url),
};
host.is_some_and(|host| host.eq_ignore_ascii_case("github.com"))
}
fn remote_host(url: &str) -> Option<String> {
let url = url.trim();
match url.contains("://") {
true => url::Url::parse(url)
.ok()
.and_then(|parsed| parsed.host_str().map(str::to_string)),
false => {
let colon = url.find(':')?;
if url[..colon].contains('/') {
return None;
}
let host = url[..colon].rsplit('@').next()?;
match host.is_empty() {
true => None,
false => Some(host.to_string()),
}
}
}
}
fn read_base_branch_config(repo: &Path, base_ref: &str) -> Option<String> {
if base_ref.is_empty() {
return None;
}
let out = Command::new("git")
.args(["show", &format!("origin/{base_ref}:nitpicker.toml")])
.current_dir(repo)
.output()
.ok()?;
match out.status.success() {
true => String::from_utf8(out.stdout).ok(),
false => {
match git_object_id(repo, &format!("origin/{base_ref}")) {
Some(_) => tracing::debug!(
base = base_ref,
"no nitpicker.toml on the PR base branch; using the global config"
),
None => tracing::warn!(
base = base_ref,
"cannot resolve `origin/{base_ref}`, so the base branch's nitpicker.toml \
could not be read; using the global config"
),
}
None
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum HeadConfig {
Absent,
SameAsBase,
Diverges,
}
fn head_config_state(repo: &Path, base_ref: &str) -> HeadConfig {
let head = git_object_id(repo, "HEAD:nitpicker.toml");
let base = git_object_id(repo, &format!("origin/{base_ref}:nitpicker.toml"));
match (head, base) {
(None, _) => HeadConfig::Absent,
(Some(head), Some(base)) if head == base => HeadConfig::SameAsBase,
(Some(_), _) => HeadConfig::Diverges,
}
}
fn git_object_id(repo: &Path, revspec: &str) -> Option<String> {
let out = Command::new("git")
.args(["rev-parse", "--verify", "--quiet", revspec])
.current_dir(repo)
.output()
.ok()?;
match out.status.success() {
true => Some(String::from_utf8_lossy(&out.stdout).trim().to_string()),
false => None,
}
}
fn choose_repo_config(
base_blob: Option<String>,
head: HeadConfig,
) -> (Option<String>, Option<&'static str>) {
match (base_blob, head) {
(Some(blob), HeadConfig::Diverges) => (
Some(blob),
Some(
"checked-out nitpicker.toml differs from the PR base branch; using the base \
version — files on a PR head are target-controlled",
),
),
(Some(blob), _) => (Some(blob), None),
(None, HeadConfig::Absent) => (None, None),
(None, _) => (
None,
Some(
"ignoring nitpicker.toml from the checked-out PR head (absent on the PR base \
branch); using the global config",
),
),
}
}
struct PreparedPr {
repo: PathBuf,
url_for_gh: Option<String>,
pr_number: Option<u32>,
meta: PrMeta,
comments: Vec<PrComment>,
_restore_guard: Option<BranchRestoreGuard>,
_tmpdir_guard: Option<tempfile::TempDir>,
_lock: Option<PrLock>,
}
fn prepare_pr(args: &PrArgs, repo_arg: &Path) -> Result<PreparedPr> {
let repo_arg = repo_arg
.canonicalize()
.wrap_err("failed to canonicalize --repo path")?;
let user_repo = crate::git_worktree_root(&repo_arg);
let flow = match args.url.as_deref() {
None => PrFlow::CurrentBranch {
repo: user_repo
.ok_or_else(|| eyre::eyre!("--repo must point inside a Git worktree"))?,
},
Some(u) => {
let (slug, pr_number) = parse_pr_url(u)?;
match user_repo.filter(|repo| {
!args.clone && get_origin_slug(repo).as_deref() == Some(slug.as_str())
}) {
Some(repo) => PrFlow::InPlace {
repo,
url: u.to_string(),
pr_number,
},
None => PrFlow::TempClone {
url: u.to_string(),
slug,
pr_number,
},
}
}
};
let _lock = flow.user_repo().map(PrLock::acquire).transpose()?;
let _tmpdir_guard: Option<tempfile::TempDir>;
let _restore_guard: Option<BranchRestoreGuard>;
let (repo, url_for_gh, meta, pr_number): (PathBuf, Option<String>, PrMeta, Option<u32>) =
match flow {
PrFlow::InPlace {
repo: user_repo,
url,
pr_number,
} => {
let meta = fetch_pr_meta(Some(&url), &user_repo)?;
refresh_remote_branches(&user_repo)?;
let head_matches = get_head_commit(&user_repo)
.ok()
.is_some_and(|sha| sha == meta.head_ref_oid);
let head = get_head_state(&user_repo)?;
let can_skip = head_matches && matches!(head, HeadState::Branch(_));
match can_skip {
true => {
assert_clean_working_tree(&user_repo)?;
_restore_guard = None;
}
false => {
checkout_pr_branch(&user_repo, pr_number).inspect_err(|_e| {
restore_head(&user_repo, &head);
})?;
_restore_guard = Some(BranchRestoreGuard {
repo: user_repo.clone(),
head,
});
}
}
_tmpdir_guard = None;
(user_repo, Some(url), meta, Some(pr_number))
}
PrFlow::TempClone {
url,
slug,
pr_number,
} => {
let cwd = std::env::current_dir().wrap_err("failed to get current directory")?;
let meta = fetch_pr_meta(Some(&url), &cwd)?;
let tmpdir = tempfile::TempDir::new().wrap_err("failed to create temp dir")?;
let path = create_temp_clone_repo_dir(tmpdir.path(), &slug)?;
clone_pr(&slug, pr_number, &path)?;
_tmpdir_guard = Some(tmpdir);
_restore_guard = None;
(path, Some(url), meta, Some(pr_number))
}
PrFlow::CurrentBranch { repo: user_repo } => {
let meta = fetch_pr_meta(None, &user_repo)?;
refresh_remote_branches(&user_repo)?;
_tmpdir_guard = None;
_restore_guard = None;
(user_repo, None, meta, None)
}
};
let comments = fetch_pr_comments(url_for_gh.as_deref(), &repo)?;
Ok(PreparedPr {
repo,
url_for_gh,
pr_number,
meta,
comments,
_restore_guard,
_tmpdir_guard,
_lock,
})
}
async fn run_review_inner(
prepared: &PreparedPr,
args: &PrArgs,
context_files: &[PathBuf],
presets: &[crate::presets::ReviewPreset],
config: &Config,
execution: PrReviewExecution,
start: std::time::Instant,
) -> Result<bool> {
use crate::output::{OutputFormat, PrInfo, PrReviewOutput, ReviewMode, Status};
let repo = prepared.repo.as_path();
let url_for_gh = prepared.url_for_gh.as_deref();
let pr_number = prepared.pr_number;
let meta = &prepared.meta;
let comments: &[PrComment] = &prepared.comments;
let PrReviewExecution {
verbose,
alloy: use_alloy,
fallback: use_fallback,
} = execution;
const FOOTER: &str =
"\n\n---\n🔍 Reviewed by [nitpicker](https://github.com/arsenyinfo/nitpicker)";
let format = args.output_format();
let diff_context = crate::detect_diff_context(repo)?;
let full_prompt = crate::context::append_to_prompt(
build_pr_prompt(meta, comments, &diff_context, args.prompt.as_deref()),
&crate::context::load_context_files(context_files)?,
);
let max_turns = config.max_turns(args.max_turns)?;
if use_alloy && args.no_debate {
eprintln!("warning: --alloy has no effect with --no-debate");
}
let debate = !args.no_debate && config.default_debate();
let (report, transcript_path, usage, degraded, coverage) = if debate {
let outcome = debate::run_debate(
repo,
&full_prompt,
config,
debate::DebateOptions {
max_rounds: args.rounds,
max_turns,
verbose,
task: RunTask::Review {
scope: ReviewScope::Diff,
presets,
},
alloy: use_alloy,
fallback: use_fallback,
format,
},
)
.await?;
(
outcome.report,
outcome.transcript_path,
outcome.usage,
outcome.degraded,
outcome.coverage,
)
} else {
let outcome = review::run_review(
repo,
&full_prompt,
config,
review::ReviewOptions {
max_turns,
verbose,
task: RunTask::Review {
scope: ReviewScope::Diff,
presets,
},
fallback: use_fallback,
format,
},
)
.await?;
(
outcome.report,
std::path::PathBuf::new(),
outcome.usage,
outcome.degraded,
outcome.coverage,
)
};
match format {
OutputFormat::Text => {
println!("{report}");
if !args.no_comment {
post_comment(url_for_gh, repo, &format!("{report}{FOOTER}"))?;
}
if verbose && !transcript_path.as_os_str().is_empty() {
eprintln!("\nTranscript saved to: {}", transcript_path.display());
}
}
OutputFormat::Json => {
let comment_posted = match args.no_comment {
true => false,
false => match post_comment(url_for_gh, repo, &format!("{report}{FOOTER}")) {
Ok(()) => true,
Err(e) => {
tracing::warn!("failed to post PR comment: {e:#}");
false
}
},
};
let envelope = PrReviewOutput {
schema_version: crate::output::SCHEMA_VERSION,
status: Status::Ok,
pr: Some(PrInfo {
url: url_for_gh.map(str::to_string),
number: pr_number,
title: meta.title.clone(),
head_sha: get_head_commit(repo).unwrap_or_else(|_| meta.head_ref_oid.clone()),
}),
mode: Some(match debate {
true => ReviewMode::Debate,
false => ReviewMode::Parallel,
}),
models: Some(crate::output::Models {
reviewers: config.reviewer.iter().map(|r| r.model.clone()).collect(),
aggregator: config.aggregator.model.clone(),
}),
presets: Some(presets.iter().map(|p| p.name.clone()).collect()),
degraded: Some(degraded),
coverage,
report_markdown: Some(report),
usage: Some(usage),
comment_posted,
duration_ms: start.elapsed().as_millis() as u64,
error: None,
};
crate::output::emit_json(&envelope)?;
}
}
Ok(degraded)
}
#[cfg(test)]
mod tests {
use super::{
BranchRestoreGuard, HeadConfig, HeadState, PrComment, choose_repo_config,
create_temp_clone_repo_dir, get_head_state, head_config_state, is_trusted_github_remote,
lock_path, pr_failure_exit, read_base_branch_config, remote_host,
};
use std::path::Path;
use std::process::Command;
#[test]
fn repo_config_source_prefers_base_blob_and_never_the_head() {
let s = |v: &str| Some(v.to_string());
let (cfg, warn) = choose_repo_config(s("base"), HeadConfig::SameAsBase);
assert_eq!(cfg.as_deref(), Some("base"));
assert!(warn.is_none());
let (cfg, warn) = choose_repo_config(s("base"), HeadConfig::Diverges);
assert_eq!(cfg.as_deref(), Some("base"));
assert!(warn.is_some());
let (cfg, warn) = choose_repo_config(s("base"), HeadConfig::Absent);
assert_eq!(cfg.as_deref(), Some("base"));
assert!(warn.is_none());
let (cfg, warn) = choose_repo_config(None, HeadConfig::Diverges);
assert!(cfg.is_none());
assert!(warn.is_some());
let (cfg, warn) = choose_repo_config(None, HeadConfig::Absent);
assert!(cfg.is_none());
assert!(warn.is_none());
}
#[test]
fn remote_host_is_extracted_from_both_url_forms() {
for (url, expected) in [
("https://github.com/owner/repo.git", Some("github.com")),
("git@github.com:owner/repo.git", Some("github.com")),
("ssh://git@github.com/owner/repo", Some("github.com")),
(
"https://attacker.example/owner/repo.git",
Some("attacker.example"),
),
(
"git@attacker.example:owner/repo.git",
Some("attacker.example"),
),
("/local/path/repo", None),
(
"file://github.com/victim/repo/../../../tmp/attacker",
Some("github.com"),
),
] {
assert_eq!(remote_host(url).as_deref(), expected, "url: {url}");
}
}
#[test]
fn only_authenticated_github_transports_are_trusted() {
for url in [
"https://github.com/owner/repo.git",
"ssh://git@github.com/owner/repo",
"git@github.com:owner/repo.git",
] {
assert!(is_trusted_github_remote(url), "must trust: {url}");
}
for url in [
"file://github.com/victim/repo/../../../tmp/attacker-repo",
"git://github.com/owner/repo",
"http://github.com/owner/repo",
"https://attacker.example/owner/repo.git",
"git@attacker.example:owner/repo.git",
"github.com::attacker-address",
"github.com::https://attacker.example/owner/repo",
"/local/path/repo",
"",
] {
assert!(!is_trusted_github_remote(url), "must reject: {url}");
}
}
#[test]
fn base_config_reads_the_ref_blob() {
let (_dir, repo) = repo_with_base_config();
assert_eq!(
read_base_branch_config(&repo, "main").as_deref(),
Some("from-base")
);
assert!(read_base_branch_config(&repo, "no-such-branch").is_none());
assert!(read_base_branch_config(&repo, "").is_none());
assert_eq!(head_config_state(&repo, "main"), HeadConfig::SameAsBase);
}
#[cfg(unix)]
#[test]
fn head_config_state_never_reads_a_worktree_symlink() {
let (_dir, repo) = repo_with_base_config();
std::fs::remove_file(repo.join("nitpicker.toml")).unwrap();
std::os::unix::fs::symlink("/dev/zero", repo.join("nitpicker.toml")).unwrap();
git(&repo, &["add", "nitpicker.toml"]);
commit(&repo, "hostile config");
assert_eq!(head_config_state(&repo, "main"), HeadConfig::Diverges);
assert_eq!(
read_base_branch_config(&repo, "main").as_deref(),
Some("from-base")
);
}
fn repo_with_base_config() -> (tempfile::TempDir, std::path::PathBuf) {
let dir = tempfile::tempdir().unwrap();
let repo = dir.path().canonicalize().unwrap();
init_repo(&repo);
std::fs::write(repo.join("nitpicker.toml"), "from-base").unwrap();
git(&repo, &["add", "nitpicker.toml"]);
commit(&repo, "config");
git(&repo, &["update-ref", "refs/remotes/origin/main", "HEAD"]);
(dir, repo)
}
fn commit(repo: &Path, msg: &str) {
git(
repo,
&[
"-c",
"user.email=t@test",
"-c",
"user.name=t",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
msg,
],
);
}
#[test]
fn pr_comments_tolerate_null_author() {
let comments: Vec<PrComment> = serde_json::from_str(
r#"[{"author":null,"body":"hi"},{"author":{"login":"octocat"},"body":"yo"}]"#,
)
.expect("null author must deserialize");
assert!(comments[0].author.is_none());
assert_eq!(comments[1].author.as_ref().unwrap().login, "octocat");
}
#[test]
fn temp_clone_workdir_uses_the_repository_name() {
let temp = tempfile::tempdir().unwrap();
let path = create_temp_clone_repo_dir(temp.path(), "owner/reviewer").unwrap();
assert_eq!(
path.file_name().and_then(|name| name.to_str()),
Some("reviewer")
);
assert!(path.is_dir());
}
#[test]
fn temp_clone_workdir_rejects_unsafe_repository_names() {
let temp = tempfile::tempdir().unwrap();
for slug in ["", "owner/..", "owner/repo\\nested"] {
assert!(
create_temp_clone_repo_dir(temp.path(), slug).is_err(),
"must reject {slug:?}"
);
}
}
fn git(repo: &Path, args: &[&str]) {
let out = Command::new("git")
.args(args)
.current_dir(repo)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&out.stderr)
);
}
fn init_repo(repo: &Path) {
git(repo, &["init", "-b", "main"]);
git(
repo,
&[
"-c",
"user.email=t@test",
"-c",
"user.name=t",
"-c",
"commit.gpgsign=false",
"commit",
"--allow-empty",
"-m",
"one",
],
);
}
#[test]
fn linked_worktrees_share_one_pr_lock() {
let dir = tempfile::tempdir().unwrap();
let primary = dir.path().join("primary");
std::fs::create_dir(&primary).unwrap();
init_repo(&primary);
let linked = dir.path().join("linked");
git(
&primary,
&["worktree", "add", "-b", "feature", linked.to_str().unwrap()],
);
assert_eq!(lock_path(&primary), lock_path(&linked));
}
#[test]
fn branch_restore_guard_switches_back_to_the_original_branch() {
let dir = tempfile::tempdir().unwrap();
let repo = dir.path().canonicalize().unwrap();
init_repo(&repo);
let head = get_head_state(&repo).unwrap();
assert!(matches!(&head, HeadState::Branch(b) if b == "main"));
git(&repo, &["switch", "-c", "nitpicker/pr-1"]);
drop(BranchRestoreGuard {
repo: repo.clone(),
head,
});
match get_head_state(&repo).unwrap() {
HeadState::Branch(b) => assert_eq!(b, "main"),
HeadState::Detached(_) => panic!("expected to be back on the main branch"),
}
}
#[test]
fn dropping_the_guard_re_detaches_onto_the_original_commit() {
let dir = tempfile::tempdir().unwrap();
let repo = dir.path().canonicalize().unwrap();
init_repo(&repo);
git(&repo, &["switch", "--detach", "HEAD"]);
let head = get_head_state(&repo).unwrap();
let original_sha = match &head {
HeadState::Detached(sha) => sha.clone(),
HeadState::Branch(_) => panic!("expected a detached HEAD"),
};
git(&repo, &["switch", "main"]);
drop(BranchRestoreGuard {
repo: repo.clone(),
head,
});
match get_head_state(&repo).unwrap() {
HeadState::Detached(sha) => assert_eq!(sha, original_sha),
HeadState::Branch(_) => panic!("expected HEAD re-detached onto the original commit"),
}
}
#[test]
fn json_failures_become_one_error_envelope_and_a_silent_failed_exit() {
let mut out = Vec::new();
let exit = pr_failure_exit(
crate::output::OutputFormat::Json,
eyre::eyre!("gh missing"),
7,
&mut out,
)
.unwrap();
assert_eq!(exit, crate::Exit::Failed);
let text = String::from_utf8(out).unwrap();
assert!(text.ends_with('\n'));
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 1, "exactly one envelope: {text:?}");
let envelope: serde_json::Value = serde_json::from_str(lines[0]).unwrap();
assert_eq!(envelope["status"], "error");
assert_eq!(envelope["error"], "gh missing");
assert_eq!(envelope["duration_ms"], 7);
}
#[test]
fn text_failures_are_handed_back_for_eyre_to_render() {
let mut out = Vec::new();
let err = pr_failure_exit(
crate::output::OutputFormat::Text,
eyre::eyre!("gh missing"),
7,
&mut out,
)
.unwrap_err();
assert_eq!(err.to_string(), "gh missing");
assert!(out.is_empty(), "text mode writes nothing to stdout");
}
}