OXYGENHUB

Coverage / src/cli/proposal.rs 0.0%

0 of 221 lines run, 0 of 48 functions · run #427 on main · run missed

1
//! Thin clients of a hub's proposals (hub spec §7): `oxy proposal show`,
2
//! `oxy proposal land`, and `oxy seal --proposal`. The hub's JSON is read
3
//! by field name (hub-api `Proposal`); nothing here needs the hub crate.
4
5
use super::{open, ui};
6
use anyhow::{anyhow, Context, Result};
7
use oxy_core::hash::ChangeHash;
8
use oxy_core::repo::Repo;
9
use serde_json::Value;
10
11
/// `https://hub/{owner}/{name}/proposal/{n}` (or the API URL) to the API
12
/// URL and the repository's clone URL.
130×
pub fn api_url(url: &str) -> Result<(String, String)> {
140×
    let url = url.trim_end_matches('/');
150×
    if url.contains("/api/v1/repos/") {
160×
        let (base, rest) = url.split_once("/api/v1/repos/").unwrap();
170×
        let mut parts = rest.split('/');
180×
        let (owner, name) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
190×
        return Ok((url.to_string(), format!("{base}/{owner}/{name}")));
200×
    }
210×
    let (repo_url, number) = url
220×
        .rsplit_once("/proposal/")
230×
        .ok_or_else(|| anyhow!("{url} is not a proposal URL (…/OWNER/NAME/proposal/N)"))?;
240×
    let (base, slug) = repo_url
250×
        .rsplit_once('/')
260×
        .and_then(|(b, n)| b.rsplit_once('/').map(|(bb, o)| (bb, format!("{o}/{n}"))))
270×
        .ok_or_else(|| anyhow!("{url} is not a proposal URL"))?;
280×
    Ok((
290×
        format!("{base}/api/v1/repos/{slug}/proposals/{number}"),
300×
        repo_url.to_string(),
310×
    ))
320×
}
33
340×
pub fn fetch(repo: &Repo, url: &str) -> Result<(Value, String)> {
350×
    let (api, repo_url) = api_url(url)?;
360×
    let options = repo.options_for_url(&repo_url);
370×
    let body = oxy_core::protocol::http_get(&api, &options).map_err(|e| anyhow!("{e}"))?;
380×
    let v: Value = serde_json::from_slice(&body).context("the hub did not answer with JSON")?;
390×
    Ok((v, repo_url))
400×
}
41
420×
fn hashes(v: &Value, key: &str) -> Vec<ChangeHash> {
430×
    v.get(key)
440×
        .and_then(Value::as_array)
450×
        .map(|a| {
460×
            a.iter()
470×
                .filter_map(|x| x.as_str().and_then(ChangeHash::from_hex))
480×
                .collect()
490×
        })
500×
        .unwrap_or_default()
510×
}
52
530×
fn change_hashes(v: &Value) -> Vec<ChangeHash> {
540×
    v.get("changes")
550×
        .and_then(Value::as_array)
560×
        .map(|a| {
570×
            a.iter()
580×
                .filter_map(|c| {
590×
                    c.get("hash")
600×
                        .and_then(Value::as_str)
610×
                        .and_then(ChangeHash::from_hex)
620×
                })
630×
                .collect()
640×
        })
650×
        .unwrap_or_default()
660×
}
67
680×
fn text<'a>(v: &'a Value, key: &str) -> &'a str {
690×
    v.get(key).and_then(Value::as_str).unwrap_or("")
700×
}
71
720×
pub fn show(url: &str, as_json: bool) -> Result<i32> {
730×
    let repo = open()?;
740×
    let (v, _) = fetch(&repo, url)?;
750×
    if as_json {
760×
        println!("{v}");
770×
        return Ok(0);
780×
    }
790×
    println!(
80
        "{} #{} {}",
810×
        ui::done("Proposal"),
820×
        v.get("number").and_then(Value::as_i64).unwrap_or(0),
830×
        ui::bookmark(text(&v, "title"))
84
    );
850×
    println!("{}", ui::kv("state", text(&v, "state")));
860×
    println!("{}", ui::kv("target", ui::bookmark(text(&v, "target"))));
870×
    println!("{}", ui::kv("author", ui::author(text(&v, "author"))));
880×
    let changes = v
890×
        .get("changes")
900×
        .and_then(Value::as_array)
910×
        .cloned()
920×
        .unwrap_or_default();
930×
    println!("{}", ui::kv("changes", changes.len().to_string()));
940×
    for c in &changes {
950×
        println!(
960×
            "  {} {}",
970×
            ui::hash(&text(c, "hash")[..12.min(text(c, "hash").len())]),
980×
            text(c, "message").lines().next().unwrap_or("")
990×
        );
1000×
    }
1010×
    if v.get("conflicted")
1020×
        .and_then(Value::as_bool)
1030×
        .unwrap_or(false)
1040×
    {
1050×
        println!("{}", ui::warn("landing would carry conflicts"));
1060×
    }
1070×
    if let Some(blockers) = v.get("blockers").and_then(Value::as_array) {
1080×
        for b in blockers {
1090×
            println!("  {} {}", ui::warn("blocked:"), b.as_str().unwrap_or(""));
1100×
        }
1110×
    }
1120×
    let approvals = v
1130×
        .get("approvals")
1140×
        .and_then(Value::as_array)
1150×
        .cloned()
1160×
        .unwrap_or_default();
1170×
    for a in &approvals {
1180×
        let mark = if a.get("sealed").and_then(Value::as_bool).unwrap_or(false) {
1190×
            ui::done("approved")
120
        } else {
1210×
            ui::warn("pending seal")
122
        };
1230×
        println!("  {mark} {}", text(a, "account"));
124
    }
1250×
    Ok(0)
1260×
}
127
128
/// Seal every change of the proposal with your key and push the seal to
129
/// the hub, so your approval counts (hub spec §7.4).
1300×
pub fn seal(url: &str, as_json: bool) -> Result<i32> {
1310×
    let repo = open()?;
1320×
    let (v, repo_url) = fetch(&repo, url)?;
1330×
    let hashes = change_hashes(&v);
1340×
    if hashes.is_empty() {
1350×
        anyhow::bail!("the proposal has no changes to seal");
1360×
    }
1370×
    ensure_changes(&repo, &repo_url, &hashes, &hashes)?;
1380×
    let mut refs = Vec::new();
1390×
    for chunk in hashes.chunks(oxy_core::attest::MAX_SEAL_HASHES) {
1400×
        refs.push(repo.seal(chunk)?);
141
    }
1420×
    let remote = repo.remote_for_url(&repo_url).ok_or_else(|| {
1430×
        anyhow!("no remote is configured for {repo_url}; add one with `oxy remote add`")
1440×
    })?;
1450×
    repo.push_seals(&remote, &refs)?;
1460×
    if as_json {
1470×
        let list: Vec<String> = hashes
1480×
            .iter()
1490×
            .map(|h| format!("\"{}\"", h.to_hex()))
1500×
            .collect();
1510×
        println!("{{\"sealed\":[{}],\"pushed\":true}}", list.join(","));
152
    } else {
1530×
        println!(
154
            "{} {} change{} of the proposal and pushed the seal to {remote}",
1550×
            ui::done("Sealed"),
1560×
            hashes.len(),
1570×
            if hashes.len() == 1 { "" } else { "s" }
158
        );
159
    }
1600×
    Ok(0)
1610×
}
162
163
/// Fetch the proposal's changes (and anything they need) from the hub
164
/// into the local store.
1650×
fn ensure_changes(
1660×
    repo: &Repo,
1670×
    repo_url: &str,
1680×
    want: &[ChangeHash],
1690×
    _changes: &[ChangeHash],
1700×
) -> Result<()> {
1710×
    let missing: Vec<ChangeHash> = want
1720×
        .iter()
1730×
        .copied()
1740×
        .filter(|h| !repo.store().has(h))
1750×
        .collect();
1760×
    if missing.is_empty() {
1770×
        return Ok(());
1780×
    }
1790×
    let (_, remote) = repo.open_remote_at(repo_url)?;
1800×
    let view = repo.view()?;
1810×
    let have = repo.known_heads(&view)?;
1820×
    let needed = remote.negotiate(&have, want)?;
1830×
    let bundle = remote.fetch(&needed, repo.config.max_blob)?;
1840×
    repo.import_bundle(&bundle, false)?;
1850×
    Ok(())
1860×
}
187
188
/// Land the proposal from this client: fetch its changes, set the target
189
/// bookmark to the projected heads, and push with your own key (hub spec
190
/// §7.6).
1910×
pub fn land(url: &str, force: bool) -> Result<i32> {
1920×
    let repo = open()?;
1930×
    let (v, repo_url) = fetch(&repo, url)?;
1940×
    let state = text(&v, "state");
1950×
    if state != "open" && !force {
1960×
        anyhow::bail!("the proposal is {state}, not open (use --force to land anyway)");
1970×
    }
1980×
    if !v.get("landable").and_then(Value::as_bool).unwrap_or(false) && !force {
1990×
        let blockers: Vec<String> = v
2000×
            .get("blockers")
2010×
            .and_then(Value::as_array)
2020×
            .map(|a| {
2030×
                a.iter()
2040×
                    .filter_map(|b| b.as_str().map(String::from))
2050×
                    .collect()
2060×
            })
2070×
            .unwrap_or_default();
2080×
        anyhow::bail!(
209
            "the hub says the proposal cannot land yet: {} (use --force to land anyway)",
2100×
            blockers.join("; ")
211
        );
2120×
    }
2130×
    let target = text(&v, "target").to_string();
2140×
    let heads = hashes(&v, "projected_heads");
2150×
    if heads.is_empty() {
2160×
        anyhow::bail!("the hub has not computed the projected state yet; try again shortly");
2170×
    }
2180×
    ensure_changes(&repo, &repo_url, &heads, &change_hashes(&v))?;
2190×
    let remote = repo.remote_for_url(&repo_url).ok_or_else(|| {
2200×
        anyhow!("no remote is configured for {repo_url}; add one with `oxy remote add`")
2210×
    })?;
222
    // Bring the target bookmark up to date first, so the push is a fast-forward.
2230×
    repo.fetch(&remote)?;
2240×
    repo.bookmark_set(&target, &heads)?;
2250×
    let results = repo.push_bookmark(&remote, &target, false)?;
2260×
    for r in &results {
2270×
        if r.ok {
2280×
            println!(
2290×
                "{} {}/{} - landed proposal",
2300×
                ui::done("Pushed"),
2310×
                remote,
2320×
                r.name
2330×
            );
2340×
        } else {
2350×
            println!(
2360×
                "{} {}/{} - {}",
2370×
                ui::warn("Rejected"),
2380×
                remote,
2390×
                r.name,
2400×
                r.reason
2410×
            );
2420×
        }
243
    }
2440×
    Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 })
2450×
}