OXYGENHUB
# 5c6e92fd8d71 oxygenhub / crates / oh / src / main.rs
25.3 KiB · Rust · last changed oh: OxygenHub from the command line 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
            let text = match data {
267
                Some(d) => c.send_text(
268
                    &method.to_uppercase(),
269
                    &path,
270
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
271
                )?,
272
                None => c.get_text(&path)?,
273
            };
274
            println!("{text}");
275
            Ok(0)
276
        }
277
        Cmd::Repo { cmd: RepoCmd::View } => {
278
            let path = t.repo_path()?;
279
            if json {
280
                println!("{}", c.get_text(&path)?);
281
                return Ok(0);
282
            }
283
            let r: serde_json::Value = c.get(&path)?;
284
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
285
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
286
                println!("{d}");
287
            }
288
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
289
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
290
            Ok(0)
291
        }
292
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
293
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
294
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
295
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
296
    }
297
}
298
299
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
300
    let hub = url.trim_end_matches('/').to_string();
301
    let token = match token {
302
        Some(t) => t,
303
        None => {
304
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
305
            let mut line = String::new();
306
            std::io::stdin().read_line(&mut line)?;
307
            line.trim().to_string()
308
        }
309
    };
310
    if token.is_empty() {
311
        bail!("no token given");
312
    }
313
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
314
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
315
    cfg.hosts.insert(hub.clone(), Host { token, ca });
316
    cfg.default_hub = Some(hub.clone());
317
    cfg.save()?;
318
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(me["username"].as_str().unwrap_or("?")));
319
    Ok(0)
320
}
321
322
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
323
    match (body, file) {
324
        (Some(b), _) => Ok(b),
325
        (None, Some(f)) if f == "-" => {
326
            let mut s = String::new();
327
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
328
            Ok(s)
329
        }
330
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
331
        (None, None) => Ok(String::new()),
332
    }
333
}
334
335
fn issue_line(i: &Issue) -> String {
336
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
337
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
338
    format!(
339
        "{glyph} {} {}{}{}",
340
        ui::dim(&format!("#{}", i.number)),
341
        i.title,
342
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
343
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
344
    )
345
}
346
347
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
348
    let base = t.repo_path()?;
349
    match cmd {
350
        IssueCmd::List { state } => {
351
            let path = format!("{base}/issues?state={}", enc(&state));
352
            if json {
353
                println!("{}", c.get_text(&path)?);
354
                return Ok(0);
355
            }
356
            let list: Vec<Issue> = c.get(&path)?;
357
            if list.is_empty() {
358
                println!("{}", ui::dim(&format!("No {state} issues.")));
359
            }
360
            for i in &list {
361
                println!("{}", issue_line(i));
362
            }
363
        }
364
        IssueCmd::View { number } => {
365
            let path = format!("{base}/issues/{number}");
366
            if json {
367
                println!("{}", c.get_text(&path)?);
368
                return Ok(0);
369
            }
370
            let i: Issue = c.get(&path)?;
371
            println!("{}", issue_line(&i));
372
            if !i.body.trim().is_empty() {
373
                println!("\n{}\n", i.body.trim_end());
374
            }
375
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
376
            for cm in comments {
377
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
378
            }
379
            println!("{}", ui::dim(&i.url));
380
        }
381
        IssueCmd::Create { title, body, body_file, label } => {
382
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
383
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
384
            if json {
385
                println!("{}", serde_json::to_string(&i)?);
386
            } else {
387
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
388
            }
389
        }
390
        IssueCmd::Close { number, reason } => {
391
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
392
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
393
        }
394
        IssueCmd::Reopen { number } => {
395
            let i: Issue =
396
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
397
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
398
        }
399
        IssueCmd::Comment { number, body } => {
400
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
401
            println!("{} commented on #{number}", ui::ok("✔"));
402
        }
403
    }
404
    Ok(0)
405
}
406
407
fn source_name(s: &hub_api::ProposalSource) -> String {
408
    match s {
409
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
410
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
411
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
412
    }
413
}
414
415
fn proposal_line(p: &Proposal) -> String {
416
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
417
    let glyph = match state.as_str() {
418
        "open" => ui::ok("●"),
419
        "draft" => ui::dim("◌"),
420
        "landed" => ui::strong("✔"),
421
        _ => ui::dim("○"),
422
    };
423
    format!(
424
        "{glyph} {} {} {}{}",
425
        ui::dim(&format!("#{}", p.number)),
426
        p.title,
427
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
428
        ui::dim(&format!(" · {} · {state}", p.author))
429
    )
430
}
431
432
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
433
    let base = t.repo_path()?;
434
    match cmd {
435
        ProposalCmd::List => {
436
            let path = format!("{base}/proposals");
437
            if json {
438
                println!("{}", c.get_text(&path)?);
439
                return Ok(0);
440
            }
441
            let list: Vec<Proposal> = c.get(&path)?;
442
            if list.is_empty() {
443
                println!("{}", ui::dim("No open proposals."));
444
            }
445
            for p in &list {
446
                println!("{}", proposal_line(p));
447
            }
448
        }
449
        ProposalCmd::View { number } => {
450
            let path = format!("{base}/proposals/{number}");
451
            if json {
452
                println!("{}", c.get_text(&path)?);
453
                return Ok(0);
454
            }
455
            let p: Proposal = c.get(&path)?;
456
            println!("{}", proposal_line(&p));
457
            if !p.body.trim().is_empty() {
458
                println!("\n{}\n", p.body.trim_end());
459
            }
460
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
461
            for ch in &p.changes {
462
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
463
            }
464
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
465
            if p.landable {
466
                println!("{} can land", ui::ok("✔"));
467
            } else {
468
                for b in &p.blockers {
469
                    println!("{} {b}", ui::bad("✘"));
470
                }
471
            }
472
            if p.conflicted {
473
                println!("{} landing it would leave conflicts", ui::bad("!"));
474
            }
475
            println!("{}", ui::dim(&p.url));
476
        }
477
        ProposalCmd::Create { title, body, from, into, draft } => {
478
            let target = match into {
479
                Some(i) => i,
480
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
481
            };
482
            let new = NewProposal { title, body: body.unwrap_or_default(), target, source: from, draft };
483
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
484
            if json {
485
                println!("{}", serde_json::to_string(&p)?);
486
            } else {
487
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
488
            }
489
        }
490
        ProposalCmd::Checks { number } => {
491
            let path = format!("{base}/proposals/{number}/checks");
492
            if json {
493
                println!("{}", c.get_text(&path)?);
494
                return Ok(0);
495
            }
496
            let checks: Vec<hub_api::Check> = c.get(&path)?;
497
            if checks.is_empty() {
498
                println!("{}", ui::dim("No checks yet."));
499
            }
500
            for ch in checks {
501
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
502
            }
503
        }
504
    }
505
    Ok(0)
506
}
507
508
fn run_line(r: &FlowRun) -> String {
509
    let what =
510
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
511
    format!(
512
        "{} {} {} {}",
513
        ui::status(&r.status),
514
        ui::dim(&format!("#{}", r.number)),
515
        what,
516
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
517
    )
518
}
519
520
fn print_run(r: &FlowRun) {
521
    println!("{}", run_line(r));
522
    for j in &r.jobs {
523
        let dur = match (j.started_ms, j.finished_ms) {
524
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
525
            _ => String::new(),
526
        };
527
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
528
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
529
    }
530
    if !r.error.is_empty() {
531
        println!("{}", ui::bad(&r.error));
532
    }
533
    println!("{}", ui::dim(&r.url));
534
}
535
536
fn live(status: &str) -> bool {
537
    matches!(status, "queued" | "running")
538
}
539
540
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
541
    let path = format!("{base}/flow/runs/{number}");
542
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
543
    loop {
544
        let r: FlowRun = c.get(&path)?;
545
        if !json {
546
            for j in &r.jobs {
547
                if seen.get(&j.name) != Some(&j.status) {
548
                    println!("{} {}", ui::status(&j.status), j.name);
549
                    seen.insert(j.name.clone(), j.status.clone());
550
                }
551
            }
552
        }
553
        if !live(&r.status) {
554
            if json {
555
                println!("{}", serde_json::to_string(&r)?);
556
            } else {
557
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
558
            }
559
            return Ok(if r.status == "passed" { 0 } else { 1 });
560
        }
561
        std::thread::sleep(Duration::from_secs(3));
562
    }
563
}
564
565
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
566
    let base = t.repo_path()?;
567
    match cmd {
568
        RunCmd::List { limit } => {
569
            let path = format!("{base}/flow/runs?limit={limit}");
570
            if json {
571
                println!("{}", c.get_text(&path)?);
572
                return Ok(0);
573
            }
574
            let runs: Vec<FlowRun> = c.get(&path)?;
575
            if runs.is_empty() {
576
                println!("{}", ui::dim("No runs yet."));
577
            }
578
            for r in &runs {
579
                println!("{}", run_line(r));
580
            }
581
        }
582
        RunCmd::View { number } => {
583
            let path = format!("{base}/flow/runs/{number}");
584
            if json {
585
                println!("{}", c.get_text(&path)?);
586
                return Ok(0);
587
            }
588
            print_run(&c.get(&path)?);
589
        }
590
        RunCmd::Start { bookmark, change, watch: follow } => {
591
            let body = match (bookmark, change) {
592
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
593
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
594
                (None, None) => serde_json::json!({}),
595
            };
596
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
597
            let n = started["number"].as_i64().context("the hub named no run")?;
598
            if !json || !follow {
599
                if json {
600
                    println!("{started}");
601
                } else {
602
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
603
                }
604
            }
605
            if follow {
606
                return watch(c, &base, n, json);
607
            }
608
        }
609
        RunCmd::Watch { number } => return watch(c, &base, number, json),
610
        RunCmd::Log { number, job } => {
611
            let mut after = 0;
612
            loop {
613
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
614
                let lines: Vec<FlowLogLine> = c.get(&path)?;
615
                if lines.is_empty() {
616
                    break;
617
                }
618
                for l in &lines {
619
                    if json {
620
                        println!("{}", serde_json::to_string(l)?);
621
                    } else if l.stream == "flow" {
622
                        println!("{}", ui::dim(&l.text));
623
                    } else {
624
                        println!("{}", l.text);
625
                    }
626
                }
627
                after = lines.last().map(|l| l.seq).unwrap_or(after);
628
            }
629
        }
630
        RunCmd::Rerun { number } => {
631
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
632
            if json {
633
                println!("{started}");
634
            } else {
635
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
636
            }
637
        }
638
    }
639
    Ok(0)
640
}
641
642
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
643
    let base = t.repo_path()?;
644
    match cmd {
645
        ReleaseCmd::List => {
646
            let path = format!("{base}/releases");
647
            if json {
648
                println!("{}", c.get_text(&path)?);
649
                return Ok(0);
650
            }
651
            let list: Vec<Release> = c.get(&path)?;
652
            if list.is_empty() {
653
                println!("{}", ui::dim("No releases."));
654
            }
655
            for r in &list {
656
                println!(
657
                    "{} {} {}{}",
658
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
659
                    ui::strong(&r.tag),
660
                    r.title,
661
                    ui::dim(&format!(
662
                        " · {} asset{} · {}",
663
                        r.assets.len(),
664
                        if r.assets.len() == 1 { "" } else { "s" },
665
                        ui::ago(r.created_ms)
666
                    ))
667
                );
668
            }
669
        }
670
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
671
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
672
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
673
            if json {
674
                println!("{}", serde_json::to_string(&r)?);
675
            } else {
676
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
677
            }
678
        }
679
        ReleaseCmd::Upload { tag, files } => {
680
            if files.is_empty() {
681
                bail!("name the files to attach");
682
            }
683
            for f in files {
684
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
685
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
686
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
687
                println!("{} attached {name} to {tag}", ui::ok("✔"));
688
            }
689
        }
690
        ReleaseCmd::Trust { tag } => {
691
            let path = format!("{base}/releases/trust/{}", enc(&tag));
692
            if json {
693
                println!("{}", c.get_text(&path)?);
694
                return Ok(0);
695
            }
696
            let r: serde_json::Value = c.get(&path)?;
697
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
698
            let mut worst = 0;
699
            for ch in r["audit"].as_array().into_iter().flatten() {
700
                let v = ch["verdict"].as_str().unwrap_or("");
701
                worst = worst.max(match v {
702
                    "fail" => 2,
703
                    "warn" => 1,
704
                    _ => 0,
705
                });
706
                let g = match v {
707
                    "pass" => ui::ok("✔"),
708
                    "warn" => ui::warn("!"),
709
                    _ => ui::bad("✘"),
710
                };
711
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
712
            }
713
            return Ok(if worst == 2 { 1 } else { 0 });
714
        }
715
    }
716
    Ok(0)
717
}