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