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