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