OXYGENHUB

Coverage / crates/oh/src/main.rs 40.6%

655 of 1613 lines run, 47 of 243 functions · run #534 on main · run missed

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 mcp;
7
mod target;
8
mod ui;
9
10
use anyhow::{bail, Context, Result};
11
use clap::{Parser, Subcommand};
12
use client::Client;
13
use hub_api::{
14
    FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag,
15
};
16
use std::time::Duration;
17
use target::{Choice, Config, Target};
18
19
#[derive(Parser)]
20
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")]
21
struct Cli {
22
    /// The repository, when not inside an Oxygen checkout
23
    #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")]
24
    repo: Option<String>,
25
    /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved)
26
    #[arg(long, global = true, value_name = "URL")]
27
    hub: Option<String>,
28
    /// Which of the checkout's remotes to use (default: origin, or the only one)
29
    #[arg(long, global = true)]
30
    remote: Option<String>,
31
    /// Machine-readable output: the API's JSON, unchanged
32
    #[arg(long, global = true)]
33
    json: bool,
34
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
35
    #[arg(long, global = true)]
36
    plain: bool,
37
    #[command(subcommand)]
38
    cmd: Cmd,
39
}
40
41
#[derive(Subcommand)]
42
enum Cmd {
43
    /// Sign in to a hub, or show who you are signed in as
44
    Auth {
45
        #[command(subcommand)]
46
        cmd: AuthCmd,
47
    },
48
    /// The repository
49
    Repo {
50
        #[command(subcommand)]
51
        cmd: RepoCmd,
52
    },
53
    /// Issues
54
    Issue {
55
        #[command(subcommand)]
56
        cmd: IssueCmd,
57
    },
58
    /// Proposals (pull requests)
59
    Proposal {
60
        #[command(subcommand)]
61
        cmd: ProposalCmd,
62
    },
63
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
64
    Coverage {
65
        #[command(subcommand)]
66
        cmd: CoverageCmd,
67
    },
68
    /// OxygenFlow runs
69
    Run {
70
        #[command(subcommand)]
71
        cmd: RunCmd,
72
    },
73
    /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348)
74
    Report {
75
        #[command(subcommand)]
76
        cmd: ReportCmd,
77
    },
78
    /// Releases
79
    Release {
80
        #[command(subcommand)]
81
        cmd: ReleaseCmd,
82
    },
83
    /// Tags: list, create, withdraw
84
    Tag {
85
        #[command(subcommand)]
86
        cmd: TagCmd,
87
    },
88
    /// The repository's labels
89
    Label {
90
        #[command(subcommand)]
91
        cmd: LabelCmd,
92
    },
93
    /// Milestones: list, create, edit, close
94
    Milestone {
95
        #[command(subcommand)]
96
        cmd: MilestoneCmd,
97
    },
98
    /// Project boards of the repository's owner (or --owner): list,
99
    /// create, view, and cards
100
    Project {
101
        #[command(subcommand)]
102
        cmd: ProjectCmd,
103
        /// A user or organisation other than the repository's owner
104
        #[arg(long, global = true)]
105
        owner: Option<String>,
106
    },
107
    /// AI assistants of the repository (its admins), or with --org or
108
    /// --site of an organisation or the site
109
    Assistant {
110
        #[command(subcommand)]
111
        cmd: AssistantCmd,
112
        /// An organisation's assistants instead of the repository's
113
        #[arg(long, global = true)]
114
        org: Option<String>,
115
        /// The site's assistants (administrators)
116
        #[arg(long, global = true, conflicts_with = "org")]
117
        site: bool,
118
    },
119
    /// Agents that act for you without a key of their own (keyless
120
    /// signing): grant, list, revoke
121
    Agent {
122
        #[command(subcommand)]
123
        cmd: AgentCmd,
124
    },
125
    /// Drops: small snippets of files, each its own repository, never
126
    /// listed among your repositories (oxygenhub#279)
127
    Drop {
128
        #[command(subcommand)]
129
        cmd: DropCmd,
130
    },
131
    /// Runners that update themselves (site administrators; oxygenhub#322):
132
    /// where builds come from, who takes them, what is held back
133
    #[command(name = "runner-updates")]
134
    RunnerUpdates {
135
        #[command(subcommand)]
136
        cmd: Option<RunnerUpdatesCmd>,
137
    },
138
    /// Serve this repository's hub to an AI agent over the Model Context Protocol (stdio); read-only unless --allow-write
139
    Mcp {
140
        /// Also offer tools that change the hub: create, comment on and close issues, comment on proposals, re-run Flow runs
141
        #[arg(long)]
142
        allow_write: bool,
143
    },
144
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
145
    Api {
146
        /// A path under /api/v1
147
        path: String,
148
        /// The method
149
        #[arg(long, short = 'X', default_value = "GET")]
150
        method: String,
151
        /// A JSON body
152
        #[arg(long, short = 'd')]
153
        data: Option<String>,
154
    },
155
}
156
157
#[derive(Subcommand)]
158
enum AgentCmd {
159
    /// Let an agent act for you: your oxy key (the one your oxy home names
160
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
161
    /// the agent a token it exchanges for ten-minute certificates. The
162
    /// token is printed once: give it to the agent (`oxy auth grant`)
163
    Grant {
164
        /// The agent's name, as in agent:NAME@YOU
165
        name: String,
166
        /// What its keys may do for you: changes, seal, refs
167
        #[arg(long, default_value = "changes,seal,refs")]
168
        scope: String,
169
        /// How long the grant lasts: 30d, 12h, 90m
170
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
171
        lasts: String,
172
    },
173
    /// Your grants, live and past
174
    List,
175
    /// Stop a grant at once: no more certificates under it
176
    Revoke { id: i64 },
177
}
178
179
#[derive(Subcommand)]
180
enum DropCmd {
181
    /// Make a drop of these files, signed by the hub as your delegate
182
    Create {
183
        /// The files (their names in the drop are their file names)
184
        #[arg(required = true)]
185
        files: Vec<std::path::PathBuf>,
186
        /// Unlisted: readable by anyone with its address, listed nowhere
187
        #[arg(long)]
188
        secret: bool,
189
        /// A description
190
        #[arg(long, short = 'd', value_name = "TEXT")]
191
        description: Option<String>,
192
        /// A title (default: the first file's name)
193
        #[arg(long, short = 't')]
194
        title: Option<String>,
195
    },
196
    /// Your drops, or someone's public ones
197
    List {
198
        /// Whose drops
199
        #[arg(long, short = 'u', value_name = "NAME")]
200
        user: Option<String>,
201
    },
202
    /// A drop's files, printed (by id or address)
203
    View {
204
        /// The drop's id, or its address
205
        id: String,
206
        /// Print only this file's content
207
        #[arg(long, short = 'f', value_name = "NAME")]
208
        file: Option<String>,
209
    },
210
    /// Delete a drop and its history
211
    Delete {
212
        /// The drop's id, or its address
213
        id: String,
214
    },
215
    /// A copy of someone's drop, history and all, as a drop of yours
216
    Fork {
217
        /// The drop's id, or its address
218
        id: String,
219
    },
220
    /// Star a drop
221
    Star {
222
        /// The drop's id, or its address
223
        id: String,
224
    },
225
    /// Take your star back
226
    Unstar {
227
        /// The drop's id, or its address
228
        id: String,
229
    },
230
    /// A drop's comments, oldest first
231
    Comments {
232
        /// The drop's id, or its address
233
        id: String,
234
    },
235
    /// Comment on a drop (Markdown); its owner is told
236
    Comment {
237
        /// The drop's id, or its address
238
        id: String,
239
        /// What to say
240
        #[arg(long, short = 'm')]
241
        message: String,
242
    },
243
}
244
245
#[derive(Subcommand)]
246
enum RunnerUpdatesCmd {
247
    /// Every level's settings, the test groups, each runner's policy and what it is offered (the default)
248
    Show,
249
    /// Change one level's settings; what is not given stays as it is
250
    Set {
251
        /// `site`, `owner:NAME`, `group:NAME` (or `group:OWNER/NAME`, `group:ID`), `runner:NAME` (or `runner:ID`)
252
        scope: String,
253
        /// `on`, `off` or `inherit`
254
        #[arg(long)]
255
        updates: Option<String>,
256
        /// `stable`, `canary`, a version, or `inherit`
257
        #[arg(long)]
258
        channel: Option<String>,
259
        /// Hours (UTC) updates may start in, `02-05`, or `inherit`
260
        #[arg(long)]
261
        window: Option<String>,
262
        /// `on`, `off` or `inherit`
263
        #[arg(long)]
264
        dry_run: Option<String>,
265
    },
266
    /// Offer a held build again (it rolled back on a runner)
267
    Lift { version: String },
268
}
269
270
#[derive(Subcommand)]
271
enum AuthCmd {
272
    /// Sign in to a hub and make it the default: approve a code on the web
273
    /// (device sign-in), or give a token
274
    Login {
275
        /// The hub, e.g. https://oxygenhub.io
276
        #[arg(long = "with-hub", value_name = "URL")]
277
        url: String,
278
        /// An API token from the hub's Settings → Tokens, instead of
279
        /// approving a code ("-" reads it from stdin)
280
        #[arg(long)]
281
        token: Option<String>,
282
        /// The hub's CA certificate, when self-signed
283
        #[arg(long)]
284
        ca: Option<std::path::PathBuf>,
285
    },
286
    /// Who the token in use belongs to
287
    Status,
288
}
289
290
#[derive(Subcommand)]
291
enum RepoCmd {
292
    /// Name, description, visibility and default bookmark
293
    View,
294
}
295
296
#[derive(Subcommand)]
297
enum IssueCmd {
298
    /// Put labels on an issue or take them off (triage)
299
    Label(LabelChange),
300
    /// Open issues (or --state closed|all)
301
    List {
302
        #[arg(long, default_value = "open")]
303
        state: String,
304
    },
305
    /// One issue with its comments
306
    View { number: i64 },
307
    /// Open an issue
308
    Create {
309
        #[arg(long, short)]
310
        title: String,
311
        #[arg(long, short)]
312
        body: Option<String>,
313
        /// Read the body from a file ("-" for stdin)
314
        #[arg(long, short = 'F')]
315
        body_file: Option<String>,
316
        /// A label (repeatable)
317
        #[arg(long, short)]
318
        label: Vec<String>,
319
        /// Also put it on this board of the repository's owner
320
        #[arg(long, short)]
321
        project: Option<i64>,
322
        /// The board's column for it, by name (default: the first)
323
        #[arg(long, requires = "project")]
324
        column: Option<String>,
325
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
326
        #[arg(long, short = 'a', value_name = "FILE")]
327
        attach: Vec<std::path::PathBuf>,
328
    },
329
    /// Close an issue
330
    Close {
331
        number: i64,
332
        /// `completed` or `not_planned`
333
        #[arg(long, default_value = "completed")]
334
        reason: String,
335
    },
336
    /// Reopen an issue
337
    Reopen { number: i64 },
338
    /// Change an issue's title or body (its author or triage), or its
339
    /// labels, assignees or milestone as whole sets (triage)
340
    Edit {
341
        number: i64,
342
        #[arg(long, short)]
343
        title: Option<String>,
344
        #[arg(long, short)]
345
        body: Option<String>,
346
        /// Read the body from a file ("-" for stdin)
347
        #[arg(long, short = 'F', conflicts_with = "body")]
348
        body_file: Option<String>,
349
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
350
        #[arg(long, short)]
351
        label: Vec<String>,
352
        /// Clear its labels
353
        #[arg(long, conflicts_with = "label")]
354
        no_labels: bool,
355
        /// The users it should be assigned to (repeatable)
356
        #[arg(long, short)]
357
        assignee: Vec<String>,
358
        /// Take everyone off it
359
        #[arg(long, conflicts_with = "assignee")]
360
        no_assignees: bool,
361
        /// A milestone's title ("" takes it out of its milestone)
362
        #[arg(long, short)]
363
        milestone: Option<String>,
364
    },
365
    /// Comment on an issue
366
    Comment {
367
        number: i64,
368
        #[arg(long, short)]
369
        body: Option<String>,
370
        /// Read the body from a file ("-" for stdin), as proposal comment
371
        /// does (#260)
372
        #[arg(long, short = 'F', conflicts_with = "body")]
373
        body_file: Option<String>,
374
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
375
        #[arg(long, short = 'a', value_name = "FILE")]
376
        attach: Vec<std::path::PathBuf>,
377
    },
378
}
379
380
#[derive(Subcommand)]
381
enum ProposalCmd {
382
    /// Open proposals (or --state draft|landed|closed|all), newest first
383
    List {
384
        #[arg(long, default_value = "open")]
385
        state: String,
386
        /// At most this many
387
        #[arg(long, default_value_t = 30)]
388
        limit: usize,
389
    },
390
    /// One proposal: its changes, approvals and whether it can land
391
    View { number: i64 },
392
    /// Propose a bookmark's changes for another bookmark
393
    Create {
394
        #[arg(long, short)]
395
        title: String,
396
        #[arg(long, short)]
397
        body: Option<String>,
398
        /// Read the body from a file ("-" for stdin)
399
        #[arg(long, short = 'F', conflicts_with = "body")]
400
        body_file: Option<String>,
401
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
402
        #[arg(long)]
403
        from: String,
404
        /// The bookmark to land them on (default: the repository's default bookmark)
405
        #[arg(long)]
406
        into: Option<String>,
407
        #[arg(long)]
408
        draft: bool,
409
    },
410
    /// Change a proposal's title or description (its author or a maintainer)
411
    Edit {
412
        number: i64,
413
        #[arg(long, short)]
414
        title: Option<String>,
415
        #[arg(long, short)]
416
        body: Option<String>,
417
        /// Read the body from a file ("-" for stdin)
418
        #[arg(long, short = 'F', conflicts_with = "body")]
419
        body_file: Option<String>,
420
    },
421
    /// Put labels on a proposal or take them off (triage)
422
    Label(LabelChange),
423
    /// Comment on a proposal's conversation
424
    Comment {
425
        number: i64,
426
        #[arg(long, short)]
427
        body: Option<String>,
428
        /// Read the comment from a file ("-" for stdin)
429
        #[arg(long, short = 'F', conflicts_with = "body")]
430
        body_file: Option<String>,
431
    },
432
    /// The checks on a proposal's projected state
433
    Checks { number: i64 },
434
    /// Land a proposal on its target, as the page's Land button does
435
    Land {
436
        number: i64,
437
        /// Land before its required checks pass, saying why (maintainers;
438
        /// recorded and audited, #261)
439
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
440
        over_checks: Option<String>,
441
        /// Land it by itself once its checks pass (#261); with --off, don't
442
        #[arg(long)]
443
        when_ready: bool,
444
        /// With --when-ready: turn it off
445
        #[arg(long, requires = "when_ready")]
446
        off: bool,
447
    },
448
    /// Close a proposal without landing it, with an optional comment
449
    Close {
450
        number: i64,
451
        /// Say why, as a comment before it closes
452
        #[arg(long, short = 'm')]
453
        message: Option<String>,
454
    },
455
    /// Reopen a closed proposal
456
    Reopen { number: i64 },
457
    /// Take a draft proposal out of draft, ready for review (its author or triage)
458
    Ready {
459
        number: i64,
460
        /// Turn an open proposal back into a draft instead
461
        #[arg(long)]
462
        undo: bool,
463
    },
464
}
465
466
#[derive(Subcommand)]
467
enum AssistantCmd {
468
    /// The assistants this level sees, its own and those inherited
469
    List,
470
    /// Add an assistant, or change the one of that name
471
    Add {
472
        /// How it shows on reviews (default: the provider's name)
473
        #[arg(long, default_value = "")]
474
        name: String,
475
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
476
        #[arg(long, default_value = "")]
477
        preset: String,
478
        /// The endpoint, when no preset or another one
479
        #[arg(long, default_value = "")]
480
        endpoint: String,
481
        /// chat-completions or anthropic-messages
482
        #[arg(long, default_value = "")]
483
        api: String,
484
        /// One the endpoint lists (`oh assistant models` shows them)
485
        #[arg(long)]
486
        model: String,
487
        /// The API key, read from this environment variable (never typed on the command line)
488
        #[arg(long, value_name = "VAR")]
489
        token_env: Option<String>,
490
        /// Add it turned off
491
        #[arg(long)]
492
        off: bool,
493
    },
494
    /// Remove this level's assistant of that name
495
    Remove { name: String },
496
    /// Show this level's prompt, and those it inherits
497
    Prompt {
498
        /// Set it from this file (`-` for standard input; an empty file clears it)
499
        #[arg(long, value_name = "FILE")]
500
        set: Option<std::path::PathBuf>,
501
    },
502
}
503
504
#[derive(Subcommand)]
505
enum LabelCmd {
506
    /// The repository's labels
507
    List,
508
    /// Create a label, or change the one of that name (triage)
509
    Create {
510
        name: String,
511
        /// `#rrggbb` (default: one the hub picks)
512
        #[arg(long)]
513
        colour: Option<String>,
514
        #[arg(long, short, default_value = "")]
515
        description: String,
516
    },
517
    /// Delete a label, taking it off every issue and proposal (triage)
518
    Delete { name: String },
519
}
520
521
#[derive(Subcommand)]
522
enum ProjectCmd {
523
    /// The owner's boards
524
    List,
525
    /// One board: its columns and cards
526
    View {
527
        number: i64,
528
        /// Its archived cards instead (#293)
529
        #[arg(long)]
530
        archived: bool,
531
    },
532
    /// Create a board (owner, or an organisation's members)
533
    Create {
534
        title: String,
535
        #[arg(long, short, default_value = "")]
536
        description: String,
537
        /// Only the owner (or the organisation's members) can see it
538
        #[arg(long)]
539
        private: bool,
540
    },
541
    /// Close a board
542
    Close { number: i64 },
543
    /// Reopen a board
544
    Reopen { number: i64 },
545
    /// Move a board to another owner you may make boards under (an
546
    /// organisation, say); it takes the next number there
547
    Transfer {
548
        number: i64,
549
        /// The new owner
550
        #[arg(long)]
551
        to: String,
552
    },
553
    /// Cards on a board: add, move, archive, restore, remove
554
    Card {
555
        #[command(subcommand)]
556
        cmd: CardCmd,
557
    },
558
}
559
560
#[derive(Subcommand)]
561
enum CardCmd {
562
    /// Put an issue or proposal on a board (`12` or `#12` in this
563
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
564
    /// or a note with --note
565
    Add {
566
        number: i64,
567
        /// The issue or proposal; a number means this repository's
568
        reference: Option<String>,
569
        /// A note card instead
570
        #[arg(long, conflicts_with = "reference")]
571
        note: Option<String>,
572
        /// The column, by name or id (default: the first)
573
        #[arg(long, short)]
574
        column: Option<String>,
575
    },
576
    /// Move a card to another column (by name or id), or with --from every
577
    /// card of a column at once
578
    Move {
579
        number: i64,
580
        /// The card (its id); leave it out with --from
581
        card: Option<i64>,
582
        #[arg(long, short)]
583
        column: String,
584
        /// Move every card of this column (#289)
585
        #[arg(long, conflicts_with = "card")]
586
        from: Option<String>,
587
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
588
        #[arg(long, value_delimiter = ',', requires = "from")]
589
        except: Vec<String>,
590
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
591
        #[arg(long, value_delimiter = ',', requires = "from")]
592
        state: Vec<String>,
593
        /// With --from: say what would move, and move nothing
594
        #[arg(long, requires = "from")]
595
        dry_run: bool,
596
    },
597
    /// Archive a column's cards: off the board, kept and restorable (#293)
598
    Archive {
599
        number: i64,
600
        /// The column, by name or id
601
        #[arg(long)]
602
        from: String,
603
        /// Only cards that joined the column more than this long ago (14d, or 14)
604
        #[arg(long)]
605
        older: Option<String>,
606
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
607
        #[arg(long, value_delimiter = ',')]
608
        except: Vec<String>,
609
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
610
        #[arg(long, value_delimiter = ',')]
611
        state: Vec<String>,
612
        /// Say what would be archived, and archive nothing
613
        #[arg(long)]
614
        dry_run: bool,
615
    },
616
    /// Put an archived card back at the end of its column
617
    Restore { number: i64, card: i64 },
618
    /// Take a card off a board
619
    Remove { number: i64, card: i64 },
620
}
621
622
#[derive(Subcommand)]
623
enum MilestoneCmd {
624
    /// The repository's milestones
625
    List,
626
    /// Create a milestone, or change the one of that title (triage)
627
    Create {
628
        title: String,
629
        #[arg(long, short, default_value = "")]
630
        description: String,
631
        /// Due date, YYYY-MM-DD
632
        #[arg(long)]
633
        due: Option<String>,
634
    },
635
    /// Change a milestone's title, description or due date (triage)
636
    Edit {
637
        title: String,
638
        #[arg(long, short)]
639
        rename: Option<String>,
640
        #[arg(long, short)]
641
        description: Option<String>,
642
        /// Due date, YYYY-MM-DD ("" for none)
643
        #[arg(long)]
644
        due: Option<String>,
645
    },
646
    /// Close a milestone
647
    Close { title: String },
648
    /// Reopen a milestone
649
    Reopen { title: String },
650
}
651
652
/// Labels to put on or take off an issue or proposal.
653
#[derive(clap::Args)]
654
struct LabelChange {
655
    number: i64,
656
    /// A label to add (repeatable)
657
    #[arg(long, short)]
658
    add: Vec<String>,
659
    /// A label to take off (repeatable)
660
    #[arg(long, short)]
661
    remove: Vec<String>,
662
}
663
664
impl LabelChange {
665
    /// The set after the change, from the one there now.
6660×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
6670×
        if self.add.is_empty() && self.remove.is_empty() {
6680×
            bail!("say what to change: --add NAME or --remove NAME");
6690×
        }
6700×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
6710×
        for a in &self.add {
6720×
            if !names.contains(a) {
6730×
                names.push(a.clone());
6740×
            }
675
        }
6760×
        Ok(names)
6770×
    }
678
}
679
6800×
fn label_names(labels: &[String]) -> String {
6810×
    if labels.is_empty() {
6820×
        ui::dim("no labels")
683
    } else {
6840×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
685
    }
6860×
}
687
688
#[derive(Subcommand)]
689
enum CoverageCmd {
690
    /// Upload an LCOV or Cobertura report measured on this machine, as the
691
    /// coverage of a bookmark's current state (default: the default
692
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
693
    /// not measured by a runner, and sets no check from it
694
    Upload {
695
        file: std::path::PathBuf,
696
        #[arg(long)]
697
        bookmark: Option<String>,
698
        /// A change's full hash
699
        #[arg(long, conflicts_with = "bookmark")]
700
        change: Option<String>,
701
    },
702
}
703
704
#[derive(Subcommand)]
705
enum RunCmd {
706
    /// Recent runs, newest first
707
    List {
708
        #[arg(long, default_value_t = 20)]
709
        limit: i64,
710
    },
711
    /// A run and its jobs
712
    View {
713
        number: i64,
714
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
715
        #[arg(long)]
716
        timings: bool,
717
    },
718
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
719
    Start {
720
        #[arg(long)]
721
        bookmark: Option<String>,
722
        /// A change's full hash
723
        #[arg(long, conflicts_with = "bookmark")]
724
        change: Option<String>,
725
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
726
        #[arg(long = "job", value_name = "NAME")]
727
        jobs: Vec<String>,
728
        /// Wait for the run and exit 1 unless it passes
729
        #[arg(long)]
730
        watch: bool,
731
    },
732
    /// Follow a run until it finishes; exit 1 unless it passes
733
    Watch { number: i64 },
734
    /// A job's log
735
    Log { number: i64, job: String },
736
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
737
    Report {
738
        number: i64,
739
        job: String,
740
        #[command(flatten)]
741
        pick: ReportPick,
742
    },
743
    /// Run a finished run's state again; with --job, only that job (and the
744
    /// jobs that depend on it) in the same run
745
    Rerun {
746
        number: i64,
747
        #[arg(long)]
748
        job: Option<String>,
749
    },
750
    /// Cancel a run still queued or running; its running jobs are stopped
751
    Cancel { number: i64 },
752
    /// Approve a job that waits for a person (oxygenflow#57)
753
    Approve {
754
        number: i64,
755
        #[arg(long)]
756
        job: String,
757
    },
758
    /// Reject a job that waits for a person: it ends cancelled
759
    Reject {
760
        number: i64,
761
        #[arg(long)]
762
        job: String,
763
    },
764
}
765
766
/// Which report of a job, and what of it to show.
767
#[derive(clap::Args)]
768
struct ReportPick {
769
    /// Which report, when the job published more than one
770
    #[arg(long)]
771
    name: Option<String>,
772
    /// What it holds: its metrics, context and files
773
    #[arg(long, conflicts_with = "file")]
774
    list: bool,
775
    /// One file of it (`data/frames.csv`), as published
776
    #[arg(long, value_name = "PATH")]
777
    file: Option<String>,
778
    /// Write the file here instead of to stdout
779
    #[arg(long, short, value_name = "FILE", requires = "file")]
780
    output: Option<std::path::PathBuf>,
781
}
782
783
#[derive(Subcommand)]
784
enum ReportCmd {
785
    /// The newest run of each report, newest first
786
    List {
787
        /// Only runs on this bookmark
788
        #[arg(long)]
789
        bookmark: Option<String>,
790
    },
791
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
792
    Show {
793
        report: String,
794
        #[arg(long, conflicts_with = "bookmark")]
795
        id: Option<i64>,
796
        #[arg(long)]
797
        bookmark: Option<String>,
798
        /// What it holds: its metrics, context and files
799
        #[arg(long, conflicts_with = "file")]
800
        list: bool,
801
        /// One file of it, as published
802
        #[arg(long, value_name = "PATH")]
803
        file: Option<String>,
804
        /// Write the file here instead of to stdout
805
        #[arg(long, short, value_name = "FILE", requires = "file")]
806
        output: Option<std::path::PathBuf>,
807
    },
808
}
809
810
#[derive(Subcommand)]
811
enum TagCmd {
812
    /// Tags, newest name first
813
    List,
814
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
815
    /// delegate (as `oxy tag create` and a push would be)
816
    Create {
817
        name: String,
818
        /// What to tag (default: the default bookmark)
819
        #[arg(long)]
820
        target: Option<String>,
821
        #[arg(long, short)]
822
        message: Option<String>,
823
    },
824
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
825
    /// their next fetch, and the name is never used again. Refused while a
826
    /// release uses the tag
827
    Delete {
828
        name: String,
829
        /// Why, recorded with the withdrawal
830
        #[arg(long, short)]
831
        reason: Option<String>,
832
    },
833
}
834
835
#[derive(Subcommand)]
836
enum ReleaseCmd {
837
    /// Releases, newest first
838
    List,
839
    /// Create a release on an existing tag
840
    Create {
841
        tag: String,
842
        #[arg(long, short)]
843
        title: Option<String>,
844
        /// Notes in Markdown (default: generated from the changes since the previous release)
845
        #[arg(long, short)]
846
        notes: Option<String>,
847
        #[arg(long)]
848
        prerelease: bool,
849
    },
850
    /// Change a release's title, notes or prerelease flag
851
    Edit {
852
        tag: String,
853
        #[arg(long, short)]
854
        title: Option<String>,
855
        /// New notes in Markdown ("-" reads them from stdin)
856
        #[arg(long, short)]
857
        notes: Option<String>,
858
        /// Mark it a prerelease (true) or not (false)
859
        #[arg(long)]
860
        prerelease: Option<bool>,
861
    },
862
    /// Attach files to a release
863
    Upload { tag: String, files: Vec<std::path::PathBuf> },
864
    /// The release's trust report: signatures, builds, receipts and audit
865
    Trust { tag: String },
866
}
867
86853×
fn main() {
869
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
870
    // other command-line tools do, instead of panicking on the failed
871
    // write (oxygenhub#92).
872
    #[cfg(unix)]
87353×
    unsafe {
87453×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
87553×
    }
87653×
    let cli = Cli::parse();
87753×
    ui::init(cli.plain);
87853×
    match run(cli) {
87945×
        Ok(code) => std::process::exit(code),
8808×
        Err(e) => {
8818×
            eprintln!("{} {e:#}", ui::bad("error:"));
8828×
            std::process::exit(2);
883
        }
884
    }
885
}
886
88722×
fn enc(s: &str) -> String {
88822×
    let mut out = String::new();
889109×
    for b in s.bytes() {
890109×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
891108×
            out.push(b as char);
892108×
        } else {
8931×
            out.push_str(&format!("%{b:02X}"));
8941×
        }
895
    }
89622×
    out
89722×
}
898
89953×
fn run(cli: Cli) -> Result<i32> {
90053×
    let cfg = Config::load()?;
9011×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
9021×
        return login(cfg, url, token.clone(), ca.clone());
90352×
    }
90452×
    let here = std::env::current_dir()?;
90552×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
90651×
    let c = Client::new(&t)?;
90751×
    let json = cli.json;
9080×
    match cli.cmd {
909
        Cmd::Auth { cmd: AuthCmd::Status } => {
9100×
            let me: serde_json::Value = c.get("/user")?;
9110×
            if json {
9120×
                println!("{me}");
9130×
            } else {
9140×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
9150×
            }
9160×
            Ok(0)
917
        }
9180×
        Cmd::Auth { .. } => unreachable!(),
9192×
        Cmd::Mcp { allow_write } => {
9202×
            t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?;
9212×
            mcp::serve(c, t, allow_write)
922
        }
9232×
        Cmd::Api { path, method, data } => {
9242×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
925
            // The method applies with or without a body (#75): without one, a
926
            // GET reads, anything else sends an empty object.
9272×
            let text = match data {
9280×
                Some(d) => c.send_text(
9290×
                    &method.to_uppercase(),
9300×
                    &path,
9310×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
9320×
                )?,
9332×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
9340×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
935
            };
9362×
            println!("{text}");
9372×
            Ok(0)
938
        }
939
        Cmd::Repo { cmd: RepoCmd::View } => {
9401×
            let path = t.repo_path()?;
9411×
            if json {
9420×
                println!("{}", c.get_text(&path)?);
9430×
                return Ok(0);
9441×
            }
9451×
            let r: serde_json::Value = c.get(&path)?;
9461×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
9471×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
9481×
                println!("{d}");
9491×
            }
9501×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
9511×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
9521×
            Ok(0)
953
        }
95418×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
9554×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
9563×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
9570×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
9580×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
9590×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
9600×
            let mut body = serde_json::json!({ "content": content });
9610×
            if let Some(b) = bookmark {
9620×
                body["bookmark"] = b.into();
9630×
            }
9640×
            if let Some(ch) = change {
9650×
                body["change"] = ch.into();
9660×
            }
9670×
            let base = t.repo_path()?;
9680×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
9690×
            if json {
9700×
                println!("{}", serde_json::to_string(&r)?);
971
            } else {
9720×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
9730×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
9740×
                println!(
975
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
9760×
                    ui::ok("✔"),
977
                    r.lines_hit,
978
                    r.lines_found,
979
                    r.files,
9800×
                    ui::dim(&r.url)
981
                );
9820×
                if r.dropped > 0 {
9830×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
9840×
                }
985
            }
9860×
            Ok(0)
987
        }
9884×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
9890×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
9900×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
9910×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
99210×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
9930×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
9940×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
9950×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
9967×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
997
    }
99853×
}
999
1000
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
10012×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
10022×
    Ok(match v {
10030×
        None => None,
10042×
        Some("on") => Some(Some(true)),
10052×
        Some("off") => Some(Some(false)),
10062×
        Some("inherit") => Some(None),
10071×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1008
    })
10092×
}
1010
1011
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
10127×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
10137×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
10141×
    Ok(match kind {
10157×
        "site" if name.is_empty() => ("site".into(), String::new()),
10166×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
10175×
        "group" => {
10183×
            let g = all
10193×
                .groups
10203×
                .iter()
10213×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
10223×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
10233×
            ("group".into(), g.id.to_string())
1024
        }
10252×
        "runner" => {
10261×
            let r = all
10271×
                .runners
10281×
                .iter()
10291×
                .find(|r| r.id.to_string() == name || r.name == name)
10301×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
10310×
            ("runner".into(), r.id.to_string())
1032
        }
10331×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1034
    })
10357×
}
1036
10370×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
10380×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
10390×
    match cmd {
10400×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1041
        RunnerUpdatesCmd::Show => {
10420×
            println!(
1043
                "{} {}",
10440×
                ui::strong("Builds from"),
10450×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1046
            );
10470×
            for h in &all.holds {
10480×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
10490×
            }
10500×
            for s in &all.settings {
10510×
                let mut said = vec![];
10520×
                if let Some(u) = s.updates {
10530×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
10540×
                }
10550×
                if let Some(ch) = &s.channel {
10560×
                    said.push(format!("channel {ch}"));
10570×
                }
10580×
                if let Some(w) = &s.window {
10590×
                    said.push(format!("window {w} UTC"));
10600×
                }
10610×
                if let Some(d) = s.dry_run {
10620×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
10630×
                }
10640×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
10650×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1066
            }
10670×
            for g in &all.groups {
10680×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
10690×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
10700×
                if let Some(w) = g.wave {
10710×
                    what.push_str(&format!(", wave {w}"));
10720×
                }
10730×
                println!(
1074
                    "  group {} ({what}): {}",
10750×
                    ui::strong(&g.name),
10760×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1077
                );
1078
            }
10790×
            for r in &all.runners {
10800×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
10810×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1082
            }
1083
        }
10840×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
10850×
            let (scope, key) = update_scope(&scope, &all)?;
10860×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
10870×
                scope: scope.clone(),
10880×
                key: key.clone(),
10890×
                ..Default::default()
10900×
            });
10910×
            if let Some(u) = switch(updates.as_deref())? {
10920×
                s.updates = u;
10930×
            }
10940×
            if let Some(d) = switch(dry_run.as_deref())? {
10950×
                s.dry_run = d;
10960×
            }
10970×
            if let Some(ch) = channel {
10980×
                s.channel = Some(ch).filter(|c| c != "inherit");
10990×
            }
11000×
            if let Some(w) = window {
11010×
                s.window = Some(w).filter(|w| w != "inherit");
11020×
            }
11030×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
11040×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1105
        }
11060×
        RunnerUpdatesCmd::Lift { version } => {
11070×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
11080×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1109
        }
1110
    }
11110×
    Ok(0)
11120×
}
1113
1114
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
11157×
fn drop_id(s: &str) -> Result<String> {
11167×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1117144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
11181×
        bail!("{s:?} is not a drop's id or address");
11196×
    }
11206×
    Ok(id.to_ascii_lowercase())
11217×
}
1122
11232×
fn drop_line(d: &hub_api::Drop) -> String {
11242×
    let title = if d.title.is_empty() { d.files.first().map(|f| f.name.clone()).unwrap_or_else(|| d.id.clone()) } else { d.title.clone() };
11254×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
11262×
    format!(
1127
        "{} {} {}{}",
11282×
        ui::dim(&d.id),
11292×
        ui::strong(&title),
11302×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
11312×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1132
    )
11332×
}
1134
1135
/// `oh drop star|unstar` (oxygenhub#349).
11360×
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
11370×
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
11380×
    if json {
11390×
        println!("{}", serde_json::to_string(&s)?);
1140
    } else {
11410×
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1142
    }
11430×
    Ok(())
11440×
}
1145
11467×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
11477×
    match cmd {
11481×
        DropCmd::Create { files, secret, description, title } => {
11491×
            let mut out = Vec::with_capacity(files.len());
11502×
            for f in &files {
11512×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
11522×
                let content =
11532×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
11542×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1155
            }
11561×
            let new =
11571×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
11581×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
11591×
            if json {
11601×
                println!("{}", serde_json::to_string(&d)?);
1161
            } else {
11620×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
11630×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1164
            }
1165
        }
11662×
        DropCmd::List { user } => {
11672×
            let path = match &user {
11681×
                Some(u) => format!("/users/{}/drops", enc(u)),
11691×
                None => "/drops".to_string(),
1170
            };
11712×
            if json {
11721×
                println!("{}", c.get_text(&path)?);
11731×
                return Ok(0);
11741×
            }
11751×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
11761×
            if list.is_empty() {
11770×
                println!("{}", ui::dim("No drops."));
11781×
            }
11791×
            for d in &list {
11801×
                println!("{}", drop_line(d));
11811×
            }
1182
        }
11833×
        DropCmd::View { id, file } => {
11843×
            let path = format!("/drops/{}", drop_id(&id)?);
11853×
            if json && file.is_none() {
11860×
                println!("{}", c.get_text(&path)?);
11870×
                return Ok(0);
11883×
            }
11893×
            let d: hub_api::Drop = c.get(&path)?;
11902×
            if let Some(name) = file {
11912×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
11921×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
11931×
                print!("{content}");
11941×
                return Ok(0);
11951×
            }
11961×
            println!("{}", drop_line(&d));
11971×
            if !d.description.is_empty() {
11981×
                println!("{}", d.description);
11991×
            }
12001×
            println!("{}", ui::kv("url", &d.url));
12011×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
12022×
            for f in &d.files {
12032×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
12042×
                match &f.content {
12052×
                    Some(text) => {
12062×
                        print!("{text}");
12072×
                        if !text.ends_with('\n') && !text.is_empty() {
12080×
                            println!();
12092×
                        }
1210
                    }
12110×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1212
                }
1213
            }
1214
        }
12151×
        DropCmd::Delete { id } => {
12161×
            let id = drop_id(&id)?;
12171×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
12181×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1219
        }
12200×
        DropCmd::Fork { id } => {
12210×
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
12220×
            if json {
12230×
                println!("{}", serde_json::to_string(&d)?);
12240×
            } else {
12250×
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
12260×
            }
1227
        }
12280×
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
12290×
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
12300×
        DropCmd::Comments { id } => {
12310×
            let path = format!("/drops/{}/comments", drop_id(&id)?);
12320×
            if json {
12330×
                println!("{}", c.get_text(&path)?);
12340×
                return Ok(0);
12350×
            }
12360×
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
12370×
            if list.is_empty() {
12380×
                println!("{}", ui::dim("No comments."));
12390×
            }
12400×
            for m in &list {
12410×
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
12420×
                println!("{}\n", m.body);
12430×
            }
1244
        }
12450×
        DropCmd::Comment { id, message } => {
12460×
            let m: hub_api::DropComment =
12470×
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
12480×
            if json {
12490×
                println!("{}", serde_json::to_string(&m)?);
12500×
            } else {
12510×
                println!("{} commented (#{})", ui::ok("✔"), m.id);
12520×
            }
1253
        }
1254
    }
12554×
    Ok(0)
12567×
}
1257
1258
/// `30d`, `12h`, `90m` in milliseconds.
12590×
fn duration_ms(s: &str) -> Result<i64> {
12600×
    let s = s.trim();
12610×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
12620×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
12630×
    let per = match unit {
12640×
        "d" => 86_400_000,
12650×
        "h" => 3_600_000,
12660×
        "m" => 60_000,
12670×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1268
    };
12690×
    if n <= 0 {
12700×
        bail!("a grant must last some time");
12710×
    }
12720×
    Ok(n * per)
12730×
}
1274
12750×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1276
    use oxy_core::cert::{Grant, SignedGrant};
1277
    use oxy_core::identity::{Identity, Scope};
12780×
    match cmd {
12790×
        AgentCmd::Grant { name, scope, lasts } => {
12800×
            let home = oxy_core::repo::default_home();
12810×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
12820×
                format!(
1283
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
12840×
                    home.display()
1285
                )
12860×
            })?;
12870×
            let me: serde_json::Value = c.get("/user")?;
12880×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
12890×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
12900×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
12910×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
12920×
            let grant = Grant {
12930×
                grantor: me_id.hash(),
12940×
                subject: format!("agent:{name}@{username}"),
12950×
                issuer: hub.hash(),
12960×
                scope,
12970×
                not_before: (now - 60_000) as u64,
12980×
                expires: (now + duration_ms(&lasts)?) as u64,
1299
            };
13000×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
13010×
            let r: serde_json::Value =
13020×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
13030×
            if json {
13040×
                println!("{r}");
13050×
                return Ok(0);
13060×
            }
13070×
            println!(
1308
                "{} {} to act for you as {} ({}), until {}",
13090×
                ui::ok("✔ granted"),
13100×
                ui::strong(&name),
13110×
                r["subject"].as_str().unwrap_or(""),
13120×
                r["scope"].as_str().unwrap_or(""),
13130×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1314
            );
13150×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
13160×
            println!(
1317
                "  {}",
13180×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1319
            );
13200×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
13210×
            Ok(0)
1322
        }
1323
        AgentCmd::List => {
13240×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
13250×
            if json {
13260×
                println!("{}", serde_json::to_string(&grants)?);
13270×
                return Ok(0);
13280×
            }
13290×
            if grants.is_empty() {
13300×
                println!("{}", ui::dim("no agent grants"));
13310×
            }
13320×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
13330×
            for g in grants {
13340×
                let state = if g["revoked_ms"].is_i64() {
13350×
                    ui::bad("revoked")
13360×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
13370×
                    ui::dim("ended")
1338
                } else {
13390×
                    ui::ok("live")
1340
                };
13410×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
13420×
                println!(
1343
                    "#{:<4} {:<8} {} · {} · until {} · {}",
13440×
                    g["id"],
1345
                    state,
13460×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
13470×
                    g["scope"].as_str().unwrap_or(""),
13480×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
13490×
                    ui::dim(&used)
1350
                );
1351
            }
13520×
            Ok(0)
1353
        }
13540×
        AgentCmd::Revoke { id } => {
13550×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
13560×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
13570×
            Ok(0)
1358
        }
1359
    }
13600×
}
1361
13621×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
13631×
    let hub = url.trim_end_matches('/').to_string();
13641×
    let token = match token.as_deref() {
13651×
        Some("-") => {
13660×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
13670×
            let mut line = String::new();
13680×
            std::io::stdin().read_line(&mut line)?;
13690×
            line.trim().to_string()
1370
        }
13711×
        Some(t) => t.to_string(),
13720×
        None => device_sign_in(&hub, ca.clone())?,
1373
    };
13741×
    if token.is_empty() {
13750×
        bail!("no token given");
13761×
    }
13771×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
13781×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
13791×
    let account = me["username"].as_str().unwrap_or("?");
1380
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
13811×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
13821×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
13831×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
13841×
    cfg.default_hub = Some(hub.clone());
13851×
    cfg.save()?;
13861×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
13871×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
13881×
    Ok(0)
13891×
}
1390
1391
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1392
/// it on the web, and the token arrives here.
13930×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
13940×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
13950×
    let c = Client::new(&t)?;
13960×
    let host = std::fs::read_to_string("/etc/hostname")
13970×
        .ok()
13980×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
13990×
        .map(|h| h.trim().to_string())
14000×
        .filter(|h| !h.is_empty());
14010×
    let client = match host {
14020×
        Some(h) => format!("oh on {h}"),
14030×
        None => "oh".to_string(),
1404
    };
14050×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
14060×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
14070×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
14080×
    if code != 200 {
14090×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
14100×
    }
14110×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
14120×
    let user = v["user_code"].as_str().unwrap_or("?");
14130×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
14140×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
14150×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
14160×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
14170×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1418
    loop {
14190×
        std::thread::sleep(std::time::Duration::from_secs(interval));
14200×
        if std::time::Instant::now() > deadline {
14210×
            bail!("the code expired before it was approved; run oh auth login again");
14220×
        }
14230×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
14240×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
14250×
        if code == 200 {
14260×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
14270×
        }
14280×
        match v["error"].as_str() {
14290×
            Some("authorization_pending") => {}
14300×
            Some("slow_down") => interval += 5,
14310×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
14320×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
14330×
            _ => bail!("signing in: HTTP {code}: {body}"),
1434
        }
1435
    }
14360×
}
1437
143810×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
143910×
    match (body, file) {
14403×
        (Some(b), _) => Ok(b),
14411×
        (None, Some(f)) if f == "-" => {
14420×
            let mut s = String::new();
14430×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
14440×
            Ok(s)
1445
        }
14461×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
14476×
        (None, None) => Ok(String::new()),
1448
    }
144910×
}
1450
14513×
fn issue_line(i: &Issue) -> String {
14523×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
14533×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
14543×
    format!(
1455
        "{glyph} {} {}{}{}",
14563×
        ui::dim(&format!("#{}", i.number)),
1457
        i.title,
14583×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
14593×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1460
    )
14613×
}
1462
146318×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
146418×
    let base = t.repo_path()?;
146518×
    match cmd {
14663×
        IssueCmd::List { state } => {
14673×
            let path = format!("{base}/issues?state={}", enc(&state));
14683×
            if json {
14691×
                println!("{}", c.get_text(&path)?);
14701×
                return Ok(0);
14712×
            }
14722×
            let list: Vec<Issue> = c.get(&path)?;
14732×
            if list.is_empty() {
14741×
                println!("{}", ui::dim(&format!("No {state} issues.")));
14751×
            }
14762×
            for i in &list {
14772×
                println!("{}", issue_line(i));
14782×
            }
1479
        }
14802×
        IssueCmd::View { number } => {
14812×
            let path = format!("{base}/issues/{number}");
14822×
            if json {
14831×
                println!("{}", c.get_text(&path)?);
14841×
                return Ok(0);
14851×
            }
14861×
            let i: Issue = c.get(&path)?;
14871×
            println!("{}", issue_line(&i));
14881×
            if !i.body.trim().is_empty() {
14891×
                println!("\n{}\n", i.body.trim_end());
14901×
            }
14911×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
14922×
            for cm in comments {
14932×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
14942×
            }
14951×
            println!("{}", ui::dim(&i.url));
1496
        }
14974×
        IssueCmd::Create { title, body, body_file, label, project, column, attach } => {
14984×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
14994×
            let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None };
15004×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
15013×
            if json {
15021×
                println!("{}", serde_json::to_string(&i)?);
15032×
            } else {
15042×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
15052×
            }
15063×
            if let Some(n) = project {
15071×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
15081×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
15091×
                if !json {
15101×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
15111×
                }
15122×
            }
1513
        }
15141×
        IssueCmd::Close { number, reason } => {
15151×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
15161×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1517
        }
15180×
        IssueCmd::Reopen { number } => {
15190×
            let i: Issue =
15200×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
15210×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1522
        }
15233×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
15243×
            let body = match (&body, &body_file) {
15253×
                (None, None) => None,
15260×
                _ => Some(body_of(body, body_file)?),
1527
            };
15283×
            let labels = if no_labels {
15291×
                Some(Vec::new())
15302×
            } else if label.is_empty() {
15311×
                None
1532
            } else {
15331×
                Some(label)
1534
            };
15353×
            let assignees = if no_assignees {
15361×
                Some(Vec::new())
15372×
            } else if assignee.is_empty() {
15381×
                None
1539
            } else {
15401×
                Some(assignee)
1541
            };
15423×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
15431×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
15442×
            }
15452×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
15462×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
15472×
            if json {
15481×
                println!("{}", serde_json::to_string(&i)?);
15491×
            } else {
15501×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
15511×
            }
1552
        }
15530×
        IssueCmd::Label(change) => {
15540×
            let path = format!("{base}/issues/{}", change.number);
15550×
            let now: Issue = c.get(&path)?;
15560×
            let labels = change.apply(&now.labels)?;
15570×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
15580×
            let i: Issue = c.send("PATCH", &path, &edit)?;
15590×
            if json {
15600×
                println!("{}", serde_json::to_string(&i)?);
15610×
            } else {
15620×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
15630×
            }
1564
        }
15655×
        IssueCmd::Comment { number, body, body_file, attach } => {
15665×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
15674×
            if body.trim().is_empty() {
15681×
                bail!("give the comment with --body, --body-file or --attach");
15693×
            }
15703×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
15713×
            println!("{} commented on #{number}", ui::ok("✔"));
1572
        }
1573
    }
157412×
    Ok(0)
157518×
}
1576
1577
/// `body` with each file attached to the repository and linked under it:
1578
/// an image shown in place, anything else a download (#350). Files are
1579
/// uploaded first, so a failed upload leaves nothing half made.
15809×
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> {
15819×
    if files.is_empty() {
15826×
        return Ok(body);
15833×
    }
15843×
    let mut links = Vec::new();
15854×
    for f in files {
15864×
        let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?;
15873×
        let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
15883×
        let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?;
15893×
        let a: hub_api::Attachment =
15903×
            serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?;
15913×
        links.push(a.markdown);
1592
    }
15932×
    let links = links.join("\n\n");
15942×
    Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) })
15959×
}
1596
15971×
fn source_name(s: &hub_api::ProposalSource) -> String {
15981×
    match s {
15991×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
16000×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
16010×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1602
    }
16031×
}
1604
16051×
fn proposal_line(p: &Proposal) -> String {
16061×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
16071×
    let glyph = match state.as_str() {
16081×
        "open" => ui::ok("●"),
16090×
        "draft" => ui::dim("◌"),
16100×
        "landed" => ui::strong("✔"),
16110×
        _ => ui::dim("○"),
1612
    };
16131×
    format!(
1614
        "{glyph} {} {} {}{}",
16151×
        ui::dim(&format!("#{}", p.number)),
1616
        p.title,
16171×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
16181×
        ui::dim(&format!(" · {} · {state}", p.author))
1619
    )
16201×
}
1621
16224×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
16234×
    let base = t.repo_path()?;
16244×
    match cmd {
16250×
        ProposalCmd::List { state, limit } => {
16260×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
16270×
            if json {
16280×
                println!("{}", c.get_text(&path)?);
16290×
                return Ok(0);
16300×
            }
16310×
            let list: Vec<Proposal> = c.get(&path)?;
16320×
            if list.is_empty() {
16330×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
16340×
            }
16350×
            for p in &list {
16360×
                println!("{}", proposal_line(p));
16370×
            }
1638
        }
16391×
        ProposalCmd::View { number } => {
16401×
            let path = format!("{base}/proposals/{number}");
16411×
            if json {
16420×
                println!("{}", c.get_text(&path)?);
16430×
                return Ok(0);
16441×
            }
16451×
            let p: Proposal = c.get(&path)?;
16461×
            println!("{}", proposal_line(&p));
16471×
            if !p.body.trim().is_empty() {
16480×
                println!("\n{}\n", p.body.trim_end());
16491×
            }
16501×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
16511×
            for ch in &p.changes {
16521×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
16531×
            }
16541×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
16551×
            if p.landable {
16561×
                println!("{} can land", ui::ok("✔"));
16571×
            } else {
16580×
                for b in &p.blockers {
16590×
                    println!("{} {b}", ui::bad("✘"));
16600×
                }
1661
            }
16621×
            if p.conflicted {
16630×
                println!("{} landing it would leave conflicts", ui::bad("!"));
16641×
            }
16651×
            println!("{}", ui::dim(&p.url));
1666
        }
16671×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
16681×
            let target = match into {
16690×
                Some(i) => i,
16701×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1671
            };
16721×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
16731×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
16741×
            if json {
16750×
                println!("{}", serde_json::to_string(&p)?);
16761×
            } else {
16771×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
16781×
            }
1679
        }
16800×
        ProposalCmd::Edit { number, title, body, body_file } => {
16810×
            let body = match (&body, &body_file) {
16820×
                (None, None) => None,
16830×
                _ => Some(body_of(body, body_file)?),
1684
            };
16850×
            if title.is_none() && body.is_none() {
16860×
                bail!("say what to change: --title, --body or --body-file");
16870×
            }
16880×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
16890×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
16900×
            if json {
16910×
                println!("{}", serde_json::to_string(&p)?);
16920×
            } else {
16930×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
16940×
            }
1695
        }
16960×
        ProposalCmd::Label(change) => {
16970×
            let path = format!("{base}/proposals/{}", change.number);
16980×
            let now: Proposal = c.get(&path)?;
16990×
            let labels = change.apply(&now.labels)?;
17000×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
17010×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
17020×
            if json {
17030×
                println!("{}", serde_json::to_string(&p)?);
17040×
            } else {
17050×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
17060×
            }
1707
        }
17080×
        ProposalCmd::Comment { number, body, body_file } => {
17090×
            let body = body_of(body, body_file)?;
17100×
            if body.trim().is_empty() {
17110×
                bail!("give the comment with --body or --body-file");
17120×
            }
17130×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
17140×
            println!("{} commented on #{number}", ui::ok("✔"));
1715
        }
17160×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
17170×
            let path = format!("{base}/proposals/{number}/auto-land");
17180×
            let p: Proposal =
17190×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
17200×
            if json {
17210×
                println!("{}", serde_json::to_string(&p)?);
17220×
            } else if p.landed.is_some() {
17230×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
17240×
            } else if p.auto_land.is_some() {
17250×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
17260×
            } else {
17270×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
17280×
            }
1729
        }
17302×
        ProposalCmd::Land { number, over_checks, .. } => {
17312×
            let body = match &over_checks {
17320×
                Some(r) => serde_json::json!({ "over_checks": r }),
17332×
                None => serde_json::json!({}),
1734
            };
17352×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
17361×
            if json {
17370×
                println!("{}", serde_json::to_string(&p)?);
17381×
            } else {
17391×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
17401×
            }
1741
        }
17420×
        ProposalCmd::Close { number, message } => {
17430×
            if let Some(body) = message {
17440×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
17450×
            }
17460×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
17470×
            if json {
17480×
                println!("{}", serde_json::to_string(&p)?);
17490×
            } else {
17500×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
17510×
            }
1752
        }
17530×
        ProposalCmd::Reopen { number } => {
17540×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
17550×
            if json {
17560×
                println!("{}", serde_json::to_string(&p)?);
17570×
            } else {
17580×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
17590×
            }
1760
        }
17610×
        ProposalCmd::Ready { number, undo } => {
17620×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
17630×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
17640×
            if json {
17650×
                println!("{}", serde_json::to_string(&p)?);
17660×
            } else if undo {
17670×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
17680×
            } else {
17690×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
17700×
            }
1771
        }
17720×
        ProposalCmd::Checks { number } => {
17730×
            let path = format!("{base}/proposals/{number}/checks");
17740×
            if json {
17750×
                println!("{}", c.get_text(&path)?);
17760×
                return Ok(0);
17770×
            }
17780×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
17790×
            if checks.is_empty() {
17800×
                println!("{}", ui::dim("No checks yet."));
17810×
            }
17820×
            for ch in checks {
17830×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
17840×
            }
1785
        }
1786
    }
17873×
    Ok(0)
17884×
}
1789
17901×
fn run_line(r: &FlowRun) -> String {
17911×
    let what =
17921×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
17931×
    format!(
1794
        "{} {} {} {}",
17951×
        ui::status(&r.status),
17961×
        ui::dim(&format!("#{}", r.number)),
1797
        what,
17981×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1799
    )
18001×
}
1801
18021×
fn print_run(r: &FlowRun, timings: bool) {
18031×
    println!("{}", run_line(r));
18041×
    for j in &r.jobs {
18051×
        let dur = match (j.started_ms, j.finished_ms) {
18060×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
18071×
            _ => String::new(),
1808
        };
18091×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
18101×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1811
        // Why a queued job no runner can take waits (oxygenhub#28), and
1812
        // why a job ran where it did (oxygenflow#42).
18131×
        if j.status == "queued" && !j.waiting.is_empty() {
18140×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
18151×
        } else if !j.placed.is_empty() {
18160×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
18171×
        }
18181×
        if timings {
18190×
            let t = timing_line(j);
18200×
            if !t.is_empty() {
18210×
                println!("    {}", ui::dim(&t));
18220×
            }
18231×
        }
1824
    }
18251×
    if !r.error.is_empty() {
18260×
        println!("{}", ui::bad(&r.error));
18271×
    }
18281×
    println!("{}", ui::dim(&r.url));
18291×
}
1830
1831
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
18323×
fn took(ms: i64) -> String {
18333×
    match ms {
18343×
        ..=999 => format!("{ms} ms"),
18352×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
18361×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1837
    }
18383×
}
1839
1840
/// MiB as a person reads them.
18412×
fn mib(m: i64) -> String {
18422×
    if m >= 1024 {
18431×
        format!("{:.1} GiB", m as f64 / 1024.0)
1844
    } else {
18451×
        format!("{m} MiB")
1846
    }
18472×
}
1848
1849
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1850
/// phase its runner reported, and the most disk and memory it took.
18512×
fn timing_line(j: &FlowJob) -> String {
18522×
    let mut parts = vec![];
18532×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
18541×
        parts.push(format!("waited {}", took((s - q).max(0))));
18551×
    }
18562×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
18572×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
18582×
        .into_iter()
18594×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
18602×
        .collect();
18612×
    if !peaks.is_empty() {
18621×
        parts.push(format!("peak {}", peaks.join(", ")));
18631×
    }
18642×
    parts.join(" · ")
18652×
}
1866
1867
/// A report's path, its segments encoded and its slashes kept.
18681×
fn enc_path(path: &str) -> String {
18691×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
18701×
}
1871
1872
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1873
/// files are at `files(path)`. By default its report.toml; with `list`
1874
/// what it holds; with `file` one file, to stdout or `output`.
18750×
fn show_report(
18760×
    c: &Client,
18770×
    at: &str,
18780×
    files: impl Fn(&str) -> String,
18790×
    list: bool,
18800×
    file: Option<String>,
18810×
    output: Option<std::path::PathBuf>,
18820×
    json: bool,
18830×
) -> Result<()> {
1884
    use std::io::Write;
18850×
    if let Some(path) = file {
18860×
        let bytes = c.get_bytes(&files(&path))?;
18870×
        match output {
18880×
            Some(out) => {
18890×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
18900×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
1891
            }
18920×
            None => std::io::stdout().write_all(&bytes)?,
1893
        }
18940×
        return Ok(());
18950×
    }
18960×
    if json {
18970×
        println!("{}", c.get_text(at)?);
18980×
        return Ok(());
18990×
    }
19000×
    if !list {
19010×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
19020×
        return Ok(());
19030×
    }
19040×
    let r: Report = c.get(at)?;
19050×
    print_report(&r);
19060×
    if r.files_expired_ms.is_some() {
19070×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
19080×
    }
19090×
    for f in &r.manifest {
19100×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
19110×
    }
19120×
    println!("{}", ui::dim(&r.url));
19130×
    Ok(())
19140×
}
1915
1916
/// A report's heading, metrics and context.
19170×
fn print_report(r: &Report) {
19180×
    let from = match r.run {
19190×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
19200×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
1921
    };
19220×
    println!(
1923
        "{} {} {}",
19240×
        ui::strong(&r.name),
19250×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
19260×
        ui::dim(&format!("· {from} · {} files", r.files))
1927
    );
19280×
    if !r.summary.is_empty() {
19290×
        println!("  {}", r.summary);
19300×
    }
19310×
    for m in &r.metrics {
19320×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
19330×
        let mut notes = vec![];
19340×
        if !m.better.is_empty() {
19350×
            notes.push(format!("{} is better", m.better));
19360×
        }
19370×
        if let Some(a) = m.fail_above {
19380×
            notes.push(format!("fails above {a}"));
19390×
        }
19400×
        if let Some(b) = m.fail_below {
19410×
            notes.push(format!("fails below {b}"));
19420×
        }
19430×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
19440×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
1945
    }
19460×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
19470×
        let line: Vec<String> =
19480×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
19490×
        println!("  {}", ui::dim(&line.join(" ")));
19500×
    }
19510×
}
1952
1953
/// `oh report …` (oxygenhub#348).
19540×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
19550×
    let base = t.repo_path()?;
19560×
    match cmd {
19570×
        ReportCmd::List { bookmark } => {
19580×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
19590×
            if json {
19600×
                println!("{}", c.get_text(&path)?);
19610×
                return Ok(0);
19620×
            }
19630×
            let list: Vec<Report> = c.get(&path)?;
19640×
            if list.is_empty() {
19650×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
19660×
            }
19670×
            for r in &list {
19680×
                print_report(r);
19690×
            }
1970
        }
19710×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
19720×
            let at = format!("{base}/reports/{}", enc(&report));
19730×
            let query = match (id, bookmark) {
19740×
                (Some(id), _) => format!("?id={id}"),
19750×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
19760×
                (None, None) => String::new(),
1977
            };
19780×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
19790×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
1980
        }
1981
    }
19820×
    Ok(0)
19830×
}
1984
19850×
fn live(status: &str) -> bool {
19860×
    matches!(status, "queued" | "running")
19870×
}
1988
1989
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
19900×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
19910×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
19920×
    if json {
19930×
        println!("{done}");
19940×
    } else {
19950×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
19960×
    }
19970×
    Ok(())
19980×
}
1999
20000×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
20010×
    let path = format!("{base}/flow/runs/{number}");
20020×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2003
    loop {
20040×
        let r: FlowRun = c.get(&path)?;
20050×
        if !json {
20060×
            for j in &r.jobs {
20070×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
20080×
                if seen.get(&j.name) != Some(&shown) {
20090×
                    println!("{} {}", ui::status(&j.status), j.name);
20100×
                    if j.status == "queued" && !j.waiting.is_empty() {
20110×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
20120×
                    }
20130×
                    seen.insert(j.name.clone(), shown);
20140×
                }
2015
            }
20160×
        }
20170×
        if !live(&r.status) {
20180×
            if json {
20190×
                println!("{}", serde_json::to_string(&r)?);
20200×
            } else {
20210×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
20220×
            }
20230×
            return Ok(if r.status == "passed" { 0 } else { 1 });
20240×
        }
20250×
        std::thread::sleep(Duration::from_secs(3));
2026
    }
20270×
}
2028
20293×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
20303×
    let base = t.repo_path()?;
20310×
    match cmd {
20321×
        RunCmd::List { limit } => {
20331×
            let path = format!("{base}/flow/runs?limit={limit}");
20341×
            if json {
20351×
                println!("{}", c.get_text(&path)?);
20361×
                return Ok(0);
20370×
            }
20380×
            let runs: Vec<FlowRun> = c.get(&path)?;
20390×
            if runs.is_empty() {
20400×
                println!("{}", ui::dim("No runs yet."));
20410×
            }
20420×
            for r in &runs {
20430×
                println!("{}", run_line(r));
20440×
            }
2045
        }
20461×
        RunCmd::View { number, timings } => {
20471×
            let path = format!("{base}/flow/runs/{number}");
20481×
            if json {
20490×
                println!("{}", c.get_text(&path)?);
20500×
                return Ok(0);
20511×
            }
20521×
            print_run(&c.get(&path)?, timings);
2053
        }
20541×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
20551×
            let mut body = match (bookmark, change) {
20560×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
20570×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
20581×
                (None, None) => serde_json::json!({}),
2059
            };
20601×
            if !jobs.is_empty() {
20610×
                body["jobs"] = serde_json::json!(jobs);
20621×
            }
20631×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
20641×
            let n = started["number"].as_i64().context("the hub named no run")?;
20651×
            if !json || !follow {
20661×
                if json {
20670×
                    println!("{started}");
20681×
                } else {
20691×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
20701×
                }
20710×
            }
20721×
            if follow {
20730×
                return watch(c, &base, n, json);
20741×
            }
2075
        }
20760×
        RunCmd::Watch { number } => return watch(c, &base, number, json),
20770×
        RunCmd::Log { number, job } => {
20780×
            let mut after = 0;
2079
            loop {
20800×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
20810×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
20820×
                if lines.is_empty() {
20830×
                    break;
20840×
                }
20850×
                for l in &lines {
20860×
                    if json {
20870×
                        println!("{}", serde_json::to_string(l)?);
20880×
                    } else if l.stream == "flow" {
20890×
                        println!("{}", ui::dim(&l.text));
20900×
                    } else {
20910×
                        println!("{}", l.text);
20920×
                    }
2093
                }
20940×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2095
            }
2096
        }
20970×
        RunCmd::Report { number, job, pick } => {
20980×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
20990×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
21000×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
21010×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2102
        }
21030×
        RunCmd::Rerun { number, job: Some(job) } => {
21040×
            let queued: serde_json::Value =
21050×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
21060×
            if json {
21070×
                println!("{queued}");
21080×
            } else {
21090×
                let n = queued["queued"].as_i64().unwrap_or(1);
21100×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
21110×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2112
            }
2113
        }
21140×
        RunCmd::Rerun { number, job: None } => {
21150×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
21160×
            if json {
21170×
                println!("{started}");
21180×
            } else {
21190×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
21200×
            }
2121
        }
21220×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
21230×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
21240×
        RunCmd::Cancel { number } => {
21250×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
21260×
            if json {
21270×
                println!("{done}");
21280×
            } else {
21290×
                println!("{} cancelled run #{number}", ui::ok("✔"));
21300×
            }
2131
        }
2132
    }
21332×
    Ok(0)
21343×
}
2135
21360×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
21370×
    let base = t.repo_path()?;
21380×
    match cmd {
2139
        LabelCmd::List => {
21400×
            let path = format!("{base}/labels");
21410×
            if json {
21420×
                println!("{}", c.get_text(&path)?);
21430×
                return Ok(0);
21440×
            }
21450×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
21460×
            if labels.is_empty() {
21470×
                println!("{}", ui::dim("No labels."));
21480×
            }
21490×
            for l in labels {
21500×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
21510×
            }
2152
        }
21530×
        LabelCmd::Create { name, colour, description } => {
21540×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
21550×
            if json {
21560×
                println!("{}", serde_json::to_string(&l)?);
21570×
            } else {
21580×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
21590×
            }
2160
        }
21610×
        LabelCmd::Delete { name } => {
21620×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
21630×
            println!("{} deleted label {name}", ui::ok("✔"));
2164
        }
2165
    }
21660×
    Ok(0)
21670×
}
2168
21690×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
21700×
    let base = match (&org, site) {
21710×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
21720×
        (None, true) => "/admin/assistants".to_string(),
21730×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2174
    };
21750×
    match cmd {
2176
        AssistantCmd::List => {
21770×
            if json {
21780×
                println!("{}", c.get_text(&base)?);
21790×
                return Ok(0);
21800×
            }
21810×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
21820×
            if list.is_empty() {
21830×
                println!("{}", ui::dim("No assistants."));
21840×
            }
21850×
            for a in list {
21860×
                let state = if a.enabled && !a.off_above {
21870×
                    ui::ok("on")
21880×
                } else if a.off_above {
21890×
                    ui::dim("off above")
2190
                } else {
21910×
                    ui::dim("off")
2192
                };
21930×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
21940×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2195
            }
2196
        }
21970×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
21980×
            let token = match token_env {
21990×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
22000×
                None => String::new(),
2201
            };
22020×
            let body =
22030×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
22040×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
22050×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2206
        }
22070×
        AssistantCmd::Remove { name } => {
22080×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
22090×
            println!("{} removed {name}", ui::ok("✔"));
2210
        }
22110×
        AssistantCmd::Prompt { set } => {
22120×
            let p: hub_api::AssistantPrompt = match set {
22130×
                Some(path) => {
22140×
                    let text = if path.as_os_str() == "-" {
22150×
                        let mut s = String::new();
22160×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
22170×
                        s
2218
                    } else {
22190×
                        std::fs::read_to_string(&path)?
2220
                    };
22210×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2222
                }
22230×
                None => c.get(&format!("{base}/prompt"))?,
2224
            };
22250×
            if json {
22260×
                println!("{}", serde_json::to_string(&p)?);
22270×
                return Ok(0);
22280×
            }
22290×
            for (from, text) in &p.inherited {
22300×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
22310×
            }
22320×
            if p.prompt.is_empty() {
22330×
                println!("{}", ui::dim("No prompt of its own."));
22340×
            } else {
22350×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
22360×
            }
2237
        }
2238
    }
22390×
    Ok(0)
22400×
}
2241
22422×
fn project_line(p: &hub_api::Project) -> String {
22432×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
22442×
    let private = if p.public { "" } else { " · private" };
22452×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
22462×
}
2247
224810×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
224910×
    let owner = match owner {
22500×
        Some(o) => o,
225110×
        None => t.repo()?.0.to_string(),
2252
    };
225310×
    let base = format!("/projects/{}", enc(&owner));
225410×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
22551×
        let p: hub_api::Project =
22561×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
22571×
        if json {
22580×
            println!("{}", serde_json::to_string(&p)?);
22591×
        } else {
22601×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
22611×
        }
22621×
        Ok(())
22631×
    };
22644×
    match cmd {
2265
        ProjectCmd::List => {
22661×
            if json {
22670×
                println!("{}", c.get_text(&base)?);
22680×
                return Ok(0);
22691×
            }
22701×
            let list: Vec<hub_api::Project> = c.get(&base)?;
22711×
            if list.is_empty() {
22720×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
22731×
            }
22741×
            for p in &list {
22751×
                println!("{}", project_line(p));
22761×
            }
2277
        }
22783×
        ProjectCmd::View { number, archived } => {
22793×
            let path = format!("{base}/{number}");
22803×
            let cards = format!("{path}/cards?archived=true");
22813×
            if json {
22822×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
22832×
                return Ok(0);
22841×
            }
22851×
            let mut b: hub_api::Board = c.get(&path)?;
22861×
            if archived {
22870×
                b.columns = c.get(&cards)?;
22881×
            }
22891×
            println!("{}", project_line(&b.project));
22901×
            if !b.project.description.is_empty() {
22911×
                println!("{}", b.project.description);
22921×
            }
22933×
            for col in &b.columns {
22943×
                println!();
22953×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
22963×
                if col.cards.is_empty() {
22971×
                    println!("  {}", ui::dim("(empty)"));
22982×
                }
22993×
                for card in &col.cards {
23002×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
23012×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
23022×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
23032×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
23042×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
23052×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2306
                }
2307
            }
23081×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2309
        }
23101×
        ProjectCmd::Create { title, description, private } => {
23111×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
23121×
            if json {
23130×
                println!("{}", serde_json::to_string(&p)?);
23141×
            } else {
23151×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
23161×
            }
2317
        }
23181×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
23190×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
23200×
        ProjectCmd::Transfer { number, to } => {
23210×
            let p: hub_api::Project =
23220×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
23230×
            if json {
23240×
                println!("{}", serde_json::to_string(&p)?);
23250×
            } else {
23260×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
23270×
            }
2328
        }
23292×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2330
            // The hub names a card's issue as `repo#N` among the owner's
2331
            // repositories.
23322×
            let reference = match reference {
23331×
                None => String::new(),
23341×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
23350×
                    Some((o, rest)) if o == owner => rest.to_string(),
23360×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
23370×
                    None => r,
2338
                },
23391×
                Some(r) => {
23401×
                    let n = r.trim_start_matches('#');
23411×
                    if n.parse::<i64>().is_err() {
23420×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
23431×
                    }
23441×
                    format!("{}#{n}", t.repo()?.1)
2345
                }
2346
            };
23472×
            let note = note.unwrap_or_default();
23482×
            if reference.is_empty() && note.is_empty() {
23490×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
23502×
            }
23511×
            let card: hub_api::ProjectCard =
23522×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
23531×
            if json {
23540×
                println!("{}", serde_json::to_string(&card)?);
2355
            } else {
23561×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2357
            }
2358
        }
23591×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
23601×
            (Some(card), None) => {
23611×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
23621×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2363
            }
23640×
            (None, Some(from)) => {
23650×
                let r: hub_api::CardsMoved = c.send(
23660×
                    "POST",
23670×
                    &format!("{base}/{number}/cards/move"),
23680×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
23690×
                )?;
23700×
                if json {
23710×
                    println!("{}", serde_json::to_string(&r)?);
23720×
                    return Ok(0);
23730×
                }
23740×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
23750×
                for m in &r.moved {
23760×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2377
                }
23780×
                let verb = if dry_run { "would move" } else { "moved" };
23790×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2380
            }
23810×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2382
        },
23830×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
23840×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
23850×
                None => None,
23860×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2387
            };
23880×
            let r: hub_api::CardsArchived = c.send(
23890×
                "POST",
23900×
                &format!("{base}/{number}/cards/archive"),
23910×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
23920×
            )?;
23930×
            if json {
23940×
                println!("{}", serde_json::to_string(&r)?);
23950×
                return Ok(0);
23960×
            }
23970×
            let verb = if dry_run { "would archive" } else { "archived" };
23980×
            for a in &r.archived {
23990×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
24000×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2401
            }
24020×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2403
        }
24040×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
24050×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
24060×
            println!("{} card {card} restored", ui::ok("✔"));
2407
        }
24081×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
24091×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
24101×
            println!("{} card {card} removed", ui::ok("✔"));
2411
        }
2412
    }
24137×
    Ok(0)
241410×
}
2415
24160×
fn milestone_line(m: &hub_api::Milestone) -> String {
24170×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
24180×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
24190×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
24200×
}
2421
24220×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
24230×
    let base = t.repo_path()?;
24240×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
24250×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
24260×
        if json {
24270×
            println!("{}", serde_json::to_string(&m)?);
24280×
        } else {
24290×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
24300×
        }
24310×
        Ok(())
24320×
    };
24330×
    match cmd {
2434
        MilestoneCmd::List => {
24350×
            let path = format!("{base}/milestones");
24360×
            if json {
24370×
                println!("{}", c.get_text(&path)?);
24380×
                return Ok(0);
24390×
            }
24400×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
24410×
            if list.is_empty() {
24420×
                println!("{}", ui::dim("No milestones."));
24430×
            }
24440×
            for m in &list {
24450×
                println!("{}", milestone_line(m));
24460×
            }
2447
        }
24480×
        MilestoneCmd::Create { title, description, due } => {
24490×
            let m: hub_api::Milestone =
24500×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
24510×
            if json {
24520×
                println!("{}", serde_json::to_string(&m)?);
24530×
            } else {
24540×
                println!("{} milestone {}", ui::ok("✔"), m.title);
24550×
            }
2456
        }
24570×
        MilestoneCmd::Edit { title, rename, description, due } => {
24580×
            if rename.is_none() && description.is_none() && due.is_none() {
24590×
                bail!("say what to change: --rename, --description or --due");
24600×
            }
24610×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2462
        }
24630×
        MilestoneCmd::Close { title } => {
24640×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2465
        }
24660×
        MilestoneCmd::Reopen { title } => {
24670×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2468
        }
2469
    }
24700×
    Ok(0)
24710×
}
2472
24730×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
24740×
    let base = t.repo_path()?;
24750×
    match cmd {
2476
        TagCmd::List => {
24770×
            let path = format!("{base}/tags");
24780×
            if json {
24790×
                println!("{}", c.get_text(&path)?);
24800×
                return Ok(0);
24810×
            }
24820×
            let tags: Vec<Tag> = c.get(&path)?;
24830×
            if tags.is_empty() {
24840×
                println!("{}", ui::dim("no tags"));
24850×
            }
24860×
            for t in tags {
24870×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
24880×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
24890×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2490
            }
2491
        }
24920×
        TagCmd::Create { name, target, message } => {
24930×
            let new = hub_api::NewTag { name, target, message };
24940×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
24950×
            if json {
24960×
                println!("{}", serde_json::to_string(&made)?);
24970×
            } else {
24980×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
24990×
            }
2500
        }
25010×
        TagCmd::Delete { name, reason } => {
25020×
            let reason = reason.unwrap_or_default();
25030×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
25040×
            if json {
25050×
                println!("{}", serde_json::json!({ "withdrawn": name }));
25060×
            } else {
25070×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
25080×
            }
2509
        }
2510
    }
25110×
    Ok(0)
25120×
}
2513
25144×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
25154×
    let base = t.repo_path()?;
25164×
    match cmd {
2517
        ReleaseCmd::List => {
25181×
            let path = format!("{base}/releases");
25191×
            if json {
25201×
                println!("{}", c.get_text(&path)?);
25211×
                return Ok(0);
25220×
            }
25230×
            let list: Vec<Release> = c.get(&path)?;
25240×
            if list.is_empty() {
25250×
                println!("{}", ui::dim("No releases."));
25260×
            }
25270×
            for r in &list {
25280×
                println!(
2529
                    "{} {} {}{}",
25300×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
25310×
                    ui::strong(&r.tag),
2532
                    r.title,
25330×
                    ui::dim(&format!(
2534
                        " · {} asset{} · {}",
25350×
                        r.assets.len(),
25360×
                        if r.assets.len() == 1 { "" } else { "s" },
25370×
                        ui::ago(r.created_ms)
2538
                    ))
2539
                );
2540
            }
2541
        }
25421×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
25431×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
25441×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
25451×
            if json {
25460×
                println!("{}", serde_json::to_string(&r)?);
25471×
            } else {
25481×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
25491×
            }
2550
        }
25510×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
25520×
            let notes = match notes.as_deref() {
25530×
                Some("-") => Some(body_of(None, Some("-".into()))?),
25540×
                _ => notes,
2555
            };
25560×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
25570×
                bail!("say what to change: --title, --notes or --prerelease");
25580×
            }
25590×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
25600×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
25610×
            if json {
25620×
                println!("{}", serde_json::to_string(&r)?);
25630×
            } else {
25640×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
25650×
            }
2566
        }
25671×
        ReleaseCmd::Upload { tag, files } => {
25681×
            if files.is_empty() {
25690×
                bail!("name the files to attach");
25701×
            }
25711×
            for f in files {
25721×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
25731×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
25741×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
25751×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2576
            }
2577
        }
25781×
        ReleaseCmd::Trust { tag } => {
25791×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
25801×
            if json {
25810×
                println!("{}", c.get_text(&path)?);
25820×
                return Ok(0);
25831×
            }
25841×
            let r: serde_json::Value = c.get(&path)?;
25851×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
25861×
            let mut worst = 0;
25874×
            for ch in r["audit"].as_array().into_iter().flatten() {
25884×
                let v = ch["verdict"].as_str().unwrap_or("");
25894×
                worst = worst.max(match v {
25904×
                    "fail" => 2,
25914×
                    "warn" => 1,
25923×
                    _ => 0,
2593
                });
25944×
                let g = match v {
25954×
                    "pass" => ui::ok("✔"),
25961×
                    "warn" => ui::warn("!"),
25970×
                    _ => ui::bad("✘"),
2598
                };
25994×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2600
            }
26011×
            return Ok(if worst == 2 { 1 } else { 0 });
2602
        }
2603
    }
26042×
    Ok(0)
26054×
}
2606
2607
#[cfg(test)]
2608
mod tests {
2609
2610
    #[test]
26111×
    fn job_timings_and_report_commands_read_plainly() {
2612
        use clap::Parser;
26131×
        let job = hub_api::FlowJob {
26141×
            name: "perf".into(),
26151×
            status: "passed".into(),
26161×
            depends_on: vec![],
26171×
            runner: "earth-1".into(),
26181×
            exit_code: Some(0),
26191×
            error: String::new(),
26201×
            started_ms: Some(13_000),
26211×
            finished_ms: Some(200_000),
26221×
            log_lines: 10,
26231×
            waiting: String::new(),
26241×
            placed: String::new(),
26251×
            approval: String::new(),
26261×
            queued_ms: Some(1_000),
26271×
            ready_ms: Some(12_500),
26281×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
26291×
            peak_disk_mib: Some(2150),
26301×
            peak_memory_mib: Some(900),
26311×
        };
26321×
        assert_eq!(super::timing_line(&job), "waited 12.0 s · image 850 ms · run 2 min 5 s · peak disk 2.1 GiB, memory 900 MiB");
26331×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
26341×
        assert_eq!(super::timing_line(&bare), "");
26351×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2636
26371×
        let cli =
26381×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
26391×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
26401×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
26411×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
26421×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
26431×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
26441×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
26451×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
26461×
    }
2647
2648
    #[test]
26491×
    fn runner_update_scopes_resolve_by_name_or_id() {
26501×
        let all = hub_api::RunnerUpdates {
26511×
            repo: String::new(),
26521×
            settings: vec![],
26531×
            groups: vec![hub_api::RunnerGroup {
26541×
                id: 4,
26551×
                owner: "acme".into(),
26561×
                name: "canary".into(),
26571×
                percent: None,
26581×
                members: vec![],
26591×
                wave: None,
26601×
            }],
26611×
            runners: vec![],
26621×
            holds: vec![],
26631×
        };
26641×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
26651×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
26663×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
26673×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2668
        }
26691×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
26701×
        assert!(update_scope("everyone", &all).is_err());
26711×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
26721×
        assert!(switch(Some("yes")).is_err());
26731×
    }
2674
    use super::*;
2675
2676
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2677
    /// help says, and a drop is named by its id or its address.
2678
    #[test]
26791×
    fn drop_commands_parse() {
26801×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
26811×
        match cli.cmd {
26821×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
26831×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
26841×
                assert!(secret);
26851×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2686
            }
26870×
            _ => panic!("not drop create"),
2688
        }
26891×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
26901×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
26911×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
26921×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
26931×
                assert!(channel.is_none() && dry_run.is_none());
2694
            }
26950×
            _ => panic!("not runner-updates set"),
2696
        }
26971×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
26981×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
26991×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
27000×
            _ => panic!("not drop list"),
2701
        }
27021×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
27031×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
27041×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2705
            }
27060×
            _ => panic!("not drop view"),
2707
        }
27081×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
27094×
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
27104×
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2711
        }
27121×
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
27131×
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
27141×
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
27150×
            _ => panic!("not drop comment"),
2716
        }
27171×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
27181×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
27191×
        assert!(drop_id("andy/notes").is_err());
27201×
    }
2721
}