OXYGENHUB

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

636 of 1593 lines run, 44 of 233 functions · run #531 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
    },
326
    /// Close an issue
327
    Close {
328
        number: i64,
329
        /// `completed` or `not_planned`
330
        #[arg(long, default_value = "completed")]
331
        reason: String,
332
    },
333
    /// Reopen an issue
334
    Reopen { number: i64 },
335
    /// Change an issue's title or body (its author or triage), or its
336
    /// labels, assignees or milestone as whole sets (triage)
337
    Edit {
338
        number: i64,
339
        #[arg(long, short)]
340
        title: Option<String>,
341
        #[arg(long, short)]
342
        body: Option<String>,
343
        /// Read the body from a file ("-" for stdin)
344
        #[arg(long, short = 'F', conflicts_with = "body")]
345
        body_file: Option<String>,
346
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
347
        #[arg(long, short)]
348
        label: Vec<String>,
349
        /// Clear its labels
350
        #[arg(long, conflicts_with = "label")]
351
        no_labels: bool,
352
        /// The users it should be assigned to (repeatable)
353
        #[arg(long, short)]
354
        assignee: Vec<String>,
355
        /// Take everyone off it
356
        #[arg(long, conflicts_with = "assignee")]
357
        no_assignees: bool,
358
        /// A milestone's title ("" takes it out of its milestone)
359
        #[arg(long, short)]
360
        milestone: Option<String>,
361
    },
362
    /// Comment on an issue
363
    Comment {
364
        number: i64,
365
        #[arg(long, short)]
366
        body: Option<String>,
367
        /// Read the body from a file ("-" for stdin), as proposal comment
368
        /// does (#260)
369
        #[arg(long, short = 'F', conflicts_with = "body")]
370
        body_file: Option<String>,
371
    },
372
}
373
374
#[derive(Subcommand)]
375
enum ProposalCmd {
376
    /// Open proposals (or --state draft|landed|closed|all), newest first
377
    List {
378
        #[arg(long, default_value = "open")]
379
        state: String,
380
        /// At most this many
381
        #[arg(long, default_value_t = 30)]
382
        limit: usize,
383
    },
384
    /// One proposal: its changes, approvals and whether it can land
385
    View { number: i64 },
386
    /// Propose a bookmark's changes for another bookmark
387
    Create {
388
        #[arg(long, short)]
389
        title: String,
390
        #[arg(long, short)]
391
        body: Option<String>,
392
        /// Read the body from a file ("-" for stdin)
393
        #[arg(long, short = 'F', conflicts_with = "body")]
394
        body_file: Option<String>,
395
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
396
        #[arg(long)]
397
        from: String,
398
        /// The bookmark to land them on (default: the repository's default bookmark)
399
        #[arg(long)]
400
        into: Option<String>,
401
        #[arg(long)]
402
        draft: bool,
403
    },
404
    /// Change a proposal's title or description (its author or a maintainer)
405
    Edit {
406
        number: i64,
407
        #[arg(long, short)]
408
        title: Option<String>,
409
        #[arg(long, short)]
410
        body: Option<String>,
411
        /// Read the body from a file ("-" for stdin)
412
        #[arg(long, short = 'F', conflicts_with = "body")]
413
        body_file: Option<String>,
414
    },
415
    /// Put labels on a proposal or take them off (triage)
416
    Label(LabelChange),
417
    /// Comment on a proposal's conversation
418
    Comment {
419
        number: i64,
420
        #[arg(long, short)]
421
        body: Option<String>,
422
        /// Read the comment from a file ("-" for stdin)
423
        #[arg(long, short = 'F', conflicts_with = "body")]
424
        body_file: Option<String>,
425
    },
426
    /// The checks on a proposal's projected state
427
    Checks { number: i64 },
428
    /// Land a proposal on its target, as the page's Land button does
429
    Land {
430
        number: i64,
431
        /// Land before its required checks pass, saying why (maintainers;
432
        /// recorded and audited, #261)
433
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
434
        over_checks: Option<String>,
435
        /// Land it by itself once its checks pass (#261); with --off, don't
436
        #[arg(long)]
437
        when_ready: bool,
438
        /// With --when-ready: turn it off
439
        #[arg(long, requires = "when_ready")]
440
        off: bool,
441
    },
442
    /// Close a proposal without landing it, with an optional comment
443
    Close {
444
        number: i64,
445
        /// Say why, as a comment before it closes
446
        #[arg(long, short = 'm')]
447
        message: Option<String>,
448
    },
449
    /// Reopen a closed proposal
450
    Reopen { number: i64 },
451
    /// Take a draft proposal out of draft, ready for review (its author or triage)
452
    Ready {
453
        number: i64,
454
        /// Turn an open proposal back into a draft instead
455
        #[arg(long)]
456
        undo: bool,
457
    },
458
}
459
460
#[derive(Subcommand)]
461
enum AssistantCmd {
462
    /// The assistants this level sees, its own and those inherited
463
    List,
464
    /// Add an assistant, or change the one of that name
465
    Add {
466
        /// How it shows on reviews (default: the provider's name)
467
        #[arg(long, default_value = "")]
468
        name: String,
469
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
470
        #[arg(long, default_value = "")]
471
        preset: String,
472
        /// The endpoint, when no preset or another one
473
        #[arg(long, default_value = "")]
474
        endpoint: String,
475
        /// chat-completions or anthropic-messages
476
        #[arg(long, default_value = "")]
477
        api: String,
478
        /// One the endpoint lists (`oh assistant models` shows them)
479
        #[arg(long)]
480
        model: String,
481
        /// The API key, read from this environment variable (never typed on the command line)
482
        #[arg(long, value_name = "VAR")]
483
        token_env: Option<String>,
484
        /// Add it turned off
485
        #[arg(long)]
486
        off: bool,
487
    },
488
    /// Remove this level's assistant of that name
489
    Remove { name: String },
490
    /// Show this level's prompt, and those it inherits
491
    Prompt {
492
        /// Set it from this file (`-` for standard input; an empty file clears it)
493
        #[arg(long, value_name = "FILE")]
494
        set: Option<std::path::PathBuf>,
495
    },
496
}
497
498
#[derive(Subcommand)]
499
enum LabelCmd {
500
    /// The repository's labels
501
    List,
502
    /// Create a label, or change the one of that name (triage)
503
    Create {
504
        name: String,
505
        /// `#rrggbb` (default: one the hub picks)
506
        #[arg(long)]
507
        colour: Option<String>,
508
        #[arg(long, short, default_value = "")]
509
        description: String,
510
    },
511
    /// Delete a label, taking it off every issue and proposal (triage)
512
    Delete { name: String },
513
}
514
515
#[derive(Subcommand)]
516
enum ProjectCmd {
517
    /// The owner's boards
518
    List,
519
    /// One board: its columns and cards
520
    View {
521
        number: i64,
522
        /// Its archived cards instead (#293)
523
        #[arg(long)]
524
        archived: bool,
525
    },
526
    /// Create a board (owner, or an organisation's members)
527
    Create {
528
        title: String,
529
        #[arg(long, short, default_value = "")]
530
        description: String,
531
        /// Only the owner (or the organisation's members) can see it
532
        #[arg(long)]
533
        private: bool,
534
    },
535
    /// Close a board
536
    Close { number: i64 },
537
    /// Reopen a board
538
    Reopen { number: i64 },
539
    /// Move a board to another owner you may make boards under (an
540
    /// organisation, say); it takes the next number there
541
    Transfer {
542
        number: i64,
543
        /// The new owner
544
        #[arg(long)]
545
        to: String,
546
    },
547
    /// Cards on a board: add, move, archive, restore, remove
548
    Card {
549
        #[command(subcommand)]
550
        cmd: CardCmd,
551
    },
552
}
553
554
#[derive(Subcommand)]
555
enum CardCmd {
556
    /// Put an issue or proposal on a board (`12` or `#12` in this
557
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
558
    /// or a note with --note
559
    Add {
560
        number: i64,
561
        /// The issue or proposal; a number means this repository's
562
        reference: Option<String>,
563
        /// A note card instead
564
        #[arg(long, conflicts_with = "reference")]
565
        note: Option<String>,
566
        /// The column, by name or id (default: the first)
567
        #[arg(long, short)]
568
        column: Option<String>,
569
    },
570
    /// Move a card to another column (by name or id), or with --from every
571
    /// card of a column at once
572
    Move {
573
        number: i64,
574
        /// The card (its id); leave it out with --from
575
        card: Option<i64>,
576
        #[arg(long, short)]
577
        column: String,
578
        /// Move every card of this column (#289)
579
        #[arg(long, conflicts_with = "card")]
580
        from: Option<String>,
581
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
582
        #[arg(long, value_delimiter = ',', requires = "from")]
583
        except: Vec<String>,
584
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
585
        #[arg(long, value_delimiter = ',', requires = "from")]
586
        state: Vec<String>,
587
        /// With --from: say what would move, and move nothing
588
        #[arg(long, requires = "from")]
589
        dry_run: bool,
590
    },
591
    /// Archive a column's cards: off the board, kept and restorable (#293)
592
    Archive {
593
        number: i64,
594
        /// The column, by name or id
595
        #[arg(long)]
596
        from: String,
597
        /// Only cards that joined the column more than this long ago (14d, or 14)
598
        #[arg(long)]
599
        older: Option<String>,
600
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
601
        #[arg(long, value_delimiter = ',')]
602
        except: Vec<String>,
603
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
604
        #[arg(long, value_delimiter = ',')]
605
        state: Vec<String>,
606
        /// Say what would be archived, and archive nothing
607
        #[arg(long)]
608
        dry_run: bool,
609
    },
610
    /// Put an archived card back at the end of its column
611
    Restore { number: i64, card: i64 },
612
    /// Take a card off a board
613
    Remove { number: i64, card: i64 },
614
}
615
616
#[derive(Subcommand)]
617
enum MilestoneCmd {
618
    /// The repository's milestones
619
    List,
620
    /// Create a milestone, or change the one of that title (triage)
621
    Create {
622
        title: String,
623
        #[arg(long, short, default_value = "")]
624
        description: String,
625
        /// Due date, YYYY-MM-DD
626
        #[arg(long)]
627
        due: Option<String>,
628
    },
629
    /// Change a milestone's title, description or due date (triage)
630
    Edit {
631
        title: String,
632
        #[arg(long, short)]
633
        rename: Option<String>,
634
        #[arg(long, short)]
635
        description: Option<String>,
636
        /// Due date, YYYY-MM-DD ("" for none)
637
        #[arg(long)]
638
        due: Option<String>,
639
    },
640
    /// Close a milestone
641
    Close { title: String },
642
    /// Reopen a milestone
643
    Reopen { title: String },
644
}
645
646
/// Labels to put on or take off an issue or proposal.
647
#[derive(clap::Args)]
648
struct LabelChange {
649
    number: i64,
650
    /// A label to add (repeatable)
651
    #[arg(long, short)]
652
    add: Vec<String>,
653
    /// A label to take off (repeatable)
654
    #[arg(long, short)]
655
    remove: Vec<String>,
656
}
657
658
impl LabelChange {
659
    /// The set after the change, from the one there now.
6600×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
6610×
        if self.add.is_empty() && self.remove.is_empty() {
6620×
            bail!("say what to change: --add NAME or --remove NAME");
6630×
        }
6640×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
6650×
        for a in &self.add {
6660×
            if !names.contains(a) {
6670×
                names.push(a.clone());
6680×
            }
669
        }
6700×
        Ok(names)
6710×
    }
672
}
673
6740×
fn label_names(labels: &[String]) -> String {
6750×
    if labels.is_empty() {
6760×
        ui::dim("no labels")
677
    } else {
6780×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
679
    }
6800×
}
681
682
#[derive(Subcommand)]
683
enum CoverageCmd {
684
    /// Upload an LCOV or Cobertura report measured on this machine, as the
685
    /// coverage of a bookmark's current state (default: the default
686
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
687
    /// not measured by a runner, and sets no check from it
688
    Upload {
689
        file: std::path::PathBuf,
690
        #[arg(long)]
691
        bookmark: Option<String>,
692
        /// A change's full hash
693
        #[arg(long, conflicts_with = "bookmark")]
694
        change: Option<String>,
695
    },
696
}
697
698
#[derive(Subcommand)]
699
enum RunCmd {
700
    /// Recent runs, newest first
701
    List {
702
        #[arg(long, default_value_t = 20)]
703
        limit: i64,
704
    },
705
    /// A run and its jobs
706
    View {
707
        number: i64,
708
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
709
        #[arg(long)]
710
        timings: bool,
711
    },
712
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
713
    Start {
714
        #[arg(long)]
715
        bookmark: Option<String>,
716
        /// A change's full hash
717
        #[arg(long, conflicts_with = "bookmark")]
718
        change: Option<String>,
719
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
720
        #[arg(long = "job", value_name = "NAME")]
721
        jobs: Vec<String>,
722
        /// Wait for the run and exit 1 unless it passes
723
        #[arg(long)]
724
        watch: bool,
725
    },
726
    /// Follow a run until it finishes; exit 1 unless it passes
727
    Watch { number: i64 },
728
    /// A job's log
729
    Log { number: i64, job: String },
730
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
731
    Report {
732
        number: i64,
733
        job: String,
734
        #[command(flatten)]
735
        pick: ReportPick,
736
    },
737
    /// Run a finished run's state again; with --job, only that job (and the
738
    /// jobs that depend on it) in the same run
739
    Rerun {
740
        number: i64,
741
        #[arg(long)]
742
        job: Option<String>,
743
    },
744
    /// Cancel a run still queued or running; its running jobs are stopped
745
    Cancel { number: i64 },
746
    /// Approve a job that waits for a person (oxygenflow#57)
747
    Approve {
748
        number: i64,
749
        #[arg(long)]
750
        job: String,
751
    },
752
    /// Reject a job that waits for a person: it ends cancelled
753
    Reject {
754
        number: i64,
755
        #[arg(long)]
756
        job: String,
757
    },
758
}
759
760
/// Which report of a job, and what of it to show.
761
#[derive(clap::Args)]
762
struct ReportPick {
763
    /// Which report, when the job published more than one
764
    #[arg(long)]
765
    name: Option<String>,
766
    /// What it holds: its metrics, context and files
767
    #[arg(long, conflicts_with = "file")]
768
    list: bool,
769
    /// One file of it (`data/frames.csv`), as published
770
    #[arg(long, value_name = "PATH")]
771
    file: Option<String>,
772
    /// Write the file here instead of to stdout
773
    #[arg(long, short, value_name = "FILE", requires = "file")]
774
    output: Option<std::path::PathBuf>,
775
}
776
777
#[derive(Subcommand)]
778
enum ReportCmd {
779
    /// The newest run of each report, newest first
780
    List {
781
        /// Only runs on this bookmark
782
        #[arg(long)]
783
        bookmark: Option<String>,
784
    },
785
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
786
    Show {
787
        report: String,
788
        #[arg(long, conflicts_with = "bookmark")]
789
        id: Option<i64>,
790
        #[arg(long)]
791
        bookmark: Option<String>,
792
        /// What it holds: its metrics, context and files
793
        #[arg(long, conflicts_with = "file")]
794
        list: bool,
795
        /// One file of it, as published
796
        #[arg(long, value_name = "PATH")]
797
        file: Option<String>,
798
        /// Write the file here instead of to stdout
799
        #[arg(long, short, value_name = "FILE", requires = "file")]
800
        output: Option<std::path::PathBuf>,
801
    },
802
}
803
804
#[derive(Subcommand)]
805
enum TagCmd {
806
    /// Tags, newest name first
807
    List,
808
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
809
    /// delegate (as `oxy tag create` and a push would be)
810
    Create {
811
        name: String,
812
        /// What to tag (default: the default bookmark)
813
        #[arg(long)]
814
        target: Option<String>,
815
        #[arg(long, short)]
816
        message: Option<String>,
817
    },
818
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
819
    /// their next fetch, and the name is never used again. Refused while a
820
    /// release uses the tag
821
    Delete {
822
        name: String,
823
        /// Why, recorded with the withdrawal
824
        #[arg(long, short)]
825
        reason: Option<String>,
826
    },
827
}
828
829
#[derive(Subcommand)]
830
enum ReleaseCmd {
831
    /// Releases, newest first
832
    List,
833
    /// Create a release on an existing tag
834
    Create {
835
        tag: String,
836
        #[arg(long, short)]
837
        title: Option<String>,
838
        /// Notes in Markdown (default: generated from the changes since the previous release)
839
        #[arg(long, short)]
840
        notes: Option<String>,
841
        #[arg(long)]
842
        prerelease: bool,
843
    },
844
    /// Change a release's title, notes or prerelease flag
845
    Edit {
846
        tag: String,
847
        #[arg(long, short)]
848
        title: Option<String>,
849
        /// New notes in Markdown ("-" reads them from stdin)
850
        #[arg(long, short)]
851
        notes: Option<String>,
852
        /// Mark it a prerelease (true) or not (false)
853
        #[arg(long)]
854
        prerelease: Option<bool>,
855
    },
856
    /// Attach files to a release
857
    Upload { tag: String, files: Vec<std::path::PathBuf> },
858
    /// The release's trust report: signatures, builds, receipts and audit
859
    Trust { tag: String },
860
}
861
86249×
fn main() {
863
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
864
    // other command-line tools do, instead of panicking on the failed
865
    // write (oxygenhub#92).
866
    #[cfg(unix)]
86749×
    unsafe {
86849×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
86949×
    }
87049×
    let cli = Cli::parse();
87149×
    ui::init(cli.plain);
87249×
    match run(cli) {
87342×
        Ok(code) => std::process::exit(code),
8747×
        Err(e) => {
8757×
            eprintln!("{} {e:#}", ui::bad("error:"));
8767×
            std::process::exit(2);
877
        }
878
    }
879
}
880
88119×
fn enc(s: &str) -> String {
88219×
    let mut out = String::new();
88386×
    for b in s.bytes() {
88486×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
88585×
            out.push(b as char);
88685×
        } else {
8871×
            out.push_str(&format!("%{b:02X}"));
8881×
        }
889
    }
89019×
    out
89119×
}
892
89349×
fn run(cli: Cli) -> Result<i32> {
89449×
    let cfg = Config::load()?;
8951×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
8961×
        return login(cfg, url, token.clone(), ca.clone());
89748×
    }
89848×
    let here = std::env::current_dir()?;
89948×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
90047×
    let c = Client::new(&t)?;
90147×
    let json = cli.json;
9020×
    match cli.cmd {
903
        Cmd::Auth { cmd: AuthCmd::Status } => {
9040×
            let me: serde_json::Value = c.get("/user")?;
9050×
            if json {
9060×
                println!("{me}");
9070×
            } else {
9080×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
9090×
            }
9100×
            Ok(0)
911
        }
9120×
        Cmd::Auth { .. } => unreachable!(),
9132×
        Cmd::Mcp { allow_write } => {
9142×
            t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?;
9152×
            mcp::serve(c, t, allow_write)
916
        }
9171×
        Cmd::Api { path, method, data } => {
9181×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
919
            // The method applies with or without a body (#75): without one, a
920
            // GET reads, anything else sends an empty object.
9211×
            let text = match data {
9220×
                Some(d) => c.send_text(
9230×
                    &method.to_uppercase(),
9240×
                    &path,
9250×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
9260×
                )?,
9271×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
9280×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
929
            };
9301×
            println!("{text}");
9311×
            Ok(0)
932
        }
933
        Cmd::Repo { cmd: RepoCmd::View } => {
9341×
            let path = t.repo_path()?;
9351×
            if json {
9360×
                println!("{}", c.get_text(&path)?);
9370×
                return Ok(0);
9381×
            }
9391×
            let r: serde_json::Value = c.get(&path)?;
9401×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
9411×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
9421×
                println!("{d}");
9431×
            }
9441×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
9451×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
9461×
            Ok(0)
947
        }
94815×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
9494×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
9503×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
9510×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
9520×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
9530×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
9540×
            let mut body = serde_json::json!({ "content": content });
9550×
            if let Some(b) = bookmark {
9560×
                body["bookmark"] = b.into();
9570×
            }
9580×
            if let Some(ch) = change {
9590×
                body["change"] = ch.into();
9600×
            }
9610×
            let base = t.repo_path()?;
9620×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
9630×
            if json {
9640×
                println!("{}", serde_json::to_string(&r)?);
965
            } else {
9660×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
9670×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
9680×
                println!(
969
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
9700×
                    ui::ok("✔"),
971
                    r.lines_hit,
972
                    r.lines_found,
973
                    r.files,
9740×
                    ui::dim(&r.url)
975
                );
9760×
                if r.dropped > 0 {
9770×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
9780×
                }
979
            }
9800×
            Ok(0)
981
        }
9824×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
9830×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
9840×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
9850×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
98610×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
9870×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
9880×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
9890×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
9907×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
991
    }
99249×
}
993
994
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
9952×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
9962×
    Ok(match v {
9970×
        None => None,
9982×
        Some("on") => Some(Some(true)),
9992×
        Some("off") => Some(Some(false)),
10002×
        Some("inherit") => Some(None),
10011×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1002
    })
10032×
}
1004
1005
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
10067×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
10077×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
10081×
    Ok(match kind {
10097×
        "site" if name.is_empty() => ("site".into(), String::new()),
10106×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
10115×
        "group" => {
10123×
            let g = all
10133×
                .groups
10143×
                .iter()
10153×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
10163×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
10173×
            ("group".into(), g.id.to_string())
1018
        }
10192×
        "runner" => {
10201×
            let r = all
10211×
                .runners
10221×
                .iter()
10231×
                .find(|r| r.id.to_string() == name || r.name == name)
10241×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
10250×
            ("runner".into(), r.id.to_string())
1026
        }
10271×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1028
    })
10297×
}
1030
10310×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
10320×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
10330×
    match cmd {
10340×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1035
        RunnerUpdatesCmd::Show => {
10360×
            println!(
1037
                "{} {}",
10380×
                ui::strong("Builds from"),
10390×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1040
            );
10410×
            for h in &all.holds {
10420×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
10430×
            }
10440×
            for s in &all.settings {
10450×
                let mut said = vec![];
10460×
                if let Some(u) = s.updates {
10470×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
10480×
                }
10490×
                if let Some(ch) = &s.channel {
10500×
                    said.push(format!("channel {ch}"));
10510×
                }
10520×
                if let Some(w) = &s.window {
10530×
                    said.push(format!("window {w} UTC"));
10540×
                }
10550×
                if let Some(d) = s.dry_run {
10560×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
10570×
                }
10580×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
10590×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1060
            }
10610×
            for g in &all.groups {
10620×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
10630×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
10640×
                if let Some(w) = g.wave {
10650×
                    what.push_str(&format!(", wave {w}"));
10660×
                }
10670×
                println!(
1068
                    "  group {} ({what}): {}",
10690×
                    ui::strong(&g.name),
10700×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1071
                );
1072
            }
10730×
            for r in &all.runners {
10740×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
10750×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1076
            }
1077
        }
10780×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
10790×
            let (scope, key) = update_scope(&scope, &all)?;
10800×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
10810×
                scope: scope.clone(),
10820×
                key: key.clone(),
10830×
                ..Default::default()
10840×
            });
10850×
            if let Some(u) = switch(updates.as_deref())? {
10860×
                s.updates = u;
10870×
            }
10880×
            if let Some(d) = switch(dry_run.as_deref())? {
10890×
                s.dry_run = d;
10900×
            }
10910×
            if let Some(ch) = channel {
10920×
                s.channel = Some(ch).filter(|c| c != "inherit");
10930×
            }
10940×
            if let Some(w) = window {
10950×
                s.window = Some(w).filter(|w| w != "inherit");
10960×
            }
10970×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
10980×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1099
        }
11000×
        RunnerUpdatesCmd::Lift { version } => {
11010×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
11020×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1103
        }
1104
    }
11050×
    Ok(0)
11060×
}
1107
1108
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
11097×
fn drop_id(s: &str) -> Result<String> {
11107×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1111144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
11121×
        bail!("{s:?} is not a drop's id or address");
11136×
    }
11146×
    Ok(id.to_ascii_lowercase())
11157×
}
1116
11172×
fn drop_line(d: &hub_api::Drop) -> String {
11182×
    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() };
11194×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
11202×
    format!(
1121
        "{} {} {}{}",
11222×
        ui::dim(&d.id),
11232×
        ui::strong(&title),
11242×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
11252×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1126
    )
11272×
}
1128
1129
/// `oh drop star|unstar` (oxygenhub#349).
11300×
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
11310×
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
11320×
    if json {
11330×
        println!("{}", serde_json::to_string(&s)?);
1134
    } else {
11350×
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1136
    }
11370×
    Ok(())
11380×
}
1139
11407×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
11417×
    match cmd {
11421×
        DropCmd::Create { files, secret, description, title } => {
11431×
            let mut out = Vec::with_capacity(files.len());
11442×
            for f in &files {
11452×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
11462×
                let content =
11472×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
11482×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1149
            }
11501×
            let new =
11511×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
11521×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
11531×
            if json {
11541×
                println!("{}", serde_json::to_string(&d)?);
1155
            } else {
11560×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
11570×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1158
            }
1159
        }
11602×
        DropCmd::List { user } => {
11612×
            let path = match &user {
11621×
                Some(u) => format!("/users/{}/drops", enc(u)),
11631×
                None => "/drops".to_string(),
1164
            };
11652×
            if json {
11661×
                println!("{}", c.get_text(&path)?);
11671×
                return Ok(0);
11681×
            }
11691×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
11701×
            if list.is_empty() {
11710×
                println!("{}", ui::dim("No drops."));
11721×
            }
11731×
            for d in &list {
11741×
                println!("{}", drop_line(d));
11751×
            }
1176
        }
11773×
        DropCmd::View { id, file } => {
11783×
            let path = format!("/drops/{}", drop_id(&id)?);
11793×
            if json && file.is_none() {
11800×
                println!("{}", c.get_text(&path)?);
11810×
                return Ok(0);
11823×
            }
11833×
            let d: hub_api::Drop = c.get(&path)?;
11842×
            if let Some(name) = file {
11852×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
11861×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
11871×
                print!("{content}");
11881×
                return Ok(0);
11891×
            }
11901×
            println!("{}", drop_line(&d));
11911×
            if !d.description.is_empty() {
11921×
                println!("{}", d.description);
11931×
            }
11941×
            println!("{}", ui::kv("url", &d.url));
11951×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
11962×
            for f in &d.files {
11972×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
11982×
                match &f.content {
11992×
                    Some(text) => {
12002×
                        print!("{text}");
12012×
                        if !text.ends_with('\n') && !text.is_empty() {
12020×
                            println!();
12032×
                        }
1204
                    }
12050×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1206
                }
1207
            }
1208
        }
12091×
        DropCmd::Delete { id } => {
12101×
            let id = drop_id(&id)?;
12111×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
12121×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1213
        }
12140×
        DropCmd::Fork { id } => {
12150×
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
12160×
            if json {
12170×
                println!("{}", serde_json::to_string(&d)?);
12180×
            } else {
12190×
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
12200×
            }
1221
        }
12220×
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
12230×
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
12240×
        DropCmd::Comments { id } => {
12250×
            let path = format!("/drops/{}/comments", drop_id(&id)?);
12260×
            if json {
12270×
                println!("{}", c.get_text(&path)?);
12280×
                return Ok(0);
12290×
            }
12300×
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
12310×
            if list.is_empty() {
12320×
                println!("{}", ui::dim("No comments."));
12330×
            }
12340×
            for m in &list {
12350×
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
12360×
                println!("{}\n", m.body);
12370×
            }
1238
        }
12390×
        DropCmd::Comment { id, message } => {
12400×
            let m: hub_api::DropComment =
12410×
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
12420×
            if json {
12430×
                println!("{}", serde_json::to_string(&m)?);
12440×
            } else {
12450×
                println!("{} commented (#{})", ui::ok("✔"), m.id);
12460×
            }
1247
        }
1248
    }
12494×
    Ok(0)
12507×
}
1251
1252
/// `30d`, `12h`, `90m` in milliseconds.
12530×
fn duration_ms(s: &str) -> Result<i64> {
12540×
    let s = s.trim();
12550×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
12560×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
12570×
    let per = match unit {
12580×
        "d" => 86_400_000,
12590×
        "h" => 3_600_000,
12600×
        "m" => 60_000,
12610×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1262
    };
12630×
    if n <= 0 {
12640×
        bail!("a grant must last some time");
12650×
    }
12660×
    Ok(n * per)
12670×
}
1268
12690×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1270
    use oxy_core::cert::{Grant, SignedGrant};
1271
    use oxy_core::identity::{Identity, Scope};
12720×
    match cmd {
12730×
        AgentCmd::Grant { name, scope, lasts } => {
12740×
            let home = oxy_core::repo::default_home();
12750×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
12760×
                format!(
1277
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
12780×
                    home.display()
1279
                )
12800×
            })?;
12810×
            let me: serde_json::Value = c.get("/user")?;
12820×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
12830×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
12840×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
12850×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
12860×
            let grant = Grant {
12870×
                grantor: me_id.hash(),
12880×
                subject: format!("agent:{name}@{username}"),
12890×
                issuer: hub.hash(),
12900×
                scope,
12910×
                not_before: (now - 60_000) as u64,
12920×
                expires: (now + duration_ms(&lasts)?) as u64,
1293
            };
12940×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
12950×
            let r: serde_json::Value =
12960×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
12970×
            if json {
12980×
                println!("{r}");
12990×
                return Ok(0);
13000×
            }
13010×
            println!(
1302
                "{} {} to act for you as {} ({}), until {}",
13030×
                ui::ok("✔ granted"),
13040×
                ui::strong(&name),
13050×
                r["subject"].as_str().unwrap_or(""),
13060×
                r["scope"].as_str().unwrap_or(""),
13070×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1308
            );
13090×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
13100×
            println!(
1311
                "  {}",
13120×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1313
            );
13140×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
13150×
            Ok(0)
1316
        }
1317
        AgentCmd::List => {
13180×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
13190×
            if json {
13200×
                println!("{}", serde_json::to_string(&grants)?);
13210×
                return Ok(0);
13220×
            }
13230×
            if grants.is_empty() {
13240×
                println!("{}", ui::dim("no agent grants"));
13250×
            }
13260×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
13270×
            for g in grants {
13280×
                let state = if g["revoked_ms"].is_i64() {
13290×
                    ui::bad("revoked")
13300×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
13310×
                    ui::dim("ended")
1332
                } else {
13330×
                    ui::ok("live")
1334
                };
13350×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
13360×
                println!(
1337
                    "#{:<4} {:<8} {} · {} · until {} · {}",
13380×
                    g["id"],
1339
                    state,
13400×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
13410×
                    g["scope"].as_str().unwrap_or(""),
13420×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
13430×
                    ui::dim(&used)
1344
                );
1345
            }
13460×
            Ok(0)
1347
        }
13480×
        AgentCmd::Revoke { id } => {
13490×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
13500×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
13510×
            Ok(0)
1352
        }
1353
    }
13540×
}
1355
13561×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
13571×
    let hub = url.trim_end_matches('/').to_string();
13581×
    let token = match token.as_deref() {
13591×
        Some("-") => {
13600×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
13610×
            let mut line = String::new();
13620×
            std::io::stdin().read_line(&mut line)?;
13630×
            line.trim().to_string()
1364
        }
13651×
        Some(t) => t.to_string(),
13660×
        None => device_sign_in(&hub, ca.clone())?,
1367
    };
13681×
    if token.is_empty() {
13690×
        bail!("no token given");
13701×
    }
13711×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
13721×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
13731×
    let account = me["username"].as_str().unwrap_or("?");
1374
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
13751×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
13761×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
13771×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
13781×
    cfg.default_hub = Some(hub.clone());
13791×
    cfg.save()?;
13801×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
13811×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
13821×
    Ok(0)
13831×
}
1384
1385
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1386
/// it on the web, and the token arrives here.
13870×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
13880×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
13890×
    let c = Client::new(&t)?;
13900×
    let host = std::fs::read_to_string("/etc/hostname")
13910×
        .ok()
13920×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
13930×
        .map(|h| h.trim().to_string())
13940×
        .filter(|h| !h.is_empty());
13950×
    let client = match host {
13960×
        Some(h) => format!("oh on {h}"),
13970×
        None => "oh".to_string(),
1398
    };
13990×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
14000×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
14010×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
14020×
    if code != 200 {
14030×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
14040×
    }
14050×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
14060×
    let user = v["user_code"].as_str().unwrap_or("?");
14070×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
14080×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
14090×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
14100×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
14110×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1412
    loop {
14130×
        std::thread::sleep(std::time::Duration::from_secs(interval));
14140×
        if std::time::Instant::now() > deadline {
14150×
            bail!("the code expired before it was approved; run oh auth login again");
14160×
        }
14170×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
14180×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
14190×
        if code == 200 {
14200×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
14210×
        }
14220×
        match v["error"].as_str() {
14230×
            Some("authorization_pending") => {}
14240×
            Some("slow_down") => interval += 5,
14250×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
14260×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
14270×
            _ => bail!("signing in: HTTP {code}: {body}"),
1428
        }
1429
    }
14300×
}
1431
14327×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
14337×
    match (body, file) {
14342×
        (Some(b), _) => Ok(b),
14351×
        (None, Some(f)) if f == "-" => {
14360×
            let mut s = String::new();
14370×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
14380×
            Ok(s)
1439
        }
14401×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
14414×
        (None, None) => Ok(String::new()),
1442
    }
14437×
}
1444
14453×
fn issue_line(i: &Issue) -> String {
14463×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
14473×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
14483×
    format!(
1449
        "{glyph} {} {}{}{}",
14503×
        ui::dim(&format!("#{}", i.number)),
1451
        i.title,
14523×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
14533×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1454
    )
14553×
}
1456
145715×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
145815×
    let base = t.repo_path()?;
145915×
    match cmd {
14603×
        IssueCmd::List { state } => {
14613×
            let path = format!("{base}/issues?state={}", enc(&state));
14623×
            if json {
14631×
                println!("{}", c.get_text(&path)?);
14641×
                return Ok(0);
14652×
            }
14662×
            let list: Vec<Issue> = c.get(&path)?;
14672×
            if list.is_empty() {
14681×
                println!("{}", ui::dim(&format!("No {state} issues.")));
14691×
            }
14702×
            for i in &list {
14712×
                println!("{}", issue_line(i));
14722×
            }
1473
        }
14742×
        IssueCmd::View { number } => {
14752×
            let path = format!("{base}/issues/{number}");
14762×
            if json {
14771×
                println!("{}", c.get_text(&path)?);
14781×
                return Ok(0);
14791×
            }
14801×
            let i: Issue = c.get(&path)?;
14811×
            println!("{}", issue_line(&i));
14821×
            if !i.body.trim().is_empty() {
14831×
                println!("\n{}\n", i.body.trim_end());
14841×
            }
14851×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
14862×
            for cm in comments {
14872×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
14882×
            }
14891×
            println!("{}", ui::dim(&i.url));
1490
        }
14913×
        IssueCmd::Create { title, body, body_file, label, project, column } => {
14923×
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
14933×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
14942×
            if json {
14950×
                println!("{}", serde_json::to_string(&i)?);
14962×
            } else {
14972×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
14982×
            }
14992×
            if let Some(n) = project {
15001×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
15011×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
15021×
                if !json {
15031×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
15041×
                }
15051×
            }
1506
        }
15071×
        IssueCmd::Close { number, reason } => {
15081×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
15091×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1510
        }
15110×
        IssueCmd::Reopen { number } => {
15120×
            let i: Issue =
15130×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
15140×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1515
        }
15163×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
15173×
            let body = match (&body, &body_file) {
15183×
                (None, None) => None,
15190×
                _ => Some(body_of(body, body_file)?),
1520
            };
15213×
            let labels = if no_labels {
15221×
                Some(Vec::new())
15232×
            } else if label.is_empty() {
15241×
                None
1525
            } else {
15261×
                Some(label)
1527
            };
15283×
            let assignees = if no_assignees {
15291×
                Some(Vec::new())
15302×
            } else if assignee.is_empty() {
15311×
                None
1532
            } else {
15331×
                Some(assignee)
1534
            };
15353×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
15361×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
15372×
            }
15382×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
15392×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
15402×
            if json {
15411×
                println!("{}", serde_json::to_string(&i)?);
15421×
            } else {
15431×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
15441×
            }
1545
        }
15460×
        IssueCmd::Label(change) => {
15470×
            let path = format!("{base}/issues/{}", change.number);
15480×
            let now: Issue = c.get(&path)?;
15490×
            let labels = change.apply(&now.labels)?;
15500×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
15510×
            let i: Issue = c.send("PATCH", &path, &edit)?;
15520×
            if json {
15530×
                println!("{}", serde_json::to_string(&i)?);
15540×
            } else {
15550×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
15560×
            }
1557
        }
15583×
        IssueCmd::Comment { number, body, body_file } => {
15593×
            let body = body_of(body, body_file)?;
15603×
            if body.trim().is_empty() {
15611×
                bail!("give the comment with --body or --body-file");
15622×
            }
15632×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
15642×
            println!("{} commented on #{number}", ui::ok("✔"));
1565
        }
1566
    }
156710×
    Ok(0)
156815×
}
1569
15701×
fn source_name(s: &hub_api::ProposalSource) -> String {
15711×
    match s {
15721×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
15730×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
15740×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1575
    }
15761×
}
1577
15781×
fn proposal_line(p: &Proposal) -> String {
15791×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
15801×
    let glyph = match state.as_str() {
15811×
        "open" => ui::ok("●"),
15820×
        "draft" => ui::dim("◌"),
15830×
        "landed" => ui::strong("✔"),
15840×
        _ => ui::dim("○"),
1585
    };
15861×
    format!(
1587
        "{glyph} {} {} {}{}",
15881×
        ui::dim(&format!("#{}", p.number)),
1589
        p.title,
15901×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
15911×
        ui::dim(&format!(" · {} · {state}", p.author))
1592
    )
15931×
}
1594
15954×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
15964×
    let base = t.repo_path()?;
15974×
    match cmd {
15980×
        ProposalCmd::List { state, limit } => {
15990×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
16000×
            if json {
16010×
                println!("{}", c.get_text(&path)?);
16020×
                return Ok(0);
16030×
            }
16040×
            let list: Vec<Proposal> = c.get(&path)?;
16050×
            if list.is_empty() {
16060×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
16070×
            }
16080×
            for p in &list {
16090×
                println!("{}", proposal_line(p));
16100×
            }
1611
        }
16121×
        ProposalCmd::View { number } => {
16131×
            let path = format!("{base}/proposals/{number}");
16141×
            if json {
16150×
                println!("{}", c.get_text(&path)?);
16160×
                return Ok(0);
16171×
            }
16181×
            let p: Proposal = c.get(&path)?;
16191×
            println!("{}", proposal_line(&p));
16201×
            if !p.body.trim().is_empty() {
16210×
                println!("\n{}\n", p.body.trim_end());
16221×
            }
16231×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
16241×
            for ch in &p.changes {
16251×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
16261×
            }
16271×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
16281×
            if p.landable {
16291×
                println!("{} can land", ui::ok("✔"));
16301×
            } else {
16310×
                for b in &p.blockers {
16320×
                    println!("{} {b}", ui::bad("✘"));
16330×
                }
1634
            }
16351×
            if p.conflicted {
16360×
                println!("{} landing it would leave conflicts", ui::bad("!"));
16371×
            }
16381×
            println!("{}", ui::dim(&p.url));
1639
        }
16401×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
16411×
            let target = match into {
16420×
                Some(i) => i,
16431×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1644
            };
16451×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
16461×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
16471×
            if json {
16480×
                println!("{}", serde_json::to_string(&p)?);
16491×
            } else {
16501×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
16511×
            }
1652
        }
16530×
        ProposalCmd::Edit { number, title, body, body_file } => {
16540×
            let body = match (&body, &body_file) {
16550×
                (None, None) => None,
16560×
                _ => Some(body_of(body, body_file)?),
1657
            };
16580×
            if title.is_none() && body.is_none() {
16590×
                bail!("say what to change: --title, --body or --body-file");
16600×
            }
16610×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
16620×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
16630×
            if json {
16640×
                println!("{}", serde_json::to_string(&p)?);
16650×
            } else {
16660×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
16670×
            }
1668
        }
16690×
        ProposalCmd::Label(change) => {
16700×
            let path = format!("{base}/proposals/{}", change.number);
16710×
            let now: Proposal = c.get(&path)?;
16720×
            let labels = change.apply(&now.labels)?;
16730×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
16740×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
16750×
            if json {
16760×
                println!("{}", serde_json::to_string(&p)?);
16770×
            } else {
16780×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
16790×
            }
1680
        }
16810×
        ProposalCmd::Comment { number, body, body_file } => {
16820×
            let body = body_of(body, body_file)?;
16830×
            if body.trim().is_empty() {
16840×
                bail!("give the comment with --body or --body-file");
16850×
            }
16860×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
16870×
            println!("{} commented on #{number}", ui::ok("✔"));
1688
        }
16890×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
16900×
            let path = format!("{base}/proposals/{number}/auto-land");
16910×
            let p: Proposal =
16920×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
16930×
            if json {
16940×
                println!("{}", serde_json::to_string(&p)?);
16950×
            } else if p.landed.is_some() {
16960×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
16970×
            } else if p.auto_land.is_some() {
16980×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
16990×
            } else {
17000×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
17010×
            }
1702
        }
17032×
        ProposalCmd::Land { number, over_checks, .. } => {
17042×
            let body = match &over_checks {
17050×
                Some(r) => serde_json::json!({ "over_checks": r }),
17062×
                None => serde_json::json!({}),
1707
            };
17082×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
17091×
            if json {
17100×
                println!("{}", serde_json::to_string(&p)?);
17111×
            } else {
17121×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
17131×
            }
1714
        }
17150×
        ProposalCmd::Close { number, message } => {
17160×
            if let Some(body) = message {
17170×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
17180×
            }
17190×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
17200×
            if json {
17210×
                println!("{}", serde_json::to_string(&p)?);
17220×
            } else {
17230×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
17240×
            }
1725
        }
17260×
        ProposalCmd::Reopen { number } => {
17270×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
17280×
            if json {
17290×
                println!("{}", serde_json::to_string(&p)?);
17300×
            } else {
17310×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
17320×
            }
1733
        }
17340×
        ProposalCmd::Ready { number, undo } => {
17350×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
17360×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
17370×
            if json {
17380×
                println!("{}", serde_json::to_string(&p)?);
17390×
            } else if undo {
17400×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
17410×
            } else {
17420×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
17430×
            }
1744
        }
17450×
        ProposalCmd::Checks { number } => {
17460×
            let path = format!("{base}/proposals/{number}/checks");
17470×
            if json {
17480×
                println!("{}", c.get_text(&path)?);
17490×
                return Ok(0);
17500×
            }
17510×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
17520×
            if checks.is_empty() {
17530×
                println!("{}", ui::dim("No checks yet."));
17540×
            }
17550×
            for ch in checks {
17560×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
17570×
            }
1758
        }
1759
    }
17603×
    Ok(0)
17614×
}
1762
17631×
fn run_line(r: &FlowRun) -> String {
17641×
    let what =
17651×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
17661×
    format!(
1767
        "{} {} {} {}",
17681×
        ui::status(&r.status),
17691×
        ui::dim(&format!("#{}", r.number)),
1770
        what,
17711×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1772
    )
17731×
}
1774
17751×
fn print_run(r: &FlowRun, timings: bool) {
17761×
    println!("{}", run_line(r));
17771×
    for j in &r.jobs {
17781×
        let dur = match (j.started_ms, j.finished_ms) {
17790×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
17801×
            _ => String::new(),
1781
        };
17821×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
17831×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1784
        // Why a queued job no runner can take waits (oxygenhub#28), and
1785
        // why a job ran where it did (oxygenflow#42).
17861×
        if j.status == "queued" && !j.waiting.is_empty() {
17870×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
17881×
        } else if !j.placed.is_empty() {
17890×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
17901×
        }
17911×
        if timings {
17920×
            let t = timing_line(j);
17930×
            if !t.is_empty() {
17940×
                println!("    {}", ui::dim(&t));
17950×
            }
17961×
        }
1797
    }
17981×
    if !r.error.is_empty() {
17990×
        println!("{}", ui::bad(&r.error));
18001×
    }
18011×
    println!("{}", ui::dim(&r.url));
18021×
}
1803
1804
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
18053×
fn took(ms: i64) -> String {
18063×
    match ms {
18073×
        ..=999 => format!("{ms} ms"),
18082×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
18091×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1810
    }
18113×
}
1812
1813
/// MiB as a person reads them.
18142×
fn mib(m: i64) -> String {
18152×
    if m >= 1024 {
18161×
        format!("{:.1} GiB", m as f64 / 1024.0)
1817
    } else {
18181×
        format!("{m} MiB")
1819
    }
18202×
}
1821
1822
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1823
/// phase its runner reported, and the most disk and memory it took.
18242×
fn timing_line(j: &FlowJob) -> String {
18252×
    let mut parts = vec![];
18262×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
18271×
        parts.push(format!("waited {}", took((s - q).max(0))));
18281×
    }
18292×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
18302×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
18312×
        .into_iter()
18324×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
18332×
        .collect();
18342×
    if !peaks.is_empty() {
18351×
        parts.push(format!("peak {}", peaks.join(", ")));
18361×
    }
18372×
    parts.join(" · ")
18382×
}
1839
1840
/// A report's path, its segments encoded and its slashes kept.
18411×
fn enc_path(path: &str) -> String {
18421×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
18431×
}
1844
1845
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1846
/// files are at `files(path)`. By default its report.toml; with `list`
1847
/// what it holds; with `file` one file, to stdout or `output`.
18480×
fn show_report(
18490×
    c: &Client,
18500×
    at: &str,
18510×
    files: impl Fn(&str) -> String,
18520×
    list: bool,
18530×
    file: Option<String>,
18540×
    output: Option<std::path::PathBuf>,
18550×
    json: bool,
18560×
) -> Result<()> {
1857
    use std::io::Write;
18580×
    if let Some(path) = file {
18590×
        let bytes = c.get_bytes(&files(&path))?;
18600×
        match output {
18610×
            Some(out) => {
18620×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
18630×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
1864
            }
18650×
            None => std::io::stdout().write_all(&bytes)?,
1866
        }
18670×
        return Ok(());
18680×
    }
18690×
    if json {
18700×
        println!("{}", c.get_text(at)?);
18710×
        return Ok(());
18720×
    }
18730×
    if !list {
18740×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
18750×
        return Ok(());
18760×
    }
18770×
    let r: Report = c.get(at)?;
18780×
    print_report(&r);
18790×
    if r.files_expired_ms.is_some() {
18800×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
18810×
    }
18820×
    for f in &r.manifest {
18830×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
18840×
    }
18850×
    println!("{}", ui::dim(&r.url));
18860×
    Ok(())
18870×
}
1888
1889
/// A report's heading, metrics and context.
18900×
fn print_report(r: &Report) {
18910×
    let from = match r.run {
18920×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
18930×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
1894
    };
18950×
    println!(
1896
        "{} {} {}",
18970×
        ui::strong(&r.name),
18980×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
18990×
        ui::dim(&format!("· {from} · {} files", r.files))
1900
    );
19010×
    if !r.summary.is_empty() {
19020×
        println!("  {}", r.summary);
19030×
    }
19040×
    for m in &r.metrics {
19050×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
19060×
        let mut notes = vec![];
19070×
        if !m.better.is_empty() {
19080×
            notes.push(format!("{} is better", m.better));
19090×
        }
19100×
        if let Some(a) = m.fail_above {
19110×
            notes.push(format!("fails above {a}"));
19120×
        }
19130×
        if let Some(b) = m.fail_below {
19140×
            notes.push(format!("fails below {b}"));
19150×
        }
19160×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
19170×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
1918
    }
19190×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
19200×
        let line: Vec<String> =
19210×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
19220×
        println!("  {}", ui::dim(&line.join(" ")));
19230×
    }
19240×
}
1925
1926
/// `oh report …` (oxygenhub#348).
19270×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
19280×
    let base = t.repo_path()?;
19290×
    match cmd {
19300×
        ReportCmd::List { bookmark } => {
19310×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
19320×
            if json {
19330×
                println!("{}", c.get_text(&path)?);
19340×
                return Ok(0);
19350×
            }
19360×
            let list: Vec<Report> = c.get(&path)?;
19370×
            if list.is_empty() {
19380×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
19390×
            }
19400×
            for r in &list {
19410×
                print_report(r);
19420×
            }
1943
        }
19440×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
19450×
            let at = format!("{base}/reports/{}", enc(&report));
19460×
            let query = match (id, bookmark) {
19470×
                (Some(id), _) => format!("?id={id}"),
19480×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
19490×
                (None, None) => String::new(),
1950
            };
19510×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
19520×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
1953
        }
1954
    }
19550×
    Ok(0)
19560×
}
1957
19580×
fn live(status: &str) -> bool {
19590×
    matches!(status, "queued" | "running")
19600×
}
1961
1962
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
19630×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
19640×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
19650×
    if json {
19660×
        println!("{done}");
19670×
    } else {
19680×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
19690×
    }
19700×
    Ok(())
19710×
}
1972
19730×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
19740×
    let path = format!("{base}/flow/runs/{number}");
19750×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1976
    loop {
19770×
        let r: FlowRun = c.get(&path)?;
19780×
        if !json {
19790×
            for j in &r.jobs {
19800×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
19810×
                if seen.get(&j.name) != Some(&shown) {
19820×
                    println!("{} {}", ui::status(&j.status), j.name);
19830×
                    if j.status == "queued" && !j.waiting.is_empty() {
19840×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
19850×
                    }
19860×
                    seen.insert(j.name.clone(), shown);
19870×
                }
1988
            }
19890×
        }
19900×
        if !live(&r.status) {
19910×
            if json {
19920×
                println!("{}", serde_json::to_string(&r)?);
19930×
            } else {
19940×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
19950×
            }
19960×
            return Ok(if r.status == "passed" { 0 } else { 1 });
19970×
        }
19980×
        std::thread::sleep(Duration::from_secs(3));
1999
    }
20000×
}
2001
20023×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
20033×
    let base = t.repo_path()?;
20040×
    match cmd {
20051×
        RunCmd::List { limit } => {
20061×
            let path = format!("{base}/flow/runs?limit={limit}");
20071×
            if json {
20081×
                println!("{}", c.get_text(&path)?);
20091×
                return Ok(0);
20100×
            }
20110×
            let runs: Vec<FlowRun> = c.get(&path)?;
20120×
            if runs.is_empty() {
20130×
                println!("{}", ui::dim("No runs yet."));
20140×
            }
20150×
            for r in &runs {
20160×
                println!("{}", run_line(r));
20170×
            }
2018
        }
20191×
        RunCmd::View { number, timings } => {
20201×
            let path = format!("{base}/flow/runs/{number}");
20211×
            if json {
20220×
                println!("{}", c.get_text(&path)?);
20230×
                return Ok(0);
20241×
            }
20251×
            print_run(&c.get(&path)?, timings);
2026
        }
20271×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
20281×
            let mut body = match (bookmark, change) {
20290×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
20300×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
20311×
                (None, None) => serde_json::json!({}),
2032
            };
20331×
            if !jobs.is_empty() {
20340×
                body["jobs"] = serde_json::json!(jobs);
20351×
            }
20361×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
20371×
            let n = started["number"].as_i64().context("the hub named no run")?;
20381×
            if !json || !follow {
20391×
                if json {
20400×
                    println!("{started}");
20411×
                } else {
20421×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
20431×
                }
20440×
            }
20451×
            if follow {
20460×
                return watch(c, &base, n, json);
20471×
            }
2048
        }
20490×
        RunCmd::Watch { number } => return watch(c, &base, number, json),
20500×
        RunCmd::Log { number, job } => {
20510×
            let mut after = 0;
2052
            loop {
20530×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
20540×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
20550×
                if lines.is_empty() {
20560×
                    break;
20570×
                }
20580×
                for l in &lines {
20590×
                    if json {
20600×
                        println!("{}", serde_json::to_string(l)?);
20610×
                    } else if l.stream == "flow" {
20620×
                        println!("{}", ui::dim(&l.text));
20630×
                    } else {
20640×
                        println!("{}", l.text);
20650×
                    }
2066
                }
20670×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2068
            }
2069
        }
20700×
        RunCmd::Report { number, job, pick } => {
20710×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
20720×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
20730×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
20740×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2075
        }
20760×
        RunCmd::Rerun { number, job: Some(job) } => {
20770×
            let queued: serde_json::Value =
20780×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
20790×
            if json {
20800×
                println!("{queued}");
20810×
            } else {
20820×
                let n = queued["queued"].as_i64().unwrap_or(1);
20830×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
20840×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2085
            }
2086
        }
20870×
        RunCmd::Rerun { number, job: None } => {
20880×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
20890×
            if json {
20900×
                println!("{started}");
20910×
            } else {
20920×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
20930×
            }
2094
        }
20950×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
20960×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
20970×
        RunCmd::Cancel { number } => {
20980×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
20990×
            if json {
21000×
                println!("{done}");
21010×
            } else {
21020×
                println!("{} cancelled run #{number}", ui::ok("✔"));
21030×
            }
2104
        }
2105
    }
21062×
    Ok(0)
21073×
}
2108
21090×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
21100×
    let base = t.repo_path()?;
21110×
    match cmd {
2112
        LabelCmd::List => {
21130×
            let path = format!("{base}/labels");
21140×
            if json {
21150×
                println!("{}", c.get_text(&path)?);
21160×
                return Ok(0);
21170×
            }
21180×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
21190×
            if labels.is_empty() {
21200×
                println!("{}", ui::dim("No labels."));
21210×
            }
21220×
            for l in labels {
21230×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
21240×
            }
2125
        }
21260×
        LabelCmd::Create { name, colour, description } => {
21270×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
21280×
            if json {
21290×
                println!("{}", serde_json::to_string(&l)?);
21300×
            } else {
21310×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
21320×
            }
2133
        }
21340×
        LabelCmd::Delete { name } => {
21350×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
21360×
            println!("{} deleted label {name}", ui::ok("✔"));
2137
        }
2138
    }
21390×
    Ok(0)
21400×
}
2141
21420×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
21430×
    let base = match (&org, site) {
21440×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
21450×
        (None, true) => "/admin/assistants".to_string(),
21460×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2147
    };
21480×
    match cmd {
2149
        AssistantCmd::List => {
21500×
            if json {
21510×
                println!("{}", c.get_text(&base)?);
21520×
                return Ok(0);
21530×
            }
21540×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
21550×
            if list.is_empty() {
21560×
                println!("{}", ui::dim("No assistants."));
21570×
            }
21580×
            for a in list {
21590×
                let state = if a.enabled && !a.off_above {
21600×
                    ui::ok("on")
21610×
                } else if a.off_above {
21620×
                    ui::dim("off above")
2163
                } else {
21640×
                    ui::dim("off")
2165
                };
21660×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
21670×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2168
            }
2169
        }
21700×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
21710×
            let token = match token_env {
21720×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
21730×
                None => String::new(),
2174
            };
21750×
            let body =
21760×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
21770×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
21780×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2179
        }
21800×
        AssistantCmd::Remove { name } => {
21810×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
21820×
            println!("{} removed {name}", ui::ok("✔"));
2183
        }
21840×
        AssistantCmd::Prompt { set } => {
21850×
            let p: hub_api::AssistantPrompt = match set {
21860×
                Some(path) => {
21870×
                    let text = if path.as_os_str() == "-" {
21880×
                        let mut s = String::new();
21890×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
21900×
                        s
2191
                    } else {
21920×
                        std::fs::read_to_string(&path)?
2193
                    };
21940×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2195
                }
21960×
                None => c.get(&format!("{base}/prompt"))?,
2197
            };
21980×
            if json {
21990×
                println!("{}", serde_json::to_string(&p)?);
22000×
                return Ok(0);
22010×
            }
22020×
            for (from, text) in &p.inherited {
22030×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
22040×
            }
22050×
            if p.prompt.is_empty() {
22060×
                println!("{}", ui::dim("No prompt of its own."));
22070×
            } else {
22080×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
22090×
            }
2210
        }
2211
    }
22120×
    Ok(0)
22130×
}
2214
22152×
fn project_line(p: &hub_api::Project) -> String {
22162×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
22172×
    let private = if p.public { "" } else { " · private" };
22182×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
22192×
}
2220
222110×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
222210×
    let owner = match owner {
22230×
        Some(o) => o,
222410×
        None => t.repo()?.0.to_string(),
2225
    };
222610×
    let base = format!("/projects/{}", enc(&owner));
222710×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
22281×
        let p: hub_api::Project =
22291×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
22301×
        if json {
22310×
            println!("{}", serde_json::to_string(&p)?);
22321×
        } else {
22331×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
22341×
        }
22351×
        Ok(())
22361×
    };
22374×
    match cmd {
2238
        ProjectCmd::List => {
22391×
            if json {
22400×
                println!("{}", c.get_text(&base)?);
22410×
                return Ok(0);
22421×
            }
22431×
            let list: Vec<hub_api::Project> = c.get(&base)?;
22441×
            if list.is_empty() {
22450×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
22461×
            }
22471×
            for p in &list {
22481×
                println!("{}", project_line(p));
22491×
            }
2250
        }
22513×
        ProjectCmd::View { number, archived } => {
22523×
            let path = format!("{base}/{number}");
22533×
            let cards = format!("{path}/cards?archived=true");
22543×
            if json {
22552×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
22562×
                return Ok(0);
22571×
            }
22581×
            let mut b: hub_api::Board = c.get(&path)?;
22591×
            if archived {
22600×
                b.columns = c.get(&cards)?;
22611×
            }
22621×
            println!("{}", project_line(&b.project));
22631×
            if !b.project.description.is_empty() {
22641×
                println!("{}", b.project.description);
22651×
            }
22663×
            for col in &b.columns {
22673×
                println!();
22683×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
22693×
                if col.cards.is_empty() {
22701×
                    println!("  {}", ui::dim("(empty)"));
22712×
                }
22723×
                for card in &col.cards {
22732×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
22742×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
22752×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
22762×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
22772×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
22782×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2279
                }
2280
            }
22811×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2282
        }
22831×
        ProjectCmd::Create { title, description, private } => {
22841×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
22851×
            if json {
22860×
                println!("{}", serde_json::to_string(&p)?);
22871×
            } else {
22881×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
22891×
            }
2290
        }
22911×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
22920×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
22930×
        ProjectCmd::Transfer { number, to } => {
22940×
            let p: hub_api::Project =
22950×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
22960×
            if json {
22970×
                println!("{}", serde_json::to_string(&p)?);
22980×
            } else {
22990×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
23000×
            }
2301
        }
23022×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2303
            // The hub names a card's issue as `repo#N` among the owner's
2304
            // repositories.
23052×
            let reference = match reference {
23061×
                None => String::new(),
23071×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
23080×
                    Some((o, rest)) if o == owner => rest.to_string(),
23090×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
23100×
                    None => r,
2311
                },
23121×
                Some(r) => {
23131×
                    let n = r.trim_start_matches('#');
23141×
                    if n.parse::<i64>().is_err() {
23150×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
23161×
                    }
23171×
                    format!("{}#{n}", t.repo()?.1)
2318
                }
2319
            };
23202×
            let note = note.unwrap_or_default();
23212×
            if reference.is_empty() && note.is_empty() {
23220×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
23232×
            }
23241×
            let card: hub_api::ProjectCard =
23252×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
23261×
            if json {
23270×
                println!("{}", serde_json::to_string(&card)?);
2328
            } else {
23291×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2330
            }
2331
        }
23321×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
23331×
            (Some(card), None) => {
23341×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
23351×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2336
            }
23370×
            (None, Some(from)) => {
23380×
                let r: hub_api::CardsMoved = c.send(
23390×
                    "POST",
23400×
                    &format!("{base}/{number}/cards/move"),
23410×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
23420×
                )?;
23430×
                if json {
23440×
                    println!("{}", serde_json::to_string(&r)?);
23450×
                    return Ok(0);
23460×
                }
23470×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
23480×
                for m in &r.moved {
23490×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2350
                }
23510×
                let verb = if dry_run { "would move" } else { "moved" };
23520×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2353
            }
23540×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2355
        },
23560×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
23570×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
23580×
                None => None,
23590×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2360
            };
23610×
            let r: hub_api::CardsArchived = c.send(
23620×
                "POST",
23630×
                &format!("{base}/{number}/cards/archive"),
23640×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
23650×
            )?;
23660×
            if json {
23670×
                println!("{}", serde_json::to_string(&r)?);
23680×
                return Ok(0);
23690×
            }
23700×
            let verb = if dry_run { "would archive" } else { "archived" };
23710×
            for a in &r.archived {
23720×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
23730×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2374
            }
23750×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2376
        }
23770×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
23780×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
23790×
            println!("{} card {card} restored", ui::ok("✔"));
2380
        }
23811×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
23821×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
23831×
            println!("{} card {card} removed", ui::ok("✔"));
2384
        }
2385
    }
23867×
    Ok(0)
238710×
}
2388
23890×
fn milestone_line(m: &hub_api::Milestone) -> String {
23900×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
23910×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
23920×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
23930×
}
2394
23950×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
23960×
    let base = t.repo_path()?;
23970×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
23980×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
23990×
        if json {
24000×
            println!("{}", serde_json::to_string(&m)?);
24010×
        } else {
24020×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
24030×
        }
24040×
        Ok(())
24050×
    };
24060×
    match cmd {
2407
        MilestoneCmd::List => {
24080×
            let path = format!("{base}/milestones");
24090×
            if json {
24100×
                println!("{}", c.get_text(&path)?);
24110×
                return Ok(0);
24120×
            }
24130×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
24140×
            if list.is_empty() {
24150×
                println!("{}", ui::dim("No milestones."));
24160×
            }
24170×
            for m in &list {
24180×
                println!("{}", milestone_line(m));
24190×
            }
2420
        }
24210×
        MilestoneCmd::Create { title, description, due } => {
24220×
            let m: hub_api::Milestone =
24230×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
24240×
            if json {
24250×
                println!("{}", serde_json::to_string(&m)?);
24260×
            } else {
24270×
                println!("{} milestone {}", ui::ok("✔"), m.title);
24280×
            }
2429
        }
24300×
        MilestoneCmd::Edit { title, rename, description, due } => {
24310×
            if rename.is_none() && description.is_none() && due.is_none() {
24320×
                bail!("say what to change: --rename, --description or --due");
24330×
            }
24340×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2435
        }
24360×
        MilestoneCmd::Close { title } => {
24370×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2438
        }
24390×
        MilestoneCmd::Reopen { title } => {
24400×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2441
        }
2442
    }
24430×
    Ok(0)
24440×
}
2445
24460×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
24470×
    let base = t.repo_path()?;
24480×
    match cmd {
2449
        TagCmd::List => {
24500×
            let path = format!("{base}/tags");
24510×
            if json {
24520×
                println!("{}", c.get_text(&path)?);
24530×
                return Ok(0);
24540×
            }
24550×
            let tags: Vec<Tag> = c.get(&path)?;
24560×
            if tags.is_empty() {
24570×
                println!("{}", ui::dim("no tags"));
24580×
            }
24590×
            for t in tags {
24600×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
24610×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
24620×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2463
            }
2464
        }
24650×
        TagCmd::Create { name, target, message } => {
24660×
            let new = hub_api::NewTag { name, target, message };
24670×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
24680×
            if json {
24690×
                println!("{}", serde_json::to_string(&made)?);
24700×
            } else {
24710×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
24720×
            }
2473
        }
24740×
        TagCmd::Delete { name, reason } => {
24750×
            let reason = reason.unwrap_or_default();
24760×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
24770×
            if json {
24780×
                println!("{}", serde_json::json!({ "withdrawn": name }));
24790×
            } else {
24800×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
24810×
            }
2482
        }
2483
    }
24840×
    Ok(0)
24850×
}
2486
24874×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
24884×
    let base = t.repo_path()?;
24894×
    match cmd {
2490
        ReleaseCmd::List => {
24911×
            let path = format!("{base}/releases");
24921×
            if json {
24931×
                println!("{}", c.get_text(&path)?);
24941×
                return Ok(0);
24950×
            }
24960×
            let list: Vec<Release> = c.get(&path)?;
24970×
            if list.is_empty() {
24980×
                println!("{}", ui::dim("No releases."));
24990×
            }
25000×
            for r in &list {
25010×
                println!(
2502
                    "{} {} {}{}",
25030×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
25040×
                    ui::strong(&r.tag),
2505
                    r.title,
25060×
                    ui::dim(&format!(
2507
                        " · {} asset{} · {}",
25080×
                        r.assets.len(),
25090×
                        if r.assets.len() == 1 { "" } else { "s" },
25100×
                        ui::ago(r.created_ms)
2511
                    ))
2512
                );
2513
            }
2514
        }
25151×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
25161×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
25171×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
25181×
            if json {
25190×
                println!("{}", serde_json::to_string(&r)?);
25201×
            } else {
25211×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
25221×
            }
2523
        }
25240×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
25250×
            let notes = match notes.as_deref() {
25260×
                Some("-") => Some(body_of(None, Some("-".into()))?),
25270×
                _ => notes,
2528
            };
25290×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
25300×
                bail!("say what to change: --title, --notes or --prerelease");
25310×
            }
25320×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
25330×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
25340×
            if json {
25350×
                println!("{}", serde_json::to_string(&r)?);
25360×
            } else {
25370×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
25380×
            }
2539
        }
25401×
        ReleaseCmd::Upload { tag, files } => {
25411×
            if files.is_empty() {
25420×
                bail!("name the files to attach");
25431×
            }
25441×
            for f in files {
25451×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
25461×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
25471×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
25481×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2549
            }
2550
        }
25511×
        ReleaseCmd::Trust { tag } => {
25521×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
25531×
            if json {
25540×
                println!("{}", c.get_text(&path)?);
25550×
                return Ok(0);
25561×
            }
25571×
            let r: serde_json::Value = c.get(&path)?;
25581×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
25591×
            let mut worst = 0;
25604×
            for ch in r["audit"].as_array().into_iter().flatten() {
25614×
                let v = ch["verdict"].as_str().unwrap_or("");
25624×
                worst = worst.max(match v {
25634×
                    "fail" => 2,
25644×
                    "warn" => 1,
25653×
                    _ => 0,
2566
                });
25674×
                let g = match v {
25684×
                    "pass" => ui::ok("✔"),
25691×
                    "warn" => ui::warn("!"),
25700×
                    _ => ui::bad("✘"),
2571
                };
25724×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2573
            }
25741×
            return Ok(if worst == 2 { 1 } else { 0 });
2575
        }
2576
    }
25772×
    Ok(0)
25784×
}
2579
2580
#[cfg(test)]
2581
mod tests {
2582
2583
    #[test]
25841×
    fn job_timings_and_report_commands_read_plainly() {
2585
        use clap::Parser;
25861×
        let job = hub_api::FlowJob {
25871×
            name: "perf".into(),
25881×
            status: "passed".into(),
25891×
            depends_on: vec![],
25901×
            runner: "earth-1".into(),
25911×
            exit_code: Some(0),
25921×
            error: String::new(),
25931×
            started_ms: Some(13_000),
25941×
            finished_ms: Some(200_000),
25951×
            log_lines: 10,
25961×
            waiting: String::new(),
25971×
            placed: String::new(),
25981×
            approval: String::new(),
25991×
            queued_ms: Some(1_000),
26001×
            ready_ms: Some(12_500),
26011×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
26021×
            peak_disk_mib: Some(2150),
26031×
            peak_memory_mib: Some(900),
26041×
        };
26051×
        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");
26061×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
26071×
        assert_eq!(super::timing_line(&bare), "");
26081×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2609
26101×
        let cli =
26111×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
26121×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
26131×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
26141×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
26151×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
26161×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
26171×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
26181×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
26191×
    }
2620
2621
    #[test]
26221×
    fn runner_update_scopes_resolve_by_name_or_id() {
26231×
        let all = hub_api::RunnerUpdates {
26241×
            repo: String::new(),
26251×
            settings: vec![],
26261×
            groups: vec![hub_api::RunnerGroup {
26271×
                id: 4,
26281×
                owner: "acme".into(),
26291×
                name: "canary".into(),
26301×
                percent: None,
26311×
                members: vec![],
26321×
                wave: None,
26331×
            }],
26341×
            runners: vec![],
26351×
            holds: vec![],
26361×
        };
26371×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
26381×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
26393×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
26403×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2641
        }
26421×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
26431×
        assert!(update_scope("everyone", &all).is_err());
26441×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
26451×
        assert!(switch(Some("yes")).is_err());
26461×
    }
2647
    use super::*;
2648
2649
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2650
    /// help says, and a drop is named by its id or its address.
2651
    #[test]
26521×
    fn drop_commands_parse() {
26531×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
26541×
        match cli.cmd {
26551×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
26561×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
26571×
                assert!(secret);
26581×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2659
            }
26600×
            _ => panic!("not drop create"),
2661
        }
26621×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
26631×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
26641×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
26651×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
26661×
                assert!(channel.is_none() && dry_run.is_none());
2667
            }
26680×
            _ => panic!("not runner-updates set"),
2669
        }
26701×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
26711×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
26721×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
26730×
            _ => panic!("not drop list"),
2674
        }
26751×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
26761×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
26771×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2678
            }
26790×
            _ => panic!("not drop view"),
2680
        }
26811×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
26824×
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
26834×
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2684
        }
26851×
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
26861×
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
26871×
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
26880×
            _ => panic!("not drop comment"),
2689
        }
26901×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
26911×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
26921×
        assert!(drop_id("andy/notes").is_err());
26931×
    }
2694
}