//! `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, }, /// Milestones: list, create, edit, close Milestone { #[command(subcommand)] cmd: MilestoneCmd, }, /// Project boards of the repository's owner (or --owner): list, /// create, view, and cards Project { #[command(subcommand)] cmd: ProjectCmd, /// A user or organisation other than the repository's owner #[arg(long, global = true)] owner: Option, }, /// AI assistants of the repository (its admins), or with --org or /// --site of an organisation or the site Assistant { #[command(subcommand)] cmd: AssistantCmd, /// An organisation's assistants instead of the repository's #[arg(long, global = true)] org: Option, /// The site's assistants (administrators) #[arg(long, global = true, conflicts_with = "org")] site: bool, }, /// 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, /// Also put it on this board of the repository's owner #[arg(long, short)] project: Option, /// The board's column for it, by name (default: the first) #[arg(long, requires = "project")] column: Option, }, /// Close an issue Close { number: i64, /// `completed` or `not_planned` #[arg(long, default_value = "completed")] reason: String, }, /// Reopen an issue Reopen { number: i64 }, /// Change an issue's title or body (its author or triage), or its /// labels, assignees or milestone as whole sets (triage) 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, /// The labels it should have (repeatable; `oh issue label` adds and removes) #[arg(long, short)] label: Vec, /// Clear its labels #[arg(long, conflicts_with = "label")] no_labels: bool, /// The users it should be assigned to (repeatable) #[arg(long, short)] assignee: Vec, /// Take everyone off it #[arg(long, conflicts_with = "assignee")] no_assignees: bool, /// A milestone's title ("" takes it out of its milestone) #[arg(long, short)] milestone: Option, }, /// 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 AssistantCmd { /// The assistants this level sees, its own and those inherited List, /// Add an assistant, or change the one of that name Add { /// How it shows on reviews (default: the provider's name) #[arg(long, default_value = "")] name: String, /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama #[arg(long, default_value = "")] preset: String, /// The endpoint, when no preset or another one #[arg(long, default_value = "")] endpoint: String, /// chat-completions or anthropic-messages #[arg(long, default_value = "")] api: String, /// One the endpoint lists (`oh assistant models` shows them) #[arg(long)] model: String, /// The API key, read from this environment variable (never typed on the command line) #[arg(long, value_name = "VAR")] token_env: Option, /// Add it turned off #[arg(long)] off: bool, }, /// Remove this level's assistant of that name Remove { name: String }, /// Show this level's prompt, and those it inherits Prompt { /// Set it from this file (`-` for standard input; an empty file clears it) #[arg(long, value_name = "FILE")] set: Option, }, } #[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 }, } #[derive(Subcommand)] enum ProjectCmd { /// The owner's boards List, /// One board: its columns and cards View { number: i64 }, /// Create a board (owner, or an organisation's members) Create { title: String, #[arg(long, short, default_value = "")] description: String, /// Only the owner (or the organisation's members) can see it #[arg(long)] private: bool, }, /// Close a board Close { number: i64 }, /// Reopen a board Reopen { number: i64 }, /// Move a board to another owner you may make boards under (an /// organisation, say); it takes the next number there Transfer { number: i64, /// The new owner #[arg(long)] to: String, }, /// Cards on a board: add, move, remove Card { #[command(subcommand)] cmd: CardCmd, }, } #[derive(Subcommand)] enum CardCmd { /// Put an issue or proposal on a board (`12` or `#12` in this /// repository, `name#12` or `owner/name#12` in another of the owner's), /// or a note with --note Add { number: i64, /// The issue or proposal; a number means this repository's reference: Option, /// A note card instead #[arg(long, conflicts_with = "reference")] note: Option, /// The column, by name or id (default: the first) #[arg(long, short)] column: Option, }, /// Move a card to another column (by name or id) Move { number: i64, card: i64, #[arg(long, short)] column: String, }, /// Take a card off a board Remove { number: i64, card: i64 }, } #[derive(Subcommand)] enum MilestoneCmd { /// The repository's milestones List, /// Create a milestone, or change the one of that title (triage) Create { title: String, #[arg(long, short, default_value = "")] description: String, /// Due date, YYYY-MM-DD #[arg(long)] due: Option, }, /// Change a milestone's title, description or due date (triage) Edit { title: String, #[arg(long, short)] rename: Option, #[arg(long, short)] description: Option, /// Due date, YYYY-MM-DD ("" for none) #[arg(long)] due: Option, }, /// Close a milestone Close { title: String }, /// Reopen a milestone Reopen { title: 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() { // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and // other command-line tools do, instead of panicking on the failed // write (oxygenhub#92). #[cfg(unix)] unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL); } 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), Cmd::Label { cmd } => label(&c, &t, cmd, json), Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json), Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json), Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, 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, project, column } => { 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)); } if let Some(n) = project { let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() }; let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?; if !json { println!("{} on project {n} as card {}", ui::ok("✔"), added.id); } } } 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::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => { let body = match (&body, &body_file) { (None, None) => None, _ => Some(body_of(body, body_file)?), }; let labels = if no_labels { Some(Vec::new()) } else if label.is_empty() { None } else { Some(label) }; let assignees = if no_assignees { Some(Vec::new()) } else if assignee.is_empty() { None } else { Some(assignee) }; if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() { bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone"); } let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone }; let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?; if json { println!("{}", serde_json::to_string(&i)?); } else { println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url)); } } 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 assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option, site: bool, json: bool) -> Result { let base = match (&org, site) { (Some(o), _) => format!("/orgs/{}/assistants", enc(o)), (None, true) => "/admin/assistants".to_string(), (None, false) => format!("{}/assistants", t.repo_path()?), }; match cmd { AssistantCmd::List => { if json { println!("{}", c.get_text(&base)?); return Ok(0); } let list: Vec = c.get(&base)?; if list.is_empty() { println!("{}", ui::dim("No assistants.")); } for a in list { let state = if a.enabled && !a.off_above { ui::ok("on") } else if a.off_above { ui::dim("off above") } else { ui::dim("off") }; let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) }; println!("{} {} {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from); } } AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => { let token = match token_env { Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?, None => String::new(), }; let body = hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None }; let r: serde_json::Value = c.send("POST", &base, &body)?; println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved")); } AssistantCmd::Remove { name } => { c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?; println!("{} removed {name}", ui::ok("✔")); } AssistantCmd::Prompt { set } => { let p: hub_api::AssistantPrompt = match set { Some(path) => { let text = if path.as_os_str() == "-" { let mut s = String::new(); std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?; s } else { std::fs::read_to_string(&path)? }; c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })? } None => c.get(&format!("{base}/prompt"))?, }; if json { println!("{}", serde_json::to_string(&p)?); return Ok(0); } for (from, text) in &p.inherited { println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text); } if p.prompt.is_empty() { println!("{}", ui::dim("No prompt of its own.")); } else { println!("{}\n{}", ui::dim("── this level"), p.prompt); } } } Ok(0) } fn project_line(p: &hub_api::Project) -> String { let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") }; let private = if p.public { "" } else { " · private" }; format!("{glyph} {} {} {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms)))) } fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option, json: bool) -> Result { let owner = match owner { Some(o) => o, None => t.repo()?.0.to_string(), }; let base = format!("/projects/{}", enc(&owner)); let state = |number: i64, closed: bool, verb: &str| -> Result<()> { let p: hub_api::Project = c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title); } Ok(()) }; match cmd { ProjectCmd::List => { if json { println!("{}", c.get_text(&base)?); return Ok(0); } let list: Vec = c.get(&base)?; if list.is_empty() { println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE"))); } for p in &list { println!("{}", project_line(p)); } } ProjectCmd::View { number } => { let path = format!("{base}/{number}"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let b: hub_api::Board = c.get(&path)?; println!("{}", project_line(&b.project)); if !b.project.description.is_empty() { println!("{}", b.project.description); } for col in &b.columns { println!(); println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id))); if col.cards.is_empty() { println!(" {}", ui::dim("(empty)")); } for card in &col.cards { let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() }; let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) }; println!(" {} {what}{st} {}", ui::dim(&format!("{:>4}", card.id)), card.title); } } println!("{}", ui::dim(&format!("\n{}", b.project.url))); } ProjectCmd::Create { title, description, private } => { let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url)); } } ProjectCmd::Close { number } => state(number, true, "closed")?, ProjectCmd::Reopen { number } => state(number, false, "reopened")?, ProjectCmd::Transfer { number, to } => { let p: hub_api::Project = c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url); } } ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => { // The hub names a card's issue as `repo#N` among the owner's // repositories. let reference = match reference { None => String::new(), Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') { Some((o, rest)) if o == owner => rest.to_string(), Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"), None => r, }, Some(r) => { let n = r.trim_start_matches('#'); if n.parse::().is_err() { bail!("{r}: give an issue or proposal number, or NAME#N"); } format!("{}#{n}", t.repo()?.1) } }; let note = note.unwrap_or_default(); if reference.is_empty() && note.is_empty() { bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT"); } let card: hub_api::ProjectCard = c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?; if json { println!("{}", serde_json::to_string(&card)?); } else { println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference }); } } ProjectCmd::Card { cmd: CardCmd::Move { number, card, column } } => { c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?; println!("{} card {card} moved to {column}", ui::ok("✔")); } ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => { c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?; println!("{} card {card} removed", ui::ok("✔")); } } Ok(0) } fn milestone_line(m: &hub_api::Milestone) -> String { let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") }; let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default(); format!("{glyph} {} {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due)) } fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result { let base = t.repo_path()?; let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> { let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?; if json { println!("{}", serde_json::to_string(&m)?); } else { println!("{} {verb} milestone {}", ui::ok("✔"), m.title); } Ok(()) }; match cmd { MilestoneCmd::List => { let path = format!("{base}/milestones"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let list: Vec = c.get(&path)?; if list.is_empty() { println!("{}", ui::dim("No milestones.")); } for m in &list { println!("{}", milestone_line(m)); } } MilestoneCmd::Create { title, description, due } => { let m: hub_api::Milestone = c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?; if json { println!("{}", serde_json::to_string(&m)?); } else { println!("{} milestone {}", ui::ok("✔"), m.title); } } MilestoneCmd::Edit { title, rename, description, due } => { if rename.is_none() && description.is_none() && due.is_none() { bail!("say what to change: --rename, --description or --due"); } edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?; } MilestoneCmd::Close { title } => { edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?; } MilestoneCmd::Reopen { title } => { edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?; } } 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) }