//! `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, Host, 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, }, /// 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 { /// Save a token for a hub (read from stdin when not given) and make it the default Login { /// The hub, e.g. https://earth.example:7343 #[arg(long = "with-hub", value_name = "URL")] url: String, /// An API token from the hub's Settings → Tokens #[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 { /// 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 List, /// 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, /// 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, }, /// The checks on a proposal's projected state Checks { number: i64 }, } #[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 }, } #[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, }, /// 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}") }; let text = match data { Some(d) => c.send_text( &method.to_uppercase(), &path, &serde_json::from_str::(&d).context("--data is not JSON")?, )?, None => c.get_text(&path)?, }; 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), } } fn login(mut cfg: Config, url: &str, token: Option, ca: Option) -> Result { let hub = url.trim_end_matches('/').to_string(); let token = match token { Some(t) => t, None => { 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() } }; 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")?; cfg.hosts.insert(hub.clone(), Host { token, ca }); cfg.default_hub = Some(hub.clone()); cfg.save()?; println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(me["username"].as_str().unwrap_or("?"))); Ok(0) } 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::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 => { let path = format!("{base}/proposals"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let list: Vec = c.get(&path)?; if list.is_empty() { println!("{}", ui::dim("No open proposals.")); } 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, 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.unwrap_or_default(), 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::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(""))); } } } 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::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) }