OXYGENHUB
# c4c87f481d05 oxygenhub / crates / oh / src / main.rs
28.1 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
5c6e92fd Andy McCall ↶ 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)]
e9bfea8e Andy McCall ↶ 17
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs and releases")]
5c6e92fd Andy McCall ↶ 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 {
df71c789 Andy McCall ↶ 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
5c6e92fd Andy McCall ↶ 87
    Login {
df71c789 Andy McCall ↶ 88
        /// The hub, e.g. https://oxygenhub.io
5c6e92fd Andy McCall ↶ 89
        #[arg(long = "with-hub", value_name = "URL")]
90
        url: String,
df71c789 Andy McCall ↶ 91
        /// An API token from the hub's Settings → Tokens, instead of
92
        /// approving a code ("-" reads it from stdin)
5c6e92fd Andy McCall ↶ 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
151
    List,
152
    /// One proposal: its changes, approvals and whether it can land
153
    View { number: i64 },
154
    /// Propose a bookmark's changes for another bookmark
155
    Create {
156
        #[arg(long, short)]
157
        title: String,
158
        #[arg(long, short)]
159
        body: Option<String>,
160
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
161
        #[arg(long)]
162
        from: String,
163
        /// The bookmark to land them on (default: the repository's default bookmark)
164
        #[arg(long)]
165
        into: Option<String>,
166
        #[arg(long)]
167
        draft: bool,
168
    },
169
    /// The checks on a proposal's projected state
170
    Checks { 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();
df71c789 Andy McCall ↶ 303
    let token = match token.as_deref() {
304
        Some("-") => {
5c6e92fd Andy McCall ↶ 305
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
306
            let mut line = String::new();
307
            std::io::stdin().read_line(&mut line)?;
308
            line.trim().to_string()
309
        }
df71c789 Andy McCall ↶ 310
        Some(t) => t.to_string(),
311
        None => device_sign_in(&hub, ca.clone())?,
5c6e92fd Andy McCall ↶ 312
    };
313
    if token.is_empty() {
314
        bail!("no token given");
315
    }
316
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
317
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
318
    cfg.hosts.insert(hub.clone(), Host { token, ca });
319
    cfg.default_hub = Some(hub.clone());
320
    cfg.save()?;
321
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(me["username"].as_str().unwrap_or("?")));
322
    Ok(0)
323
}
324
df71c789 Andy McCall ↶ 325
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
326
/// it on the web, and the token arrives here.
327
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
328
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
329
    let c = Client::new(&t)?;
330
    let host = std::fs::read_to_string("/etc/hostname")
331
        .ok()
332
        .or_else(|| std::env::var("COMPUTERNAME").ok())
333
        .map(|h| h.trim().to_string())
334
        .filter(|h| !h.is_empty());
335
    let client = match host {
336
        Some(h) => format!("oh on {h}"),
337
        None => "oh".to_string(),
338
    };
339
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
340
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
341
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
342
    if code != 200 {
343
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
344
    }
345
    let device = v["device_code"].as_str().context("no device code")?.to_string();
346
    let user = v["user_code"].as_str().unwrap_or("?");
347
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
348
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
349
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
350
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
351
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
352
    loop {
353
        std::thread::sleep(std::time::Duration::from_secs(interval));
354
        if std::time::Instant::now() > deadline {
355
            bail!("the code expired before it was approved; run oh auth login again");
356
        }
357
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
358
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
359
        if code == 200 {
360
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
361
        }
362
        match v["error"].as_str() {
363
            Some("authorization_pending") => {}
364
            Some("slow_down") => interval += 5,
365
            Some("access_denied") => bail!("the sign-in was denied on the web"),
366
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
367
            _ => bail!("signing in: HTTP {code}: {body}"),
368
        }
369
    }
370
}
371
5c6e92fd Andy McCall ↶ 372
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
373
    match (body, file) {
374
        (Some(b), _) => Ok(b),
375
        (None, Some(f)) if f == "-" => {
376
            let mut s = String::new();
377
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
378
            Ok(s)
379
        }
380
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
381
        (None, None) => Ok(String::new()),
382
    }
383
}
384
385
fn issue_line(i: &Issue) -> String {
386
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
387
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
388
    format!(
389
        "{glyph} {} {}{}{}",
390
        ui::dim(&format!("#{}", i.number)),
391
        i.title,
392
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
393
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
394
    )
395
}
396
397
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
398
    let base = t.repo_path()?;
399
    match cmd {
400
        IssueCmd::List { state } => {
401
            let path = format!("{base}/issues?state={}", enc(&state));
402
            if json {
403
                println!("{}", c.get_text(&path)?);
404
                return Ok(0);
405
            }
406
            let list: Vec<Issue> = c.get(&path)?;
407
            if list.is_empty() {
408
                println!("{}", ui::dim(&format!("No {state} issues.")));
409
            }
410
            for i in &list {
411
                println!("{}", issue_line(i));
412
            }
413
        }
414
        IssueCmd::View { number } => {
415
            let path = format!("{base}/issues/{number}");
416
            if json {
417
                println!("{}", c.get_text(&path)?);
418
                return Ok(0);
419
            }
420
            let i: Issue = c.get(&path)?;
421
            println!("{}", issue_line(&i));
422
            if !i.body.trim().is_empty() {
423
                println!("\n{}\n", i.body.trim_end());
424
            }
425
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
426
            for cm in comments {
427
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
428
            }
429
            println!("{}", ui::dim(&i.url));
430
        }
431
        IssueCmd::Create { title, body, body_file, label } => {
432
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
433
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
434
            if json {
435
                println!("{}", serde_json::to_string(&i)?);
436
            } else {
437
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
438
            }
439
        }
440
        IssueCmd::Close { number, reason } => {
441
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
442
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
443
        }
444
        IssueCmd::Reopen { number } => {
445
            let i: Issue =
446
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
447
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
448
        }
449
        IssueCmd::Comment { number, body } => {
450
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
451
            println!("{} commented on #{number}", ui::ok("✔"));
452
        }
453
    }
454
    Ok(0)
455
}
456
457
fn source_name(s: &hub_api::ProposalSource) -> String {
458
    match s {
459
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
460
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
461
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
462
    }
463
}
464
465
fn proposal_line(p: &Proposal) -> String {
466
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
467
    let glyph = match state.as_str() {
468
        "open" => ui::ok("●"),
469
        "draft" => ui::dim("◌"),
470
        "landed" => ui::strong("✔"),
471
        _ => ui::dim("○"),
472
    };
473
    format!(
474
        "{glyph} {} {} {}{}",
475
        ui::dim(&format!("#{}", p.number)),
476
        p.title,
477
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
478
        ui::dim(&format!(" · {} · {state}", p.author))
479
    )
480
}
481
482
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
483
    let base = t.repo_path()?;
484
    match cmd {
485
        ProposalCmd::List => {
486
            let path = format!("{base}/proposals");
487
            if json {
488
                println!("{}", c.get_text(&path)?);
489
                return Ok(0);
490
            }
491
            let list: Vec<Proposal> = c.get(&path)?;
492
            if list.is_empty() {
493
                println!("{}", ui::dim("No open proposals."));
494
            }
495
            for p in &list {
496
                println!("{}", proposal_line(p));
497
            }
498
        }
499
        ProposalCmd::View { number } => {
500
            let path = format!("{base}/proposals/{number}");
501
            if json {
502
                println!("{}", c.get_text(&path)?);
503
                return Ok(0);
504
            }
505
            let p: Proposal = c.get(&path)?;
506
            println!("{}", proposal_line(&p));
507
            if !p.body.trim().is_empty() {
508
                println!("\n{}\n", p.body.trim_end());
509
            }
510
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
511
            for ch in &p.changes {
512
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
513
            }
514
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
515
            if p.landable {
516
                println!("{} can land", ui::ok("✔"));
517
            } else {
518
                for b in &p.blockers {
519
                    println!("{} {b}", ui::bad("✘"));
520
                }
521
            }
522
            if p.conflicted {
523
                println!("{} landing it would leave conflicts", ui::bad("!"));
524
            }
525
            println!("{}", ui::dim(&p.url));
526
        }
527
        ProposalCmd::Create { title, body, from, into, draft } => {
528
            let target = match into {
529
                Some(i) => i,
530
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
531
            };
532
            let new = NewProposal { title, body: body.unwrap_or_default(), target, source: from, draft };
533
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
534
            if json {
535
                println!("{}", serde_json::to_string(&p)?);
536
            } else {
537
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
538
            }
539
        }
540
        ProposalCmd::Checks { number } => {
541
            let path = format!("{base}/proposals/{number}/checks");
542
            if json {
543
                println!("{}", c.get_text(&path)?);
544
                return Ok(0);
545
            }
546
            let checks: Vec<hub_api::Check> = c.get(&path)?;
547
            if checks.is_empty() {
548
                println!("{}", ui::dim("No checks yet."));
549
            }
550
            for ch in checks {
551
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
552
            }
553
        }
554
    }
555
    Ok(0)
556
}
557
558
fn run_line(r: &FlowRun) -> String {
559
    let what =
560
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
561
    format!(
562
        "{} {} {} {}",
563
        ui::status(&r.status),
564
        ui::dim(&format!("#{}", r.number)),
565
        what,
566
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
567
    )
568
}
569
570
fn print_run(r: &FlowRun) {
571
    println!("{}", run_line(r));
572
    for j in &r.jobs {
573
        let dur = match (j.started_ms, j.finished_ms) {
574
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
575
            _ => String::new(),
576
        };
577
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
578
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
579
    }
580
    if !r.error.is_empty() {
581
        println!("{}", ui::bad(&r.error));
582
    }
583
    println!("{}", ui::dim(&r.url));
584
}
585
586
fn live(status: &str) -> bool {
587
    matches!(status, "queued" | "running")
588
}
589
590
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
591
    let path = format!("{base}/flow/runs/{number}");
592
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
593
    loop {
594
        let r: FlowRun = c.get(&path)?;
595
        if !json {
596
            for j in &r.jobs {
597
                if seen.get(&j.name) != Some(&j.status) {
598
                    println!("{} {}", ui::status(&j.status), j.name);
599
                    seen.insert(j.name.clone(), j.status.clone());
600
                }
601
            }
602
        }
603
        if !live(&r.status) {
604
            if json {
605
                println!("{}", serde_json::to_string(&r)?);
606
            } else {
607
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
608
            }
609
            return Ok(if r.status == "passed" { 0 } else { 1 });
610
        }
611
        std::thread::sleep(Duration::from_secs(3));
612
    }
613
}
614
615
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
616
    let base = t.repo_path()?;
617
    match cmd {
618
        RunCmd::List { limit } => {
619
            let path = format!("{base}/flow/runs?limit={limit}");
620
            if json {
621
                println!("{}", c.get_text(&path)?);
622
                return Ok(0);
623
            }
624
            let runs: Vec<FlowRun> = c.get(&path)?;
625
            if runs.is_empty() {
626
                println!("{}", ui::dim("No runs yet."));
627
            }
628
            for r in &runs {
629
                println!("{}", run_line(r));
630
            }
631
        }
632
        RunCmd::View { number } => {
633
            let path = format!("{base}/flow/runs/{number}");
634
            if json {
635
                println!("{}", c.get_text(&path)?);
636
                return Ok(0);
637
            }
638
            print_run(&c.get(&path)?);
639
        }
640
        RunCmd::Start { bookmark, change, watch: follow } => {
641
            let body = match (bookmark, change) {
642
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
643
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
644
                (None, None) => serde_json::json!({}),
645
            };
646
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
647
            let n = started["number"].as_i64().context("the hub named no run")?;
648
            if !json || !follow {
649
                if json {
650
                    println!("{started}");
651
                } else {
652
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
653
                }
654
            }
655
            if follow {
656
                return watch(c, &base, n, json);
657
            }
658
        }
659
        RunCmd::Watch { number } => return watch(c, &base, number, json),
660
        RunCmd::Log { number, job } => {
661
            let mut after = 0;
662
            loop {
663
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
664
                let lines: Vec<FlowLogLine> = c.get(&path)?;
665
                if lines.is_empty() {
666
                    break;
667
                }
668
                for l in &lines {
669
                    if json {
670
                        println!("{}", serde_json::to_string(l)?);
671
                    } else if l.stream == "flow" {
672
                        println!("{}", ui::dim(&l.text));
673
                    } else {
674
                        println!("{}", l.text);
675
                    }
676
                }
677
                after = lines.last().map(|l| l.seq).unwrap_or(after);
678
            }
679
        }
680
        RunCmd::Rerun { number } => {
681
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
682
            if json {
683
                println!("{started}");
684
            } else {
685
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
686
            }
687
        }
688
    }
689
    Ok(0)
690
}
691
692
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
693
    let base = t.repo_path()?;
694
    match cmd {
695
        ReleaseCmd::List => {
696
            let path = format!("{base}/releases");
697
            if json {
698
                println!("{}", c.get_text(&path)?);
699
                return Ok(0);
700
            }
701
            let list: Vec<Release> = c.get(&path)?;
702
            if list.is_empty() {
703
                println!("{}", ui::dim("No releases."));
704
            }
705
            for r in &list {
706
                println!(
707
                    "{} {} {}{}",
708
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
709
                    ui::strong(&r.tag),
710
                    r.title,
711
                    ui::dim(&format!(
712
                        " · {} asset{} · {}",
713
                        r.assets.len(),
714
                        if r.assets.len() == 1 { "" } else { "s" },
715
                        ui::ago(r.created_ms)
716
                    ))
717
                );
718
            }
719
        }
720
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
721
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
722
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
723
            if json {
724
                println!("{}", serde_json::to_string(&r)?);
725
            } else {
726
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
727
            }
728
        }
729
        ReleaseCmd::Upload { tag, files } => {
730
            if files.is_empty() {
731
                bail!("name the files to attach");
732
            }
733
            for f in files {
734
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
735
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
736
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
737
                println!("{} attached {name} to {tag}", ui::ok("✔"));
738
            }
739
        }
740
        ReleaseCmd::Trust { tag } => {
741
            let path = format!("{base}/releases/trust/{}", enc(&tag));
742
            if json {
743
                println!("{}", c.get_text(&path)?);
744
                return Ok(0);
745
            }
746
            let r: serde_json::Value = c.get(&path)?;
747
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
748
            let mut worst = 0;
749
            for ch in r["audit"].as_array().into_iter().flatten() {
750
                let v = ch["verdict"].as_str().unwrap_or("");
751
                worst = worst.max(match v {
752
                    "fail" => 2,
753
                    "warn" => 1,
754
                    _ => 0,
755
                });
756
                let g = match v {
757
                    "pass" => ui::ok("✔"),
758
                    "warn" => ui::warn("!"),
759
                    _ => ui::bad("✘"),
760
                };
761
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
762
            }
763
            return Ok(if worst == 2 { 1 } else { 0 });
764
        }
765
    }
766
    Ok(0)
767
}