OXYGENHUB
# 745d225de344 oxygenhub / crates / oh / src / main.rs
37.0 KiB · Rust · last changed Cancel runs from oh, the run page, and newer pushes 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
    /// Cancel a run still queued or running; its running jobs are stopped
290
    Cancel { number: i64 },
291
}
292
293
#[derive(Subcommand)]
294
enum ReleaseCmd {
295
    /// Releases, newest first
296
    List,
297
    /// Create a release on an existing tag
298
    Create {
299
        tag: String,
300
        #[arg(long, short)]
301
        title: Option<String>,
302
        /// Notes in Markdown (default: generated from the changes since the previous release)
303
        #[arg(long, short)]
304
        notes: Option<String>,
305
        #[arg(long)]
306
        prerelease: bool,
307
    },
308
    /// Change a release's title, notes or prerelease flag
309
    Edit {
310
        tag: String,
311
        #[arg(long, short)]
312
        title: Option<String>,
313
        /// New notes in Markdown ("-" reads them from stdin)
314
        #[arg(long, short)]
315
        notes: Option<String>,
316
        /// Mark it a prerelease (true) or not (false)
317
        #[arg(long)]
318
        prerelease: Option<bool>,
319
    },
320
    /// Attach files to a release
321
    Upload { tag: String, files: Vec<std::path::PathBuf> },
322
    /// The release's trust report: signatures, builds, receipts and audit
323
    Trust { tag: String },
324
}
325
326
fn main() {
327
    let cli = Cli::parse();
328
    ui::init(cli.plain);
329
    match run(cli) {
330
        Ok(code) => std::process::exit(code),
331
        Err(e) => {
332
            eprintln!("{} {e:#}", ui::bad("error:"));
333
            std::process::exit(2);
334
        }
335
    }
336
}
337
338
fn enc(s: &str) -> String {
339
    let mut out = String::new();
340
    for b in s.bytes() {
341
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
342
            out.push(b as char);
343
        } else {
344
            out.push_str(&format!("%{b:02X}"));
345
        }
346
    }
347
    out
348
}
349
350
fn run(cli: Cli) -> Result<i32> {
351
    let cfg = Config::load()?;
352
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
353
        return login(cfg, url, token.clone(), ca.clone());
354
    }
355
    let here = std::env::current_dir()?;
356
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
357
    let c = Client::new(&t)?;
358
    let json = cli.json;
359
    match cli.cmd {
360
        Cmd::Auth { cmd: AuthCmd::Status } => {
361
            let me: serde_json::Value = c.get("/user")?;
362
            if json {
363
                println!("{me}");
364
            } else {
365
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
366
            }
367
            Ok(0)
368
        }
369
        Cmd::Auth { .. } => unreachable!(),
370
        Cmd::Api { path, method, data } => {
371
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
372
            let text = match data {
373
                Some(d) => c.send_text(
374
                    &method.to_uppercase(),
375
                    &path,
376
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
377
                )?,
378
                None => c.get_text(&path)?,
379
            };
380
            println!("{text}");
381
            Ok(0)
382
        }
383
        Cmd::Repo { cmd: RepoCmd::View } => {
384
            let path = t.repo_path()?;
385
            if json {
386
                println!("{}", c.get_text(&path)?);
387
                return Ok(0);
388
            }
389
            let r: serde_json::Value = c.get(&path)?;
390
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
391
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
392
                println!("{d}");
393
            }
394
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
395
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
396
            Ok(0)
397
        }
398
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
399
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
400
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
401
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
402
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
403
    }
404
}
405
406
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
407
    let hub = url.trim_end_matches('/').to_string();
408
    let token = match token.as_deref() {
409
        Some("-") => {
410
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
411
            let mut line = String::new();
412
            std::io::stdin().read_line(&mut line)?;
413
            line.trim().to_string()
414
        }
415
        Some(t) => t.to_string(),
416
        None => device_sign_in(&hub, ca.clone())?,
417
    };
418
    if token.is_empty() {
419
        bail!("no token given");
420
    }
421
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
422
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
423
    let account = me["username"].as_str().unwrap_or("?");
424
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
425
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
426
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
427
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
428
    cfg.default_hub = Some(hub.clone());
429
    cfg.save()?;
430
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
431
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
432
    Ok(0)
433
}
434
435
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
436
/// it on the web, and the token arrives here.
437
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
438
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
439
    let c = Client::new(&t)?;
440
    let host = std::fs::read_to_string("/etc/hostname")
441
        .ok()
442
        .or_else(|| std::env::var("COMPUTERNAME").ok())
443
        .map(|h| h.trim().to_string())
444
        .filter(|h| !h.is_empty());
445
    let client = match host {
446
        Some(h) => format!("oh on {h}"),
447
        None => "oh".to_string(),
448
    };
449
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
450
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
451
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
452
    if code != 200 {
453
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
454
    }
455
    let device = v["device_code"].as_str().context("no device code")?.to_string();
456
    let user = v["user_code"].as_str().unwrap_or("?");
457
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
458
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
459
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
460
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
461
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
462
    loop {
463
        std::thread::sleep(std::time::Duration::from_secs(interval));
464
        if std::time::Instant::now() > deadline {
465
            bail!("the code expired before it was approved; run oh auth login again");
466
        }
467
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
468
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
469
        if code == 200 {
470
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
471
        }
472
        match v["error"].as_str() {
473
            Some("authorization_pending") => {}
474
            Some("slow_down") => interval += 5,
475
            Some("access_denied") => bail!("the sign-in was denied on the web"),
476
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
477
            _ => bail!("signing in: HTTP {code}: {body}"),
478
        }
479
    }
480
}
481
482
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
483
    match (body, file) {
484
        (Some(b), _) => Ok(b),
485
        (None, Some(f)) if f == "-" => {
486
            let mut s = String::new();
487
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
488
            Ok(s)
489
        }
490
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
491
        (None, None) => Ok(String::new()),
492
    }
493
}
494
495
fn issue_line(i: &Issue) -> String {
496
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
497
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
498
    format!(
499
        "{glyph} {} {}{}{}",
500
        ui::dim(&format!("#{}", i.number)),
501
        i.title,
502
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
503
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
504
    )
505
}
506
507
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
508
    let base = t.repo_path()?;
509
    match cmd {
510
        IssueCmd::List { state } => {
511
            let path = format!("{base}/issues?state={}", enc(&state));
512
            if json {
513
                println!("{}", c.get_text(&path)?);
514
                return Ok(0);
515
            }
516
            let list: Vec<Issue> = c.get(&path)?;
517
            if list.is_empty() {
518
                println!("{}", ui::dim(&format!("No {state} issues.")));
519
            }
520
            for i in &list {
521
                println!("{}", issue_line(i));
522
            }
523
        }
524
        IssueCmd::View { number } => {
525
            let path = format!("{base}/issues/{number}");
526
            if json {
527
                println!("{}", c.get_text(&path)?);
528
                return Ok(0);
529
            }
530
            let i: Issue = c.get(&path)?;
531
            println!("{}", issue_line(&i));
532
            if !i.body.trim().is_empty() {
533
                println!("\n{}\n", i.body.trim_end());
534
            }
535
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
536
            for cm in comments {
537
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
538
            }
539
            println!("{}", ui::dim(&i.url));
540
        }
541
        IssueCmd::Create { title, body, body_file, label } => {
542
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
543
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
544
            if json {
545
                println!("{}", serde_json::to_string(&i)?);
546
            } else {
547
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
548
            }
549
        }
550
        IssueCmd::Close { number, reason } => {
551
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
552
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
553
        }
554
        IssueCmd::Reopen { number } => {
555
            let i: Issue =
556
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
557
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
558
        }
559
        IssueCmd::Label(change) => {
560
            let path = format!("{base}/issues/{}", change.number);
561
            let now: Issue = c.get(&path)?;
562
            let labels = change.apply(&now.labels)?;
563
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
564
            let i: Issue = c.send("PATCH", &path, &edit)?;
565
            if json {
566
                println!("{}", serde_json::to_string(&i)?);
567
            } else {
568
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
569
            }
570
        }
571
        IssueCmd::Comment { number, body } => {
572
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
573
            println!("{} commented on #{number}", ui::ok("✔"));
574
        }
575
    }
576
    Ok(0)
577
}
578
579
fn source_name(s: &hub_api::ProposalSource) -> String {
580
    match s {
581
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
582
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
583
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
584
    }
585
}
586
587
fn proposal_line(p: &Proposal) -> String {
588
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
589
    let glyph = match state.as_str() {
590
        "open" => ui::ok("●"),
591
        "draft" => ui::dim("◌"),
592
        "landed" => ui::strong("✔"),
593
        _ => ui::dim("○"),
594
    };
595
    format!(
596
        "{glyph} {} {} {}{}",
597
        ui::dim(&format!("#{}", p.number)),
598
        p.title,
599
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
600
        ui::dim(&format!(" · {} · {state}", p.author))
601
    )
602
}
603
604
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
605
    let base = t.repo_path()?;
606
    match cmd {
607
        ProposalCmd::List { state } => {
608
            let path = format!("{base}/proposals?state={state}");
609
            if json {
610
                println!("{}", c.get_text(&path)?);
611
                return Ok(0);
612
            }
613
            let list: Vec<Proposal> = c.get(&path)?;
614
            if list.is_empty() {
615
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
616
            }
617
            for p in &list {
618
                println!("{}", proposal_line(p));
619
            }
620
        }
621
        ProposalCmd::View { number } => {
622
            let path = format!("{base}/proposals/{number}");
623
            if json {
624
                println!("{}", c.get_text(&path)?);
625
                return Ok(0);
626
            }
627
            let p: Proposal = c.get(&path)?;
628
            println!("{}", proposal_line(&p));
629
            if !p.body.trim().is_empty() {
630
                println!("\n{}\n", p.body.trim_end());
631
            }
632
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
633
            for ch in &p.changes {
634
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
635
            }
636
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
637
            if p.landable {
638
                println!("{} can land", ui::ok("✔"));
639
            } else {
640
                for b in &p.blockers {
641
                    println!("{} {b}", ui::bad("✘"));
642
                }
643
            }
644
            if p.conflicted {
645
                println!("{} landing it would leave conflicts", ui::bad("!"));
646
            }
647
            println!("{}", ui::dim(&p.url));
648
        }
649
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
650
            let target = match into {
651
                Some(i) => i,
652
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
653
            };
654
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
655
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
656
            if json {
657
                println!("{}", serde_json::to_string(&p)?);
658
            } else {
659
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
660
            }
661
        }
662
        ProposalCmd::Edit { number, title, body, body_file } => {
663
            let body = match (&body, &body_file) {
664
                (None, None) => None,
665
                _ => Some(body_of(body, body_file)?),
666
            };
667
            if title.is_none() && body.is_none() {
668
                bail!("say what to change: --title, --body or --body-file");
669
            }
670
            let edit = hub_api::ProposalEdit { title, body, labels: None };
671
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
672
            if json {
673
                println!("{}", serde_json::to_string(&p)?);
674
            } else {
675
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
676
            }
677
        }
678
        ProposalCmd::Label(change) => {
679
            let path = format!("{base}/proposals/{}", change.number);
680
            let now: Proposal = c.get(&path)?;
681
            let labels = change.apply(&now.labels)?;
682
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
683
            let p: Proposal = c.send("PATCH", &path, &edit)?;
684
            if json {
685
                println!("{}", serde_json::to_string(&p)?);
686
            } else {
687
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
688
            }
689
        }
690
        ProposalCmd::Comment { number, body, body_file } => {
691
            let body = body_of(body, body_file)?;
692
            if body.trim().is_empty() {
693
                bail!("give the comment with --body or --body-file");
694
            }
695
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
696
            println!("{} commented on #{number}", ui::ok("✔"));
697
        }
698
        ProposalCmd::Land { number } => {
699
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &serde_json::json!({}))?;
700
            if json {
701
                println!("{}", serde_json::to_string(&p)?);
702
            } else {
703
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
704
            }
705
        }
706
        ProposalCmd::Checks { number } => {
707
            let path = format!("{base}/proposals/{number}/checks");
708
            if json {
709
                println!("{}", c.get_text(&path)?);
710
                return Ok(0);
711
            }
712
            let checks: Vec<hub_api::Check> = c.get(&path)?;
713
            if checks.is_empty() {
714
                println!("{}", ui::dim("No checks yet."));
715
            }
716
            for ch in checks {
717
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
718
            }
719
        }
720
    }
721
    Ok(0)
722
}
723
724
fn run_line(r: &FlowRun) -> String {
725
    let what =
726
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
727
    format!(
728
        "{} {} {} {}",
729
        ui::status(&r.status),
730
        ui::dim(&format!("#{}", r.number)),
731
        what,
732
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
733
    )
734
}
735
736
fn print_run(r: &FlowRun) {
737
    println!("{}", run_line(r));
738
    for j in &r.jobs {
739
        let dur = match (j.started_ms, j.finished_ms) {
740
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
741
            _ => String::new(),
742
        };
743
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
744
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
745
    }
746
    if !r.error.is_empty() {
747
        println!("{}", ui::bad(&r.error));
748
    }
749
    println!("{}", ui::dim(&r.url));
750
}
751
752
fn live(status: &str) -> bool {
753
    matches!(status, "queued" | "running")
754
}
755
756
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
757
    let path = format!("{base}/flow/runs/{number}");
758
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
759
    loop {
760
        let r: FlowRun = c.get(&path)?;
761
        if !json {
762
            for j in &r.jobs {
763
                if seen.get(&j.name) != Some(&j.status) {
764
                    println!("{} {}", ui::status(&j.status), j.name);
765
                    seen.insert(j.name.clone(), j.status.clone());
766
                }
767
            }
768
        }
769
        if !live(&r.status) {
770
            if json {
771
                println!("{}", serde_json::to_string(&r)?);
772
            } else {
773
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
774
            }
775
            return Ok(if r.status == "passed" { 0 } else { 1 });
776
        }
777
        std::thread::sleep(Duration::from_secs(3));
778
    }
779
}
780
781
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
782
    let base = t.repo_path()?;
783
    match cmd {
784
        RunCmd::List { limit } => {
785
            let path = format!("{base}/flow/runs?limit={limit}");
786
            if json {
787
                println!("{}", c.get_text(&path)?);
788
                return Ok(0);
789
            }
790
            let runs: Vec<FlowRun> = c.get(&path)?;
791
            if runs.is_empty() {
792
                println!("{}", ui::dim("No runs yet."));
793
            }
794
            for r in &runs {
795
                println!("{}", run_line(r));
796
            }
797
        }
798
        RunCmd::View { number } => {
799
            let path = format!("{base}/flow/runs/{number}");
800
            if json {
801
                println!("{}", c.get_text(&path)?);
802
                return Ok(0);
803
            }
804
            print_run(&c.get(&path)?);
805
        }
806
        RunCmd::Start { bookmark, change, watch: follow } => {
807
            let body = match (bookmark, change) {
808
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
809
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
810
                (None, None) => serde_json::json!({}),
811
            };
812
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
813
            let n = started["number"].as_i64().context("the hub named no run")?;
814
            if !json || !follow {
815
                if json {
816
                    println!("{started}");
817
                } else {
818
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
819
                }
820
            }
821
            if follow {
822
                return watch(c, &base, n, json);
823
            }
824
        }
825
        RunCmd::Watch { number } => return watch(c, &base, number, json),
826
        RunCmd::Log { number, job } => {
827
            let mut after = 0;
828
            loop {
829
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
830
                let lines: Vec<FlowLogLine> = c.get(&path)?;
831
                if lines.is_empty() {
832
                    break;
833
                }
834
                for l in &lines {
835
                    if json {
836
                        println!("{}", serde_json::to_string(l)?);
837
                    } else if l.stream == "flow" {
838
                        println!("{}", ui::dim(&l.text));
839
                    } else {
840
                        println!("{}", l.text);
841
                    }
842
                }
843
                after = lines.last().map(|l| l.seq).unwrap_or(after);
844
            }
845
        }
846
        RunCmd::Rerun { number } => {
847
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
848
            if json {
849
                println!("{started}");
850
            } else {
851
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
852
            }
853
        }
854
        RunCmd::Cancel { number } => {
855
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
856
            if json {
857
                println!("{done}");
858
            } else {
859
                println!("{} cancelled run #{number}", ui::ok("✔"));
860
            }
861
        }
862
    }
863
    Ok(0)
864
}
865
866
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
867
    let base = t.repo_path()?;
868
    match cmd {
869
        LabelCmd::List => {
870
            let path = format!("{base}/labels");
871
            if json {
872
                println!("{}", c.get_text(&path)?);
873
                return Ok(0);
874
            }
875
            let labels: Vec<hub_api::Label> = c.get(&path)?;
876
            if labels.is_empty() {
877
                println!("{}", ui::dim("No labels."));
878
            }
879
            for l in labels {
880
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
881
            }
882
        }
883
        LabelCmd::Create { name, colour, description } => {
884
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
885
            if json {
886
                println!("{}", serde_json::to_string(&l)?);
887
            } else {
888
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
889
            }
890
        }
891
        LabelCmd::Delete { name } => {
892
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
893
            println!("{} deleted label {name}", ui::ok("✔"));
894
        }
895
    }
896
    Ok(0)
897
}
898
899
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
900
    let base = t.repo_path()?;
901
    match cmd {
902
        ReleaseCmd::List => {
903
            let path = format!("{base}/releases");
904
            if json {
905
                println!("{}", c.get_text(&path)?);
906
                return Ok(0);
907
            }
908
            let list: Vec<Release> = c.get(&path)?;
909
            if list.is_empty() {
910
                println!("{}", ui::dim("No releases."));
911
            }
912
            for r in &list {
913
                println!(
914
                    "{} {} {}{}",
915
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
916
                    ui::strong(&r.tag),
917
                    r.title,
918
                    ui::dim(&format!(
919
                        " · {} asset{} · {}",
920
                        r.assets.len(),
921
                        if r.assets.len() == 1 { "" } else { "s" },
922
                        ui::ago(r.created_ms)
923
                    ))
924
                );
925
            }
926
        }
927
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
928
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
929
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
930
            if json {
931
                println!("{}", serde_json::to_string(&r)?);
932
            } else {
933
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
934
            }
935
        }
936
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
937
            let notes = match notes.as_deref() {
938
                Some("-") => Some(body_of(None, Some("-".into()))?),
939
                _ => notes,
940
            };
941
            if title.is_none() && notes.is_none() && prerelease.is_none() {
942
                bail!("say what to change: --title, --notes or --prerelease");
943
            }
944
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
945
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
946
            if json {
947
                println!("{}", serde_json::to_string(&r)?);
948
            } else {
949
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
950
            }
951
        }
952
        ReleaseCmd::Upload { tag, files } => {
953
            if files.is_empty() {
954
                bail!("name the files to attach");
955
            }
956
            for f in files {
957
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
958
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
959
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
960
                println!("{} attached {name} to {tag}", ui::ok("✔"));
961
            }
962
        }
963
        ReleaseCmd::Trust { tag } => {
964
            let path = format!("{base}/releases/trust/{}", enc(&tag));
965
            if json {
966
                println!("{}", c.get_text(&path)?);
967
                return Ok(0);
968
            }
969
            let r: serde_json::Value = c.get(&path)?;
970
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
971
            let mut worst = 0;
972
            for ch in r["audit"].as_array().into_iter().flatten() {
973
                let v = ch["verdict"].as_str().unwrap_or("");
974
                worst = worst.max(match v {
975
                    "fail" => 2,
976
                    "warn" => 1,
977
                    _ => 0,
978
                });
979
                let g = match v {
980
                    "pass" => ui::ok("✔"),
981
                    "warn" => ui::warn("!"),
982
                    _ => ui::bad("✘"),
983
                };
984
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
985
            }
986
            return Ok(if worst == 2 { 1 } else { 0 });
987
        }
988
    }
989
    Ok(0)
990
}