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