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