Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ Native knowledge, plan, fix and configuration commands send the selected organiz

`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 findings --review ID --head SHA` reads the named review directly and verifies its head before printing findings. This works outside a checkout, including with `--wait`, `--json` or `--sarif`. A different or missing head in the result exits 1 with empty stdout. A search with `findings --head SHA`, or plain `findings` at the checkout's HEAD, also verifies the detail returned for the selected review.

`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.

`proofline review --range BASE..HEAD --fail-on serious` exits 3 when a complete review has an unresolved finding at or above the threshold. PR reviews use the server’s effective open-item counts; other reviews count unresolved findings. Incomplete and unavailable results retain their nonzero exits. `--fail-on` cannot be combined with `--no-wait`.
Expand Down
7 changes: 4 additions & 3 deletions src/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,9 +495,10 @@ async fn request(
verify_finding_ids: Vec::new(),
};
let requested = api.request_patch_review(repository_id, &request).await?;
let (_, detail, state) = read_review(api, requested.review_id, Some(deadline), false)
.await?
.context("Proofline did not answer a read of the review before the deadline")?;
let (_, detail, state) =
read_review(api, requested.review_id.into(), Some(deadline), false)
.await?
.context("Proofline did not answer a read of the review before the deadline")?;
anyhow::Ok((requested.review_id, detail, state))
};
match requested.await {
Expand Down
174 changes: 108 additions & 66 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,14 +369,13 @@ struct ReviewArgs {
}

#[derive(Debug, Args)]
#[group(multiple = false)]
struct Selector {
/// Latest review of this pull request.
#[arg(long, value_name = "NUMBER")]
#[arg(long, value_name = "NUMBER", conflicts_with_all = ["head", "review"])]
pr: Option<u64>,
/// Latest review whose head is exactly this pushed commit. Defaults to
/// the checkout's HEAD.
#[arg(long, value_name = "SHA")]
/// Find the latest review at this commit, or verify the head of --review ID.
/// With no selector, use the checkout's HEAD.
#[arg(long, value_name = "SHA", value_parser = git::commit_sha)]
head: Option<String>,
/// This review.
#[arg(long, value_name = "ID")]
Expand All @@ -391,7 +390,7 @@ struct FindingsArgs {
#[arg(long)]
wait: bool,
/// Export this retained pull-request review as SARIF 2.1.0.
#[arg(long, requires = "review", conflicts_with_all = ["json", "pr", "head"])]
#[arg(long, requires = "review", conflicts_with = "json")]
sarif: bool,
#[command(flatten)]
repository: RepositoryArgs,
Expand Down Expand Up @@ -601,9 +600,6 @@ pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdic
tools::export(&api, &args).await
}
Command::Findings(args) => {
if let Some(head) = &args.selector.head {
git::commit_sha(head)?;
}
let api = connect(Http::new(origin)?, token, cli.org).await?;
findings(&api, &args).await
}
Expand Down Expand Up @@ -1197,7 +1193,7 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result
}
show(
api,
review_id,
review_id.into(),
true,
&args.output,
OutputFormat::from_json(args.output.json),
Expand All @@ -1207,30 +1203,46 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result
}

async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result<Verdict> {
let review_id = match (&args.selector.review, args.selector.pr) {
(Some(id), _) => *id,
(None, Some(number)) => pull_request_review(api, &args.repository, number).await?,
let (review_id, expected_head) = match (args.selector.review, args.selector.pr) {
(Some(id), _) => (id, args.selector.head.clone()),
(None, Some(number)) => (
pull_request_review(api, &args.repository, number).await?,
None,
),
(None, None) => {
let sha = match &args.selector.head {
Some(raw) => git::commit_sha(raw)?,
Some(head) => head.clone(),
None => git::head().await?,
};
let (name, repository_id) = reviewed_repository(api, &args.repository).await?;
// An audit is a revision scan of this commit too, but its
// findings are in its report, so it never answers for the head.
latest(api, repository_id, &sha, |item| {
item.audit_mode.is_none() && item.head_commit_sha.as_deref() == Some(sha.as_str())
let id = latest(api, repository_id, &sha, |item| {
item.audit_mode.is_none()
&& head_matches(item.head_commit_sha.as_deref(), &sha)
})
.await?
.with_context(|| format!("no review of {name} has head commit {sha}; push it and open a pull request, or name one with --pr"))?
.with_context(|| format!("no review of {name} has head commit {sha}; push it and open a pull request, or name one with --pr"))?;
(id, Some(sha))
}
};
let format = if args.sarif {
OutputFormat::Sarif
} else {
OutputFormat::from_json(args.output.json)
};
show(api, review_id, args.wait, &args.output, format, None).await
show(
api,
ReviewTarget {
id: review_id,
head: expected_head.as_deref(),
},
args.wait,
&args.output,
format,
None,
)
.await
}

#[derive(Debug, thiserror::Error)]
Expand All @@ -1251,6 +1263,36 @@ fn poll_deadline(minutes: u64) -> Result<tokio::time::Instant, PollTimeoutTooLar
/// A review read: the server's answer, its parsed detail and its outcome.
type ReviewRead = (serde_json::Value, ReviewDetail, Option<Outcome>);

/// The review a caller expects to read. A held commit must be confirmed
/// before its findings can be returned.
#[derive(Clone, Copy)]
struct ReviewTarget<'a> {
id: Uuid,
head: Option<&'a str>,
}

impl From<Uuid> for ReviewTarget<'_> {
fn from(id: Uuid) -> Self {
Self { id, head: None }
}
}

impl ReviewTarget<'_> {
fn validate(self, detail: &ReviewDetail, sarif: bool, polling: bool) -> anyhow::Result<()> {
outcome::same_review(detail, self.id)?;
// Only an intermediate text or JSON read may wait for a missing head.
if let Some(head) = self.head
&& (!polling || sarif || detail.head_commit_sha.is_some())
{
confirm_head(detail, head)?;
}
if sarif {
sarif::validate_subject(detail, self.id)?;
}
Ok(())
}
}

/// Reads the review, polling until it finishes or `deadline` passes. Without
/// a deadline, or with one already passed (`--timeout 0`), it reads once.
/// Otherwise no read starts at or after the deadline, and a read still
Expand All @@ -1261,46 +1303,40 @@ type ReviewRead = (serde_json::Value, ReviewDetail, Option<Outcome>);
/// a result for a different review decide this one's outcome.
async fn read_review(
api: &Api,
review_id: Uuid,
target: ReviewTarget<'_>,
deadline: Option<tokio::time::Instant>,
sarif: bool,
) -> anyhow::Result<Option<ReviewRead>> {
let deadline = match deadline {
Some(deadline) if tokio::time::Instant::now() < deadline => deadline,
_ => return read_review_once(api, review_id, sarif).await.map(Some),
};
let deadline = deadline.filter(|end| tokio::time::Instant::now() < *end);
let mut delay = FIRST_POLL_SECONDS;
loop {
let Ok(read) =
tokio::time::timeout_at(deadline, read_review_once(api, review_id, sarif)).await
else {
return Ok(None);
let last = loop {
let request = api.review(target.id);
let (raw, detail) = if let Some(end) = deadline {
let Ok(response) = tokio::time::timeout_at(end, request).await else {
return Ok(None);
};
response?
} else {
request.await?
};
let read = read?;
let state = outcome::terminal(&detail);
let now = tokio::time::Instant::now();
if read.2.is_some() || now >= deadline {
return Ok(Some(read));
}
let Some(end) = deadline.filter(|end| state.is_none() && now < *end) else {
break (raw, detail, state);
};
target.validate(&detail, sarif, true)?;
say(&format!(
"Review is {}; checking again in {delay} seconds.",
text::one_line(&read.1.status)
text::one_line(&detail.status)
));
tokio::time::sleep_until(deadline.min(now + Duration::from_secs(delay))).await;
if tokio::time::Instant::now() >= deadline {
return Ok(Some(read));
tokio::time::sleep_until(end.min(now + Duration::from_secs(delay))).await;
if tokio::time::Instant::now() >= end {
break (raw, detail, state);
}
delay = (delay * 2).min(LONGEST_POLL_SECONDS);
}
}

async fn read_review_once(api: &Api, review_id: Uuid, sarif: bool) -> anyhow::Result<ReviewRead> {
let (raw, detail) = api.review(review_id).await?;
outcome::same_review(&detail, review_id)?;
if sarif {
sarif::validate_subject(&detail, review_id)?;
}
let state = outcome::terminal(&detail);
Ok((raw, detail, state))
};
target.validate(&last.1, sarif, false)?;
Ok(Some(last))
}

/// Said when no read of the review answered before the deadline.
Expand All @@ -1314,7 +1350,7 @@ fn say_not_established(api: &Api, review_id: Uuid, timeout_minutes: u64) {
/// Prints the review, after waiting for it to finish when `wait` is set.
async fn show(
api: &Api,
review_id: Uuid,
target: ReviewTarget<'_>,
wait: bool,
output: &OutputArgs,
format: OutputFormat,
Expand All @@ -1326,16 +1362,16 @@ async fn show(
None
};
let sarif = matches!(format, OutputFormat::Sarif);
let Some((raw, detail, state)) = read_review(api, review_id, deadline, sarif).await? else {
say_not_established(api, review_id, output.timeout);
let Some((raw, detail, state)) = read_review(api, target, deadline, sarif).await? else {
say_not_established(api, target.id, output.timeout);
return Ok(Verdict::Unavailable);
};
// `audit_mode` marks an audit, as on a listed review (`ReviewSummary`).
if raw.get("audit_mode").is_some_and(|mode| !mode.is_null()) {
print_audit(api, raw, &detail, format)?;
return Ok(Verdict::NotComplete);
}
print_review(api, review_id, raw, &detail, state, format)?;
print_review(api, target.id, raw, &detail, state, format)?;
match state {
Some(Outcome::Completed) => {
let verdict = review_verdict(&detail, fail_on);
Expand All @@ -1355,7 +1391,7 @@ async fn show(
"The review was still {} after {} minutes; it continues at {}",
text::one_line(&detail.status),
output.timeout,
api.review_url(review_id)
api.review_url(target.id)
)),
None => say("The review has not finished; pass --wait to wait for its result."),
}
Expand Down Expand Up @@ -1435,6 +1471,24 @@ async fn ci_job(
/// it asks for one.
const REQUEST_AFTER: Duration = Duration::from_secs(120);

fn head_matches(reported: Option<&str>, expected: &str) -> bool {
reported.is_some_and(|head| head.eq_ignore_ascii_case(expected))
}

/// A matching review ID alone cannot establish which commit its findings describe.
fn confirm_head(detail: &ReviewDetail, commit: &str) -> anyhow::Result<()> {
if !head_matches(detail.head_commit_sha.as_deref(), commit) {
bail!(
"proofline asked for the review of {commit}, but the server returned head commit {}",
detail
.head_commit_sha
.as_deref()
.map_or_else(|| "none".to_owned(), text::one_line)
);
}
Ok(())
}

/// Confirms `detail` is actually the pull-request review of `commit` in
/// `repository_id` before it is allowed to decide a CI verdict or produce a
/// SARIF artifact. [`read_review`] already confirms `detail` is the review
Expand All @@ -1458,19 +1512,7 @@ fn confirm_ci_subject(
text::one_line(&detail.kind)
);
}
if !detail
.head_commit_sha
.as_deref()
.is_some_and(|head| head.eq_ignore_ascii_case(commit))
{
bail!(
"proofline asked for the review of {commit}, but the server returned head commit {}",
detail
.head_commit_sha
.as_deref()
.map_or_else(|| "none".to_owned(), text::one_line)
);
}
confirm_head(detail, commit)?;
if let Some(detail_repository) = detail.repository_id
&& detail_repository != repository_id
{
Expand Down Expand Up @@ -1511,7 +1553,7 @@ async fn ci_review(
};
let sarif_path = args.sarif.as_deref();
let Some((raw, detail, state)) =
read_review(api, review_id, Some(deadline), sarif_path.is_some()).await?
read_review(api, review_id.into(), Some(deadline), sarif_path.is_some()).await?
else {
say_not_established(api, review_id, args.timeout);
return Ok(Verdict::Unavailable);
Expand Down
2 changes: 1 addition & 1 deletion src/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ pub(crate) async fn run(
}
match show(
api,
review_id,
review_id.into(),
true,
&args.output,
OutputFormat::from_json(args.output.json),
Expand Down
2 changes: 1 addition & 1 deletion src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result<Verdict
}
show(
api,
id,
id.into(),
true,
&args.output,
OutputFormat::from_json(args.output.json),
Expand Down
Loading