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