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