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