Skip to content
Merged
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
409 changes: 404 additions & 5 deletions openapi.public.json

Large diffs are not rendered by default.

48 changes: 46 additions & 2 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ use url::Url;
use uuid::Uuid;

use crate::model::{
CommitReviewRequest, CommitReviewResponse, PatchReviewRequest, PatchReviewResponse,
RepositoryNames, ReviewDetail, ReviewPage, RunNowMode, RunNowRequest, RunNowResponse,
CommitReviewRequest, CommitReviewResponse, FileReviewRequest, FileReviewResponse,
PatchReviewRequest, PatchReviewResponse, RepositoryNames, ReviewDetail, ReviewPage, RunNowMode,
RunNowRequest, RunNowResponse, StopResponse,
};
use crate::origin::Origin;
use crate::text::terminal_safe;
Expand Down Expand Up @@ -472,6 +473,24 @@ impl Api {
Err(self.http.problem(&reply))
}

/// Requests whole-file review of a selection at one pushed commit.
pub async fn request_file_review(
&self,
repository_id: Uuid,
request: &FileReviewRequest,
) -> Result<FileReviewResponse, ApiError> {
let repository = repository_id.to_string();
let url = self.url(&["repositories", &repository, "file-reviews"]);
let (reply, _) = self
.http
.send(self.request(Method::POST, url).json(request))
.await?;
if reply.status.is_success() {
return self.decode(&reply.body);
}
Err(self.http.problem(&reply))
}

/// Requests a review of the change from one pushed commit to another. One
/// attempt; the server returns the existing review of the same commits.
pub async fn request_commit_review(
Expand All @@ -491,6 +510,31 @@ impl Api {
Err(self.http.problem(&reply))
}

/// Stops the holder's own local review in one bounded attempt. A refusal
/// starts no replacement review, and the client never repeats the POST.
pub async fn stop_review(
&self,
review_id: Uuid,
) -> Result<(serde_json::Value, StopResponse), ApiError> {
let id = review_id.to_string();
let (reply, _) = self
.http
.send(self.request(Method::POST, self.url(&["reviews", &id, "stop"])))
.await?;
if !reply.status.is_success() {
return Err(self.http.problem(&reply));
}
let raw: serde_json::Value = self.decode(&reply.body)?;
let stopped: StopResponse = serde_json::from_value(raw.clone())
.map_err(|error| self.http.protocol(error.to_string()))?;
if stopped.review_id != review_id || stopped.status != "STOPPED" {
return Err(self
.http
.protocol("the stop response does not confirm this review is STOPPED"));
}
Ok((raw, stopped))
}

/// The console page for a review, which resolves the organization and
/// review IDs to the current display names after sign-in.
pub fn review_url(&self, review_id: Uuid) -> Url {
Expand Down
55 changes: 55 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ pub enum GitError {
NoParent(String),
#[error("{0:?} is not a range; write it as BASE..HEAD")]
NotRange(String),
#[error("name between 1 and 20 exact repository-relative file paths")]
FileCount,
#[error("{0:?} is not a regular tracked file at commit {1}; no review was requested")]
NotTrackedFile(String, String),
}

/// Two exact commits of a pushed change: the head, and the base it is
Expand Down Expand Up @@ -66,6 +70,57 @@ async fn resolve(dir: &Path, revision: &str) -> Result<String, GitError> {
commit_sha(String::from_utf8_lossy(&output).trim())
}

/// Resolve a whole-file selection once, using only the named commit's tree.
/// Working-tree and index contents never contribute to this request.
pub async fn named_files(
dir: &Path,
revision: &str,
paths: &[String],
) -> Result<(String, Vec<String>), GitError> {
if paths.is_empty() || paths.len() > 20 {
return Err(GitError::FileCount);
}
let commit = resolve(dir, revision).await?;
let mut selected = paths.to_vec();
selected.sort();
selected.dedup();
for path in &selected {
if path.chars().count() > 1_000
|| path.contains('\0')
|| path.split('/').any(|part| matches!(part, "" | "." | ".."))
{
return Err(GitError::NotTrackedFile(path.clone(), commit.clone()));
}
let entries = git_in(
dir,
None,
&[
"--literal-pathspecs",
"ls-tree",
"-z",
"--full-tree",
&commit,
"--",
path,
],
)
.await?;
let found = entries.split(|byte| *byte == 0).any(|entry| {
let Some(separator) = entry.iter().position(|byte| *byte == b'\t') else {
return false;
};
let (metadata, remainder) = entry.split_at(separator);
let found = &remainder[1..];
found == path.as_bytes()
&& (metadata.starts_with(b"100644 blob ") || metadata.starts_with(b"100755 blob "))
});
if !found {
return Err(GitError::NotTrackedFile(path.clone(), commit.clone()));
}
}
Ok((commit, selected))
}

/// The change one commit makes: the commit against its first parent.
pub async fn pushed_commit(dir: &Path, revision: &str) -> Result<PushedChange, GitError> {
let head_commit_sha = resolve(dir, revision).await?;
Expand Down
60 changes: 57 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ use uuid::Uuid;
use crate::api::{Api, ApiError, Http};
use crate::credentials::{Credential, Source};
use crate::model::{
CodeAssessment, CommitReviewRequest, OpenItems, PatchReviewRequest, ReviewDetail, ReviewSummary,
CodeAssessment, CommitReviewRequest, FileReviewRequest, OpenItems, PatchReviewRequest,
ReviewDetail, ReviewSummary,
};
use crate::origin::{DEFAULT_ORIGIN, Origin};
use crate::outcome::Outcome;
Expand All @@ -42,15 +43,15 @@ use crate::severity::Severity;
const FIRST_POLL_SECONDS: u64 = 5;
const LONGEST_POLL_SECONDS: u64 = 60;
const SEARCH_PAGES: usize = 10;
/// What `findings` and `review` need. The approval page shows each one
/// What `findings`, `review` and `stop` need. The approval page shows each one
/// and can narrow them.
const DEFAULT_SCOPES: [&str; 3] = ["reviews:read", "findings:read", "reviews:request"];

#[derive(Debug, Parser)]
#[command(
name = "proofline",
version,
about = "Read and request Proofline reviews from a terminal"
about = "Read, request and stop Proofline reviews from a terminal"
)]
pub struct Cli {
/// Proofline console origin.
Expand Down Expand Up @@ -84,6 +85,8 @@ enum Command {
/// Review the checkout's local changes, pushed commits, or an open pull
/// request's current head.
Review(ReviewArgs),
/// Stop your own pending or running local patch, pushed-commit or named-file review.
Stop(StopArgs),
/// Show the findings of the latest review of a commit or pull request.
Findings(FindingsArgs),
/// Forward a coding agent's stdio messages to this console's MCP server.
Expand Down Expand Up @@ -165,6 +168,15 @@ struct OutputArgs {
timeout: u64,
}

#[derive(Debug, Args)]
struct StopArgs {
/// The review ID returned by `review --no-wait`.
review_id: Uuid,
/// Print the server's stop acknowledgment as JSON.
#[arg(long)]
json: bool,
}

#[derive(Debug, Args)]
struct LocalSelectionArgs {
/// Review the original index against the base, excluding unstaged changes.
Expand All @@ -188,12 +200,17 @@ struct ReviewArgs {
local_selection: LocalSelectionArgs,
/// 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.
#[arg(
long,
value_name = "REVISION",
conflicts_with_all = ["pr", "range", "staged", "include_untracked", "allow_path"]
)]
commit: Option<String>,
/// Review the complete contents of up to twenty tracked files at --commit.
#[arg(long, value_name = "PATH", num_args = 1..=20, requires = "commit",
conflicts_with_all = ["pr", "range", "staged", "include_untracked", "allow_path"])]
files: Vec<String>,
/// Review the change from BASE to HEAD, both pushed, BASE an ancestor of
/// HEAD. The names are resolved once in the checkout.
#[arg(
Expand Down Expand Up @@ -320,6 +337,17 @@ pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdic
let api = connect(Http::new(origin)?, token, cli.org).await?;
review(&api, &args).await
}
Command::Stop(args) => {
let api = connect(Http::new(origin)?, token, cli.org).await?;
let (raw, stopped) = api.stop_review(args.review_id).await?;
let mut stdout = std::io::stdout().lock();
if args.json {
writeln!(stdout, "{}", serde_json::to_string(&raw)?)?;
} else {
writeln!(stdout, "Stopped review {}.", stopped.review_id)?;
}
Ok(Verdict::Done)
}
Command::Findings(args) => {
if let Some(head) = &args.selector.head {
git::commit_sha(head)?;
Expand Down Expand Up @@ -568,6 +596,9 @@ async fn latest(

async fn review(api: &Api, args: &ReviewArgs) -> anyhow::Result<Verdict> {
let Some(number) = args.pr else {
if !args.files.is_empty() {
return review_files(api, args).await;
}
if args.commit.is_some() || args.range.is_some() {
return review_pushed(api, args).await;
}
Expand Down Expand Up @@ -651,6 +682,29 @@ async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result<Verdict> {
finish(api, requested.review_id, args).await
}

async fn review_files(api: &Api, args: &ReviewArgs) -> anyhow::Result<Verdict> {
let revision = args
.commit
.as_deref()
.context("--files requires --commit")?;
let (commit_sha, paths) =
git::named_files(std::path::Path::new("."), revision, &args.files).await?;
let (name, repository_id) = connected_repository(api, &args.repository).await?;
let request = FileReviewRequest { commit_sha, paths };
let requested = api.request_file_review(repository_id, &request).await?;
say(&format!(
"{} whole-file review of {} selected files in {name} at {}.",
if requested.existing {
"Found the existing"
} else {
"Requested a"
},
request.paths.len(),
request.commit_sha
));
finish(api, requested.review_id, args).await
}

/// Reviews pushed commits: one commit against its parent, or a range. The
/// names are resolved to exact commits once, here; nothing leaves the
/// machine but the two SHAs, because GitHub already has the code.
Expand Down
36 changes: 36 additions & 0 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,22 @@ pub struct ReviewDetail {
pub pull_request_number: Option<i64>,
pub repository_full_name: Option<String>,
pub run_number: Option<i64>,
#[serde(default)]
pub subjects: Vec<ReviewSubject>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct ReviewSubject {
pub kind: String,
pub role: String,
pub file_scope: Option<FileScope>,
}

/// Selection identity at one commit, not a digest of file contents.
#[derive(Debug, Deserialize, Serialize)]
pub struct FileScope {
pub paths: Vec<String>,
pub paths_digest: String,
}

/// A malformed or newer CODE record cannot establish completeness. Keep it
Expand Down Expand Up @@ -194,6 +210,12 @@ pub struct RunNowResponse {
pub automatic_reviews_paused: bool,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct StopResponse {
pub review_id: Uuid,
pub status: String,
}

/// Whether the server may reuse a settled review of the live pull-request head.
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
Expand Down Expand Up @@ -241,6 +263,20 @@ pub struct PatchReviewResponse {
pub patch_digest: String,
}

/// Complete selected files at one exact pushed commit.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct FileReviewRequest {
pub commit_sha: String,
pub paths: Vec<String>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct FileReviewResponse {
pub review_id: Uuid,
pub existing: bool,
}

/// Pushed commits to review: two exact commits GitHub has, the base an
/// ancestor of the head.
#[derive(Debug, Deserialize, Serialize)]
Expand Down
1 change: 1 addition & 0 deletions src/outcome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ mod tests {
assessment_count: count,
assessments,
code_assessment: None,
subjects: Vec::new(),
base_commit_sha: None,
head_commit_sha: None,
open_items: None,
Expand Down
18 changes: 18 additions & 0 deletions src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,23 @@ pub fn review(review: &ReviewDetail, state: Option<Outcome>, url: &Url) -> Strin
);
out.push(format!("{subject}{run}{head}: {status}"));
out.push(url.to_string());
if review.kind == "FILES"
&& let Some(scope) = review
.subjects
.iter()
.find(|subject| subject.role == "PRIMARY" && subject.kind == "GIT_REVISION")
.and_then(|subject| subject.file_scope.as_ref())
{
out.push(format!(
"Selected files: {}",
scope
.paths
.iter()
.map(|path| one_line(path))
.collect::<Vec<_>>()
.join(", ")
));
}
if let Some(code) = outcome::code_assessment(review) {
out.push(String::new());
code_assessment(&mut out, code);
Expand Down Expand Up @@ -160,6 +177,7 @@ mod tests {
status: "COMPLETED".to_owned(),
assessment_count: 1,
code_assessment: None,
subjects: Vec::new(),
assessments: vec![Assessment {
id: uuid::Uuid::nil(),
environment_display_name: "production".to_owned(),
Expand Down
Loading
Loading