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