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