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