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