//! `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::{ FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag, }; 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, releases and drops")] 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, }, /// Coverage: upload a report measured off the hub (oxygenhub#136) Coverage { #[command(subcommand)] cmd: CoverageCmd, }, /// OxygenFlow runs Run { #[command(subcommand)] cmd: RunCmd, }, /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348) Report { #[command(subcommand)] cmd: ReportCmd, }, /// Releases Release { #[command(subcommand)] cmd: ReleaseCmd, }, /// Tags: list, create, withdraw Tag { #[command(subcommand)] cmd: TagCmd, }, /// 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, }, /// Agents that act for you without a key of their own (keyless /// signing): grant, list, revoke Agent { #[command(subcommand)] cmd: AgentCmd, }, /// Drops: small snippets of files, each its own repository, never /// listed among your repositories (oxygenhub#279) Drop { #[command(subcommand)] cmd: DropCmd, }, /// Runners that update themselves (site administrators; oxygenhub#322): /// where builds come from, who takes them, what is held back #[command(name = "runner-updates")] RunnerUpdates { #[command(subcommand)] cmd: Option, }, /// 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 AgentCmd { /// Let an agent act for you: your oxy key (the one your oxy home names /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives /// the agent a token it exchanges for ten-minute certificates. The /// token is printed once: give it to the agent (`oxy auth grant`) Grant { /// The agent's name, as in agent:NAME@YOU name: String, /// What its keys may do for you: changes, seal, refs #[arg(long, default_value = "changes,seal,refs")] scope: String, /// How long the grant lasts: 30d, 12h, 90m #[arg(long = "for", value_name = "DURATION", default_value = "30d")] lasts: String, }, /// Your grants, live and past List, /// Stop a grant at once: no more certificates under it Revoke { id: i64 }, } #[derive(Subcommand)] enum DropCmd { /// Make a drop of these files, signed by the hub as your delegate Create { /// The files (their names in the drop are their file names) #[arg(required = true)] files: Vec, /// Unlisted: readable by anyone with its address, listed nowhere #[arg(long)] secret: bool, /// A description #[arg(long, short = 'd', value_name = "TEXT")] description: Option, /// A title (default: the first file's name) #[arg(long, short = 't')] title: Option, }, /// Your drops, or someone's public ones List { /// Whose drops #[arg(long, short = 'u', value_name = "NAME")] user: Option, }, /// A drop's files, printed (by id or address) View { /// The drop's id, or its address id: String, /// Print only this file's content #[arg(long, short = 'f', value_name = "NAME")] file: Option, }, /// Delete a drop and its history Delete { /// The drop's id, or its address id: String, }, } #[derive(Subcommand)] enum RunnerUpdatesCmd { /// Every level's settings, the test groups, each runner's policy and what it is offered (the default) Show, /// Change one level's settings; what is not given stays as it is Set { /// `site`, `owner:NAME`, `group:NAME` (or `group:OWNER/NAME`, `group:ID`), `runner:NAME` (or `runner:ID`) scope: String, /// `on`, `off` or `inherit` #[arg(long)] updates: Option, /// `stable`, `canary`, a version, or `inherit` #[arg(long)] channel: Option, /// Hours (UTC) updates may start in, `02-05`, or `inherit` #[arg(long)] window: Option, /// `on`, `off` or `inherit` #[arg(long)] dry_run: Option, }, /// Offer a held build again (it rolled back on a runner) Lift { version: String }, } #[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: Option, /// Read the body from a file ("-" for stdin), as proposal comment /// does (#260) #[arg(long, short = 'F', conflicts_with = "body")] body_file: Option, }, } #[derive(Subcommand)] enum ProposalCmd { /// Open proposals (or --state draft|landed|closed|all), newest first List { #[arg(long, default_value = "open")] state: String, /// At most this many #[arg(long, default_value_t = 30)] limit: usize, }, /// 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, /// Land before its required checks pass, saying why (maintainers; /// recorded and audited, #261) #[arg(long, value_name = "REASON", conflicts_with = "when_ready")] over_checks: Option, /// Land it by itself once its checks pass (#261); with --off, don't #[arg(long)] when_ready: bool, /// With --when-ready: turn it off #[arg(long, requires = "when_ready")] off: bool, }, /// Close a proposal without landing it, with an optional comment Close { number: i64, /// Say why, as a comment before it closes #[arg(long, short = 'm')] message: Option, }, /// Reopen a closed proposal Reopen { number: i64 }, /// Take a draft proposal out of draft, ready for review (its author or triage) Ready { number: i64, /// Turn an open proposal back into a draft instead #[arg(long)] undo: bool, }, } #[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, /// Its archived cards instead (#293) #[arg(long)] archived: bool, }, /// 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, archive, restore, 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), or with --from every /// card of a column at once Move { number: i64, /// The card (its id); leave it out with --from card: Option, #[arg(long, short)] column: String, /// Move every card of this column (#289) #[arg(long, conflicts_with = "card")] from: Option, /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated #[arg(long, value_delimiter = ',', requires = "from")] except: Vec, /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated #[arg(long, value_delimiter = ',', requires = "from")] state: Vec, /// With --from: say what would move, and move nothing #[arg(long, requires = "from")] dry_run: bool, }, /// Archive a column's cards: off the board, kept and restorable (#293) Archive { number: i64, /// The column, by name or id #[arg(long)] from: String, /// Only cards that joined the column more than this long ago (14d, or 14) #[arg(long)] older: Option, /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated #[arg(long, value_delimiter = ',')] except: Vec, /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated #[arg(long, value_delimiter = ',')] state: Vec, /// Say what would be archived, and archive nothing #[arg(long)] dry_run: bool, }, /// Put an archived card back at the end of its column Restore { number: i64, card: i64 }, /// 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 CoverageCmd { /// Upload an LCOV or Cobertura report measured on this machine, as the /// coverage of a bookmark's current state (default: the default /// bookmark) or of one change's. The hub shows it as uploaded by you, /// not measured by a runner, and sets no check from it Upload { file: std::path::PathBuf, #[arg(long)] bookmark: Option, /// A change's full hash #[arg(long, conflicts_with = "bookmark")] change: Option, }, } #[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, /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory #[arg(long)] timings: bool, }, /// 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, /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts) #[arg(long = "job", value_name = "NAME")] jobs: Vec, /// 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 }, /// A report a job published: its report.toml; --list for what it holds, --file for one file Report { number: i64, job: String, #[command(flatten)] pick: ReportPick, }, /// Run a finished run's state again; with --job, only that job (and the /// jobs that depend on it) in the same run Rerun { number: i64, #[arg(long)] job: Option, }, /// Cancel a run still queued or running; its running jobs are stopped Cancel { number: i64 }, /// Approve a job that waits for a person (oxygenflow#57) Approve { number: i64, #[arg(long)] job: String, }, /// Reject a job that waits for a person: it ends cancelled Reject { number: i64, #[arg(long)] job: String, }, } /// Which report of a job, and what of it to show. #[derive(clap::Args)] struct ReportPick { /// Which report, when the job published more than one #[arg(long)] name: Option, /// What it holds: its metrics, context and files #[arg(long, conflicts_with = "file")] list: bool, /// One file of it (`data/frames.csv`), as published #[arg(long, value_name = "PATH")] file: Option, /// Write the file here instead of to stdout #[arg(long, short, value_name = "FILE", requires = "file")] output: Option, } #[derive(Subcommand)] enum ReportCmd { /// The newest run of each report, newest first List { /// Only runs on this bookmark #[arg(long)] bookmark: Option, }, /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names Show { report: String, #[arg(long, conflicts_with = "bookmark")] id: Option, #[arg(long)] bookmark: Option, /// What it holds: its metrics, context and files #[arg(long, conflicts_with = "file")] list: bool, /// One file of it, as published #[arg(long, value_name = "PATH")] file: Option, /// Write the file here instead of to stdout #[arg(long, short, value_name = "FILE", requires = "file")] output: Option, }, } #[derive(Subcommand)] enum TagCmd { /// Tags, newest name first List, /// Tag the state of a bookmark, tag or change, signed by the hub as your /// delegate (as `oxy tag create` and a push would be) Create { name: String, /// What to tag (default: the default bookmark) #[arg(long)] target: Option, #[arg(long, short)] message: Option, }, /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on /// their next fetch, and the name is never used again. Refused while a /// release uses the tag Delete { name: String, /// Why, recorded with the withdrawal #[arg(long, short)] reason: Option, }, } #[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}") }; // 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::Report { cmd } => report(&c, &t, cmd, json), Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => { let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?; let mut body = serde_json::json!({ "content": content }); if let Some(b) = bookmark { body["bookmark"] = b.into(); } if let Some(ch) = change { body["change"] = ch.into(); } let base = t.repo_path()?; let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?; if json { println!("{}", serde_json::to_string(&r)?); } else { let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into()); let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() }; println!( "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}", ui::ok("✔"), r.lines_hit, r.lines_found, r.files, ui::dim(&r.url) ); if r.dropped > 0 { println!(" {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped))); } } Ok(0) } Cmd::Release { cmd } => release(&c, &t, cmd, json), Cmd::Tag { cmd } => tag(&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), Cmd::Agent { cmd } => agent(&c, cmd, json), Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json), Cmd::Drop { cmd } => drop_cmd(&c, cmd, json), } } /// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit. fn switch(v: Option<&str>) -> Result>> { Ok(match v { None => None, Some("on") => Some(Some(true)), Some("off") => Some(Some(false)), Some("inherit") => Some(None), Some(other) => bail!("{other:?}: say on, off or inherit"), }) } /// A scope as `oh runner-updates set` takes it, resolved to (scope, key). fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> { let (kind, name) = scope.split_once(':').unwrap_or((scope, "")); Ok(match kind { "site" if name.is_empty() => ("site".into(), String::new()), "owner" if !name.is_empty() => ("owner".into(), name.into()), "group" => { let g = all .groups .iter() .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name) .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?; ("group".into(), g.id.to_string()) } "runner" => { let r = all .runners .iter() .find(|r| r.id.to_string() == name || r.name == name) .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?; ("runner".into(), r.id.to_string()) } _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"), }) } fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result { let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?; match cmd { RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?), RunnerUpdatesCmd::Show => { println!( "{} {}", ui::strong("Builds from"), if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() } ); for h in &all.holds { println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why); } for s in &all.settings { let mut said = vec![]; if let Some(u) = s.updates { said.push(format!("updates {}", if u { "on" } else { "off" })); } if let Some(ch) = &s.channel { said.push(format!("channel {ch}")); } if let Some(w) = &s.window { said.push(format!("window {w} UTC")); } if let Some(d) = s.dry_run { said.push(format!("dry run {}", if d { "on" } else { "off" })); } let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) }; println!(" {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") }); } for g in &all.groups { let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) }; let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}")); if let Some(w) = g.wave { what.push_str(&format!(", wave {w}")); } println!( " group {} ({what}): {}", ui::strong(&g.name), if g.members.is_empty() { "none".into() } else { g.members.join(", ") } ); } for r in &all.runners { let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") }; println!(" {:<16} flow {:<22} {} ({}) {}", r.name, r.version, on, r.from[0], ui::dim(&r.now)); } } RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => { let (scope, key) = update_scope(&scope, &all)?; let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting { scope: scope.clone(), key: key.clone(), ..Default::default() }); if let Some(u) = switch(updates.as_deref())? { s.updates = u; } if let Some(d) = switch(dry_run.as_deref())? { s.dry_run = d; } if let Some(ch) = channel { s.channel = Some(ch).filter(|c| c != "inherit"); } if let Some(w) = window { s.window = Some(w).filter(|w| w != "inherit"); } let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?; println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved")); } RunnerUpdatesCmd::Lift { version } => { c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?; println!("{} flow {version} is offered again where the settings say so", ui::ok("✔")); } } Ok(0) } /// A drop's id from an id or its address (`https://hub/owner/drops/ID`). fn drop_id(s: &str) -> Result { let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string(); if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) { bail!("{s:?} is not a drop's id or address"); } Ok(id.to_ascii_lowercase()) } fn drop_line(d: &hub_api::Drop) -> String { let title = if d.title.is_empty() { d.files.first().map(|f| f.name.clone()).unwrap_or_else(|| d.id.clone()) } else { d.title.clone() }; let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect(); format!( "{} {} {}{}", ui::dim(&d.id), ui::strong(&title), if d.visibility == "secret" { ui::warn("secret ") } else { String::new() }, ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms))) ) } fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result { match cmd { DropCmd::Create { files, secret, description, title } => { let mut out = Vec::with_capacity(files.len()); for f in &files { let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?; let content = std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?; out.push(hub_api::NewDropFile { name: name.to_string(), content }); } let new = hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out }; let d: hub_api::Drop = c.send("POST", "/drops", &new)?; if json { println!("{}", serde_json::to_string(&d)?); } else { println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url)); println!(" {}", ui::dim(&format!("oxy clone {}", d.clone_url))); } } DropCmd::List { user } => { let path = match &user { Some(u) => format!("/users/{}/drops", enc(u)), None => "/drops".to_string(), }; if json { println!("{}", c.get_text(&path)?); return Ok(0); } let list: Vec = c.get(&path)?; if list.is_empty() { println!("{}", ui::dim("No drops.")); } for d in &list { println!("{}", drop_line(d)); } } DropCmd::View { id, file } => { let path = format!("/drops/{}", drop_id(&id)?); if json && file.is_none() { println!("{}", c.get_text(&path)?); return Ok(0); } let d: hub_api::Drop = c.get(&path)?; if let Some(name) = file { let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?; let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?; print!("{content}"); return Ok(0); } println!("{}", drop_line(&d)); if !d.description.is_empty() { println!("{}", d.description); } println!("{}", ui::kv("url", &d.url)); println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url))); for f in &d.files { println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size))); match &f.content { Some(text) => { print!("{text}"); if !text.ends_with('\n') && !text.is_empty() { println!(); } } None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))), } } } DropCmd::Delete { id } => { let id = drop_id(&id)?; c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?; println!("{} drop {id}", ui::ok("✔ deleted")); } } Ok(0) } /// `30d`, `12h`, `90m` in milliseconds. fn duration_ms(s: &str) -> Result { let s = s.trim(); let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len())); let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?; let per = match unit { "d" => 86_400_000, "h" => 3_600_000, "m" => 60_000, _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"), }; if n <= 0 { bail!("a grant must last some time"); } Ok(n * per) } fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result { use oxy_core::cert::{Grant, SignedGrant}; use oxy_core::identity::{Identity, Scope}; match cmd { AgentCmd::Grant { name, scope, lasts } => { let home = oxy_core::repo::default_home(); let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| { format!( "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell", home.display() ) })?; let me: serde_json::Value = c.get("/user")?; let username = me["username"].as_str().context("the hub did not say who you are")?; let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?; let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?; let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64; let grant = Grant { grantor: me_id.hash(), subject: format!("agent:{name}@{username}"), issuer: hub.hash(), scope, not_before: (now - 60_000) as u64, expires: (now + duration_ms(&lasts)?) as u64, }; let signed = SignedGrant::sign(grant, &me_id, &sk); let r: serde_json::Value = c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?; if json { println!("{r}"); return Ok(0); } println!( "{} {} to act for you as {} ({}), until {}", ui::ok("✔ granted"), ui::strong(&name), r["subject"].as_str().unwrap_or(""), r["scope"].as_str().unwrap_or(""), ui::date(r["expires_ms"].as_i64().unwrap_or(0)) ); println!(" token (shown once): {}", r["token"].as_str().unwrap_or("")); println!( " {}", ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless") ); println!(" {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"]))); Ok(0) } AgentCmd::List => { let grants: Vec = c.get("/agents/grants")?; if json { println!("{}", serde_json::to_string(&grants)?); return Ok(0); } if grants.is_empty() { println!("{}", ui::dim("no agent grants")); } let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64; for g in grants { let state = if g["revoked_ms"].is_i64() { ui::bad("revoked") } else if g["expires_ms"].as_i64().unwrap_or(0) <= now { ui::dim("ended") } else { ui::ok("live") }; let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into()); println!( "#{:<4} {:<8} {} · {} · until {} · {}", g["id"], state, ui::strong(g["subject"].as_str().unwrap_or("")), g["scope"].as_str().unwrap_or(""), ui::date(g["expires_ms"].as_i64().unwrap_or(0)), ui::dim(&used) ); } Ok(0) } AgentCmd::Revoke { id } => { c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?; println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked")); Ok(0) } } } 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, 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}/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, limit } => { let path = format!("{base}/proposals?state={state}&limit={limit}"); 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, ..Default::default() }; 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, when_ready: true, off, .. } => { let path = format!("{base}/proposals/{number}/auto-land"); let p: Proposal = if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? }; if json { println!("{}", serde_json::to_string(&p)?); } else if p.landed.is_some() { println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target); } else if p.auto_land.is_some() { println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number); } else { println!("{} #{} will not land by itself", ui::ok("✔"), p.number); } } ProposalCmd::Land { number, over_checks, .. } => { let body = match &over_checks { Some(r) => serde_json::json!({ "over_checks": r }), None => serde_json::json!({}), }; let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target); } } ProposalCmd::Close { number, message } => { if let Some(body) = message { c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?; } let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title); } } ProposalCmd::Reopen { number } => { let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?; if json { println!("{}", serde_json::to_string(&p)?); } else { println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title); } } ProposalCmd::Ready { number, undo } => { let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() }; let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?; if json { println!("{}", serde_json::to_string(&p)?); } else if undo { println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title); } else { println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title); } } 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, timings: bool) { 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}"))); // Why a queued job no runner can take waits (oxygenhub#28), and // why a job ran where it did (oxygenflow#42). if j.status == "queued" && !j.waiting.is_empty() { println!(" {}", ui::warn(&format!("waiting: {}", j.waiting))); } else if !j.placed.is_empty() { println!(" {}", ui::dim(&format!("placed: {}", j.placed))); } if timings { let t = timing_line(j); if !t.is_empty() { println!(" {}", ui::dim(&t)); } } } if !r.error.is_empty() { println!("{}", ui::bad(&r.error)); } println!("{}", ui::dim(&r.url)); } /// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s". fn took(ms: i64) -> String { match ms { ..=999 => format!("{ms} ms"), 1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0), _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000), } } /// MiB as a person reads them. fn mib(m: i64) -> String { if m >= 1024 { format!("{:.1} GiB", m as f64 / 1024.0) } else { format!("{m} MiB") } } /// Where a job's time went (oxygenhub#348): its wait for a runner, each /// phase its runner reported, and the most disk and memory it took. fn timing_line(j: &FlowJob) -> String { let mut parts = vec![]; if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) { parts.push(format!("waited {}", took((s - q).max(0)))); } parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64)))); let peaks: Vec = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)] .into_iter() .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m)))) .collect(); if !peaks.is_empty() { parts.push(format!("peak {}", peaks.join(", "))); } parts.join(" · ") } /// A report's path, its segments encoded and its slashes kept. fn enc_path(path: &str) -> String { path.split('/').map(enc).collect::>().join("/") } /// `oh run report` and `oh report show`: the report at `at` (JSON), whose /// files are at `files(path)`. By default its report.toml; with `list` /// what it holds; with `file` one file, to stdout or `output`. fn show_report( c: &Client, at: &str, files: impl Fn(&str) -> String, list: bool, file: Option, output: Option, json: bool, ) -> Result<()> { use std::io::Write; if let Some(path) = file { let bytes = c.get_bytes(&files(&path))?; match output { Some(out) => { std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?; eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display()); } None => std::io::stdout().write_all(&bytes)?, } return Ok(()); } if json { println!("{}", c.get_text(at)?); return Ok(()); } if !list { std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?; return Ok(()); } let r: Report = c.get(at)?; print_report(&r); if r.files_expired_ms.is_some() { println!("{}", ui::warn("its files expired under retention; its metrics stay")); } for f in &r.manifest { println!(" {:>10} {}", ui::dim(&f.size.to_string()), f.path); } println!("{}", ui::dim(&r.url)); Ok(()) } /// A report's heading, metrics and context. fn print_report(r: &Report) { let from = match r.run { Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark), None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }), }; println!( "{} {} {}", ui::strong(&r.name), ui::dim(&format!("{} · {:?}", r.kind, r.title)), ui::dim(&format!("· {from} · {} files", r.files)) ); if !r.summary.is_empty() { println!(" {}", r.summary); } for m in &r.metrics { let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) }; let mut notes = vec![]; if !m.better.is_empty() { notes.push(format!("{} is better", m.better)); } if let Some(a) = m.fail_above { notes.push(format!("fails above {a}")); } if let Some(b) = m.fail_below { notes.push(format!("fails below {b}")); } let notes = if notes.is_empty() { String::new() } else { format!(" ({})", notes.join(", ")) }; println!(" {} {}{unit}{}", m.key, m.value, ui::dim(¬es)); } if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) { let line: Vec = ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect(); println!(" {}", ui::dim(&line.join(" "))); } } /// `oh report …` (oxygenhub#348). fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result { let base = t.repo_path()?; match cmd { ReportCmd::List { bookmark } => { let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default()); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let list: Vec = c.get(&path)?; if list.is_empty() { println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`.")); } for r in &list { print_report(r); } } ReportCmd::Show { report, id, bookmark, list, file, output } => { let at = format!("{base}/reports/{}", enc(&report)); let query = match (id, bookmark) { (Some(id), _) => format!("?id={id}"), (None, Some(b)) => format!("?bookmark={}", enc(&b)), (None, None) => String::new(), }; let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path)); show_report(c, &format!("{at}{query}"), files, list, file, output, json)?; } } Ok(0) } fn live(status: &str) -> bool { matches!(status, "queued" | "running") } /// `oh run approve|reject N --job NAME` (oxygenflow#57). fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> { let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?; if json { println!("{done}"); } else { println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or("")); } Ok(()) } 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 { let shown = format!("{}\u{0}{}", j.status, j.waiting); if seen.get(&j.name) != Some(&shown) { println!("{} {}", ui::status(&j.status), j.name); if j.status == "queued" && !j.waiting.is_empty() { println!(" {}", ui::warn(&format!("waiting: {}", j.waiting))); } seen.insert(j.name.clone(), shown); } } } 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, timings } => { let path = format!("{base}/flow/runs/{number}"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } print_run(&c.get(&path)?, timings); } RunCmd::Start { bookmark, change, jobs, watch: follow } => { let mut body = match (bookmark, change) { (_, Some(ch)) => serde_json::json!({ "change": ch }), (Some(b), None) => serde_json::json!({ "bookmark": b }), (None, None) => serde_json::json!({}), }; if !jobs.is_empty() { body["jobs"] = serde_json::json!(jobs); } 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::Report { number, job, pick } => { let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job)); let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default(); let files = |path: &str| format!("{at}/{}{query}", enc_path(path)); show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?; } RunCmd::Rerun { number, job: Some(job) } => { let queued: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?; if json { println!("{queued}"); } else { let n = queued["queued"].as_i64().unwrap_or(1); let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() }; println!("{} queued {job} of run #{number} again{with}", ui::ok("✔")); } } RunCmd::Rerun { number, job: None } => { 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::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?, RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?, 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, archived } => { let path = format!("{base}/{number}"); let cards = format!("{path}/cards?archived=true"); if json { println!("{}", c.get_text(if archived { &cards } else { &path })?); return Ok(0); } let mut b: hub_api::Board = c.get(&path)?; if archived { b.columns = c.get(&cards)?; } 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)) }; let mut tags: Vec = card.labels.iter().map(|l| format!("[{l}]")).collect(); tags.extend(card.assignees.iter().map(|a| format!("@{a}"))); let tags = if tags.is_empty() { String::new() } else { format!(" {}", ui::dim(&tags.join(" "))) }; println!(" {} {what}{st} {}{tags}", 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, from, except, state, dry_run } } => match (card, from) { (Some(card), None) => { c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?; println!("{} card {card} moved to {column}", ui::ok("✔")); } (None, Some(from)) => { let r: hub_api::CardsMoved = c.send( "POST", &format!("{base}/{number}/cards/move"), &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run }, )?; if json { println!("{}", serde_json::to_string(&r)?); return Ok(0); } let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() }; for m in &r.moved { println!(" {} {} {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title)); } let verb = if dry_run { "would move" } else { "moved" }; println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len()); } _ => bail!("name a card, or --from COLUMN to move every card of a column"), }, ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => { let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) { None => None, Some(d) => Some(d.parse::().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?), }; let r: hub_api::CardsArchived = c.send( "POST", &format!("{base}/{number}/cards/archive"), &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run }, )?; if json { println!("{}", serde_json::to_string(&r)?); return Ok(0); } let verb = if dry_run { "would archive" } else { "archived" }; for a in &r.archived { let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() }; println!(" {verb} {name} {}", ui::dim(&a.title)); } println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len()); } ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => { c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?; println!("{} card {card} restored", 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 tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result { let base = t.repo_path()?; match cmd { TagCmd::List => { let path = format!("{base}/tags"); if json { println!("{}", c.get_text(&path)?); return Ok(0); } let tags: Vec = c.get(&path)?; if tags.is_empty() { println!("{}", ui::dim("no tags")); } for t in tags { let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect(); let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into()); println!("{} {} {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer)); } } TagCmd::Create { name, target, message } => { let new = hub_api::NewTag { name, target, message }; let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?; if json { println!("{}", serde_json::to_string(&made)?); } else { println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len()))); } } TagCmd::Delete { name, reason } => { let reason = reason.unwrap_or_default(); c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?; if json { println!("{}", serde_json::json!({ "withdrawn": name })); } else { println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)")); } } } 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) } #[cfg(test)] mod tests { #[test] fn job_timings_and_report_commands_read_plainly() { use clap::Parser; let job = hub_api::FlowJob { name: "perf".into(), status: "passed".into(), depends_on: vec![], runner: "earth-1".into(), exit_code: Some(0), error: String::new(), started_ms: Some(13_000), finished_ms: Some(200_000), log_lines: 10, waiting: String::new(), placed: String::new(), approval: String::new(), queued_ms: Some(1_000), ready_ms: Some(12_500), phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }], peak_disk_mib: Some(2150), peak_memory_mib: Some(900), }; assert_eq!(super::timing_line(&job), "waited 12.0 s · image 850 ms · run 2 min 5 s · peak disk 2.1 GiB, memory 900 MiB"); let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job }; assert_eq!(super::timing_line(&bare), ""); assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv"); let cli = super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap(); let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") }; assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false)); assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other"); assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file"); let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap(); assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } })); assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok()); } #[test] fn runner_update_scopes_resolve_by_name_or_id() { let all = hub_api::RunnerUpdates { repo: String::new(), settings: vec![], groups: vec![hub_api::RunnerGroup { id: 4, owner: "acme".into(), name: "canary".into(), percent: None, members: vec![], wave: None, }], runners: vec![], holds: vec![], }; assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new())); assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string())); for g in ["group:canary", "group:acme/canary", "group:4"] { assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}"); } assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner")); assert!(update_scope("everyone", &all).is_err()); assert_eq!(switch(Some("inherit")).unwrap(), Some(None)); assert!(switch(Some("yes")).is_err()); } use super::*; /// `oh drop` (oxygenhub#279): its commands and flags parse as the /// help says, and a drop is named by its id or its address. #[test] fn drop_commands_parse() { let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap(); match cli.cmd { Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => { assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]); assert!(secret); assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes"))); } _ => panic!("not drop create"), } assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file"); match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() { Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => { assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05"))); assert!(channel.is_none() && dry_run.is_none()); } _ => panic!("not runner-updates set"), } assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None })); match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() { Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)), _ => panic!("not drop list"), } match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd { Cmd::Drop { cmd: DropCmd::View { id, file } } => { assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt"))) } _ => panic!("not drop view"), } assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } })); assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567"); assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567"); assert!(drop_id("andy/notes").is_err()); } }