diff --git a/README.md b/README.md index c56770c..2b928ca 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ This repository is the published distribution of the Proofline CLI. `openapi.pub On Linux and macOS, install the CLI with `curl -fsSL https://proofline.sh/cli | sh`, then run `proofline login`. Run `proofline setup` to open the browser organization selector. Pass `--organization NAME` to open that GitHub organization's installation page, or `--print` to only print its address. Cloud trust and connection changes still require a signed-in administrator browser. +`proofline status` reports the active origin, organization ID, token source, and server verification status. Pass `--json` to output structured status metadata for automation and scripts. + `proofline completions SHELL` prints a completion script for `zsh`, `bash`, `fish`, `powershell`, or `elvish` without signing in or making a network call. For example, add `source <(proofline completions zsh)` to `~/.zshrc`. ### Windows installation diff --git a/src/lib.rs b/src/lib.rs index 6273dcc..2293e74 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -152,7 +152,7 @@ enum Command { /// Remove the stored token from the OS keychain. Logout, /// Show which organization and token the CLI uses. - Status, + Status(StatusArgs), /// Review the checkout's local changes, pushed commits, or an open pull /// request's current head. Review(ReviewArgs), @@ -247,6 +247,13 @@ struct OutputArgs { timeout: u64, } +#[derive(Debug, Args)] +struct StatusArgs { + /// Print the status information as JSON. + #[arg(long)] + json: bool, +} + #[derive(Debug, Args)] struct StopArgs { /// The review ID returned by `review --no-wait`. @@ -502,7 +509,7 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result logout(&origin, token.is_some()) .await .map(|()| Verdict::Done), - Command::Status => status(Http::new(origin)?, token, cli.org) + Command::Status(args) => status(Http::new(origin)?, token, cli.org, args.json) .await .map(|()| Verdict::Done), Command::Review(args) => { @@ -688,7 +695,12 @@ async fn logout(origin: &Origin, environment: bool) -> anyhow::Result<()> { Ok(()) } -async fn status(http: Http, token: Option, org: Option) -> anyhow::Result<()> { +async fn status( + http: Http, + token: Option, + org: Option, + json: bool, +) -> anyhow::Result<()> { let Credential { token, organization_id, @@ -697,38 +709,80 @@ async fn status(http: Http, token: Option, org: Option) -> a source, } = credentials::load(http.origin(), token, org).await?; let origin = http.origin().clone(); - let mut lines = vec![ - format!("console: {origin}"), - format!("organization: {organization_id}"), - format!( - "token: {}", - match source { - Source::Environment => "PROOFLINE_TOKEN", - Source::Keychain => "OS keychain", - } - ), - ]; - if let Some(scope) = scope { - lines.push(format!("scopes: {}", text::one_line(&scope))); - } - if let Some(expires_at) = expires_at { - let left = expires_at.saturating_sub(device::now()); - lines.push(if left == 0 { - "expires: expired; run `proofline login`".to_owned() - } else { - format!("expires: in {} hours", left.div_ceil(3600)) - }); - } let api = Api::new(http, token, organization_id); let result = api.reviews(None, None, None).await; - lines.push(match &result { - Ok(_) => "server: accepted the token".to_owned(), - Err(error) if error.status() == Some(401) => { - "server: the token is expired, revoked or malformed; run `proofline login`".to_owned() + + if json { + let server_message = match &result { + Ok(_) => "accepted the token".to_owned(), + Err(error) if error.status() == Some(401) => { + "the token is expired, revoked or malformed; run `proofline login`".to_owned() + } + Err(error) => format!("{error}"), + }; + let token_source = match source { + Source::Environment => "PROOFLINE_TOKEN", + Source::Keychain => "OS keychain", + }; + let expires_in_hours = expires_at.map(|exp| { + let left = exp.saturating_sub(device::now()); + if left == 0 { + 0 + } else { + left.div_ceil(3600) + } + }); + let is_expired = expires_at.map(|exp| exp.saturating_sub(device::now()) == 0); + let payload = serde_json::json!({ + "console": origin.to_string(), + "organization_id": organization_id, + "token": token_source, + "scopes": scope.as_deref().map(text::one_line), + "expires_at": expires_at, + "expires_in_hours": expires_in_hours, + "expired": is_expired, + "server": { + "accepted": result.is_ok(), + "message": server_message, + } + }); + writeln!( + std::io::stdout().lock(), + "{}", + serde_json::to_string_pretty(&payload)? + )?; + } else { + let mut lines = vec![ + format!("console: {origin}"), + format!("organization: {organization_id}"), + format!( + "token: {}", + match source { + Source::Environment => "PROOFLINE_TOKEN", + Source::Keychain => "OS keychain", + } + ), + ]; + if let Some(scope) = &scope { + lines.push(format!("scopes: {}", text::one_line(scope))); } - Err(error) => format!("server: {error}"), - }); - writeln!(std::io::stdout().lock(), "{}", lines.join("\n"))?; + if let Some(expires_at) = expires_at { + let left = expires_at.saturating_sub(device::now()); + lines.push(if left == 0 { + "expires: expired; run `proofline login`".to_owned() + } else { + format!("expires: in {} hours", left.div_ceil(3600)) + }); + } + lines.push(match &result { + Ok(_) => "server: accepted the token".to_owned(), + Err(error) if error.status() == Some(401) => { + "server: the token is expired, revoked or malformed; run `proofline login`".to_owned() + } + Err(error) => format!("server: {error}"), + }); + writeln!(std::io::stdout().lock(), "{}", lines.join("\n"))?; + } result?; Ok(()) } diff --git a/tests/http.rs b/tests/http.rs index eb6157d..3cd63b7 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -291,6 +291,54 @@ async fn status_preserves_metadata_and_reports_failed_checks_with_exit_one() { } } +#[tokio::test] +async fn status_json_reports_structured_metadata_and_respects_server_outcome() { + for (status, expected_code, expected_accepted) in [ + (StatusCode::OK, 0, true), + (StatusCode::UNAUTHORIZED, 1, false), + ] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let app = Router::new().route( + &format!("/api/v1/organizations/{ORG}/reviews"), + get(move |headers: HeaderMap| async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + let body = if status.is_success() { + json!({ + "items": [], + "next_cursor": null, + "truncated": false, + "filters": { "repositories": [] }, + }) + } else { + json!({ "title": "Access refused", "status": status.as_u16() }) + }; + (status, Json(body)) + }), + ); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let output = cli(&origin, &["status", "--json"]).await; + assert_eq!(output.status.code(), Some(expected_code)); + let value: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("status --json outputs valid JSON"); + assert_eq!(value["console"], origin); + assert_eq!(value["organization_id"], ORG); + assert_eq!(value["token"], "PROOFLINE_TOKEN"); + assert_eq!(value["server"]["accepted"], expected_accepted); + if expected_accepted { + assert_eq!(value["server"]["message"], "accepted the token"); + } else { + assert!(value["server"]["message"] + .as_str() + .unwrap_or_default() + .contains("run `proofline login`")); + } + server.abort(); + } +} + #[tokio::test] async fn findings_timeout_applies_only_to_waiting_and_never_panics() { for (timeout, wait, code, reads) in [