//! Thin clients of a hub's proposals (hub spec §7): `oxy proposal show`, //! `oxy proposal land`, and `oxy seal --proposal`. The hub's JSON is read //! by field name (hub-api `Proposal`); nothing here needs the hub crate. use super::{open, ui}; use anyhow::{anyhow, Context, Result}; use oxy_core::hash::ChangeHash; use oxy_core::repo::Repo; use serde_json::Value; /// `https://hub/{owner}/{name}/proposal/{n}` (or the API URL) to the API /// URL and the repository's clone URL. pub fn api_url(url: &str) -> Result<(String, String)> { let url = url.trim_end_matches('/'); if url.contains("/api/v1/repos/") { let (base, rest) = url.split_once("/api/v1/repos/").unwrap(); let mut parts = rest.split('/'); let (owner, name) = (parts.next().unwrap_or(""), parts.next().unwrap_or("")); return Ok((url.to_string(), format!("{base}/{owner}/{name}"))); } let (repo_url, number) = url .rsplit_once("/proposal/") .ok_or_else(|| anyhow!("{url} is not a proposal URL (…/OWNER/NAME/proposal/N)"))?; let (base, slug) = repo_url .rsplit_once('/') .and_then(|(b, n)| b.rsplit_once('/').map(|(bb, o)| (bb, format!("{o}/{n}")))) .ok_or_else(|| anyhow!("{url} is not a proposal URL"))?; Ok(( format!("{base}/api/v1/repos/{slug}/proposals/{number}"), repo_url.to_string(), )) } pub fn fetch(repo: &Repo, url: &str) -> Result<(Value, String)> { let (api, repo_url) = api_url(url)?; let options = repo.options_for_url(&repo_url); let body = oxy_core::protocol::http_get(&api, &options).map_err(|e| anyhow!("{e}"))?; let v: Value = serde_json::from_slice(&body).context("the hub did not answer with JSON")?; Ok((v, repo_url)) } fn hashes(v: &Value, key: &str) -> Vec { v.get(key) .and_then(Value::as_array) .map(|a| { a.iter() .filter_map(|x| x.as_str().and_then(ChangeHash::from_hex)) .collect() }) .unwrap_or_default() } fn change_hashes(v: &Value) -> Vec { v.get("changes") .and_then(Value::as_array) .map(|a| { a.iter() .filter_map(|c| { c.get("hash") .and_then(Value::as_str) .and_then(ChangeHash::from_hex) }) .collect() }) .unwrap_or_default() } fn text<'a>(v: &'a Value, key: &str) -> &'a str { v.get(key).and_then(Value::as_str).unwrap_or("") } pub fn show(url: &str, as_json: bool) -> Result { let repo = open()?; let (v, _) = fetch(&repo, url)?; if as_json { println!("{v}"); return Ok(0); } println!( "{} #{} {}", ui::done("Proposal"), v.get("number").and_then(Value::as_i64).unwrap_or(0), ui::bookmark(text(&v, "title")) ); println!("{}", ui::kv("state", text(&v, "state"))); println!("{}", ui::kv("target", ui::bookmark(text(&v, "target")))); println!("{}", ui::kv("author", ui::author(text(&v, "author")))); let changes = v .get("changes") .and_then(Value::as_array) .cloned() .unwrap_or_default(); println!("{}", ui::kv("changes", changes.len().to_string())); for c in &changes { println!( " {} {}", ui::hash(&text(c, "hash")[..12.min(text(c, "hash").len())]), text(c, "message").lines().next().unwrap_or("") ); } if v.get("conflicted") .and_then(Value::as_bool) .unwrap_or(false) { println!("{}", ui::warn("landing would carry conflicts")); } if let Some(blockers) = v.get("blockers").and_then(Value::as_array) { for b in blockers { println!(" {} {}", ui::warn("blocked:"), b.as_str().unwrap_or("")); } } let approvals = v .get("approvals") .and_then(Value::as_array) .cloned() .unwrap_or_default(); for a in &approvals { let mark = if a.get("sealed").and_then(Value::as_bool).unwrap_or(false) { ui::done("approved") } else { ui::warn("pending seal") }; println!(" {mark} {}", text(a, "account")); } Ok(0) } /// Seal every change of the proposal with your key and push the seal to /// the hub, so your approval counts (hub spec §7.4). pub fn seal(url: &str, as_json: bool) -> Result { let repo = open()?; let (v, repo_url) = fetch(&repo, url)?; let hashes = change_hashes(&v); if hashes.is_empty() { anyhow::bail!("the proposal has no changes to seal"); } ensure_changes(&repo, &repo_url, &hashes, &hashes)?; let mut refs = Vec::new(); for chunk in hashes.chunks(oxy_core::attest::MAX_SEAL_HASHES) { refs.push(repo.seal(chunk)?); } let remote = repo.remote_for_url(&repo_url).ok_or_else(|| { anyhow!("no remote is configured for {repo_url}; add one with `oxy remote add`") })?; repo.push_seals(&remote, &refs)?; if as_json { let list: Vec = hashes .iter() .map(|h| format!("\"{}\"", h.to_hex())) .collect(); println!("{{\"sealed\":[{}],\"pushed\":true}}", list.join(",")); } else { println!( "{} {} change{} of the proposal and pushed the seal to {remote}", ui::done("Sealed"), hashes.len(), if hashes.len() == 1 { "" } else { "s" } ); } Ok(0) } /// Fetch the proposal's changes (and anything they need) from the hub /// into the local store. fn ensure_changes( repo: &Repo, repo_url: &str, want: &[ChangeHash], _changes: &[ChangeHash], ) -> Result<()> { let missing: Vec = want .iter() .copied() .filter(|h| !repo.store().has(h)) .collect(); if missing.is_empty() { return Ok(()); } let (_, remote) = repo.open_remote_at(repo_url)?; let view = repo.view()?; let have = repo.known_heads(&view)?; let needed = remote.negotiate(&have, want)?; let bundle = remote.fetch(&needed, repo.config.max_blob)?; repo.import_bundle(&bundle, false)?; Ok(()) } /// Land the proposal from this client: fetch its changes, set the target /// bookmark to the projected heads, and push with your own key (hub spec /// §7.6). pub fn land(url: &str, force: bool) -> Result { let repo = open()?; let (v, repo_url) = fetch(&repo, url)?; let state = text(&v, "state"); if state != "open" && !force { anyhow::bail!("the proposal is {state}, not open (use --force to land anyway)"); } if !v.get("landable").and_then(Value::as_bool).unwrap_or(false) && !force { let blockers: Vec = v .get("blockers") .and_then(Value::as_array) .map(|a| { a.iter() .filter_map(|b| b.as_str().map(String::from)) .collect() }) .unwrap_or_default(); anyhow::bail!( "the hub says the proposal cannot land yet: {} (use --force to land anyway)", blockers.join("; ") ); } let target = text(&v, "target").to_string(); let heads = hashes(&v, "projected_heads"); if heads.is_empty() { anyhow::bail!("the hub has not computed the projected state yet; try again shortly"); } ensure_changes(&repo, &repo_url, &heads, &change_hashes(&v))?; let remote = repo.remote_for_url(&repo_url).ok_or_else(|| { anyhow!("no remote is configured for {repo_url}; add one with `oxy remote add`") })?; // Bring the target bookmark up to date first, so the push is a fast-forward. repo.fetch(&remote)?; repo.bookmark_set(&target, &heads)?; let results = repo.push_bookmark(&remote, &target, false)?; for r in &results { if r.ok { println!( "{} {}/{} - landed proposal", ui::done("Pushed"), remote, r.name ); } else { println!( "{} {}/{} - {}", ui::warn("Rejected"), remote, r.name, r.reason ); } } Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 }) }