OXYGENHUB
# 1b770a1fecf0 oxygenhub / crates / oh / src / main.rs
25.6 KiB · Rust · last changed oh api applies -X without a body too (closes #75) 1 month ago source blame history raw
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;
14
use target::{Choice, Config, Host, Target};
15
16
#[derive(Parser)]
17
#[command(name = "oh", version, about = "OxygenHub from the command line: issues, proposals, Flow runs and releases")]
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 {
85
    /// Save a token for a hub (read from stdin when not given) and make it the default
86
    Login {
87
        /// The hub, e.g. https://earth.example:7343
88
        #[arg(long = "with-hub", value_name = "URL")]
89
        url: String,
90
        /// An API token from the hub's Settings → Tokens
91
        #[arg(long)]
92
        token: Option<String>,
93
        /// The hub's CA certificate, when self-signed
94
        #[arg(long)]
95
        ca: Option<std::path::PathBuf>,
96
    },
97
    /// Who the token in use belongs to
98
    Status,
99
}
100
101
#[derive(Subcommand)]
102
enum RepoCmd {
103
    /// Name, description, visibility and default bookmark
104
    View,
105
}
106
107
#[derive(Subcommand)]
108
enum IssueCmd {
109
    /// Open issues (or --state closed|all)
110
    List {
111
        #[arg(long, default_value = "open")]
112
        state: String,
113
    },
114
    /// One issue with its comments
115
    View { number: i64 },
116
    /// Open an issue
117
    Create {
118
        #[arg(long, short)]
119
        title: String,
120
        #[arg(long, short)]
121
        body: Option<String>,
122
        /// Read the body from a file ("-" for stdin)
123
        #[arg(long, short = 'F')]
124
        body_file: Option<String>,
125
        /// A label (repeatable)
126
        #[arg(long, short)]
127
        label: Vec<String>,
128
    },
129
    /// Close an issue
130
    Close {
131
        number: i64,
132
        /// `completed` or `not_planned`
133
        #[arg(long, default_value = "completed")]
134
        reason: String,
135
    },
136
    /// Reopen an issue
137
    Reopen { number: i64 },
138
    /// Comment on an issue
139
    Comment {
140
        number: i64,
141
        #[arg(long, short)]
142
        body: String,
143
    },
144
}
145
146
#[derive(Subcommand)]
147
enum ProposalCmd {
148
    /// Open proposals
149
    List,
150
    /// One proposal: its changes, approvals and whether it can land
151
    View { number: i64 },
152
    /// Propose a bookmark's changes for another bookmark
153
    Create {
154
        #[arg(long, short)]
155
        title: String,
156
        #[arg(long, short)]
157
        body: Option<String>,
158
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
159
        #[arg(long)]
160
        from: String,
161
        /// The bookmark to land them on (default: the repository's default bookmark)
162
        #[arg(long)]
163
        into: Option<String>,
164
        #[arg(long)]
165
        draft: bool,
166
    },
167
    /// The checks on a proposal's projected state
168
    Checks { number: i64 },
169
}
170
171
#[derive(Subcommand)]
172
enum RunCmd {
173
    /// Recent runs, newest first
174
    List {
175
        #[arg(long, default_value_t = 20)]
176
        limit: i64,
177
    },
178
    /// A run and its jobs
179
    View { number: i64 },
180
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
181
    Start {
182
        #[arg(long)]
183
        bookmark: Option<String>,
184
        /// A change's full hash
185
        #[arg(long, conflicts_with = "bookmark")]
186
        change: Option<String>,
187
        /// Wait for the run and exit 1 unless it passes
188
        #[arg(long)]
189
        watch: bool,
190
    },
191
    /// Follow a run until it finishes; exit 1 unless it passes
192
    Watch { number: i64 },
193
    /// A job's log
194
    Log { number: i64, job: String },
195
    /// Run a finished run's state again
196
    Rerun { number: i64 },
197
}
198
199
#[derive(Subcommand)]
200
enum ReleaseCmd {
201
    /// Releases, newest first
202
    List,
203
    /// Create a release on an existing tag
204
    Create {
205
        tag: String,
206
        #[arg(long, short)]
207
        title: Option<String>,
208
        /// Notes in Markdown (default: generated from the changes since the previous release)
209
        #[arg(long, short)]
210
        notes: Option<String>,
211
        #[arg(long)]
212
        prerelease: bool,
213
    },
214
    /// Attach files to a release
215
    Upload { tag: String, files: Vec<std::path::PathBuf> },
216
    /// The release's trust report: signatures, builds, receipts and audit
217
    Trust { tag: String },
218
}
219
220
fn main() {
221
    let cli = Cli::parse();
222
    ui::init(cli.plain);
223
    match run(cli) {
224
        Ok(code) => std::process::exit(code),
225
        Err(e) => {
226
            eprintln!("{} {e:#}", ui::bad("error:"));
227
            std::process::exit(2);
228
        }
229
    }
230
}
231
232
fn enc(s: &str) -> String {
233
    let mut out = String::new();
234
    for b in s.bytes() {
235
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
236
            out.push(b as char);
237
        } else {
238
            out.push_str(&format!("%{b:02X}"));
239
        }
240
    }
241
    out
242
}
243
244
fn run(cli: Cli) -> Result<i32> {
245
    let cfg = Config::load()?;
246
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
247
        return login(cfg, url, token.clone(), ca.clone());
248
    }
249
    let here = std::env::current_dir()?;
250
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
251
    let c = Client::new(&t)?;
252
    let json = cli.json;
253
    match cli.cmd {
254
        Cmd::Auth { cmd: AuthCmd::Status } => {
255
            let me: serde_json::Value = c.get("/user")?;
256
            if json {
257
                println!("{me}");
258
            } else {
259
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
260
            }
261
            Ok(0)
262
        }
263
        Cmd::Auth { .. } => unreachable!(),
264
        Cmd::Api { path, method, data } => {
265
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
266
            // The method applies with or without a body (#75): without one, a
267
            // GET reads, anything else sends an empty object.
268
            let text = match data {
269
                Some(d) => c.send_text(
270
                    &method.to_uppercase(),
271
                    &path,
272
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
273
                )?,
274
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
275
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
276
            };
277
            println!("{text}");
278
            Ok(0)
279
        }
280
        Cmd::Repo { cmd: RepoCmd::View } => {
281
            let path = t.repo_path()?;
282
            if json {
283
                println!("{}", c.get_text(&path)?);
284
                return Ok(0);
285
            }
286
            let r: serde_json::Value = c.get(&path)?;
287
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
288
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
289
                println!("{d}");
290
            }
291
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
292
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
293
            Ok(0)
294
        }
295
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
296
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
297
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
298
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
299
    }
300
}
301
302
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
303
    let hub = url.trim_end_matches('/').to_string();
304
    let token = match token {
305
        Some(t) => t,
306
        None => {
307
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
308
            let mut line = String::new();
309
            std::io::stdin().read_line(&mut line)?;
310
            line.trim().to_string()
311
        }
312
    };
313
    if token.is_empty() {
314
        bail!("no token given");
315
    }
316
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
317
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
318
    cfg.hosts.insert(hub.clone(), Host { token, ca });
319
    cfg.default_hub = Some(hub.clone());
320
    cfg.save()?;
321
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(me["username"].as_str().unwrap_or("?")));
322
    Ok(0)
323
}
324
325
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
326
    match (body, file) {
327
        (Some(b), _) => Ok(b),
328
        (None, Some(f)) if f == "-" => {
329
            let mut s = String::new();
330
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
331
            Ok(s)
332
        }
333
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
334
        (None, None) => Ok(String::new()),
335
    }
336
}
337
338
fn issue_line(i: &Issue) -> String {
339
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
340
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
341
    format!(
342
        "{glyph} {} {}{}{}",
343
        ui::dim(&format!("#{}", i.number)),
344
        i.title,
345
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
346
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
347
    )
348
}
349
350
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
351
    let base = t.repo_path()?;
352
    match cmd {
353
        IssueCmd::List { state } => {
354
            let path = format!("{base}/issues?state={}", enc(&state));
355
            if json {
356
                println!("{}", c.get_text(&path)?);
357
                return Ok(0);
358
            }
359
            let list: Vec<Issue> = c.get(&path)?;
360
            if list.is_empty() {
361
                println!("{}", ui::dim(&format!("No {state} issues.")));
362
            }
363
            for i in &list {
364
                println!("{}", issue_line(i));
365
            }
366
        }
367
        IssueCmd::View { number } => {
368
            let path = format!("{base}/issues/{number}");
369
            if json {
370
                println!("{}", c.get_text(&path)?);
371
                return Ok(0);
372
            }
373
            let i: Issue = c.get(&path)?;
374
            println!("{}", issue_line(&i));
375
            if !i.body.trim().is_empty() {
376
                println!("\n{}\n", i.body.trim_end());
377
            }
378
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
379
            for cm in comments {
380
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
381
            }
382
            println!("{}", ui::dim(&i.url));
383
        }
384
        IssueCmd::Create { title, body, body_file, label } => {
385
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
386
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
387
            if json {
388
                println!("{}", serde_json::to_string(&i)?);
389
            } else {
390
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
391
            }
392
        }
393
        IssueCmd::Close { number, reason } => {
394
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
395
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
396
        }
397
        IssueCmd::Reopen { number } => {
398
            let i: Issue =
399
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
400
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
401
        }
402
        IssueCmd::Comment { number, body } => {
403
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
404
            println!("{} commented on #{number}", ui::ok("✔"));
405
        }
406
    }
407
    Ok(0)
408
}
409
410
fn source_name(s: &hub_api::ProposalSource) -> String {
411
    match s {
412
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
413
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
414
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
415
    }
416
}
417
418
fn proposal_line(p: &Proposal) -> String {
419
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
420
    let glyph = match state.as_str() {
421
        "open" => ui::ok("●"),
422
        "draft" => ui::dim("◌"),
423
        "landed" => ui::strong("✔"),
424
        _ => ui::dim("○"),
425
    };
426
    format!(
427
        "{glyph} {} {} {}{}",
428
        ui::dim(&format!("#{}", p.number)),
429
        p.title,
430
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
431
        ui::dim(&format!(" · {} · {state}", p.author))
432
    )
433
}
434
435
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
436
    let base = t.repo_path()?;
437
    match cmd {
438
        ProposalCmd::List => {
439
            let path = format!("{base}/proposals");
440
            if json {
441
                println!("{}", c.get_text(&path)?);
442
                return Ok(0);
443
            }
444
            let list: Vec<Proposal> = c.get(&path)?;
445
            if list.is_empty() {
446
                println!("{}", ui::dim("No open proposals."));
447
            }
448
            for p in &list {
449
                println!("{}", proposal_line(p));
450
            }
451
        }
452
        ProposalCmd::View { number } => {
453
            let path = format!("{base}/proposals/{number}");
454
            if json {
455
                println!("{}", c.get_text(&path)?);
456
                return Ok(0);
457
            }
458
            let p: Proposal = c.get(&path)?;
459
            println!("{}", proposal_line(&p));
460
            if !p.body.trim().is_empty() {
461
                println!("\n{}\n", p.body.trim_end());
462
            }
463
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
464
            for ch in &p.changes {
465
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
466
            }
467
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
468
            if p.landable {
469
                println!("{} can land", ui::ok("✔"));
470
            } else {
471
                for b in &p.blockers {
472
                    println!("{} {b}", ui::bad("✘"));
473
                }
474
            }
475
            if p.conflicted {
476
                println!("{} landing it would leave conflicts", ui::bad("!"));
477
            }
478
            println!("{}", ui::dim(&p.url));
479
        }
480
        ProposalCmd::Create { title, body, from, into, draft } => {
481
            let target = match into {
482
                Some(i) => i,
483
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
484
            };
485
            let new = NewProposal { title, body: body.unwrap_or_default(), target, source: from, draft };
486
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
487
            if json {
488
                println!("{}", serde_json::to_string(&p)?);
489
            } else {
490
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
491
            }
492
        }
493
        ProposalCmd::Checks { number } => {
494
            let path = format!("{base}/proposals/{number}/checks");
495
            if json {
496
                println!("{}", c.get_text(&path)?);
497
                return Ok(0);
498
            }
499
            let checks: Vec<hub_api::Check> = c.get(&path)?;
500
            if checks.is_empty() {
501
                println!("{}", ui::dim("No checks yet."));
502
            }
503
            for ch in checks {
504
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
505
            }
506
        }
507
    }
508
    Ok(0)
509
}
510
511
fn run_line(r: &FlowRun) -> String {
512
    let what =
513
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
514
    format!(
515
        "{} {} {} {}",
516
        ui::status(&r.status),
517
        ui::dim(&format!("#{}", r.number)),
518
        what,
519
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
520
    )
521
}
522
523
fn print_run(r: &FlowRun) {
524
    println!("{}", run_line(r));
525
    for j in &r.jobs {
526
        let dur = match (j.started_ms, j.finished_ms) {
527
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
528
            _ => String::new(),
529
        };
530
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
531
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
532
    }
533
    if !r.error.is_empty() {
534
        println!("{}", ui::bad(&r.error));
535
    }
536
    println!("{}", ui::dim(&r.url));
537
}
538
539
fn live(status: &str) -> bool {
540
    matches!(status, "queued" | "running")
541
}
542
543
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
544
    let path = format!("{base}/flow/runs/{number}");
545
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
546
    loop {
547
        let r: FlowRun = c.get(&path)?;
548
        if !json {
549
            for j in &r.jobs {
550
                if seen.get(&j.name) != Some(&j.status) {
551
                    println!("{} {}", ui::status(&j.status), j.name);
552
                    seen.insert(j.name.clone(), j.status.clone());
553
                }
554
            }
555
        }
556
        if !live(&r.status) {
557
            if json {
558
                println!("{}", serde_json::to_string(&r)?);
559
            } else {
560
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
561
            }
562
            return Ok(if r.status == "passed" { 0 } else { 1 });
563
        }
564
        std::thread::sleep(Duration::from_secs(3));
565
    }
566
}
567
568
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
569
    let base = t.repo_path()?;
570
    match cmd {
571
        RunCmd::List { limit } => {
572
            let path = format!("{base}/flow/runs?limit={limit}");
573
            if json {
574
                println!("{}", c.get_text(&path)?);
575
                return Ok(0);
576
            }
577
            let runs: Vec<FlowRun> = c.get(&path)?;
578
            if runs.is_empty() {
579
                println!("{}", ui::dim("No runs yet."));
580
            }
581
            for r in &runs {
582
                println!("{}", run_line(r));
583
            }
584
        }
585
        RunCmd::View { number } => {
586
            let path = format!("{base}/flow/runs/{number}");
587
            if json {
588
                println!("{}", c.get_text(&path)?);
589
                return Ok(0);
590
            }
591
            print_run(&c.get(&path)?);
592
        }
593
        RunCmd::Start { bookmark, change, watch: follow } => {
594
            let body = match (bookmark, change) {
595
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
596
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
597
                (None, None) => serde_json::json!({}),
598
            };
599
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
600
            let n = started["number"].as_i64().context("the hub named no run")?;
601
            if !json || !follow {
602
                if json {
603
                    println!("{started}");
604
                } else {
605
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
606
                }
607
            }
608
            if follow {
609
                return watch(c, &base, n, json);
610
            }
611
        }
612
        RunCmd::Watch { number } => return watch(c, &base, number, json),
613
        RunCmd::Log { number, job } => {
614
            let mut after = 0;
615
            loop {
616
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
617
                let lines: Vec<FlowLogLine> = c.get(&path)?;
618
                if lines.is_empty() {
619
                    break;
620
                }
621
                for l in &lines {
622
                    if json {
623
                        println!("{}", serde_json::to_string(l)?);
624
                    } else if l.stream == "flow" {
625
                        println!("{}", ui::dim(&l.text));
626
                    } else {
627
                        println!("{}", l.text);
628
                    }
629
                }
630
                after = lines.last().map(|l| l.seq).unwrap_or(after);
631
            }
632
        }
633
        RunCmd::Rerun { number } => {
634
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
635
            if json {
636
                println!("{started}");
637
            } else {
638
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
639
            }
640
        }
641
    }
642
    Ok(0)
643
}
644
645
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
646
    let base = t.repo_path()?;
647
    match cmd {
648
        ReleaseCmd::List => {
649
            let path = format!("{base}/releases");
650
            if json {
651
                println!("{}", c.get_text(&path)?);
652
                return Ok(0);
653
            }
654
            let list: Vec<Release> = c.get(&path)?;
655
            if list.is_empty() {
656
                println!("{}", ui::dim("No releases."));
657
            }
658
            for r in &list {
659
                println!(
660
                    "{} {} {}{}",
661
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
662
                    ui::strong(&r.tag),
663
                    r.title,
664
                    ui::dim(&format!(
665
                        " · {} asset{} · {}",
666
                        r.assets.len(),
667
                        if r.assets.len() == 1 { "" } else { "s" },
668
                        ui::ago(r.created_ms)
669
                    ))
670
                );
671
            }
672
        }
673
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
674
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
675
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
676
            if json {
677
                println!("{}", serde_json::to_string(&r)?);
678
            } else {
679
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
680
            }
681
        }
682
        ReleaseCmd::Upload { tag, files } => {
683
            if files.is_empty() {
684
                bail!("name the files to attach");
685
            }
686
            for f in files {
687
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
688
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
689
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
690
                println!("{} attached {name} to {tag}", ui::ok("✔"));
691
            }
692
        }
693
        ReleaseCmd::Trust { tag } => {
694
            let path = format!("{base}/releases/trust/{}", enc(&tag));
695
            if json {
696
                println!("{}", c.get_text(&path)?);
697
                return Ok(0);
698
            }
699
            let r: serde_json::Value = c.get(&path)?;
700
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
701
            let mut worst = 0;
702
            for ch in r["audit"].as_array().into_iter().flatten() {
703
                let v = ch["verdict"].as_str().unwrap_or("");
704
                worst = worst.max(match v {
705
                    "fail" => 2,
706
                    "warn" => 1,
707
                    _ => 0,
708
                });
709
                let g = match v {
710
                    "pass" => ui::ok("✔"),
711
                    "warn" => ui::warn("!"),
712
                    _ => ui::bad("✘"),
713
                };
714
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
715
            }
716
            return Ok(if worst == 2 { 1 } else { 0 });
717
        }
718
    }
719
    Ok(0)
720
}