OXYGENHUB
◆ cancel-landed-runs oxygenhub / crates / oh / src / main.rs
70.0 KiB · Rust · last changed Land when checks pass 17 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
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
61
    Coverage {
62
        #[command(subcommand)]
63
        cmd: CoverageCmd,
64
    },
65
    /// OxygenFlow runs
66
    Run {
67
        #[command(subcommand)]
68
        cmd: RunCmd,
69
    },
70
    /// Releases
71
    Release {
72
        #[command(subcommand)]
73
        cmd: ReleaseCmd,
74
    },
75
    /// The repository's labels
76
    Label {
77
        #[command(subcommand)]
78
        cmd: LabelCmd,
79
    },
80
    /// Milestones: list, create, edit, close
81
    Milestone {
82
        #[command(subcommand)]
83
        cmd: MilestoneCmd,
84
    },
85
    /// Project boards of the repository's owner (or --owner): list,
86
    /// create, view, and cards
87
    Project {
88
        #[command(subcommand)]
89
        cmd: ProjectCmd,
90
        /// A user or organisation other than the repository's owner
91
        #[arg(long, global = true)]
92
        owner: Option<String>,
93
    },
94
    /// AI assistants of the repository (its admins), or with --org or
95
    /// --site of an organisation or the site
96
    Assistant {
97
        #[command(subcommand)]
98
        cmd: AssistantCmd,
99
        /// An organisation's assistants instead of the repository's
100
        #[arg(long, global = true)]
101
        org: Option<String>,
102
        /// The site's assistants (administrators)
103
        #[arg(long, global = true, conflicts_with = "org")]
104
        site: bool,
105
    },
106
    /// Agents that act for you without a key of their own (keyless
107
    /// signing): grant, list, revoke
108
    Agent {
109
        #[command(subcommand)]
110
        cmd: AgentCmd,
111
    },
112
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
113
    Api {
114
        /// A path under /api/v1
115
        path: String,
116
        /// The method
117
        #[arg(long, short = 'X', default_value = "GET")]
118
        method: String,
119
        /// A JSON body
120
        #[arg(long, short = 'd')]
121
        data: Option<String>,
122
    },
123
}
124
125
#[derive(Subcommand)]
126
enum AgentCmd {
127
    /// Let an agent act for you: your oxy key (the one your oxy home names
128
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
129
    /// the agent a token it exchanges for ten-minute certificates. The
130
    /// token is printed once: give it to the agent (`oxy auth grant`)
131
    Grant {
132
        /// The agent's name, as in agent:NAME@YOU
133
        name: String,
134
        /// What its keys may do for you: changes, seal, refs
135
        #[arg(long, default_value = "changes,seal,refs")]
136
        scope: String,
137
        /// How long the grant lasts: 30d, 12h, 90m
138
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
139
        lasts: String,
140
    },
141
    /// Your grants, live and past
142
    List,
143
    /// Stop a grant at once: no more certificates under it
144
    Revoke { id: i64 },
145
}
146
147
#[derive(Subcommand)]
148
enum AuthCmd {
149
    /// Sign in to a hub and make it the default: approve a code on the web
150
    /// (device sign-in), or give a token
151
    Login {
152
        /// The hub, e.g. https://oxygenhub.io
153
        #[arg(long = "with-hub", value_name = "URL")]
154
        url: String,
155
        /// An API token from the hub's Settings → Tokens, instead of
156
        /// approving a code ("-" reads it from stdin)
157
        #[arg(long)]
158
        token: Option<String>,
159
        /// The hub's CA certificate, when self-signed
160
        #[arg(long)]
161
        ca: Option<std::path::PathBuf>,
162
    },
163
    /// Who the token in use belongs to
164
    Status,
165
}
166
167
#[derive(Subcommand)]
168
enum RepoCmd {
169
    /// Name, description, visibility and default bookmark
170
    View,
171
}
172
173
#[derive(Subcommand)]
174
enum IssueCmd {
175
    /// Put labels on an issue or take them off (triage)
176
    Label(LabelChange),
177
    /// Open issues (or --state closed|all)
178
    List {
179
        #[arg(long, default_value = "open")]
180
        state: String,
181
    },
182
    /// One issue with its comments
183
    View { number: i64 },
184
    /// Open an issue
185
    Create {
186
        #[arg(long, short)]
187
        title: String,
188
        #[arg(long, short)]
189
        body: Option<String>,
190
        /// Read the body from a file ("-" for stdin)
191
        #[arg(long, short = 'F')]
192
        body_file: Option<String>,
193
        /// A label (repeatable)
194
        #[arg(long, short)]
195
        label: Vec<String>,
196
        /// Also put it on this board of the repository's owner
197
        #[arg(long, short)]
198
        project: Option<i64>,
199
        /// The board's column for it, by name (default: the first)
200
        #[arg(long, requires = "project")]
201
        column: Option<String>,
202
    },
203
    /// Close an issue
204
    Close {
205
        number: i64,
206
        /// `completed` or `not_planned`
207
        #[arg(long, default_value = "completed")]
208
        reason: String,
209
    },
210
    /// Reopen an issue
211
    Reopen { number: i64 },
212
    /// Change an issue's title or body (its author or triage), or its
213
    /// labels, assignees or milestone as whole sets (triage)
214
    Edit {
215
        number: i64,
216
        #[arg(long, short)]
217
        title: Option<String>,
218
        #[arg(long, short)]
219
        body: Option<String>,
220
        /// Read the body from a file ("-" for stdin)
221
        #[arg(long, short = 'F', conflicts_with = "body")]
222
        body_file: Option<String>,
223
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
224
        #[arg(long, short)]
225
        label: Vec<String>,
226
        /// Clear its labels
227
        #[arg(long, conflicts_with = "label")]
228
        no_labels: bool,
229
        /// The users it should be assigned to (repeatable)
230
        #[arg(long, short)]
231
        assignee: Vec<String>,
232
        /// Take everyone off it
233
        #[arg(long, conflicts_with = "assignee")]
234
        no_assignees: bool,
235
        /// A milestone's title ("" takes it out of its milestone)
236
        #[arg(long, short)]
237
        milestone: Option<String>,
238
    },
239
    /// Comment on an issue
240
    Comment {
241
        number: i64,
242
        #[arg(long, short)]
243
        body: Option<String>,
244
        /// Read the body from a file ("-" for stdin), as proposal comment
245
        /// does (#260)
246
        #[arg(long, short = 'F', conflicts_with = "body")]
247
        body_file: Option<String>,
248
    },
249
}
250
251
#[derive(Subcommand)]
252
enum ProposalCmd {
253
    /// Open proposals (or --state draft|landed|closed|all)
254
    List {
255
        #[arg(long, default_value = "open")]
256
        state: String,
257
    },
258
    /// One proposal: its changes, approvals and whether it can land
259
    View { number: i64 },
260
    /// Propose a bookmark's changes for another bookmark
261
    Create {
262
        #[arg(long, short)]
263
        title: String,
264
        #[arg(long, short)]
265
        body: Option<String>,
266
        /// Read the body from a file ("-" for stdin)
267
        #[arg(long, short = 'F', conflicts_with = "body")]
268
        body_file: Option<String>,
269
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
270
        #[arg(long)]
271
        from: String,
272
        /// The bookmark to land them on (default: the repository's default bookmark)
273
        #[arg(long)]
274
        into: Option<String>,
275
        #[arg(long)]
276
        draft: bool,
277
    },
278
    /// Change a proposal's title or description (its author or a maintainer)
279
    Edit {
280
        number: i64,
281
        #[arg(long, short)]
282
        title: Option<String>,
283
        #[arg(long, short)]
284
        body: Option<String>,
285
        /// Read the body from a file ("-" for stdin)
286
        #[arg(long, short = 'F', conflicts_with = "body")]
287
        body_file: Option<String>,
288
    },
289
    /// Put labels on a proposal or take them off (triage)
290
    Label(LabelChange),
291
    /// Comment on a proposal's conversation
292
    Comment {
293
        number: i64,
294
        #[arg(long, short)]
295
        body: Option<String>,
296
        /// Read the comment from a file ("-" for stdin)
297
        #[arg(long, short = 'F', conflicts_with = "body")]
298
        body_file: Option<String>,
299
    },
300
    /// The checks on a proposal's projected state
301
    Checks { number: i64 },
302
    /// Land a proposal on its target, as the page's Land button does
303
    Land {
304
        number: i64,
305
        /// Land before its required checks pass, saying why (maintainers;
306
        /// recorded and audited, #261)
307
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
308
        over_checks: Option<String>,
309
        /// Land it by itself once its checks pass (#261); with --off, don't
310
        #[arg(long)]
311
        when_ready: bool,
312
        /// With --when-ready: turn it off
313
        #[arg(long, requires = "when_ready")]
314
        off: bool,
315
    },
316
    /// Close a proposal without landing it, with an optional comment
317
    Close {
318
        number: i64,
319
        /// Say why, as a comment before it closes
320
        #[arg(long, short = 'm')]
321
        message: Option<String>,
322
    },
323
    /// Reopen a closed proposal
324
    Reopen { number: i64 },
325
}
326
327
#[derive(Subcommand)]
328
enum AssistantCmd {
329
    /// The assistants this level sees, its own and those inherited
330
    List,
331
    /// Add an assistant, or change the one of that name
332
    Add {
333
        /// How it shows on reviews (default: the provider's name)
334
        #[arg(long, default_value = "")]
335
        name: String,
336
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
337
        #[arg(long, default_value = "")]
338
        preset: String,
339
        /// The endpoint, when no preset or another one
340
        #[arg(long, default_value = "")]
341
        endpoint: String,
342
        /// chat-completions or anthropic-messages
343
        #[arg(long, default_value = "")]
344
        api: String,
345
        /// One the endpoint lists (`oh assistant models` shows them)
346
        #[arg(long)]
347
        model: String,
348
        /// The API key, read from this environment variable (never typed on the command line)
349
        #[arg(long, value_name = "VAR")]
350
        token_env: Option<String>,
351
        /// Add it turned off
352
        #[arg(long)]
353
        off: bool,
354
    },
355
    /// Remove this level's assistant of that name
356
    Remove { name: String },
357
    /// Show this level's prompt, and those it inherits
358
    Prompt {
359
        /// Set it from this file (`-` for standard input; an empty file clears it)
360
        #[arg(long, value_name = "FILE")]
361
        set: Option<std::path::PathBuf>,
362
    },
363
}
364
365
#[derive(Subcommand)]
366
enum LabelCmd {
367
    /// The repository's labels
368
    List,
369
    /// Create a label, or change the one of that name (triage)
370
    Create {
371
        name: String,
372
        /// `#rrggbb` (default: one the hub picks)
373
        #[arg(long)]
374
        colour: Option<String>,
375
        #[arg(long, short, default_value = "")]
376
        description: String,
377
    },
378
    /// Delete a label, taking it off every issue and proposal (triage)
379
    Delete { name: String },
380
}
381
382
#[derive(Subcommand)]
383
enum ProjectCmd {
384
    /// The owner's boards
385
    List,
386
    /// One board: its columns and cards
387
    View { number: i64 },
388
    /// Create a board (owner, or an organisation's members)
389
    Create {
390
        title: String,
391
        #[arg(long, short, default_value = "")]
392
        description: String,
393
        /// Only the owner (or the organisation's members) can see it
394
        #[arg(long)]
395
        private: bool,
396
    },
397
    /// Close a board
398
    Close { number: i64 },
399
    /// Reopen a board
400
    Reopen { number: i64 },
401
    /// Move a board to another owner you may make boards under (an
402
    /// organisation, say); it takes the next number there
403
    Transfer {
404
        number: i64,
405
        /// The new owner
406
        #[arg(long)]
407
        to: String,
408
    },
409
    /// Cards on a board: add, move, remove
410
    Card {
411
        #[command(subcommand)]
412
        cmd: CardCmd,
413
    },
414
}
415
416
#[derive(Subcommand)]
417
enum CardCmd {
418
    /// Put an issue or proposal on a board (`12` or `#12` in this
419
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
420
    /// or a note with --note
421
    Add {
422
        number: i64,
423
        /// The issue or proposal; a number means this repository's
424
        reference: Option<String>,
425
        /// A note card instead
426
        #[arg(long, conflicts_with = "reference")]
427
        note: Option<String>,
428
        /// The column, by name or id (default: the first)
429
        #[arg(long, short)]
430
        column: Option<String>,
431
    },
432
    /// Move a card to another column (by name or id)
433
    Move {
434
        number: i64,
435
        card: i64,
436
        #[arg(long, short)]
437
        column: String,
438
    },
439
    /// Take a card off a board
440
    Remove { number: i64, card: i64 },
441
}
442
443
#[derive(Subcommand)]
444
enum MilestoneCmd {
445
    /// The repository's milestones
446
    List,
447
    /// Create a milestone, or change the one of that title (triage)
448
    Create {
449
        title: String,
450
        #[arg(long, short, default_value = "")]
451
        description: String,
452
        /// Due date, YYYY-MM-DD
453
        #[arg(long)]
454
        due: Option<String>,
455
    },
456
    /// Change a milestone's title, description or due date (triage)
457
    Edit {
458
        title: String,
459
        #[arg(long, short)]
460
        rename: Option<String>,
461
        #[arg(long, short)]
462
        description: Option<String>,
463
        /// Due date, YYYY-MM-DD ("" for none)
464
        #[arg(long)]
465
        due: Option<String>,
466
    },
467
    /// Close a milestone
468
    Close { title: String },
469
    /// Reopen a milestone
470
    Reopen { title: String },
471
}
472
473
/// Labels to put on or take off an issue or proposal.
474
#[derive(clap::Args)]
475
struct LabelChange {
476
    number: i64,
477
    /// A label to add (repeatable)
478
    #[arg(long, short)]
479
    add: Vec<String>,
480
    /// A label to take off (repeatable)
481
    #[arg(long, short)]
482
    remove: Vec<String>,
483
}
484
485
impl LabelChange {
486
    /// The set after the change, from the one there now.
487
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
488
        if self.add.is_empty() && self.remove.is_empty() {
489
            bail!("say what to change: --add NAME or --remove NAME");
490
        }
491
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
492
        for a in &self.add {
493
            if !names.contains(a) {
494
                names.push(a.clone());
495
            }
496
        }
497
        Ok(names)
498
    }
499
}
500
501
fn label_names(labels: &[String]) -> String {
502
    if labels.is_empty() {
503
        ui::dim("no labels")
504
    } else {
505
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
506
    }
507
}
508
509
#[derive(Subcommand)]
510
enum CoverageCmd {
511
    /// Upload an LCOV or Cobertura report measured on this machine, as the
512
    /// coverage of a bookmark's current state (default: the default
513
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
514
    /// not measured by a runner, and sets no check from it
515
    Upload {
516
        file: std::path::PathBuf,
517
        #[arg(long)]
518
        bookmark: Option<String>,
519
        /// A change's full hash
520
        #[arg(long, conflicts_with = "bookmark")]
521
        change: Option<String>,
522
    },
523
}
524
525
#[derive(Subcommand)]
526
enum RunCmd {
527
    /// Recent runs, newest first
528
    List {
529
        #[arg(long, default_value_t = 20)]
530
        limit: i64,
531
    },
532
    /// A run and its jobs
533
    View { number: i64 },
534
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
535
    Start {
536
        #[arg(long)]
537
        bookmark: Option<String>,
538
        /// A change's full hash
539
        #[arg(long, conflicts_with = "bookmark")]
540
        change: Option<String>,
541
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
542
        #[arg(long = "job", value_name = "NAME")]
543
        jobs: Vec<String>,
544
        /// Wait for the run and exit 1 unless it passes
545
        #[arg(long)]
546
        watch: bool,
547
    },
548
    /// Follow a run until it finishes; exit 1 unless it passes
549
    Watch { number: i64 },
550
    /// A job's log
551
    Log { number: i64, job: String },
552
    /// Run a finished run's state again; with --job, only that job (and the
553
    /// jobs that depend on it) in the same run
554
    Rerun {
555
        number: i64,
556
        #[arg(long)]
557
        job: Option<String>,
558
    },
559
    /// Cancel a run still queued or running; its running jobs are stopped
560
    Cancel { number: i64 },
561
    /// Approve a job that waits for a person (oxygenflow#57)
562
    Approve {
563
        number: i64,
564
        #[arg(long)]
565
        job: String,
566
    },
567
    /// Reject a job that waits for a person: it ends cancelled
568
    Reject {
569
        number: i64,
570
        #[arg(long)]
571
        job: String,
572
    },
573
}
574
575
#[derive(Subcommand)]
576
enum ReleaseCmd {
577
    /// Releases, newest first
578
    List,
579
    /// Create a release on an existing tag
580
    Create {
581
        tag: String,
582
        #[arg(long, short)]
583
        title: Option<String>,
584
        /// Notes in Markdown (default: generated from the changes since the previous release)
585
        #[arg(long, short)]
586
        notes: Option<String>,
587
        #[arg(long)]
588
        prerelease: bool,
589
    },
590
    /// Change a release's title, notes or prerelease flag
591
    Edit {
592
        tag: String,
593
        #[arg(long, short)]
594
        title: Option<String>,
595
        /// New notes in Markdown ("-" reads them from stdin)
596
        #[arg(long, short)]
597
        notes: Option<String>,
598
        /// Mark it a prerelease (true) or not (false)
599
        #[arg(long)]
600
        prerelease: Option<bool>,
601
    },
602
    /// Attach files to a release
603
    Upload { tag: String, files: Vec<std::path::PathBuf> },
604
    /// The release's trust report: signatures, builds, receipts and audit
605
    Trust { tag: String },
606
}
607
608
fn main() {
609
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
610
    // other command-line tools do, instead of panicking on the failed
611
    // write (oxygenhub#92).
612
    #[cfg(unix)]
613
    unsafe {
614
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
615
    }
616
    let cli = Cli::parse();
617
    ui::init(cli.plain);
618
    match run(cli) {
619
        Ok(code) => std::process::exit(code),
620
        Err(e) => {
621
            eprintln!("{} {e:#}", ui::bad("error:"));
622
            std::process::exit(2);
623
        }
624
    }
625
}
626
627
fn enc(s: &str) -> String {
628
    let mut out = String::new();
629
    for b in s.bytes() {
630
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
631
            out.push(b as char);
632
        } else {
633
            out.push_str(&format!("%{b:02X}"));
634
        }
635
    }
636
    out
637
}
638
639
fn run(cli: Cli) -> Result<i32> {
640
    let cfg = Config::load()?;
641
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
642
        return login(cfg, url, token.clone(), ca.clone());
643
    }
644
    let here = std::env::current_dir()?;
645
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
646
    let c = Client::new(&t)?;
647
    let json = cli.json;
648
    match cli.cmd {
649
        Cmd::Auth { cmd: AuthCmd::Status } => {
650
            let me: serde_json::Value = c.get("/user")?;
651
            if json {
652
                println!("{me}");
653
            } else {
654
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
655
            }
656
            Ok(0)
657
        }
658
        Cmd::Auth { .. } => unreachable!(),
659
        Cmd::Api { path, method, data } => {
660
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
661
            // The method applies with or without a body (#75): without one, a
662
            // GET reads, anything else sends an empty object.
663
            let text = match data {
664
                Some(d) => c.send_text(
665
                    &method.to_uppercase(),
666
                    &path,
667
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
668
                )?,
669
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
670
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
671
            };
672
            println!("{text}");
673
            Ok(0)
674
        }
675
        Cmd::Repo { cmd: RepoCmd::View } => {
676
            let path = t.repo_path()?;
677
            if json {
678
                println!("{}", c.get_text(&path)?);
679
                return Ok(0);
680
            }
681
            let r: serde_json::Value = c.get(&path)?;
682
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
683
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
684
                println!("{d}");
685
            }
686
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
687
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
688
            Ok(0)
689
        }
690
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
691
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
692
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
693
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
694
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
695
            let mut body = serde_json::json!({ "content": content });
696
            if let Some(b) = bookmark {
697
                body["bookmark"] = b.into();
698
            }
699
            if let Some(ch) = change {
700
                body["change"] = ch.into();
701
            }
702
            let base = t.repo_path()?;
703
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
704
            if json {
705
                println!("{}", serde_json::to_string(&r)?);
706
            } else {
707
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
708
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
709
                println!(
710
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
711
                    ui::ok("✔"),
712
                    r.lines_hit,
713
                    r.lines_found,
714
                    r.files,
715
                    ui::dim(&r.url)
716
                );
717
                if r.dropped > 0 {
718
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
719
                }
720
            }
721
            Ok(0)
722
        }
723
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
724
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
725
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
726
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
727
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
728
        Cmd::Agent { cmd } => agent(&c, cmd, json),
729
    }
730
}
731
732
/// `30d`, `12h`, `90m` in milliseconds.
733
fn duration_ms(s: &str) -> Result<i64> {
734
    let s = s.trim();
735
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
736
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
737
    let per = match unit {
738
        "d" => 86_400_000,
739
        "h" => 3_600_000,
740
        "m" => 60_000,
741
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
742
    };
743
    if n <= 0 {
744
        bail!("a grant must last some time");
745
    }
746
    Ok(n * per)
747
}
748
749
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
750
    use oxy_core::cert::{Grant, SignedGrant};
751
    use oxy_core::identity::{Identity, Scope};
752
    match cmd {
753
        AgentCmd::Grant { name, scope, lasts } => {
754
            let home = oxy_core::repo::default_home();
755
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
756
                format!(
757
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
758
                    home.display()
759
                )
760
            })?;
761
            let me: serde_json::Value = c.get("/user")?;
762
            let username = me["username"].as_str().context("the hub did not say who you are")?;
763
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
764
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
765
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
766
            let grant = Grant {
767
                grantor: me_id.hash(),
768
                subject: format!("agent:{name}@{username}"),
769
                issuer: hub.hash(),
770
                scope,
771
                not_before: (now - 60_000) as u64,
772
                expires: (now + duration_ms(&lasts)?) as u64,
773
            };
774
            let signed = SignedGrant::sign(grant, &me_id, &sk);
775
            let r: serde_json::Value =
776
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
777
            if json {
778
                println!("{r}");
779
                return Ok(0);
780
            }
781
            println!(
782
                "{} {} to act for you as {} ({}), until {}",
783
                ui::ok("✔ granted"),
784
                ui::strong(&name),
785
                r["subject"].as_str().unwrap_or(""),
786
                r["scope"].as_str().unwrap_or(""),
787
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
788
            );
789
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
790
            println!(
791
                "  {}",
792
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
793
            );
794
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
795
            Ok(0)
796
        }
797
        AgentCmd::List => {
798
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
799
            if json {
800
                println!("{}", serde_json::to_string(&grants)?);
801
                return Ok(0);
802
            }
803
            if grants.is_empty() {
804
                println!("{}", ui::dim("no agent grants"));
805
            }
806
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
807
            for g in grants {
808
                let state = if g["revoked_ms"].is_i64() {
809
                    ui::bad("revoked")
810
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
811
                    ui::dim("ended")
812
                } else {
813
                    ui::ok("live")
814
                };
815
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
816
                println!(
817
                    "#{:<4} {:<8} {} · {} · until {} · {}",
818
                    g["id"],
819
                    state,
820
                    ui::strong(g["subject"].as_str().unwrap_or("")),
821
                    g["scope"].as_str().unwrap_or(""),
822
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
823
                    ui::dim(&used)
824
                );
825
            }
826
            Ok(0)
827
        }
828
        AgentCmd::Revoke { id } => {
829
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
830
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
831
            Ok(0)
832
        }
833
    }
834
}
835
836
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
837
    let hub = url.trim_end_matches('/').to_string();
838
    let token = match token.as_deref() {
839
        Some("-") => {
840
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
841
            let mut line = String::new();
842
            std::io::stdin().read_line(&mut line)?;
843
            line.trim().to_string()
844
        }
845
        Some(t) => t.to_string(),
846
        None => device_sign_in(&hub, ca.clone())?,
847
    };
848
    if token.is_empty() {
849
        bail!("no token given");
850
    }
851
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
852
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
853
    let account = me["username"].as_str().unwrap_or("?");
854
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
855
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
856
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
857
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
858
    cfg.default_hub = Some(hub.clone());
859
    cfg.save()?;
860
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
861
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
862
    Ok(0)
863
}
864
865
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
866
/// it on the web, and the token arrives here.
867
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
868
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
869
    let c = Client::new(&t)?;
870
    let host = std::fs::read_to_string("/etc/hostname")
871
        .ok()
872
        .or_else(|| std::env::var("COMPUTERNAME").ok())
873
        .map(|h| h.trim().to_string())
874
        .filter(|h| !h.is_empty());
875
    let client = match host {
876
        Some(h) => format!("oh on {h}"),
877
        None => "oh".to_string(),
878
    };
879
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
880
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
881
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
882
    if code != 200 {
883
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
884
    }
885
    let device = v["device_code"].as_str().context("no device code")?.to_string();
886
    let user = v["user_code"].as_str().unwrap_or("?");
887
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
888
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
889
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
890
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
891
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
892
    loop {
893
        std::thread::sleep(std::time::Duration::from_secs(interval));
894
        if std::time::Instant::now() > deadline {
895
            bail!("the code expired before it was approved; run oh auth login again");
896
        }
897
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
898
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
899
        if code == 200 {
900
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
901
        }
902
        match v["error"].as_str() {
903
            Some("authorization_pending") => {}
904
            Some("slow_down") => interval += 5,
905
            Some("access_denied") => bail!("the sign-in was denied on the web"),
906
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
907
            _ => bail!("signing in: HTTP {code}: {body}"),
908
        }
909
    }
910
}
911
912
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
913
    match (body, file) {
914
        (Some(b), _) => Ok(b),
915
        (None, Some(f)) if f == "-" => {
916
            let mut s = String::new();
917
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
918
            Ok(s)
919
        }
920
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
921
        (None, None) => Ok(String::new()),
922
    }
923
}
924
925
fn issue_line(i: &Issue) -> String {
926
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
927
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
928
    format!(
929
        "{glyph} {} {}{}{}",
930
        ui::dim(&format!("#{}", i.number)),
931
        i.title,
932
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
933
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
934
    )
935
}
936
937
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
938
    let base = t.repo_path()?;
939
    match cmd {
940
        IssueCmd::List { state } => {
941
            let path = format!("{base}/issues?state={}", enc(&state));
942
            if json {
943
                println!("{}", c.get_text(&path)?);
944
                return Ok(0);
945
            }
946
            let list: Vec<Issue> = c.get(&path)?;
947
            if list.is_empty() {
948
                println!("{}", ui::dim(&format!("No {state} issues.")));
949
            }
950
            for i in &list {
951
                println!("{}", issue_line(i));
952
            }
953
        }
954
        IssueCmd::View { number } => {
955
            let path = format!("{base}/issues/{number}");
956
            if json {
957
                println!("{}", c.get_text(&path)?);
958
                return Ok(0);
959
            }
960
            let i: Issue = c.get(&path)?;
961
            println!("{}", issue_line(&i));
962
            if !i.body.trim().is_empty() {
963
                println!("\n{}\n", i.body.trim_end());
964
            }
965
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
966
            for cm in comments {
967
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
968
            }
969
            println!("{}", ui::dim(&i.url));
970
        }
971
        IssueCmd::Create { title, body, body_file, label, project, column } => {
972
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
973
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
974
            if json {
975
                println!("{}", serde_json::to_string(&i)?);
976
            } else {
977
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
978
            }
979
            if let Some(n) = project {
980
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
981
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
982
                if !json {
983
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
984
                }
985
            }
986
        }
987
        IssueCmd::Close { number, reason } => {
988
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
989
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
990
        }
991
        IssueCmd::Reopen { number } => {
992
            let i: Issue =
993
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
994
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
995
        }
996
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
997
            let body = match (&body, &body_file) {
998
                (None, None) => None,
999
                _ => Some(body_of(body, body_file)?),
1000
            };
1001
            let labels = if no_labels {
1002
                Some(Vec::new())
1003
            } else if label.is_empty() {
1004
                None
1005
            } else {
1006
                Some(label)
1007
            };
1008
            let assignees = if no_assignees {
1009
                Some(Vec::new())
1010
            } else if assignee.is_empty() {
1011
                None
1012
            } else {
1013
                Some(assignee)
1014
            };
1015
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
1016
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
1017
            }
1018
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
1019
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
1020
            if json {
1021
                println!("{}", serde_json::to_string(&i)?);
1022
            } else {
1023
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
1024
            }
1025
        }
1026
        IssueCmd::Label(change) => {
1027
            let path = format!("{base}/issues/{}", change.number);
1028
            let now: Issue = c.get(&path)?;
1029
            let labels = change.apply(&now.labels)?;
1030
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
1031
            let i: Issue = c.send("PATCH", &path, &edit)?;
1032
            if json {
1033
                println!("{}", serde_json::to_string(&i)?);
1034
            } else {
1035
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
1036
            }
1037
        }
1038
        IssueCmd::Comment { number, body, body_file } => {
1039
            let body = body_of(body, body_file)?;
1040
            if body.trim().is_empty() {
1041
                bail!("give the comment with --body or --body-file");
1042
            }
1043
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
1044
            println!("{} commented on #{number}", ui::ok("✔"));
1045
        }
1046
    }
1047
    Ok(0)
1048
}
1049
1050
fn source_name(s: &hub_api::ProposalSource) -> String {
1051
    match s {
1052
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
1053
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
1054
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1055
    }
1056
}
1057
1058
fn proposal_line(p: &Proposal) -> String {
1059
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
1060
    let glyph = match state.as_str() {
1061
        "open" => ui::ok("●"),
1062
        "draft" => ui::dim("◌"),
1063
        "landed" => ui::strong("✔"),
1064
        _ => ui::dim("○"),
1065
    };
1066
    format!(
1067
        "{glyph} {} {} {}{}",
1068
        ui::dim(&format!("#{}", p.number)),
1069
        p.title,
1070
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
1071
        ui::dim(&format!(" · {} · {state}", p.author))
1072
    )
1073
}
1074
1075
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
1076
    let base = t.repo_path()?;
1077
    match cmd {
1078
        ProposalCmd::List { state } => {
1079
            let path = format!("{base}/proposals?state={state}");
1080
            if json {
1081
                println!("{}", c.get_text(&path)?);
1082
                return Ok(0);
1083
            }
1084
            let list: Vec<Proposal> = c.get(&path)?;
1085
            if list.is_empty() {
1086
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
1087
            }
1088
            for p in &list {
1089
                println!("{}", proposal_line(p));
1090
            }
1091
        }
1092
        ProposalCmd::View { number } => {
1093
            let path = format!("{base}/proposals/{number}");
1094
            if json {
1095
                println!("{}", c.get_text(&path)?);
1096
                return Ok(0);
1097
            }
1098
            let p: Proposal = c.get(&path)?;
1099
            println!("{}", proposal_line(&p));
1100
            if !p.body.trim().is_empty() {
1101
                println!("\n{}\n", p.body.trim_end());
1102
            }
1103
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
1104
            for ch in &p.changes {
1105
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
1106
            }
1107
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
1108
            if p.landable {
1109
                println!("{} can land", ui::ok("✔"));
1110
            } else {
1111
                for b in &p.blockers {
1112
                    println!("{} {b}", ui::bad("✘"));
1113
                }
1114
            }
1115
            if p.conflicted {
1116
                println!("{} landing it would leave conflicts", ui::bad("!"));
1117
            }
1118
            println!("{}", ui::dim(&p.url));
1119
        }
1120
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
1121
            let target = match into {
1122
                Some(i) => i,
1123
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1124
            };
1125
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
1126
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
1127
            if json {
1128
                println!("{}", serde_json::to_string(&p)?);
1129
            } else {
1130
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1131
            }
1132
        }
1133
        ProposalCmd::Edit { number, title, body, body_file } => {
1134
            let body = match (&body, &body_file) {
1135
                (None, None) => None,
1136
                _ => Some(body_of(body, body_file)?),
1137
            };
1138
            if title.is_none() && body.is_none() {
1139
                bail!("say what to change: --title, --body or --body-file");
1140
            }
1141
            let edit = hub_api::ProposalEdit { title, body, labels: None, state: None };
1142
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1143
            if json {
1144
                println!("{}", serde_json::to_string(&p)?);
1145
            } else {
1146
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1147
            }
1148
        }
1149
        ProposalCmd::Label(change) => {
1150
            let path = format!("{base}/proposals/{}", change.number);
1151
            let now: Proposal = c.get(&path)?;
1152
            let labels = change.apply(&now.labels)?;
1153
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
1154
            let p: Proposal = c.send("PATCH", &path, &edit)?;
1155
            if json {
1156
                println!("{}", serde_json::to_string(&p)?);
1157
            } else {
1158
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
1159
            }
1160
        }
1161
        ProposalCmd::Comment { number, body, body_file } => {
1162
            let body = body_of(body, body_file)?;
1163
            if body.trim().is_empty() {
1164
                bail!("give the comment with --body or --body-file");
1165
            }
1166
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1167
            println!("{} commented on #{number}", ui::ok("✔"));
1168
        }
1169
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
1170
            let path = format!("{base}/proposals/{number}/auto-land");
1171
            let p: Proposal =
1172
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
1173
            if json {
1174
                println!("{}", serde_json::to_string(&p)?);
1175
            } else if p.landed.is_some() {
1176
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
1177
            } else if p.auto_land.is_some() {
1178
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
1179
            } else {
1180
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
1181
            }
1182
        }
1183
        ProposalCmd::Land { number, over_checks, .. } => {
1184
            let body = match &over_checks {
1185
                Some(r) => serde_json::json!({ "over_checks": r }),
1186
                None => serde_json::json!({}),
1187
            };
1188
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
1189
            if json {
1190
                println!("{}", serde_json::to_string(&p)?);
1191
            } else {
1192
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
1193
            }
1194
        }
1195
        ProposalCmd::Close { number, message } => {
1196
            if let Some(body) = message {
1197
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1198
            }
1199
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
1200
            if json {
1201
                println!("{}", serde_json::to_string(&p)?);
1202
            } else {
1203
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
1204
            }
1205
        }
1206
        ProposalCmd::Reopen { number } => {
1207
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
1208
            if json {
1209
                println!("{}", serde_json::to_string(&p)?);
1210
            } else {
1211
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
1212
            }
1213
        }
1214
        ProposalCmd::Checks { number } => {
1215
            let path = format!("{base}/proposals/{number}/checks");
1216
            if json {
1217
                println!("{}", c.get_text(&path)?);
1218
                return Ok(0);
1219
            }
1220
            let checks: Vec<hub_api::Check> = c.get(&path)?;
1221
            if checks.is_empty() {
1222
                println!("{}", ui::dim("No checks yet."));
1223
            }
1224
            for ch in checks {
1225
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
1226
            }
1227
        }
1228
    }
1229
    Ok(0)
1230
}
1231
1232
fn run_line(r: &FlowRun) -> String {
1233
    let what =
1234
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
1235
    format!(
1236
        "{} {} {} {}",
1237
        ui::status(&r.status),
1238
        ui::dim(&format!("#{}", r.number)),
1239
        what,
1240
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1241
    )
1242
}
1243
1244
fn print_run(r: &FlowRun) {
1245
    println!("{}", run_line(r));
1246
    for j in &r.jobs {
1247
        let dur = match (j.started_ms, j.finished_ms) {
1248
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
1249
            _ => String::new(),
1250
        };
1251
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
1252
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1253
        // Why a queued job no runner can take waits (oxygenhub#28), and
1254
        // why a job ran where it did (oxygenflow#42).
1255
        if j.status == "queued" && !j.waiting.is_empty() {
1256
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
1257
        } else if !j.placed.is_empty() {
1258
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
1259
        }
1260
    }
1261
    if !r.error.is_empty() {
1262
        println!("{}", ui::bad(&r.error));
1263
    }
1264
    println!("{}", ui::dim(&r.url));
1265
}
1266
1267
fn live(status: &str) -> bool {
1268
    matches!(status, "queued" | "running")
1269
}
1270
1271
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
1272
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
1273
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
1274
    if json {
1275
        println!("{done}");
1276
    } else {
1277
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
1278
    }
1279
    Ok(())
1280
}
1281
1282
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
1283
    let path = format!("{base}/flow/runs/{number}");
1284
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1285
    loop {
1286
        let r: FlowRun = c.get(&path)?;
1287
        if !json {
1288
            for j in &r.jobs {
1289
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
1290
                if seen.get(&j.name) != Some(&shown) {
1291
                    println!("{} {}", ui::status(&j.status), j.name);
1292
                    if j.status == "queued" && !j.waiting.is_empty() {
1293
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
1294
                    }
1295
                    seen.insert(j.name.clone(), shown);
1296
                }
1297
            }
1298
        }
1299
        if !live(&r.status) {
1300
            if json {
1301
                println!("{}", serde_json::to_string(&r)?);
1302
            } else {
1303
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
1304
            }
1305
            return Ok(if r.status == "passed" { 0 } else { 1 });
1306
        }
1307
        std::thread::sleep(Duration::from_secs(3));
1308
    }
1309
}
1310
1311
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
1312
    let base = t.repo_path()?;
1313
    match cmd {
1314
        RunCmd::List { limit } => {
1315
            let path = format!("{base}/flow/runs?limit={limit}");
1316
            if json {
1317
                println!("{}", c.get_text(&path)?);
1318
                return Ok(0);
1319
            }
1320
            let runs: Vec<FlowRun> = c.get(&path)?;
1321
            if runs.is_empty() {
1322
                println!("{}", ui::dim("No runs yet."));
1323
            }
1324
            for r in &runs {
1325
                println!("{}", run_line(r));
1326
            }
1327
        }
1328
        RunCmd::View { number } => {
1329
            let path = format!("{base}/flow/runs/{number}");
1330
            if json {
1331
                println!("{}", c.get_text(&path)?);
1332
                return Ok(0);
1333
            }
1334
            print_run(&c.get(&path)?);
1335
        }
1336
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
1337
            let mut body = match (bookmark, change) {
1338
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
1339
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
1340
                (None, None) => serde_json::json!({}),
1341
            };
1342
            if !jobs.is_empty() {
1343
                body["jobs"] = serde_json::json!(jobs);
1344
            }
1345
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
1346
            let n = started["number"].as_i64().context("the hub named no run")?;
1347
            if !json || !follow {
1348
                if json {
1349
                    println!("{started}");
1350
                } else {
1351
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
1352
                }
1353
            }
1354
            if follow {
1355
                return watch(c, &base, n, json);
1356
            }
1357
        }
1358
        RunCmd::Watch { number } => return watch(c, &base, number, json),
1359
        RunCmd::Log { number, job } => {
1360
            let mut after = 0;
1361
            loop {
1362
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
1363
                let lines: Vec<FlowLogLine> = c.get(&path)?;
1364
                if lines.is_empty() {
1365
                    break;
1366
                }
1367
                for l in &lines {
1368
                    if json {
1369
                        println!("{}", serde_json::to_string(l)?);
1370
                    } else if l.stream == "flow" {
1371
                        println!("{}", ui::dim(&l.text));
1372
                    } else {
1373
                        println!("{}", l.text);
1374
                    }
1375
                }
1376
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1377
            }
1378
        }
1379
        RunCmd::Rerun { number, job: Some(job) } => {
1380
            let queued: serde_json::Value =
1381
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
1382
            if json {
1383
                println!("{queued}");
1384
            } else {
1385
                let n = queued["queued"].as_i64().unwrap_or(1);
1386
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
1387
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
1388
            }
1389
        }
1390
        RunCmd::Rerun { number, job: None } => {
1391
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
1392
            if json {
1393
                println!("{started}");
1394
            } else {
1395
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
1396
            }
1397
        }
1398
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
1399
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
1400
        RunCmd::Cancel { number } => {
1401
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
1402
            if json {
1403
                println!("{done}");
1404
            } else {
1405
                println!("{} cancelled run #{number}", ui::ok("✔"));
1406
            }
1407
        }
1408
    }
1409
    Ok(0)
1410
}
1411
1412
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
1413
    let base = t.repo_path()?;
1414
    match cmd {
1415
        LabelCmd::List => {
1416
            let path = format!("{base}/labels");
1417
            if json {
1418
                println!("{}", c.get_text(&path)?);
1419
                return Ok(0);
1420
            }
1421
            let labels: Vec<hub_api::Label> = c.get(&path)?;
1422
            if labels.is_empty() {
1423
                println!("{}", ui::dim("No labels."));
1424
            }
1425
            for l in labels {
1426
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
1427
            }
1428
        }
1429
        LabelCmd::Create { name, colour, description } => {
1430
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
1431
            if json {
1432
                println!("{}", serde_json::to_string(&l)?);
1433
            } else {
1434
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
1435
            }
1436
        }
1437
        LabelCmd::Delete { name } => {
1438
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
1439
            println!("{} deleted label {name}", ui::ok("✔"));
1440
        }
1441
    }
1442
    Ok(0)
1443
}
1444
1445
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
1446
    let base = match (&org, site) {
1447
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
1448
        (None, true) => "/admin/assistants".to_string(),
1449
        (None, false) => format!("{}/assistants", t.repo_path()?),
1450
    };
1451
    match cmd {
1452
        AssistantCmd::List => {
1453
            if json {
1454
                println!("{}", c.get_text(&base)?);
1455
                return Ok(0);
1456
            }
1457
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
1458
            if list.is_empty() {
1459
                println!("{}", ui::dim("No assistants."));
1460
            }
1461
            for a in list {
1462
                let state = if a.enabled && !a.off_above {
1463
                    ui::ok("on")
1464
                } else if a.off_above {
1465
                    ui::dim("off above")
1466
                } else {
1467
                    ui::dim("off")
1468
                };
1469
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
1470
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
1471
            }
1472
        }
1473
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
1474
            let token = match token_env {
1475
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
1476
                None => String::new(),
1477
            };
1478
            let body =
1479
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
1480
            let r: serde_json::Value = c.send("POST", &base, &body)?;
1481
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
1482
        }
1483
        AssistantCmd::Remove { name } => {
1484
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
1485
            println!("{} removed {name}", ui::ok("✔"));
1486
        }
1487
        AssistantCmd::Prompt { set } => {
1488
            let p: hub_api::AssistantPrompt = match set {
1489
                Some(path) => {
1490
                    let text = if path.as_os_str() == "-" {
1491
                        let mut s = String::new();
1492
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1493
                        s
1494
                    } else {
1495
                        std::fs::read_to_string(&path)?
1496
                    };
1497
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
1498
                }
1499
                None => c.get(&format!("{base}/prompt"))?,
1500
            };
1501
            if json {
1502
                println!("{}", serde_json::to_string(&p)?);
1503
                return Ok(0);
1504
            }
1505
            for (from, text) in &p.inherited {
1506
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
1507
            }
1508
            if p.prompt.is_empty() {
1509
                println!("{}", ui::dim("No prompt of its own."));
1510
            } else {
1511
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
1512
            }
1513
        }
1514
    }
1515
    Ok(0)
1516
}
1517
1518
fn project_line(p: &hub_api::Project) -> String {
1519
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
1520
    let private = if p.public { "" } else { " · private" };
1521
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
1522
}
1523
1524
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
1525
    let owner = match owner {
1526
        Some(o) => o,
1527
        None => t.repo()?.0.to_string(),
1528
    };
1529
    let base = format!("/projects/{}", enc(&owner));
1530
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
1531
        let p: hub_api::Project =
1532
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
1533
        if json {
1534
            println!("{}", serde_json::to_string(&p)?);
1535
        } else {
1536
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
1537
        }
1538
        Ok(())
1539
    };
1540
    match cmd {
1541
        ProjectCmd::List => {
1542
            if json {
1543
                println!("{}", c.get_text(&base)?);
1544
                return Ok(0);
1545
            }
1546
            let list: Vec<hub_api::Project> = c.get(&base)?;
1547
            if list.is_empty() {
1548
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
1549
            }
1550
            for p in &list {
1551
                println!("{}", project_line(p));
1552
            }
1553
        }
1554
        ProjectCmd::View { number } => {
1555
            let path = format!("{base}/{number}");
1556
            if json {
1557
                println!("{}", c.get_text(&path)?);
1558
                return Ok(0);
1559
            }
1560
            let b: hub_api::Board = c.get(&path)?;
1561
            println!("{}", project_line(&b.project));
1562
            if !b.project.description.is_empty() {
1563
                println!("{}", b.project.description);
1564
            }
1565
            for col in &b.columns {
1566
                println!();
1567
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
1568
                if col.cards.is_empty() {
1569
                    println!("  {}", ui::dim("(empty)"));
1570
                }
1571
                for card in &col.cards {
1572
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
1573
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
1574
                    println!("  {} {what}{st}  {}", ui::dim(&format!("{:>4}", card.id)), card.title);
1575
                }
1576
            }
1577
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
1578
        }
1579
        ProjectCmd::Create { title, description, private } => {
1580
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
1581
            if json {
1582
                println!("{}", serde_json::to_string(&p)?);
1583
            } else {
1584
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
1585
            }
1586
        }
1587
        ProjectCmd::Close { number } => state(number, true, "closed")?,
1588
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
1589
        ProjectCmd::Transfer { number, to } => {
1590
            let p: hub_api::Project =
1591
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
1592
            if json {
1593
                println!("{}", serde_json::to_string(&p)?);
1594
            } else {
1595
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
1596
            }
1597
        }
1598
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
1599
            // The hub names a card's issue as `repo#N` among the owner's
1600
            // repositories.
1601
            let reference = match reference {
1602
                None => String::new(),
1603
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
1604
                    Some((o, rest)) if o == owner => rest.to_string(),
1605
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
1606
                    None => r,
1607
                },
1608
                Some(r) => {
1609
                    let n = r.trim_start_matches('#');
1610
                    if n.parse::<i64>().is_err() {
1611
                        bail!("{r}: give an issue or proposal number, or NAME#N");
1612
                    }
1613
                    format!("{}#{n}", t.repo()?.1)
1614
                }
1615
            };
1616
            let note = note.unwrap_or_default();
1617
            if reference.is_empty() && note.is_empty() {
1618
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
1619
            }
1620
            let card: hub_api::ProjectCard =
1621
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
1622
            if json {
1623
                println!("{}", serde_json::to_string(&card)?);
1624
            } else {
1625
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
1626
            }
1627
        }
1628
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column } } => {
1629
            c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
1630
            println!("{} card {card} moved to {column}", ui::ok("✔"));
1631
        }
1632
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
1633
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
1634
            println!("{} card {card} removed", ui::ok("✔"));
1635
        }
1636
    }
1637
    Ok(0)
1638
}
1639
1640
fn milestone_line(m: &hub_api::Milestone) -> String {
1641
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
1642
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
1643
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
1644
}
1645
1646
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
1647
    let base = t.repo_path()?;
1648
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
1649
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
1650
        if json {
1651
            println!("{}", serde_json::to_string(&m)?);
1652
        } else {
1653
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
1654
        }
1655
        Ok(())
1656
    };
1657
    match cmd {
1658
        MilestoneCmd::List => {
1659
            let path = format!("{base}/milestones");
1660
            if json {
1661
                println!("{}", c.get_text(&path)?);
1662
                return Ok(0);
1663
            }
1664
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
1665
            if list.is_empty() {
1666
                println!("{}", ui::dim("No milestones."));
1667
            }
1668
            for m in &list {
1669
                println!("{}", milestone_line(m));
1670
            }
1671
        }
1672
        MilestoneCmd::Create { title, description, due } => {
1673
            let m: hub_api::Milestone =
1674
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
1675
            if json {
1676
                println!("{}", serde_json::to_string(&m)?);
1677
            } else {
1678
                println!("{} milestone {}", ui::ok("✔"), m.title);
1679
            }
1680
        }
1681
        MilestoneCmd::Edit { title, rename, description, due } => {
1682
            if rename.is_none() && description.is_none() && due.is_none() {
1683
                bail!("say what to change: --rename, --description or --due");
1684
            }
1685
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
1686
        }
1687
        MilestoneCmd::Close { title } => {
1688
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
1689
        }
1690
        MilestoneCmd::Reopen { title } => {
1691
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
1692
        }
1693
    }
1694
    Ok(0)
1695
}
1696
1697
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
1698
    let base = t.repo_path()?;
1699
    match cmd {
1700
        ReleaseCmd::List => {
1701
            let path = format!("{base}/releases");
1702
            if json {
1703
                println!("{}", c.get_text(&path)?);
1704
                return Ok(0);
1705
            }
1706
            let list: Vec<Release> = c.get(&path)?;
1707
            if list.is_empty() {
1708
                println!("{}", ui::dim("No releases."));
1709
            }
1710
            for r in &list {
1711
                println!(
1712
                    "{} {} {}{}",
1713
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
1714
                    ui::strong(&r.tag),
1715
                    r.title,
1716
                    ui::dim(&format!(
1717
                        " · {} asset{} · {}",
1718
                        r.assets.len(),
1719
                        if r.assets.len() == 1 { "" } else { "s" },
1720
                        ui::ago(r.created_ms)
1721
                    ))
1722
                );
1723
            }
1724
        }
1725
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
1726
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
1727
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
1728
            if json {
1729
                println!("{}", serde_json::to_string(&r)?);
1730
            } else {
1731
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
1732
            }
1733
        }
1734
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
1735
            let notes = match notes.as_deref() {
1736
                Some("-") => Some(body_of(None, Some("-".into()))?),
1737
                _ => notes,
1738
            };
1739
            if title.is_none() && notes.is_none() && prerelease.is_none() {
1740
                bail!("say what to change: --title, --notes or --prerelease");
1741
            }
1742
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
1743
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
1744
            if json {
1745
                println!("{}", serde_json::to_string(&r)?);
1746
            } else {
1747
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
1748
            }
1749
        }
1750
        ReleaseCmd::Upload { tag, files } => {
1751
            if files.is_empty() {
1752
                bail!("name the files to attach");
1753
            }
1754
            for f in files {
1755
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
1756
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
1757
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
1758
                println!("{} attached {name} to {tag}", ui::ok("✔"));
1759
            }
1760
        }
1761
        ReleaseCmd::Trust { tag } => {
1762
            let path = format!("{base}/releases/trust/{}", enc(&tag));
1763
            if json {
1764
                println!("{}", c.get_text(&path)?);
1765
                return Ok(0);
1766
            }
1767
            let r: serde_json::Value = c.get(&path)?;
1768
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
1769
            let mut worst = 0;
1770
            for ch in r["audit"].as_array().into_iter().flatten() {
1771
                let v = ch["verdict"].as_str().unwrap_or("");
1772
                worst = worst.max(match v {
1773
                    "fail" => 2,
1774
                    "warn" => 1,
1775
                    _ => 0,
1776
                });
1777
                let g = match v {
1778
                    "pass" => ui::ok("✔"),
1779
                    "warn" => ui::warn("!"),
1780
                    _ => ui::bad("✘"),
1781
                };
1782
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
1783
            }
1784
            return Ok(if worst == 2 { 1 } else { 0 });
1785
        }
1786
    }
1787
    Ok(0)
1788
}