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