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