//! `oh`: OxygenHub from the command line, as `gh` is for GitHub. It talks //! to the hub's JSON API (hub spec §12) as the checkout's remote does: //! same hub, same token, same CA. mod client; mod target; mod ui; use anyhow::{bail, Context, Result}; use clap::{Parser, Subcommand}; use client::Client; use hub_api::{FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release}; use std::time::Duration; use target::{Choice, Config, Target}; #[derive(Parser)] #[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs and releases")] struct Cli { /// The repository, when not inside an Oxygen checkout #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")] repo: Option, /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved) #[arg(long, global = true, value_name = "URL")] hub: Option, /// Which of the checkout's remotes to use (default: origin, or the only one) #[arg(long, global = true)] remote: Option, /// Machine-readable output: the API's JSON, unchanged #[arg(long, global = true)] json: bool, /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal) #[arg(long, global = true)] plain: bool, #[command(subcommand)] cmd: Cmd, } #[derive(Subcommand)] enum Cmd { /// Sign in to a hub, or show who you are signed in as Auth { #[command(subcommand)] cmd: AuthCmd, }, /// The repository Repo { #[command(subcommand)] cmd: RepoCmd, }, /// Issues Issue { #[command(subcommand)] cmd: IssueCmd, }, /// Proposals (pull requests) Proposal { #[command(subcommand)] cmd: ProposalCmd, }, /// OxygenFlow runs Run { #[command(subcommand)] cmd: RunCmd, }, /// Releases Release { #[command(subcommand)] cmd: ReleaseCmd, }, /// The repository's labels Label { #[command(subcommand)] cmd: LabelCmd, }, /// Call the API directly: `oh api /repos/OWNER/NAME/issues` Api { /// A path under /api/v1 path: String, /// The method #[arg(long, short = 'X', default_value = "GET")] method: String, /// A JSON body #[arg(long, short = 'd')] data: Option, }, } #[derive(Subcommand)] enum AuthCmd { /// Sign in to a hub and make it the default: approve a code on the web /// (device sign-in), or give a token Login { /// The hub, e.g. https://oxygenhub.io #[arg(long = "with-hub", value_name = "URL")] url: String, /// An API token from the hub's Settings → Tokens, instead of /// approving a code ("-" reads it from stdin) #[arg(long)] token: Option, /// The hub's CA certificate, when self-signed #[arg(long)] ca: Option, }, /// Who the token in use belongs to Status, } #[derive(Subcommand)] enum RepoCmd { /// Name, description, visibility and default bookmark View, } #[derive(Subcommand)] enum IssueCmd { /// Put labels on an issue or take them off (triage) Label(LabelChange), /// Open issues (or --state closed|all) List { #[arg(long, default_value = "open")] state: String, }, /// One issue with its comments View { number: i64 }, /// Open an issue Create { #[arg(long, short)] title: String, #[arg(long, short)] body: Option, /// Read the body from a file ("-" for stdin) #[arg(long, short = 'F')] body_file: Option, /// A label (repeatable) #[arg(long, short)] label: Vec, }, /// Close an issue Close { number: i64, /// `completed` or `not_planned` #[arg(long, default_value = "completed")] reason: String, }, /// Reopen an issue Reopen { number: i64 }, /// Comment on an issue Comment { number: i64, #[arg(long, short)] body: String, }, } #[derive(Subcommand)] enum ProposalCmd { /// Open proposals (or --state draft|landed|closed|all) List { #[arg(long, default_value = "open")] state: String, }, /// One proposal: its changes, approvals and whether it can land View { number: i64 }, /// Propose a bookmark's changes for another bookmark Create { #[arg(long, short)] title: String, #[arg(long, short)] body: Option, /// Read the body from a file ("-" for stdin) #[arg(long, short = 'F', conflicts_with = "body")] body_file: Option, /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork) #[arg(long)] from: String, /// The bookmark to land them on (default: the repository's default bookmark) #[arg(long)] into: Option, #[arg(long)] draft: bool, }, /// Change a proposal's title or description (its author or a maintainer) Edit { number: i64, #[arg(long, short)] title: Option, #[arg(long, short)] body: Option, /// Read the body from a file ("-" for stdin) #[arg(long, short = 'F', conflicts_with = "body")] body_file: Option, }, /// Put labels on a proposal or take them off (triage) Label(LabelChange), /// Comment on a proposal's conversation Comment { number: i64, #[arg(long, short)] body: Option, /// Read the comment from a file ("-" for stdin) #[arg(long, short = 'F', conflicts_with = "body")] body_file: Option, }, /// The checks on a proposal's projected state Checks { number: i64 }, /// Land a proposal on its target, as the page's Land button does Land { number: i64 }, } #[derive(Subcommand)] enum LabelCmd { /// The repository's labels List, /// Create a label, or change the one of that name (triage) Create { name: String, /// `#rrggbb` (default: one the hub picks) #[arg(long)] colour: Option, #[arg(long, short, default_value = "")] description: String, }, /// Delete a label, taking it off every issue and proposal (triage) Delete { name: String }, } /// Labels to put on or take off an issue or proposal. #[derive(clap::Args)] struct LabelChange { number: i64, /// A label to add (repeatable) #[arg(long, short)] add: Vec, /// A label to take off (repeatable) #[arg(long, short)] remove: Vec, } impl LabelChange { /// The set after the change, from the one there now. fn apply(&self, now: &[hub_api::Label]) -> Result> { if self.add.is_empty() && self.remove.is_empty() { bail!("say what to change: --add NAME or --remove NAME"); } let mut names: Vec = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect(); for a in &self.add { if !names.contains(a) { names.push(a.clone()); } } Ok(names) } } fn label_names(labels: &[String]) -> String { if labels.is_empty() { ui::dim("no labels") } else { labels.iter().map(|l| format!("[{l}]")).collect::>().join(" ") } } #[derive(Subcommand)] enum RunCmd { /// Recent runs, newest first List { #[arg(long, default_value_t = 20)] limit: i64, }, /// A run and its jobs View { number: i64 }, /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's Start { #[arg(long)] bookmark: Option, /// A change's full hash #[arg(long, conflicts_with = "bookmark")] change: Option, /// Wait for the run and exit 1 unless it passes #[arg(long)] watch: bool, }, /// Follow a run until it finishes; exit 1 unless it passes Watch { number: i64 }, /// A job's log Log { number: i64, job: String }, /// Run a finished run's state again Rerun { number: i64 }, /// Cancel a run still queued or running; its running jobs are stopped Cancel { number: i64 }, } #[derive(Subcommand)] enum ReleaseCmd { /// Releases, newest first List, /// Create a release on an existing tag Create { tag: String, #[arg(long, short)] title: Option, /// Notes in Markdown (default: generated from the changes since the previous release) #[arg(long, short)] notes: Option, #[arg(long)] prerelease: bool, }, /// Change a release's title, notes or prerelease flag Edit { tag: String, #[arg(long, short)] title: Option, /// New notes in Markdown ("-" reads them from stdin) #[arg(long, short)] notes: Option, /// Mark it a prerelease (true) or not (false) #[arg(long)] prerelease: Option, }, /// Attach files to a release Upload { tag: String, files: Vec }, /// The release's trust report: signatures, builds, receipts and audit Trust { tag: String }, } fn main() { let cli = Cli::parse(); ui::init(cli.plain); match run(cli) { Ok(code) => std::process::exit(code), Err(e) => { eprintln!("{} {e:#}", ui::bad("error:")); std::process::exit(2); } } } fn enc(s: &str) -> String { let mut out = String::new(); for b in s.bytes() { if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { out.push(b as char); } else { out.push_str(&format!("%{b:02X}")); } } out } fn run(cli: Cli) -> Result { let cfg = Config::load()?; if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd { return login(cfg, url, token.clone(), ca.clone()); } let here = std::env::current_dir()?; let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?; let c = Client::new(&t)?; let json = cli.json; match cli.cmd { Cmd::Auth { cmd: AuthCmd::Status } => { let me: serde_json::Value = c.get("/user")?; if json { println!("{me}"); } else { println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?"))); } Ok(0) } Cmd::Auth { .. } => unreachable!(), Cmd::Api { path, method, data } => { let path = if path.starts_with('/') { path } else { format!("/{path}") }; // The method applies with or without a body (#75): without one, a // GET reads, anything else sends an empty object. let text = match data { Some(d) => c.send_text( &method.to_uppercase(), &path, &serde_json::from_str::(&d).context("--data is not JSON")?, )?, None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?, None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?, }; println!("{text}"); Ok(0) } Cmd::Repo { cmd: RepoCmd::View } => { let path = t.repo_path()?; if json { println!("{}", c.get_text(&path)?); return Ok(0); } let r: serde_json::Value = c.get(&path)?; println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or(""))); if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) { println!("{d}"); } println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or(""))); println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name))); Ok(0) } Cmd::Issue { cmd } => issue(&c, &t, cmd, json), Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json), Cmd::Run { cmd } => flow(&c, &t, cmd, json), Cmd::Release { cmd } => release(&c, &t, cmd, json), Cmd::Label { cmd } => label(&c, &t, cmd, json), } } fn login(mut cfg: Config, url: &str, token: Option, ca: Option) -> Result { let hub = url.trim_end_matches('/').to_string(); let token = match token.as_deref() { Some("-") => { eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:"); let mut line = String::new(); std::io::stdin().read_line(&mut line)?; line.trim().to_string() } Some(t) => t.to_string(), None => device_sign_in(&hub, ca.clone())?, }; if token.is_empty() { bail!("no token given"); } let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() }; let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?; let account = me["username"].as_str().unwrap_or("?"); // One sign-in for oh and oxy alike: the token goes to oxy's store. let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?; let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c)); oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?; cfg.default_hub = Some(hub.clone()); cfg.save()?; println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account)); println!("{}", ui::dim(" oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it")); Ok(0) } /// Device sign-in (oxygenhub#67): the hub gives a code, the user approves /// it on the web, and the token arrives here. fn device_sign_in(hub: &str, ca: Option) -> Result { let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() }; let c = Client::new(&t)?; let host = std::fs::read_to_string("/etc/hostname") .ok() .or_else(|| std::env::var("COMPUTERNAME").ok()) .map(|h| h.trim().to_string()) .filter(|h| !h.is_empty()); let client = match host { Some(h) => format!("oh on {h}"), None => "oh".to_string(), }; let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"]; let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?; let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?; if code != 200 { bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body)); } let device = v["device_code"].as_str().context("no device code")?.to_string(); let user = v["user_code"].as_str().unwrap_or("?"); let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub); let mut interval = v["interval"].as_u64().unwrap_or(5).max(1); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900)); eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user)); eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…")); loop { std::thread::sleep(std::time::Duration::from_secs(interval)); if std::time::Instant::now() > deadline { bail!("the code expired before it was approved; run oh auth login again"); } let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?; let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); if code == 200 { return v["access_token"].as_str().map(String::from).context("no token in the hub's answer"); } match v["error"].as_str() { Some("authorization_pending") => {} Some("slow_down") => interval += 5, Some("access_denied") => bail!("the sign-in was denied on the web"), Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"), _ => bail!("signing in: HTTP {code}: {body}"), } } } fn body_of(body: Option, file: Option) -> Result { match (body, file) { (Some(b), _) => Ok(b), (None, Some(f)) if f == "-" => { let mut s = String::new(); std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?; Ok(s) } (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")), (None, None) => Ok(String::new()), } } fn issue_line(i: &Issue) -> String { let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") }; let labels: Vec = i.labels.iter().map(|l| format!("[{}]", l.name)).collect(); format!( "{glyph} {} {}{}{}", ui::dim(&format!("#{}", i.number)), i.title, if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) }, ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms))) ) } fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result { let base = t.repo_path()?; match cmd { IssueCmd::List { state } => { let path = format!("{base}/issues?state={}", enc(&state)); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let list: Vec = c.get(&path)?; if list.is_empty() { println!("{}", ui::dim(&format!("No {state} issues."))); } for i in &list { println!("{}", issue_line(i)); } } IssueCmd::View { number } => { let path = format!("{base}/issues/{number}"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let i: Issue = c.get(&path)?; println!("{}", issue_line(&i)); if !i.body.trim().is_empty() { println!("\n{}\n", i.body.trim_end()); } let comments: Vec = c.get(&format!("{path}/comments"))?; for cm in comments { println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end()); } println!("{}", ui::dim(&i.url)); } IssueCmd::Create { title, body, body_file, label } => { let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None }; let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?; if json { println!("{}", serde_json::to_string(&i)?); } else { println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url)); } } IssueCmd::Close { number, reason } => { let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?; println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title); } IssueCmd::Reopen { number } => { let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?; println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title); } IssueCmd::Label(change) => { let path = format!("{base}/issues/{}", change.number); let now: Issue = c.get(&path)?; let labels = change.apply(&now.labels)?; let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None }; let i: Issue = c.send("PATCH", &path, &edit)?; if json { println!("{}", serde_json::to_string(&i)?); } else { println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels)); } } IssueCmd::Comment { number, body } => { c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?; println!("{} commented on #{number}", ui::ok("✔")); } } Ok(0) } fn source_name(s: &hub_api::ProposalSource) -> String { match s { hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(), hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"), hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()), } } fn proposal_line(p: &Proposal) -> String { let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default(); let glyph = match state.as_str() { "open" => ui::ok("●"), "draft" => ui::dim("◌"), "landed" => ui::strong("✔"), _ => ui::dim("○"), }; format!( "{glyph} {} {} {}{}", ui::dim(&format!("#{}", p.number)), p.title, ui::dim(&format!("{} → {}", source_name(&p.source), p.target)), ui::dim(&format!(" · {} · {state}", p.author)) ) } fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result { let base = t.repo_path()?; match cmd { ProposalCmd::List { state } => { let path = format!("{base}/proposals?state={state}"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let list: Vec = c.get(&path)?; if list.is_empty() { println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace(" ", " "))); } for p in &list { println!("{}", proposal_line(p)); } } ProposalCmd::View { number } => { let path = format!("{base}/proposals/{number}"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let p: Proposal = c.get(&path)?; println!("{}", proposal_line(&p)); if !p.body.trim().is_empty() { println!("\n{}\n", p.body.trim_end()); } println!("{}", ui::kv("changes", &p.changes.len().to_string())); for ch in &p.changes { println!(" {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or("")); } println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::>().join(", "))); if p.landable { println!("{} can land", ui::ok("✔")); } else { for b in &p.blockers { println!("{} {b}", ui::bad("✘")); } } if p.conflicted { println!("{} landing it would leave conflicts", ui::bad("!")); } println!("{}", ui::dim(&p.url)); } ProposalCmd::Create { title, body, body_file, from, into, draft } => { let target = match into { Some(i) => i, None => c.get::(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(), }; let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft }; let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url)); } } ProposalCmd::Edit { number, title, body, body_file } => { let body = match (&body, &body_file) { (None, None) => None, _ => Some(body_of(body, body_file)?), }; if title.is_none() && body.is_none() { bail!("say what to change: --title, --body or --body-file"); } let edit = hub_api::ProposalEdit { title, body, labels: None }; let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url)); } } ProposalCmd::Label(change) => { let path = format!("{base}/proposals/{}", change.number); let now: Proposal = c.get(&path)?; let labels = change.apply(&now.labels)?; let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() }; let p: Proposal = c.send("PATCH", &path, &edit)?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels)); } } ProposalCmd::Comment { number, body, body_file } => { let body = body_of(body, body_file)?; if body.trim().is_empty() { bail!("give the comment with --body or --body-file"); } c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?; println!("{} commented on #{number}", ui::ok("✔")); } ProposalCmd::Land { number } => { let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &serde_json::json!({}))?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target); } } ProposalCmd::Checks { number } => { let path = format!("{base}/proposals/{number}/checks"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let checks: Vec = c.get(&path)?; if checks.is_empty() { println!("{}", ui::dim("No checks yet.")); } for ch in checks { println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary)); } } } Ok(0) } fn run_line(r: &FlowRun) -> String { let what = if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() }; format!( "{} {} {} {}", ui::status(&r.status), ui::dim(&format!("#{}", r.number)), what, ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms))) ) } fn print_run(r: &FlowRun) { println!("{}", run_line(r)); for j in &r.jobs { let dur = match (j.started_ms, j.finished_ms) { (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0), _ => String::new(), }; let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) }; println!(" {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}"))); } if !r.error.is_empty() { println!("{}", ui::bad(&r.error)); } println!("{}", ui::dim(&r.url)); } fn live(status: &str) -> bool { matches!(status, "queued" | "running") } fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result { let path = format!("{base}/flow/runs/{number}"); let mut seen: std::collections::HashMap = std::collections::HashMap::new(); loop { let r: FlowRun = c.get(&path)?; if !json { for j in &r.jobs { if seen.get(&j.name) != Some(&j.status) { println!("{} {}", ui::status(&j.status), j.name); seen.insert(j.name.clone(), j.status.clone()); } } } if !live(&r.status) { if json { println!("{}", serde_json::to_string(&r)?); } else { println!("{} run #{} {}", ui::status(&r.status), r.number, r.status); } return Ok(if r.status == "passed" { 0 } else { 1 }); } std::thread::sleep(Duration::from_secs(3)); } } fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result { let base = t.repo_path()?; match cmd { RunCmd::List { limit } => { let path = format!("{base}/flow/runs?limit={limit}"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let runs: Vec = c.get(&path)?; if runs.is_empty() { println!("{}", ui::dim("No runs yet.")); } for r in &runs { println!("{}", run_line(r)); } } RunCmd::View { number } => { let path = format!("{base}/flow/runs/{number}"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } print_run(&c.get(&path)?); } RunCmd::Start { bookmark, change, watch: follow } => { let body = match (bookmark, change) { (_, Some(ch)) => serde_json::json!({ "change": ch }), (Some(b), None) => serde_json::json!({ "bookmark": b }), (None, None) => serde_json::json!({}), }; let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?; let n = started["number"].as_i64().context("the hub named no run")?; if !json || !follow { if json { println!("{started}"); } else { println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or(""))); } } if follow { return watch(c, &base, n, json); } } RunCmd::Watch { number } => return watch(c, &base, number, json), RunCmd::Log { number, job } => { let mut after = 0; loop { let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job)); let lines: Vec = c.get(&path)?; if lines.is_empty() { break; } for l in &lines { if json { println!("{}", serde_json::to_string(l)?); } else if l.stream == "flow" { println!("{}", ui::dim(&l.text)); } else { println!("{}", l.text); } } after = lines.last().map(|l| l.seq).unwrap_or(after); } } RunCmd::Rerun { number } => { let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?; if json { println!("{started}"); } else { println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or(""))); } } RunCmd::Cancel { number } => { let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?; if json { println!("{done}"); } else { println!("{} cancelled run #{number}", ui::ok("✔")); } } } Ok(0) } fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result { let base = t.repo_path()?; match cmd { LabelCmd::List => { let path = format!("{base}/labels"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let labels: Vec = c.get(&path)?; if labels.is_empty() { println!("{}", ui::dim("No labels.")); } for l in labels { println!("{} {} {}", ui::dim(&l.colour), l.name, ui::dim(&l.description)); } } LabelCmd::Create { name, colour, description } => { let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?; if json { println!("{}", serde_json::to_string(&l)?); } else { println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour)); } } LabelCmd::Delete { name } => { c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?; println!("{} deleted label {name}", ui::ok("✔")); } } Ok(0) } fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result { let base = t.repo_path()?; match cmd { ReleaseCmd::List => { let path = format!("{base}/releases"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let list: Vec = c.get(&path)?; if list.is_empty() { println!("{}", ui::dim("No releases.")); } for r in &list { println!( "{} {} {}{}", if r.latest { ui::ok("●") } else { ui::dim("○") }, ui::strong(&r.tag), r.title, ui::dim(&format!( " · {} asset{} · {}", r.assets.len(), if r.assets.len() == 1 { "" } else { "s" }, ui::ago(r.created_ms) )) ); } } ReleaseCmd::Create { tag, title, notes, prerelease } => { let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease }; let r: Release = c.send("POST", &format!("{base}/releases"), &new)?; if json { println!("{}", serde_json::to_string(&r)?); } else { println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url)); } } ReleaseCmd::Edit { tag, title, notes, prerelease } => { let notes = match notes.as_deref() { Some("-") => Some(body_of(None, Some("-".into()))?), _ => notes, }; if title.is_none() && notes.is_none() && prerelease.is_none() { bail!("say what to change: --title, --notes or --prerelease"); } let edit = hub_api::ReleaseEdit { title, notes, prerelease }; let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?; if json { println!("{}", serde_json::to_string(&r)?); } else { println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url)); } } ReleaseCmd::Upload { tag, files } => { if files.is_empty() { bail!("name the files to attach"); } for f in files { let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string(); let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?; c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?; println!("{} attached {name} to {tag}", ui::ok("✔")); } } ReleaseCmd::Trust { tag } => { let path = format!("{base}/releases/trust/{}", enc(&tag)); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let r: serde_json::Value = c.get(&path)?; println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"]))); let mut worst = 0; for ch in r["audit"].as_array().into_iter().flatten() { let v = ch["verdict"].as_str().unwrap_or(""); worst = worst.max(match v { "fail" => 2, "warn" => 1, _ => 0, }); let g = match v { "pass" => ui::ok("✔"), "warn" => ui::warn("!"), _ => ui::bad("✘"), }; println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or(""))); } return Ok(if worst == 2 { 1 } else { 0 }); } } Ok(0) }