OXYGENHUB
◆ v0.3.0 oxygenhub / crates / oh / src / main.rs
32.6 KiB · Rust · last changed Edit a proposal through the API; oh proposal edit, comment and create -F 1 month ago source blame history raw
5c6e92fd Andy McCall ↶ 1
//! `oh`: OxygenHub from the command line, as `gh` is for GitHub. It talks
2
//! to the hub's JSON API (hub spec §12) as the checkout's remote does:
3
//! same hub, same token, same CA.
4
5
mod client;
6
mod target;
7
mod ui;
8
9
use anyhow::{bail, Context, Result};
10
use clap::{Parser, Subcommand};
11
use client::Client;
12
use hub_api::{FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release};
13
use std::time::Duration;
2bbe88a8 Andy McCall ↶ 14
use target::{Choice, Config, Target};
5c6e92fd Andy McCall ↶ 15
16
#[derive(Parser)]
e9bfea8e Andy McCall ↶ 17
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs and releases")]
5c6e92fd Andy McCall ↶ 18
struct Cli {
19
    /// The repository, when not inside an Oxygen checkout
20
    #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")]
21
    repo: Option<String>,
22
    /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved)
23
    #[arg(long, global = true, value_name = "URL")]
24
    hub: Option<String>,
25
    /// Which of the checkout's remotes to use (default: origin, or the only one)
26
    #[arg(long, global = true)]
27
    remote: Option<String>,
28
    /// Machine-readable output: the API's JSON, unchanged
29
    #[arg(long, global = true)]
30
    json: bool,
31
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
32
    #[arg(long, global = true)]
33
    plain: bool,
34
    #[command(subcommand)]
35
    cmd: Cmd,
36
}
37
38
#[derive(Subcommand)]
39
enum Cmd {
40
    /// Sign in to a hub, or show who you are signed in as
41
    Auth {
42
        #[command(subcommand)]
43
        cmd: AuthCmd,
44
    },
45
    /// The repository
46
    Repo {
47
        #[command(subcommand)]
48
        cmd: RepoCmd,
49
    },
50
    /// Issues
51
    Issue {
52
        #[command(subcommand)]
53
        cmd: IssueCmd,
54
    },
55
    /// Proposals (pull requests)
56
    Proposal {
57
        #[command(subcommand)]
58
        cmd: ProposalCmd,
59
    },
60
    /// OxygenFlow runs
61
    Run {
62
        #[command(subcommand)]
63
        cmd: RunCmd,
64
    },
65
    /// Releases
66
    Release {
67
        #[command(subcommand)]
68
        cmd: ReleaseCmd,
69
    },
70
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
71
    Api {
72
        /// A path under /api/v1
73
        path: String,
74
        /// The method
75
        #[arg(long, short = 'X', default_value = "GET")]
76
        method: String,
77
        /// A JSON body
78
        #[arg(long, short = 'd')]
79
        data: Option<String>,
80
    },
81
}
82
83
#[derive(Subcommand)]
84
enum AuthCmd {
df71c789 Andy McCall ↶ 85
    /// Sign in to a hub and make it the default: approve a code on the web
86
    /// (device sign-in), or give a token
5c6e92fd Andy McCall ↶ 87
    Login {
df71c789 Andy McCall ↶ 88
        /// The hub, e.g. https://oxygenhub.io
5c6e92fd Andy McCall ↶ 89
        #[arg(long = "with-hub", value_name = "URL")]
90
        url: String,
df71c789 Andy McCall ↶ 91
        /// An API token from the hub's Settings → Tokens, instead of
92
        /// approving a code ("-" reads it from stdin)
5c6e92fd Andy McCall ↶ 93
        #[arg(long)]
94
        token: Option<String>,
95
        /// The hub's CA certificate, when self-signed
96
        #[arg(long)]
97
        ca: Option<std::path::PathBuf>,
98
    },
99
    /// Who the token in use belongs to
100
    Status,
101
}
102
103
#[derive(Subcommand)]
104
enum RepoCmd {
105
    /// Name, description, visibility and default bookmark
106
    View,
107
}
108
109
#[derive(Subcommand)]
110
enum IssueCmd {
111
    /// Open issues (or --state closed|all)
112
    List {
113
        #[arg(long, default_value = "open")]
114
        state: String,
115
    },
116
    /// One issue with its comments
117
    View { number: i64 },
118
    /// Open an issue
119
    Create {
120
        #[arg(long, short)]
121
        title: String,
122
        #[arg(long, short)]
123
        body: Option<String>,
124
        /// Read the body from a file ("-" for stdin)
125
        #[arg(long, short = 'F')]
126
        body_file: Option<String>,
127
        /// A label (repeatable)
128
        #[arg(long, short)]
129
        label: Vec<String>,
130
    },
131
    /// Close an issue
132
    Close {
133
        number: i64,
134
        /// `completed` or `not_planned`
135
        #[arg(long, default_value = "completed")]
136
        reason: String,
137
    },
138
    /// Reopen an issue
139
    Reopen { number: i64 },
140
    /// Comment on an issue
141
    Comment {
142
        number: i64,
143
        #[arg(long, short)]
144
        body: String,
145
    },
146
}
147
148
#[derive(Subcommand)]
149
enum ProposalCmd {
0b20f1ec Andy McCall ↶ 150
    /// Open proposals (or --state draft|landed|closed|all)
151
    List {
152
        #[arg(long, default_value = "open")]
153
        state: String,
154
    },
5c6e92fd Andy McCall ↶ 155
    /// One proposal: its changes, approvals and whether it can land
156
    View { number: i64 },
157
    /// Propose a bookmark's changes for another bookmark
158
    Create {
159
        #[arg(long, short)]
160
        title: String,
161
        #[arg(long, short)]
162
        body: Option<String>,
739a763a Andy McCall ↶ 163
        /// Read the body from a file ("-" for stdin)
164
        #[arg(long, short = 'F', conflicts_with = "body")]
165
        body_file: Option<String>,
5c6e92fd Andy McCall ↶ 166
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
167
        #[arg(long)]
168
        from: String,
169
        /// The bookmark to land them on (default: the repository's default bookmark)
170
        #[arg(long)]
171
        into: Option<String>,
172
        #[arg(long)]
173
        draft: bool,
739a763a Andy McCall ↶ 174
    },
175
    /// Change a proposal's title or description (its author or a maintainer)
176
    Edit {
177
        number: i64,
178
        #[arg(long, short)]
179
        title: Option<String>,
180
        #[arg(long, short)]
181
        body: Option<String>,
182
        /// Read the body from a file ("-" for stdin)
183
        #[arg(long, short = 'F', conflicts_with = "body")]
184
        body_file: Option<String>,
5c6e92fd Andy McCall ↶ 185
    },
739a763a Andy McCall ↶ 186
    /// Comment on a proposal's conversation
187
    Comment {
188
        number: i64,
189
        #[arg(long, short)]
190
        body: Option<String>,
191
        /// Read the comment from a file ("-" for stdin)
192
        #[arg(long, short = 'F', conflicts_with = "body")]
193
        body_file: Option<String>,
194
    },
5c6e92fd Andy McCall ↶ 195
    /// The checks on a proposal's projected state
196
    Checks { number: i64 },
1f1eb06a Andy McCall ↶ 197
    /// Land a proposal on its target, as the page's Land button does
198
    Land { number: i64 },
5c6e92fd Andy McCall ↶ 199
}
200
201
#[derive(Subcommand)]
202
enum RunCmd {
203
    /// Recent runs, newest first
204
    List {
205
        #[arg(long, default_value_t = 20)]
206
        limit: i64,
207
    },
208
    /// A run and its jobs
209
    View { number: i64 },
210
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
211
    Start {
212
        #[arg(long)]
213
        bookmark: Option<String>,
214
        /// A change's full hash
215
        #[arg(long, conflicts_with = "bookmark")]
216
        change: Option<String>,
217
        /// Wait for the run and exit 1 unless it passes
218
        #[arg(long)]
219
        watch: bool,
220
    },
221
    /// Follow a run until it finishes; exit 1 unless it passes
222
    Watch { number: i64 },
223
    /// A job's log
224
    Log { number: i64, job: String },
225
    /// Run a finished run's state again
226
    Rerun { number: i64 },
227
}
228
229
#[derive(Subcommand)]
230
enum ReleaseCmd {
231
    /// Releases, newest first
232
    List,
233
    /// Create a release on an existing tag
234
    Create {
235
        tag: String,
236
        #[arg(long, short)]
237
        title: Option<String>,
238
        /// Notes in Markdown (default: generated from the changes since the previous release)
239
        #[arg(long, short)]
240
        notes: Option<String>,
241
        #[arg(long)]
242
        prerelease: bool,
243
    },
ced6d3af Andy McCall ↶ 244
    /// Change a release's title, notes or prerelease flag
245
    Edit {
246
        tag: String,
247
        #[arg(long, short)]
248
        title: Option<String>,
249
        /// New notes in Markdown ("-" reads them from stdin)
250
        #[arg(long, short)]
251
        notes: Option<String>,
252
        /// Mark it a prerelease (true) or not (false)
253
        #[arg(long)]
254
        prerelease: Option<bool>,
255
    },
5c6e92fd Andy McCall ↶ 256
    /// Attach files to a release
257
    Upload { tag: String, files: Vec<std::path::PathBuf> },
258
    /// The release's trust report: signatures, builds, receipts and audit
259
    Trust { tag: String },
260
}
261
262
fn main() {
263
    let cli = Cli::parse();
264
    ui::init(cli.plain);
265
    match run(cli) {
266
        Ok(code) => std::process::exit(code),
267
        Err(e) => {
268
            eprintln!("{} {e:#}", ui::bad("error:"));
269
            std::process::exit(2);
270
        }
271
    }
272
}
273
274
fn enc(s: &str) -> String {
275
    let mut out = String::new();
276
    for b in s.bytes() {
277
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
278
            out.push(b as char);
279
        } else {
280
            out.push_str(&format!("%{b:02X}"));
281
        }
282
    }
283
    out
284
}
285
286
fn run(cli: Cli) -> Result<i32> {
287
    let cfg = Config::load()?;
288
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
289
        return login(cfg, url, token.clone(), ca.clone());
290
    }
291
    let here = std::env::current_dir()?;
292
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
293
    let c = Client::new(&t)?;
294
    let json = cli.json;
295
    match cli.cmd {
296
        Cmd::Auth { cmd: AuthCmd::Status } => {
297
            let me: serde_json::Value = c.get("/user")?;
298
            if json {
299
                println!("{me}");
300
            } else {
301
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
302
            }
303
            Ok(0)
304
        }
305
        Cmd::Auth { .. } => unreachable!(),
306
        Cmd::Api { path, method, data } => {
307
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
1b770a1f Andy McCall ↶ 308
            // The method applies with or without a body (#75): without one, a
309
            // GET reads, anything else sends an empty object.
5c6e92fd Andy McCall ↶ 310
            let text = match data {
311
                Some(d) => c.send_text(
312
                    &method.to_uppercase(),
313
                    &path,
314
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
315
                )?,
1b770a1f Andy McCall ↶ 316
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
317
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
5c6e92fd Andy McCall ↶ 318
            };
319
            println!("{text}");
320
            Ok(0)
321
        }
322
        Cmd::Repo { cmd: RepoCmd::View } => {
323
            let path = t.repo_path()?;
324
            if json {
325
                println!("{}", c.get_text(&path)?);
326
                return Ok(0);
327
            }
328
            let r: serde_json::Value = c.get(&path)?;
329
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
330
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
331
                println!("{d}");
332
            }
333
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
334
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
335
            Ok(0)
336
        }
337
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
338
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
339
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
340
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
341
    }
342
}
343
344
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
345
    let hub = url.trim_end_matches('/').to_string();
df71c789 Andy McCall ↶ 346
    let token = match token.as_deref() {
347
        Some("-") => {
5c6e92fd Andy McCall ↶ 348
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
349
            let mut line = String::new();
350
            std::io::stdin().read_line(&mut line)?;
351
            line.trim().to_string()
352
        }
df71c789 Andy McCall ↶ 353
        Some(t) => t.to_string(),
354
        None => device_sign_in(&hub, ca.clone())?,
5c6e92fd Andy McCall ↶ 355
    };
356
    if token.is_empty() {
357
        bail!("no token given");
358
    }
359
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
360
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
2bbe88a8 Andy McCall ↶ 361
    let account = me["username"].as_str().unwrap_or("?");
362
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
363
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
364
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
365
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
5c6e92fd Andy McCall ↶ 366
    cfg.default_hub = Some(hub.clone());
367
    cfg.save()?;
2bbe88a8 Andy McCall ↶ 368
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
369
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
5c6e92fd Andy McCall ↶ 370
    Ok(0)
371
}
372
df71c789 Andy McCall ↶ 373
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
374
/// it on the web, and the token arrives here.
375
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
376
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
377
    let c = Client::new(&t)?;
378
    let host = std::fs::read_to_string("/etc/hostname")
379
        .ok()
380
        .or_else(|| std::env::var("COMPUTERNAME").ok())
381
        .map(|h| h.trim().to_string())
382
        .filter(|h| !h.is_empty());
383
    let client = match host {
384
        Some(h) => format!("oh on {h}"),
385
        None => "oh".to_string(),
386
    };
387
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
388
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
389
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
390
    if code != 200 {
391
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
392
    }
393
    let device = v["device_code"].as_str().context("no device code")?.to_string();
394
    let user = v["user_code"].as_str().unwrap_or("?");
395
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
396
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
397
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
398
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
399
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
400
    loop {
401
        std::thread::sleep(std::time::Duration::from_secs(interval));
402
        if std::time::Instant::now() > deadline {
403
            bail!("the code expired before it was approved; run oh auth login again");
404
        }
405
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
406
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
407
        if code == 200 {
408
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
409
        }
410
        match v["error"].as_str() {
411
            Some("authorization_pending") => {}
412
            Some("slow_down") => interval += 5,
413
            Some("access_denied") => bail!("the sign-in was denied on the web"),
414
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
415
            _ => bail!("signing in: HTTP {code}: {body}"),
416
        }
417
    }
418
}
419
5c6e92fd Andy McCall ↶ 420
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
421
    match (body, file) {
422
        (Some(b), _) => Ok(b),
423
        (None, Some(f)) if f == "-" => {
424
            let mut s = String::new();
425
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
426
            Ok(s)
427
        }
428
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
429
        (None, None) => Ok(String::new()),
430
    }
431
}
432
433
fn issue_line(i: &Issue) -> String {
434
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
435
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
436
    format!(
437
        "{glyph} {} {}{}{}",
438
        ui::dim(&format!("#{}", i.number)),
439
        i.title,
440
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
441
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
442
    )
443
}
444
445
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
446
    let base = t.repo_path()?;
447
    match cmd {
448
        IssueCmd::List { state } => {
449
            let path = format!("{base}/issues?state={}", enc(&state));
450
            if json {
451
                println!("{}", c.get_text(&path)?);
452
                return Ok(0);
453
            }
454
            let list: Vec<Issue> = c.get(&path)?;
455
            if list.is_empty() {
456
                println!("{}", ui::dim(&format!("No {state} issues.")));
457
            }
458
            for i in &list {
459
                println!("{}", issue_line(i));
460
            }
461
        }
462
        IssueCmd::View { number } => {
463
            let path = format!("{base}/issues/{number}");
464
            if json {
465
                println!("{}", c.get_text(&path)?);
466
                return Ok(0);
467
            }
468
            let i: Issue = c.get(&path)?;
469
            println!("{}", issue_line(&i));
470
            if !i.body.trim().is_empty() {
471
                println!("\n{}\n", i.body.trim_end());
472
            }
473
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
474
            for cm in comments {
475
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
476
            }
477
            println!("{}", ui::dim(&i.url));
478
        }
479
        IssueCmd::Create { title, body, body_file, label } => {
480
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
481
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
482
            if json {
483
                println!("{}", serde_json::to_string(&i)?);
484
            } else {
485
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
486
            }
487
        }
488
        IssueCmd::Close { number, reason } => {
489
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
490
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
491
        }
492
        IssueCmd::Reopen { number } => {
493
            let i: Issue =
494
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
495
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
496
        }
497
        IssueCmd::Comment { number, body } => {
498
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
499
            println!("{} commented on #{number}", ui::ok("✔"));
500
        }
501
    }
502
    Ok(0)
503
}
504
505
fn source_name(s: &hub_api::ProposalSource) -> String {
506
    match s {
507
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
508
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
509
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
510
    }
511
}
512
513
fn proposal_line(p: &Proposal) -> String {
514
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
515
    let glyph = match state.as_str() {
516
        "open" => ui::ok("●"),
517
        "draft" => ui::dim("◌"),
518
        "landed" => ui::strong("✔"),
519
        _ => ui::dim("○"),
520
    };
521
    format!(
522
        "{glyph} {} {} {}{}",
523
        ui::dim(&format!("#{}", p.number)),
524
        p.title,
525
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
526
        ui::dim(&format!(" · {} · {state}", p.author))
527
    )
528
}
529
530
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
531
    let base = t.repo_path()?;
532
    match cmd {
0b20f1ec Andy McCall ↶ 533
        ProposalCmd::List { state } => {
534
            let path = format!("{base}/proposals?state={state}");
5c6e92fd Andy McCall ↶ 535
            if json {
536
                println!("{}", c.get_text(&path)?);
537
                return Ok(0);
538
            }
539
            let list: Vec<Proposal> = c.get(&path)?;
540
            if list.is_empty() {
0b20f1ec Andy McCall ↶ 541
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
5c6e92fd Andy McCall ↶ 542
            }
543
            for p in &list {
544
                println!("{}", proposal_line(p));
545
            }
546
        }
547
        ProposalCmd::View { number } => {
548
            let path = format!("{base}/proposals/{number}");
549
            if json {
550
                println!("{}", c.get_text(&path)?);
551
                return Ok(0);
552
            }
553
            let p: Proposal = c.get(&path)?;
554
            println!("{}", proposal_line(&p));
555
            if !p.body.trim().is_empty() {
556
                println!("\n{}\n", p.body.trim_end());
557
            }
558
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
559
            for ch in &p.changes {
560
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
561
            }
562
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
563
            if p.landable {
564
                println!("{} can land", ui::ok("✔"));
565
            } else {
566
                for b in &p.blockers {
567
                    println!("{} {b}", ui::bad("✘"));
568
                }
569
            }
570
            if p.conflicted {
571
                println!("{} landing it would leave conflicts", ui::bad("!"));
572
            }
573
            println!("{}", ui::dim(&p.url));
574
        }
739a763a Andy McCall ↶ 575
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
5c6e92fd Andy McCall ↶ 576
            let target = match into {
577
                Some(i) => i,
578
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
579
            };
739a763a Andy McCall ↶ 580
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
5c6e92fd Andy McCall ↶ 581
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
582
            if json {
583
                println!("{}", serde_json::to_string(&p)?);
584
            } else {
585
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1f1eb06a Andy McCall ↶ 586
            }
739a763a Andy McCall ↶ 587
        }
588
        ProposalCmd::Edit { number, title, body, body_file } => {
589
            let body = match (&body, &body_file) {
590
                (None, None) => None,
591
                _ => Some(body_of(body, body_file)?),
592
            };
593
            if title.is_none() && body.is_none() {
594
                bail!("say what to change: --title, --body or --body-file");
595
            }
596
            let edit = hub_api::ProposalEdit { title, body };
597
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
598
            if json {
599
                println!("{}", serde_json::to_string(&p)?);
600
            } else {
601
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
602
            }
603
        }
604
        ProposalCmd::Comment { number, body, body_file } => {
605
            let body = body_of(body, body_file)?;
606
            if body.trim().is_empty() {
607
                bail!("give the comment with --body or --body-file");
608
            }
609
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
610
            println!("{} commented on #{number}", ui::ok("✔"));
1f1eb06a Andy McCall ↶ 611
        }
612
        ProposalCmd::Land { number } => {
613
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &serde_json::json!({}))?;
614
            if json {
615
                println!("{}", serde_json::to_string(&p)?);
616
            } else {
617
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
5c6e92fd Andy McCall ↶ 618
            }
619
        }
620
        ProposalCmd::Checks { number } => {
621
            let path = format!("{base}/proposals/{number}/checks");
622
            if json {
623
                println!("{}", c.get_text(&path)?);
624
                return Ok(0);
625
            }
626
            let checks: Vec<hub_api::Check> = c.get(&path)?;
627
            if checks.is_empty() {
628
                println!("{}", ui::dim("No checks yet."));
629
            }
630
            for ch in checks {
631
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
632
            }
633
        }
634
    }
635
    Ok(0)
636
}
637
638
fn run_line(r: &FlowRun) -> String {
639
    let what =
640
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
641
    format!(
642
        "{} {} {} {}",
643
        ui::status(&r.status),
644
        ui::dim(&format!("#{}", r.number)),
645
        what,
646
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
647
    )
648
}
649
650
fn print_run(r: &FlowRun) {
651
    println!("{}", run_line(r));
652
    for j in &r.jobs {
653
        let dur = match (j.started_ms, j.finished_ms) {
654
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
655
            _ => String::new(),
656
        };
657
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
658
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
659
    }
660
    if !r.error.is_empty() {
661
        println!("{}", ui::bad(&r.error));
662
    }
663
    println!("{}", ui::dim(&r.url));
664
}
665
666
fn live(status: &str) -> bool {
667
    matches!(status, "queued" | "running")
668
}
669
670
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
671
    let path = format!("{base}/flow/runs/{number}");
672
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
673
    loop {
674
        let r: FlowRun = c.get(&path)?;
675
        if !json {
676
            for j in &r.jobs {
677
                if seen.get(&j.name) != Some(&j.status) {
678
                    println!("{} {}", ui::status(&j.status), j.name);
679
                    seen.insert(j.name.clone(), j.status.clone());
680
                }
681
            }
682
        }
683
        if !live(&r.status) {
684
            if json {
685
                println!("{}", serde_json::to_string(&r)?);
686
            } else {
687
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
688
            }
689
            return Ok(if r.status == "passed" { 0 } else { 1 });
690
        }
691
        std::thread::sleep(Duration::from_secs(3));
692
    }
693
}
694
695
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
696
    let base = t.repo_path()?;
697
    match cmd {
698
        RunCmd::List { limit } => {
699
            let path = format!("{base}/flow/runs?limit={limit}");
700
            if json {
701
                println!("{}", c.get_text(&path)?);
702
                return Ok(0);
703
            }
704
            let runs: Vec<FlowRun> = c.get(&path)?;
705
            if runs.is_empty() {
706
                println!("{}", ui::dim("No runs yet."));
707
            }
708
            for r in &runs {
709
                println!("{}", run_line(r));
710
            }
711
        }
712
        RunCmd::View { number } => {
713
            let path = format!("{base}/flow/runs/{number}");
714
            if json {
715
                println!("{}", c.get_text(&path)?);
716
                return Ok(0);
717
            }
718
            print_run(&c.get(&path)?);
719
        }
720
        RunCmd::Start { bookmark, change, watch: follow } => {
721
            let body = match (bookmark, change) {
722
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
723
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
724
                (None, None) => serde_json::json!({}),
725
            };
726
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
727
            let n = started["number"].as_i64().context("the hub named no run")?;
728
            if !json || !follow {
729
                if json {
730
                    println!("{started}");
731
                } else {
732
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
733
                }
734
            }
735
            if follow {
736
                return watch(c, &base, n, json);
737
            }
738
        }
739
        RunCmd::Watch { number } => return watch(c, &base, number, json),
740
        RunCmd::Log { number, job } => {
741
            let mut after = 0;
742
            loop {
743
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
744
                let lines: Vec<FlowLogLine> = c.get(&path)?;
745
                if lines.is_empty() {
746
                    break;
747
                }
748
                for l in &lines {
749
                    if json {
750
                        println!("{}", serde_json::to_string(l)?);
751
                    } else if l.stream == "flow" {
752
                        println!("{}", ui::dim(&l.text));
753
                    } else {
754
                        println!("{}", l.text);
755
                    }
756
                }
757
                after = lines.last().map(|l| l.seq).unwrap_or(after);
758
            }
759
        }
760
        RunCmd::Rerun { number } => {
761
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
762
            if json {
763
                println!("{started}");
764
            } else {
765
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
766
            }
767
        }
768
    }
769
    Ok(0)
770
}
771
772
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
773
    let base = t.repo_path()?;
774
    match cmd {
775
        ReleaseCmd::List => {
776
            let path = format!("{base}/releases");
777
            if json {
778
                println!("{}", c.get_text(&path)?);
779
                return Ok(0);
780
            }
781
            let list: Vec<Release> = c.get(&path)?;
782
            if list.is_empty() {
783
                println!("{}", ui::dim("No releases."));
784
            }
785
            for r in &list {
786
                println!(
787
                    "{} {} {}{}",
788
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
789
                    ui::strong(&r.tag),
790
                    r.title,
791
                    ui::dim(&format!(
792
                        " · {} asset{} · {}",
793
                        r.assets.len(),
794
                        if r.assets.len() == 1 { "" } else { "s" },
795
                        ui::ago(r.created_ms)
796
                    ))
797
                );
798
            }
799
        }
800
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
801
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
802
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
803
            if json {
804
                println!("{}", serde_json::to_string(&r)?);
805
            } else {
806
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
ced6d3af Andy McCall ↶ 807
            }
808
        }
809
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
810
            let notes = match notes.as_deref() {
811
                Some("-") => Some(body_of(None, Some("-".into()))?),
812
                _ => notes,
813
            };
814
            if title.is_none() && notes.is_none() && prerelease.is_none() {
815
                bail!("say what to change: --title, --notes or --prerelease");
816
            }
817
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
818
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
819
            if json {
820
                println!("{}", serde_json::to_string(&r)?);
821
            } else {
822
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
5c6e92fd Andy McCall ↶ 823
            }
824
        }
825
        ReleaseCmd::Upload { tag, files } => {
826
            if files.is_empty() {
827
                bail!("name the files to attach");
828
            }
829
            for f in files {
830
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
831
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
832
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
833
                println!("{} attached {name} to {tag}", ui::ok("✔"));
834
            }
835
        }
836
        ReleaseCmd::Trust { tag } => {
837
            let path = format!("{base}/releases/trust/{}", enc(&tag));
838
            if json {
839
                println!("{}", c.get_text(&path)?);
840
                return Ok(0);
841
            }
842
            let r: serde_json::Value = c.get(&path)?;
843
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
844
            let mut worst = 0;
845
            for ch in r["audit"].as_array().into_iter().flatten() {
846
                let v = ch["verdict"].as_str().unwrap_or("");
847
                worst = worst.max(match v {
848
                    "fail" => 2,
849
                    "warn" => 1,
850
                    _ => 0,
851
                });
852
                let g = match v {
853
                    "pass" => ui::ok("✔"),
854
                    "warn" => ui::warn("!"),
855
                    _ => ui::bad("✘"),
856
                };
857
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
858
            }
859
            return Ok(if worst == 2 { 1 } else { 0 });
860
        }
861
    }
862
    Ok(0)
863
}