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