OXYGENHUB
# 7bd805ffb418 oxygen / src / cli / proposal.rs
8.2 KiB · Rust · last changed Roadmap: phase D done 1 month ago source blame history raw
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.
13
pub fn api_url(url: &str) -> Result<(String, String)> {
14
    let url = url.trim_end_matches('/');
15
    if url.contains("/api/v1/repos/") {
16
        let (base, rest) = url.split_once("/api/v1/repos/").unwrap();
17
        let mut parts = rest.split('/');
18
        let (owner, name) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
19
        return Ok((url.to_string(), format!("{base}/{owner}/{name}")));
20
    }
21
    let (repo_url, number) = url
22
        .rsplit_once("/proposal/")
23
        .ok_or_else(|| anyhow!("{url} is not a proposal URL (…/OWNER/NAME/proposal/N)"))?;
24
    let (base, slug) = repo_url
25
        .rsplit_once('/')
26
        .and_then(|(b, n)| b.rsplit_once('/').map(|(bb, o)| (bb, format!("{o}/{n}"))))
27
        .ok_or_else(|| anyhow!("{url} is not a proposal URL"))?;
28
    Ok((
29
        format!("{base}/api/v1/repos/{slug}/proposals/{number}"),
30
        repo_url.to_string(),
31
    ))
32
}
33
34
pub fn fetch(repo: &Repo, url: &str) -> Result<(Value, String)> {
35
    let (api, repo_url) = api_url(url)?;
36
    let options = repo.options_for_url(&repo_url);
37
    let body = oxy_core::protocol::http_get(&api, &options).map_err(|e| anyhow!("{e}"))?;
38
    let v: Value = serde_json::from_slice(&body).context("the hub did not answer with JSON")?;
39
    Ok((v, repo_url))
40
}
41
42
fn hashes(v: &Value, key: &str) -> Vec<ChangeHash> {
43
    v.get(key)
44
        .and_then(Value::as_array)
45
        .map(|a| {
46
            a.iter()
47
                .filter_map(|x| x.as_str().and_then(ChangeHash::from_hex))
48
                .collect()
49
        })
50
        .unwrap_or_default()
51
}
52
53
fn change_hashes(v: &Value) -> Vec<ChangeHash> {
54
    v.get("changes")
55
        .and_then(Value::as_array)
56
        .map(|a| {
57
            a.iter()
58
                .filter_map(|c| {
59
                    c.get("hash")
60
                        .and_then(Value::as_str)
61
                        .and_then(ChangeHash::from_hex)
62
                })
63
                .collect()
64
        })
65
        .unwrap_or_default()
66
}
67
68
fn text<'a>(v: &'a Value, key: &str) -> &'a str {
69
    v.get(key).and_then(Value::as_str).unwrap_or("")
70
}
71
72
pub fn show(url: &str, as_json: bool) -> Result<i32> {
73
    let repo = open()?;
74
    let (v, _) = fetch(&repo, url)?;
75
    if as_json {
76
        println!("{v}");
77
        return Ok(0);
78
    }
79
    println!(
80
        "{} #{} {}",
81
        ui::done("Proposal"),
82
        v.get("number").and_then(Value::as_i64).unwrap_or(0),
83
        ui::bookmark(text(&v, "title"))
84
    );
85
    println!("{}", ui::kv("state", text(&v, "state")));
86
    println!("{}", ui::kv("target", ui::bookmark(text(&v, "target"))));
87
    println!("{}", ui::kv("author", ui::author(text(&v, "author"))));
88
    let changes = v
89
        .get("changes")
90
        .and_then(Value::as_array)
91
        .cloned()
92
        .unwrap_or_default();
93
    println!("{}", ui::kv("changes", changes.len().to_string()));
94
    for c in &changes {
95
        println!(
96
            "  {} {}",
97
            ui::hash(&text(c, "hash")[..12.min(text(c, "hash").len())]),
98
            text(c, "message").lines().next().unwrap_or("")
99
        );
100
    }
101
    if v.get("conflicted")
102
        .and_then(Value::as_bool)
103
        .unwrap_or(false)
104
    {
105
        println!("{}", ui::warn("landing would carry conflicts"));
106
    }
107
    if let Some(blockers) = v.get("blockers").and_then(Value::as_array) {
108
        for b in blockers {
109
            println!("  {} {}", ui::warn("blocked:"), b.as_str().unwrap_or(""));
110
        }
111
    }
112
    let approvals = v
113
        .get("approvals")
114
        .and_then(Value::as_array)
115
        .cloned()
116
        .unwrap_or_default();
117
    for a in &approvals {
118
        let mark = if a.get("sealed").and_then(Value::as_bool).unwrap_or(false) {
119
            ui::done("approved")
120
        } else {
121
            ui::warn("pending seal")
122
        };
123
        println!("  {mark} {}", text(a, "account"));
124
    }
125
    Ok(0)
126
}
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).
130
pub fn seal(url: &str, as_json: bool) -> Result<i32> {
131
    let repo = open()?;
132
    let (v, repo_url) = fetch(&repo, url)?;
133
    let hashes = change_hashes(&v);
134
    if hashes.is_empty() {
135
        anyhow::bail!("the proposal has no changes to seal");
136
    }
137
    ensure_changes(&repo, &repo_url, &hashes, &hashes)?;
138
    let mut refs = Vec::new();
139
    for chunk in hashes.chunks(oxy_core::attest::MAX_SEAL_HASHES) {
140
        refs.push(repo.seal(chunk)?);
141
    }
142
    let remote = repo.remote_for_url(&repo_url).ok_or_else(|| {
143
        anyhow!("no remote is configured for {repo_url}; add one with `oxy remote add`")
144
    })?;
145
    repo.push_seals(&remote, &refs)?;
146
    if as_json {
147
        let list: Vec<String> = hashes
148
            .iter()
149
            .map(|h| format!("\"{}\"", h.to_hex()))
150
            .collect();
151
        println!("{{\"sealed\":[{}],\"pushed\":true}}", list.join(","));
152
    } else {
153
        println!(
154
            "{} {} change{} of the proposal and pushed the seal to {remote}",
155
            ui::done("Sealed"),
156
            hashes.len(),
157
            if hashes.len() == 1 { "" } else { "s" }
158
        );
159
    }
160
    Ok(0)
161
}
162
163
/// Fetch the proposal's changes (and anything they need) from the hub
164
/// into the local store.
165
fn ensure_changes(
166
    repo: &Repo,
167
    repo_url: &str,
168
    want: &[ChangeHash],
169
    _changes: &[ChangeHash],
170
) -> Result<()> {
171
    let missing: Vec<ChangeHash> = want
172
        .iter()
173
        .copied()
174
        .filter(|h| !repo.store().has(h))
175
        .collect();
176
    if missing.is_empty() {
177
        return Ok(());
178
    }
179
    let (_, remote) = repo.open_remote_at(repo_url)?;
180
    let view = repo.view()?;
181
    let have = repo.known_heads(&view)?;
182
    let needed = remote.negotiate(&have, want)?;
183
    let bundle = remote.fetch(&needed, repo.config.max_blob)?;
184
    repo.import_bundle(&bundle, false)?;
185
    Ok(())
186
}
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).
191
pub fn land(url: &str, force: bool) -> Result<i32> {
192
    let repo = open()?;
193
    let (v, repo_url) = fetch(&repo, url)?;
194
    let state = text(&v, "state");
195
    if state != "open" && !force {
196
        anyhow::bail!("the proposal is {state}, not open (use --force to land anyway)");
197
    }
198
    if !v.get("landable").and_then(Value::as_bool).unwrap_or(false) && !force {
199
        let blockers: Vec<String> = v
200
            .get("blockers")
201
            .and_then(Value::as_array)
202
            .map(|a| {
203
                a.iter()
204
                    .filter_map(|b| b.as_str().map(String::from))
205
                    .collect()
206
            })
207
            .unwrap_or_default();
208
        anyhow::bail!(
209
            "the hub says the proposal cannot land yet: {} (use --force to land anyway)",
210
            blockers.join("; ")
211
        );
212
    }
213
    let target = text(&v, "target").to_string();
214
    let heads = hashes(&v, "projected_heads");
215
    if heads.is_empty() {
216
        anyhow::bail!("the hub has not computed the projected state yet; try again shortly");
217
    }
218
    ensure_changes(&repo, &repo_url, &heads, &change_hashes(&v))?;
219
    let remote = repo.remote_for_url(&repo_url).ok_or_else(|| {
220
        anyhow!("no remote is configured for {repo_url}; add one with `oxy remote add`")
221
    })?;
222
    // Bring the target bookmark up to date first, so the push is a fast-forward.
223
    repo.fetch(&remote)?;
224
    repo.bookmark_set(&target, &heads)?;
225
    let results = repo.push_bookmark(&remote, &target, false)?;
226
    for r in &results {
227
        if r.ok {
228
            println!(
229
                "{} {}/{} - landed proposal",
230
                ui::done("Pushed"),
231
                remote,
232
                r.name
233
            );
234
        } else {
235
            println!(
236
                "{} {}/{} - {}",
237
                ui::warn("Rejected"),
238
                remote,
239
                r.name,
240
                r.reason
241
            );
242
        }
243
    }
244
    Ok(if results.iter().all(|r| r.ok) { 0 } else { 1 })
245
}