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