OXYGENHUB
# 7d2eb590051f oxygenhub / crates / oh / src / main.rs
42.9 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
            let text = match data {
442
                Some(d) => c.send_text(
443
                    &method.to_uppercase(),
444
                    &path,
445
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
446
                )?,
447
                None => c.get_text(&path)?,
448
            };
449
            println!("{text}");
450
            Ok(0)
451
        }
452
        Cmd::Repo { cmd: RepoCmd::View } => {
453
            let path = t.repo_path()?;
454
            if json {
455
                println!("{}", c.get_text(&path)?);
456
                return Ok(0);
457
            }
458
            let r: serde_json::Value = c.get(&path)?;
459
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
460
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
461
                println!("{d}");
462
            }
463
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
464
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
465
            Ok(0)
466
        }
467
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
468
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
469
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
470
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
471
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
472
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
473
    }
474
}
475
476
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
477
    let hub = url.trim_end_matches('/').to_string();
478
    let token = match token.as_deref() {
479
        Some("-") => {
480
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
481
            let mut line = String::new();
482
            std::io::stdin().read_line(&mut line)?;
483
            line.trim().to_string()
484
        }
485
        Some(t) => t.to_string(),
486
        None => device_sign_in(&hub, ca.clone())?,
487
    };
488
    if token.is_empty() {
489
        bail!("no token given");
490
    }
491
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
492
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
493
    let account = me["username"].as_str().unwrap_or("?");
494
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
495
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
496
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
497
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
498
    cfg.default_hub = Some(hub.clone());
499
    cfg.save()?;
500
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
501
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
502
    Ok(0)
503
}
504
505
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
506
/// it on the web, and the token arrives here.
507
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
508
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
509
    let c = Client::new(&t)?;
510
    let host = std::fs::read_to_string("/etc/hostname")
511
        .ok()
512
        .or_else(|| std::env::var("COMPUTERNAME").ok())
513
        .map(|h| h.trim().to_string())
514
        .filter(|h| !h.is_empty());
515
    let client = match host {
516
        Some(h) => format!("oh on {h}"),
517
        None => "oh".to_string(),
518
    };
519
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
520
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
521
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
522
    if code != 200 {
523
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
524
    }
525
    let device = v["device_code"].as_str().context("no device code")?.to_string();
526
    let user = v["user_code"].as_str().unwrap_or("?");
527
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
528
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
529
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
530
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
531
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
532
    loop {
533
        std::thread::sleep(std::time::Duration::from_secs(interval));
534
        if std::time::Instant::now() > deadline {
535
            bail!("the code expired before it was approved; run oh auth login again");
536
        }
537
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
538
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
539
        if code == 200 {
540
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
541
        }
542
        match v["error"].as_str() {
543
            Some("authorization_pending") => {}
544
            Some("slow_down") => interval += 5,
545
            Some("access_denied") => bail!("the sign-in was denied on the web"),
546
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
547
            _ => bail!("signing in: HTTP {code}: {body}"),
548
        }
549
    }
550
}
551
552
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
553
    match (body, file) {
554
        (Some(b), _) => Ok(b),
555
        (None, Some(f)) if f == "-" => {
556
            let mut s = String::new();
557
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
558
            Ok(s)
559
        }
560
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
561
        (None, None) => Ok(String::new()),
562
    }
563
}
564
565
fn issue_line(i: &Issue) -> String {
566
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
567
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
568
    format!(
569
        "{glyph} {} {}{}{}",
570
        ui::dim(&format!("#{}", i.number)),
571
        i.title,
572
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
573
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
574
    )
575
}
576
577
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
578
    let base = t.repo_path()?;
579
    match cmd {
580
        IssueCmd::List { state } => {
581
            let path = format!("{base}/issues?state={}", enc(&state));
582
            if json {
583
                println!("{}", c.get_text(&path)?);
584
                return Ok(0);
585
            }
586
            let list: Vec<Issue> = c.get(&path)?;
587
            if list.is_empty() {
588
                println!("{}", ui::dim(&format!("No {state} issues.")));
589
            }
590
            for i in &list {
591
                println!("{}", issue_line(i));
592
            }
593
        }
594
        IssueCmd::View { number } => {
595
            let path = format!("{base}/issues/{number}");
596
            if json {
597
                println!("{}", c.get_text(&path)?);
598
                return Ok(0);
599
            }
600
            let i: Issue = c.get(&path)?;
601
            println!("{}", issue_line(&i));
602
            if !i.body.trim().is_empty() {
603
                println!("\n{}\n", i.body.trim_end());
604
            }
605
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
606
            for cm in comments {
607
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
608
            }
609
            println!("{}", ui::dim(&i.url));
610
        }
611
        IssueCmd::Create { title, body, body_file, label } => {
612
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
613
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
614
            if json {
615
                println!("{}", serde_json::to_string(&i)?);
616
            } else {
617
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
618
            }
619
        }
620
        IssueCmd::Close { number, reason } => {
621
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
622
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
623
        }
624
        IssueCmd::Reopen { number } => {
625
            let i: Issue =
626
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
627
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
628
        }
629
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
630
            let body = match (&body, &body_file) {
631
                (None, None) => None,
632
                _ => Some(body_of(body, body_file)?),
633
            };
634
            let labels = if no_labels {
635
                Some(Vec::new())
636
            } else if label.is_empty() {
637
                None
638
            } else {
639
                Some(label)
640
            };
641
            let assignees = if no_assignees {
642
                Some(Vec::new())
643
            } else if assignee.is_empty() {
644
                None
645
            } else {
646
                Some(assignee)
647
            };
648
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
649
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
650
            }
651
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
652
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
653
            if json {
654
                println!("{}", serde_json::to_string(&i)?);
655
            } else {
656
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
657
            }
658
        }
659
        IssueCmd::Label(change) => {
660
            let path = format!("{base}/issues/{}", change.number);
661
            let now: Issue = c.get(&path)?;
662
            let labels = change.apply(&now.labels)?;
663
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
664
            let i: Issue = c.send("PATCH", &path, &edit)?;
665
            if json {
666
                println!("{}", serde_json::to_string(&i)?);
667
            } else {
668
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
669
            }
670
        }
671
        IssueCmd::Comment { number, body } => {
672
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
673
            println!("{} commented on #{number}", ui::ok("✔"));
674
        }
675
    }
676
    Ok(0)
677
}
678
679
fn source_name(s: &hub_api::ProposalSource) -> String {
680
    match s {
681
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
682
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
683
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
684
    }
685
}
686
687
fn proposal_line(p: &Proposal) -> String {
688
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
689
    let glyph = match state.as_str() {
690
        "open" => ui::ok("●"),
691
        "draft" => ui::dim("◌"),
692
        "landed" => ui::strong("✔"),
693
        _ => ui::dim("○"),
694
    };
695
    format!(
696
        "{glyph} {} {} {}{}",
697
        ui::dim(&format!("#{}", p.number)),
698
        p.title,
699
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
700
        ui::dim(&format!(" · {} · {state}", p.author))
701
    )
702
}
703
704
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
705
    let base = t.repo_path()?;
706
    match cmd {
707
        ProposalCmd::List { state } => {
708
            let path = format!("{base}/proposals?state={state}");
709
            if json {
710
                println!("{}", c.get_text(&path)?);
711
                return Ok(0);
712
            }
713
            let list: Vec<Proposal> = c.get(&path)?;
714
            if list.is_empty() {
715
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
716
            }
717
            for p in &list {
718
                println!("{}", proposal_line(p));
719
            }
720
        }
721
        ProposalCmd::View { number } => {
722
            let path = format!("{base}/proposals/{number}");
723
            if json {
724
                println!("{}", c.get_text(&path)?);
725
                return Ok(0);
726
            }
727
            let p: Proposal = c.get(&path)?;
728
            println!("{}", proposal_line(&p));
729
            if !p.body.trim().is_empty() {
730
                println!("\n{}\n", p.body.trim_end());
731
            }
732
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
733
            for ch in &p.changes {
734
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
735
            }
736
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
737
            if p.landable {
738
                println!("{} can land", ui::ok("✔"));
739
            } else {
740
                for b in &p.blockers {
741
                    println!("{} {b}", ui::bad("✘"));
742
                }
743
            }
744
            if p.conflicted {
745
                println!("{} landing it would leave conflicts", ui::bad("!"));
746
            }
747
            println!("{}", ui::dim(&p.url));
748
        }
749
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
750
            let target = match into {
751
                Some(i) => i,
752
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
753
            };
754
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
755
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
756
            if json {
757
                println!("{}", serde_json::to_string(&p)?);
758
            } else {
759
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
760
            }
761
        }
762
        ProposalCmd::Edit { number, title, body, body_file } => {
763
            let body = match (&body, &body_file) {
764
                (None, None) => None,
765
                _ => Some(body_of(body, body_file)?),
766
            };
767
            if title.is_none() && body.is_none() {
768
                bail!("say what to change: --title, --body or --body-file");
769
            }
770
            let edit = hub_api::ProposalEdit { title, body, labels: None };
771
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
772
            if json {
773
                println!("{}", serde_json::to_string(&p)?);
774
            } else {
775
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
776
            }
777
        }
778
        ProposalCmd::Label(change) => {
779
            let path = format!("{base}/proposals/{}", change.number);
780
            let now: Proposal = c.get(&path)?;
781
            let labels = change.apply(&now.labels)?;
782
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
783
            let p: Proposal = c.send("PATCH", &path, &edit)?;
784
            if json {
785
                println!("{}", serde_json::to_string(&p)?);
786
            } else {
787
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
788
            }
789
        }
790
        ProposalCmd::Comment { number, body, body_file } => {
791
            let body = body_of(body, body_file)?;
792
            if body.trim().is_empty() {
793
                bail!("give the comment with --body or --body-file");
794
            }
795
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
796
            println!("{} commented on #{number}", ui::ok("✔"));
797
        }
798
        ProposalCmd::Land { number } => {
799
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &serde_json::json!({}))?;
800
            if json {
801
                println!("{}", serde_json::to_string(&p)?);
802
            } else {
803
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
804
            }
805
        }
806
        ProposalCmd::Checks { number } => {
807
            let path = format!("{base}/proposals/{number}/checks");
808
            if json {
809
                println!("{}", c.get_text(&path)?);
810
                return Ok(0);
811
            }
812
            let checks: Vec<hub_api::Check> = c.get(&path)?;
813
            if checks.is_empty() {
814
                println!("{}", ui::dim("No checks yet."));
815
            }
816
            for ch in checks {
817
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
818
            }
819
        }
820
    }
821
    Ok(0)
822
}
823
824
fn run_line(r: &FlowRun) -> String {
825
    let what =
826
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
827
    format!(
828
        "{} {} {} {}",
829
        ui::status(&r.status),
830
        ui::dim(&format!("#{}", r.number)),
831
        what,
832
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
833
    )
834
}
835
836
fn print_run(r: &FlowRun) {
837
    println!("{}", run_line(r));
838
    for j in &r.jobs {
839
        let dur = match (j.started_ms, j.finished_ms) {
840
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
841
            _ => String::new(),
842
        };
843
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
844
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
845
    }
846
    if !r.error.is_empty() {
847
        println!("{}", ui::bad(&r.error));
848
    }
849
    println!("{}", ui::dim(&r.url));
850
}
851
852
fn live(status: &str) -> bool {
853
    matches!(status, "queued" | "running")
854
}
855
856
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
857
    let path = format!("{base}/flow/runs/{number}");
858
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
859
    loop {
860
        let r: FlowRun = c.get(&path)?;
861
        if !json {
862
            for j in &r.jobs {
863
                if seen.get(&j.name) != Some(&j.status) {
864
                    println!("{} {}", ui::status(&j.status), j.name);
865
                    seen.insert(j.name.clone(), j.status.clone());
866
                }
867
            }
868
        }
869
        if !live(&r.status) {
870
            if json {
871
                println!("{}", serde_json::to_string(&r)?);
872
            } else {
873
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
874
            }
875
            return Ok(if r.status == "passed" { 0 } else { 1 });
876
        }
877
        std::thread::sleep(Duration::from_secs(3));
878
    }
879
}
880
881
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
882
    let base = t.repo_path()?;
883
    match cmd {
884
        RunCmd::List { limit } => {
885
            let path = format!("{base}/flow/runs?limit={limit}");
886
            if json {
887
                println!("{}", c.get_text(&path)?);
888
                return Ok(0);
889
            }
890
            let runs: Vec<FlowRun> = c.get(&path)?;
891
            if runs.is_empty() {
892
                println!("{}", ui::dim("No runs yet."));
893
            }
894
            for r in &runs {
895
                println!("{}", run_line(r));
896
            }
897
        }
898
        RunCmd::View { number } => {
899
            let path = format!("{base}/flow/runs/{number}");
900
            if json {
901
                println!("{}", c.get_text(&path)?);
902
                return Ok(0);
903
            }
904
            print_run(&c.get(&path)?);
905
        }
906
        RunCmd::Start { bookmark, change, watch: follow } => {
907
            let body = match (bookmark, change) {
908
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
909
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
910
                (None, None) => serde_json::json!({}),
911
            };
912
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
913
            let n = started["number"].as_i64().context("the hub named no run")?;
914
            if !json || !follow {
915
                if json {
916
                    println!("{started}");
917
                } else {
918
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
919
                }
920
            }
921
            if follow {
922
                return watch(c, &base, n, json);
923
            }
924
        }
925
        RunCmd::Watch { number } => return watch(c, &base, number, json),
926
        RunCmd::Log { number, job } => {
927
            let mut after = 0;
928
            loop {
929
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
930
                let lines: Vec<FlowLogLine> = c.get(&path)?;
931
                if lines.is_empty() {
932
                    break;
933
                }
934
                for l in &lines {
935
                    if json {
936
                        println!("{}", serde_json::to_string(l)?);
937
                    } else if l.stream == "flow" {
938
                        println!("{}", ui::dim(&l.text));
939
                    } else {
940
                        println!("{}", l.text);
941
                    }
942
                }
943
                after = lines.last().map(|l| l.seq).unwrap_or(after);
944
            }
945
        }
946
        RunCmd::Rerun { number } => {
947
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
948
            if json {
949
                println!("{started}");
950
            } else {
951
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
952
            }
953
        }
954
        RunCmd::Cancel { number } => {
955
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
956
            if json {
957
                println!("{done}");
958
            } else {
959
                println!("{} cancelled run #{number}", ui::ok("✔"));
960
            }
961
        }
962
    }
963
    Ok(0)
964
}
965
966
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
967
    let base = t.repo_path()?;
968
    match cmd {
969
        LabelCmd::List => {
970
            let path = format!("{base}/labels");
971
            if json {
972
                println!("{}", c.get_text(&path)?);
973
                return Ok(0);
974
            }
975
            let labels: Vec<hub_api::Label> = c.get(&path)?;
976
            if labels.is_empty() {
977
                println!("{}", ui::dim("No labels."));
978
            }
979
            for l in labels {
980
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
981
            }
982
        }
983
        LabelCmd::Create { name, colour, description } => {
984
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
985
            if json {
986
                println!("{}", serde_json::to_string(&l)?);
987
            } else {
988
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
989
            }
990
        }
991
        LabelCmd::Delete { name } => {
992
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
993
            println!("{} deleted label {name}", ui::ok("✔"));
994
        }
995
    }
996
    Ok(0)
997
}
998
999
fn milestone_line(m: &hub_api::Milestone) -> String {
1000
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
1001
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
1002
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
1003
}
1004
1005
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
1006
    let base = t.repo_path()?;
1007
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
1008
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
1009
        if json {
1010
            println!("{}", serde_json::to_string(&m)?);
1011
        } else {
1012
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
1013
        }
1014
        Ok(())
1015
    };
1016
    match cmd {
1017
        MilestoneCmd::List => {
1018
            let path = format!("{base}/milestones");
1019
            if json {
1020
                println!("{}", c.get_text(&path)?);
1021
                return Ok(0);
1022
            }
1023
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
1024
            if list.is_empty() {
1025
                println!("{}", ui::dim("No milestones."));
1026
            }
1027
            for m in &list {
1028
                println!("{}", milestone_line(m));
1029
            }
1030
        }
1031
        MilestoneCmd::Create { title, description, due } => {
1032
            let m: hub_api::Milestone =
1033
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
1034
            if json {
1035
                println!("{}", serde_json::to_string(&m)?);
1036
            } else {
1037
                println!("{} milestone {}", ui::ok("✔"), m.title);
1038
            }
1039
        }
1040
        MilestoneCmd::Edit { title, rename, description, due } => {
1041
            if rename.is_none() && description.is_none() && due.is_none() {
1042
                bail!("say what to change: --rename, --description or --due");
1043
            }
1044
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
1045
        }
1046
        MilestoneCmd::Close { title } => {
1047
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
1048
        }
1049
        MilestoneCmd::Reopen { title } => {
1050
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
1051
        }
1052
    }
1053
    Ok(0)
1054
}
1055
1056
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
1057
    let base = t.repo_path()?;
1058
    match cmd {
1059
        ReleaseCmd::List => {
1060
            let path = format!("{base}/releases");
1061
            if json {
1062
                println!("{}", c.get_text(&path)?);
1063
                return Ok(0);
1064
            }
1065
            let list: Vec<Release> = c.get(&path)?;
1066
            if list.is_empty() {
1067
                println!("{}", ui::dim("No releases."));
1068
            }
1069
            for r in &list {
1070
                println!(
1071
                    "{} {} {}{}",
1072
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
1073
                    ui::strong(&r.tag),
1074
                    r.title,
1075
                    ui::dim(&format!(
1076
                        " · {} asset{} · {}",
1077
                        r.assets.len(),
1078
                        if r.assets.len() == 1 { "" } else { "s" },
1079
                        ui::ago(r.created_ms)
1080
                    ))
1081
                );
1082
            }
1083
        }
1084
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
1085
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
1086
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
1087
            if json {
1088
                println!("{}", serde_json::to_string(&r)?);
1089
            } else {
1090
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
1091
            }
1092
        }
1093
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
1094
            let notes = match notes.as_deref() {
1095
                Some("-") => Some(body_of(None, Some("-".into()))?),
1096
                _ => notes,
1097
            };
1098
            if title.is_none() && notes.is_none() && prerelease.is_none() {
1099
                bail!("say what to change: --title, --notes or --prerelease");
1100
            }
1101
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
1102
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
1103
            if json {
1104
                println!("{}", serde_json::to_string(&r)?);
1105
            } else {
1106
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
1107
            }
1108
        }
1109
        ReleaseCmd::Upload { tag, files } => {
1110
            if files.is_empty() {
1111
                bail!("name the files to attach");
1112
            }
1113
            for f in files {
1114
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
1115
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
1116
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
1117
                println!("{} attached {name} to {tag}", ui::ok("✔"));
1118
            }
1119
        }
1120
        ReleaseCmd::Trust { tag } => {
1121
            let path = format!("{base}/releases/trust/{}", enc(&tag));
1122
            if json {
1123
                println!("{}", c.get_text(&path)?);
1124
                return Ok(0);
1125
            }
1126
            let r: serde_json::Value = c.get(&path)?;
1127
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
1128
            let mut worst = 0;
1129
            for ch in r["audit"].as_array().into_iter().flatten() {
1130
                let v = ch["verdict"].as_str().unwrap_or("");
1131
                worst = worst.max(match v {
1132
                    "fail" => 2,
1133
                    "warn" => 1,
1134
                    _ => 0,
1135
                });
1136
                let g = match v {
1137
                    "pass" => ui::ok("✔"),
1138
                    "warn" => ui::warn("!"),
1139
                    _ => ui::bad("✘"),
1140
                };
1141
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
1142
            }
1143
            return Ok(if worst == 2 { 1 } else { 0 });
1144
        }
1145
    }
1146
    Ok(0)
1147
}