OXYGENHUB

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

633 of 1590 lines run, 44 of 233 functions · run #529 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 target;
7
mod ui;
8
9
use anyhow::{bail, Context, Result};
10
use clap::{Parser, Subcommand};
11
use client::Client;
12
use hub_api::{
13
    FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag,
14
};
15
use std::time::Duration;
16
use target::{Choice, Config, Target};
17
18
#[derive(Parser)]
19
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")]
20
struct Cli {
21
    /// The repository, when not inside an Oxygen checkout
22
    #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")]
23
    repo: Option<String>,
24
    /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved)
25
    #[arg(long, global = true, value_name = "URL")]
26
    hub: Option<String>,
27
    /// Which of the checkout's remotes to use (default: origin, or the only one)
28
    #[arg(long, global = true)]
29
    remote: Option<String>,
30
    /// Machine-readable output: the API's JSON, unchanged
31
    #[arg(long, global = true)]
32
    json: bool,
33
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
34
    #[arg(long, global = true)]
35
    plain: bool,
36
    #[command(subcommand)]
37
    cmd: Cmd,
38
}
39
40
#[derive(Subcommand)]
41
enum Cmd {
42
    /// Sign in to a hub, or show who you are signed in as
43
    Auth {
44
        #[command(subcommand)]
45
        cmd: AuthCmd,
46
    },
47
    /// The repository
48
    Repo {
49
        #[command(subcommand)]
50
        cmd: RepoCmd,
51
    },
52
    /// Issues
53
    Issue {
54
        #[command(subcommand)]
55
        cmd: IssueCmd,
56
    },
57
    /// Proposals (pull requests)
58
    Proposal {
59
        #[command(subcommand)]
60
        cmd: ProposalCmd,
61
    },
62
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
63
    Coverage {
64
        #[command(subcommand)]
65
        cmd: CoverageCmd,
66
    },
67
    /// OxygenFlow runs
68
    Run {
69
        #[command(subcommand)]
70
        cmd: RunCmd,
71
    },
72
    /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348)
73
    Report {
74
        #[command(subcommand)]
75
        cmd: ReportCmd,
76
    },
77
    /// Releases
78
    Release {
79
        #[command(subcommand)]
80
        cmd: ReleaseCmd,
81
    },
82
    /// Tags: list, create, withdraw
83
    Tag {
84
        #[command(subcommand)]
85
        cmd: TagCmd,
86
    },
87
    /// The repository's labels
88
    Label {
89
        #[command(subcommand)]
90
        cmd: LabelCmd,
91
    },
92
    /// Milestones: list, create, edit, close
93
    Milestone {
94
        #[command(subcommand)]
95
        cmd: MilestoneCmd,
96
    },
97
    /// Project boards of the repository's owner (or --owner): list,
98
    /// create, view, and cards
99
    Project {
100
        #[command(subcommand)]
101
        cmd: ProjectCmd,
102
        /// A user or organisation other than the repository's owner
103
        #[arg(long, global = true)]
104
        owner: Option<String>,
105
    },
106
    /// AI assistants of the repository (its admins), or with --org or
107
    /// --site of an organisation or the site
108
    Assistant {
109
        #[command(subcommand)]
110
        cmd: AssistantCmd,
111
        /// An organisation's assistants instead of the repository's
112
        #[arg(long, global = true)]
113
        org: Option<String>,
114
        /// The site's assistants (administrators)
115
        #[arg(long, global = true, conflicts_with = "org")]
116
        site: bool,
117
    },
118
    /// Agents that act for you without a key of their own (keyless
119
    /// signing): grant, list, revoke
120
    Agent {
121
        #[command(subcommand)]
122
        cmd: AgentCmd,
123
    },
124
    /// Drops: small snippets of files, each its own repository, never
125
    /// listed among your repositories (oxygenhub#279)
126
    Drop {
127
        #[command(subcommand)]
128
        cmd: DropCmd,
129
    },
130
    /// Runners that update themselves (site administrators; oxygenhub#322):
131
    /// where builds come from, who takes them, what is held back
132
    #[command(name = "runner-updates")]
133
    RunnerUpdates {
134
        #[command(subcommand)]
135
        cmd: Option<RunnerUpdatesCmd>,
136
    },
137
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
138
    Api {
139
        /// A path under /api/v1
140
        path: String,
141
        /// The method
142
        #[arg(long, short = 'X', default_value = "GET")]
143
        method: String,
144
        /// A JSON body
145
        #[arg(long, short = 'd')]
146
        data: Option<String>,
147
    },
148
}
149
150
#[derive(Subcommand)]
151
enum AgentCmd {
152
    /// Let an agent act for you: your oxy key (the one your oxy home names
153
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
154
    /// the agent a token it exchanges for ten-minute certificates. The
155
    /// token is printed once: give it to the agent (`oxy auth grant`)
156
    Grant {
157
        /// The agent's name, as in agent:NAME@YOU
158
        name: String,
159
        /// What its keys may do for you: changes, seal, refs
160
        #[arg(long, default_value = "changes,seal,refs")]
161
        scope: String,
162
        /// How long the grant lasts: 30d, 12h, 90m
163
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
164
        lasts: String,
165
    },
166
    /// Your grants, live and past
167
    List,
168
    /// Stop a grant at once: no more certificates under it
169
    Revoke { id: i64 },
170
}
171
172
#[derive(Subcommand)]
173
enum DropCmd {
174
    /// Make a drop of these files, signed by the hub as your delegate
175
    Create {
176
        /// The files (their names in the drop are their file names)
177
        #[arg(required = true)]
178
        files: Vec<std::path::PathBuf>,
179
        /// Unlisted: readable by anyone with its address, listed nowhere
180
        #[arg(long)]
181
        secret: bool,
182
        /// A description
183
        #[arg(long, short = 'd', value_name = "TEXT")]
184
        description: Option<String>,
185
        /// A title (default: the first file's name)
186
        #[arg(long, short = 't')]
187
        title: Option<String>,
188
    },
189
    /// Your drops, or someone's public ones
190
    List {
191
        /// Whose drops
192
        #[arg(long, short = 'u', value_name = "NAME")]
193
        user: Option<String>,
194
    },
195
    /// A drop's files, printed (by id or address)
196
    View {
197
        /// The drop's id, or its address
198
        id: String,
199
        /// Print only this file's content
200
        #[arg(long, short = 'f', value_name = "NAME")]
201
        file: Option<String>,
202
    },
203
    /// Delete a drop and its history
204
    Delete {
205
        /// The drop's id, or its address
206
        id: String,
207
    },
208
    /// A copy of someone's drop, history and all, as a drop of yours
209
    Fork {
210
        /// The drop's id, or its address
211
        id: String,
212
    },
213
    /// Star a drop
214
    Star {
215
        /// The drop's id, or its address
216
        id: String,
217
    },
218
    /// Take your star back
219
    Unstar {
220
        /// The drop's id, or its address
221
        id: String,
222
    },
223
    /// A drop's comments, oldest first
224
    Comments {
225
        /// The drop's id, or its address
226
        id: String,
227
    },
228
    /// Comment on a drop (Markdown); its owner is told
229
    Comment {
230
        /// The drop's id, or its address
231
        id: String,
232
        /// What to say
233
        #[arg(long, short = 'm')]
234
        message: String,
235
    },
236
}
237
238
#[derive(Subcommand)]
239
enum RunnerUpdatesCmd {
240
    /// Every level's settings, the test groups, each runner's policy and what it is offered (the default)
241
    Show,
242
    /// Change one level's settings; what is not given stays as it is
243
    Set {
244
        /// `site`, `owner:NAME`, `group:NAME` (or `group:OWNER/NAME`, `group:ID`), `runner:NAME` (or `runner:ID`)
245
        scope: String,
246
        /// `on`, `off` or `inherit`
247
        #[arg(long)]
248
        updates: Option<String>,
249
        /// `stable`, `canary`, a version, or `inherit`
250
        #[arg(long)]
251
        channel: Option<String>,
252
        /// Hours (UTC) updates may start in, `02-05`, or `inherit`
253
        #[arg(long)]
254
        window: Option<String>,
255
        /// `on`, `off` or `inherit`
256
        #[arg(long)]
257
        dry_run: Option<String>,
258
    },
259
    /// Offer a held build again (it rolled back on a runner)
260
    Lift { version: String },
261
}
262
263
#[derive(Subcommand)]
264
enum AuthCmd {
265
    /// Sign in to a hub and make it the default: approve a code on the web
266
    /// (device sign-in), or give a token
267
    Login {
268
        /// The hub, e.g. https://oxygenhub.io
269
        #[arg(long = "with-hub", value_name = "URL")]
270
        url: String,
271
        /// An API token from the hub's Settings → Tokens, instead of
272
        /// approving a code ("-" reads it from stdin)
273
        #[arg(long)]
274
        token: Option<String>,
275
        /// The hub's CA certificate, when self-signed
276
        #[arg(long)]
277
        ca: Option<std::path::PathBuf>,
278
    },
279
    /// Who the token in use belongs to
280
    Status,
281
}
282
283
#[derive(Subcommand)]
284
enum RepoCmd {
285
    /// Name, description, visibility and default bookmark
286
    View,
287
}
288
289
#[derive(Subcommand)]
290
enum IssueCmd {
291
    /// Put labels on an issue or take them off (triage)
292
    Label(LabelChange),
293
    /// Open issues (or --state closed|all)
294
    List {
295
        #[arg(long, default_value = "open")]
296
        state: String,
297
    },
298
    /// One issue with its comments
299
    View { number: i64 },
300
    /// Open an issue
301
    Create {
302
        #[arg(long, short)]
303
        title: String,
304
        #[arg(long, short)]
305
        body: Option<String>,
306
        /// Read the body from a file ("-" for stdin)
307
        #[arg(long, short = 'F')]
308
        body_file: Option<String>,
309
        /// A label (repeatable)
310
        #[arg(long, short)]
311
        label: Vec<String>,
312
        /// Also put it on this board of the repository's owner
313
        #[arg(long, short)]
314
        project: Option<i64>,
315
        /// The board's column for it, by name (default: the first)
316
        #[arg(long, requires = "project")]
317
        column: Option<String>,
318
    },
319
    /// Close an issue
320
    Close {
321
        number: i64,
322
        /// `completed` or `not_planned`
323
        #[arg(long, default_value = "completed")]
324
        reason: String,
325
    },
326
    /// Reopen an issue
327
    Reopen { number: i64 },
328
    /// Change an issue's title or body (its author or triage), or its
329
    /// labels, assignees or milestone as whole sets (triage)
330
    Edit {
331
        number: i64,
332
        #[arg(long, short)]
333
        title: Option<String>,
334
        #[arg(long, short)]
335
        body: Option<String>,
336
        /// Read the body from a file ("-" for stdin)
337
        #[arg(long, short = 'F', conflicts_with = "body")]
338
        body_file: Option<String>,
339
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
340
        #[arg(long, short)]
341
        label: Vec<String>,
342
        /// Clear its labels
343
        #[arg(long, conflicts_with = "label")]
344
        no_labels: bool,
345
        /// The users it should be assigned to (repeatable)
346
        #[arg(long, short)]
347
        assignee: Vec<String>,
348
        /// Take everyone off it
349
        #[arg(long, conflicts_with = "assignee")]
350
        no_assignees: bool,
351
        /// A milestone's title ("" takes it out of its milestone)
352
        #[arg(long, short)]
353
        milestone: Option<String>,
354
    },
355
    /// Comment on an issue
356
    Comment {
357
        number: i64,
358
        #[arg(long, short)]
359
        body: Option<String>,
360
        /// Read the body from a file ("-" for stdin), as proposal comment
361
        /// does (#260)
362
        #[arg(long, short = 'F', conflicts_with = "body")]
363
        body_file: Option<String>,
364
    },
365
}
366
367
#[derive(Subcommand)]
368
enum ProposalCmd {
369
    /// Open proposals (or --state draft|landed|closed|all), newest first
370
    List {
371
        #[arg(long, default_value = "open")]
372
        state: String,
373
        /// At most this many
374
        #[arg(long, default_value_t = 30)]
375
        limit: usize,
376
    },
377
    /// One proposal: its changes, approvals and whether it can land
378
    View { number: i64 },
379
    /// Propose a bookmark's changes for another bookmark
380
    Create {
381
        #[arg(long, short)]
382
        title: String,
383
        #[arg(long, short)]
384
        body: Option<String>,
385
        /// Read the body from a file ("-" for stdin)
386
        #[arg(long, short = 'F', conflicts_with = "body")]
387
        body_file: Option<String>,
388
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
389
        #[arg(long)]
390
        from: String,
391
        /// The bookmark to land them on (default: the repository's default bookmark)
392
        #[arg(long)]
393
        into: Option<String>,
394
        #[arg(long)]
395
        draft: bool,
396
    },
397
    /// Change a proposal's title or description (its author or a maintainer)
398
    Edit {
399
        number: i64,
400
        #[arg(long, short)]
401
        title: Option<String>,
402
        #[arg(long, short)]
403
        body: Option<String>,
404
        /// Read the body from a file ("-" for stdin)
405
        #[arg(long, short = 'F', conflicts_with = "body")]
406
        body_file: Option<String>,
407
    },
408
    /// Put labels on a proposal or take them off (triage)
409
    Label(LabelChange),
410
    /// Comment on a proposal's conversation
411
    Comment {
412
        number: i64,
413
        #[arg(long, short)]
414
        body: Option<String>,
415
        /// Read the comment from a file ("-" for stdin)
416
        #[arg(long, short = 'F', conflicts_with = "body")]
417
        body_file: Option<String>,
418
    },
419
    /// The checks on a proposal's projected state
420
    Checks { number: i64 },
421
    /// Land a proposal on its target, as the page's Land button does
422
    Land {
423
        number: i64,
424
        /// Land before its required checks pass, saying why (maintainers;
425
        /// recorded and audited, #261)
426
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
427
        over_checks: Option<String>,
428
        /// Land it by itself once its checks pass (#261); with --off, don't
429
        #[arg(long)]
430
        when_ready: bool,
431
        /// With --when-ready: turn it off
432
        #[arg(long, requires = "when_ready")]
433
        off: bool,
434
    },
435
    /// Close a proposal without landing it, with an optional comment
436
    Close {
437
        number: i64,
438
        /// Say why, as a comment before it closes
439
        #[arg(long, short = 'm')]
440
        message: Option<String>,
441
    },
442
    /// Reopen a closed proposal
443
    Reopen { number: i64 },
444
    /// Take a draft proposal out of draft, ready for review (its author or triage)
445
    Ready {
446
        number: i64,
447
        /// Turn an open proposal back into a draft instead
448
        #[arg(long)]
449
        undo: bool,
450
    },
451
}
452
453
#[derive(Subcommand)]
454
enum AssistantCmd {
455
    /// The assistants this level sees, its own and those inherited
456
    List,
457
    /// Add an assistant, or change the one of that name
458
    Add {
459
        /// How it shows on reviews (default: the provider's name)
460
        #[arg(long, default_value = "")]
461
        name: String,
462
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
463
        #[arg(long, default_value = "")]
464
        preset: String,
465
        /// The endpoint, when no preset or another one
466
        #[arg(long, default_value = "")]
467
        endpoint: String,
468
        /// chat-completions or anthropic-messages
469
        #[arg(long, default_value = "")]
470
        api: String,
471
        /// One the endpoint lists (`oh assistant models` shows them)
472
        #[arg(long)]
473
        model: String,
474
        /// The API key, read from this environment variable (never typed on the command line)
475
        #[arg(long, value_name = "VAR")]
476
        token_env: Option<String>,
477
        /// Add it turned off
478
        #[arg(long)]
479
        off: bool,
480
    },
481
    /// Remove this level's assistant of that name
482
    Remove { name: String },
483
    /// Show this level's prompt, and those it inherits
484
    Prompt {
485
        /// Set it from this file (`-` for standard input; an empty file clears it)
486
        #[arg(long, value_name = "FILE")]
487
        set: Option<std::path::PathBuf>,
488
    },
489
}
490
491
#[derive(Subcommand)]
492
enum LabelCmd {
493
    /// The repository's labels
494
    List,
495
    /// Create a label, or change the one of that name (triage)
496
    Create {
497
        name: String,
498
        /// `#rrggbb` (default: one the hub picks)
499
        #[arg(long)]
500
        colour: Option<String>,
501
        #[arg(long, short, default_value = "")]
502
        description: String,
503
    },
504
    /// Delete a label, taking it off every issue and proposal (triage)
505
    Delete { name: String },
506
}
507
508
#[derive(Subcommand)]
509
enum ProjectCmd {
510
    /// The owner's boards
511
    List,
512
    /// One board: its columns and cards
513
    View {
514
        number: i64,
515
        /// Its archived cards instead (#293)
516
        #[arg(long)]
517
        archived: bool,
518
    },
519
    /// Create a board (owner, or an organisation's members)
520
    Create {
521
        title: String,
522
        #[arg(long, short, default_value = "")]
523
        description: String,
524
        /// Only the owner (or the organisation's members) can see it
525
        #[arg(long)]
526
        private: bool,
527
    },
528
    /// Close a board
529
    Close { number: i64 },
530
    /// Reopen a board
531
    Reopen { number: i64 },
532
    /// Move a board to another owner you may make boards under (an
533
    /// organisation, say); it takes the next number there
534
    Transfer {
535
        number: i64,
536
        /// The new owner
537
        #[arg(long)]
538
        to: String,
539
    },
540
    /// Cards on a board: add, move, archive, restore, remove
541
    Card {
542
        #[command(subcommand)]
543
        cmd: CardCmd,
544
    },
545
}
546
547
#[derive(Subcommand)]
548
enum CardCmd {
549
    /// Put an issue or proposal on a board (`12` or `#12` in this
550
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
551
    /// or a note with --note
552
    Add {
553
        number: i64,
554
        /// The issue or proposal; a number means this repository's
555
        reference: Option<String>,
556
        /// A note card instead
557
        #[arg(long, conflicts_with = "reference")]
558
        note: Option<String>,
559
        /// The column, by name or id (default: the first)
560
        #[arg(long, short)]
561
        column: Option<String>,
562
    },
563
    /// Move a card to another column (by name or id), or with --from every
564
    /// card of a column at once
565
    Move {
566
        number: i64,
567
        /// The card (its id); leave it out with --from
568
        card: Option<i64>,
569
        #[arg(long, short)]
570
        column: String,
571
        /// Move every card of this column (#289)
572
        #[arg(long, conflicts_with = "card")]
573
        from: Option<String>,
574
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
575
        #[arg(long, value_delimiter = ',', requires = "from")]
576
        except: Vec<String>,
577
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
578
        #[arg(long, value_delimiter = ',', requires = "from")]
579
        state: Vec<String>,
580
        /// With --from: say what would move, and move nothing
581
        #[arg(long, requires = "from")]
582
        dry_run: bool,
583
    },
584
    /// Archive a column's cards: off the board, kept and restorable (#293)
585
    Archive {
586
        number: i64,
587
        /// The column, by name or id
588
        #[arg(long)]
589
        from: String,
590
        /// Only cards that joined the column more than this long ago (14d, or 14)
591
        #[arg(long)]
592
        older: Option<String>,
593
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
594
        #[arg(long, value_delimiter = ',')]
595
        except: Vec<String>,
596
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
597
        #[arg(long, value_delimiter = ',')]
598
        state: Vec<String>,
599
        /// Say what would be archived, and archive nothing
600
        #[arg(long)]
601
        dry_run: bool,
602
    },
603
    /// Put an archived card back at the end of its column
604
    Restore { number: i64, card: i64 },
605
    /// Take a card off a board
606
    Remove { number: i64, card: i64 },
607
}
608
609
#[derive(Subcommand)]
610
enum MilestoneCmd {
611
    /// The repository's milestones
612
    List,
613
    /// Create a milestone, or change the one of that title (triage)
614
    Create {
615
        title: String,
616
        #[arg(long, short, default_value = "")]
617
        description: String,
618
        /// Due date, YYYY-MM-DD
619
        #[arg(long)]
620
        due: Option<String>,
621
    },
622
    /// Change a milestone's title, description or due date (triage)
623
    Edit {
624
        title: String,
625
        #[arg(long, short)]
626
        rename: Option<String>,
627
        #[arg(long, short)]
628
        description: Option<String>,
629
        /// Due date, YYYY-MM-DD ("" for none)
630
        #[arg(long)]
631
        due: Option<String>,
632
    },
633
    /// Close a milestone
634
    Close { title: String },
635
    /// Reopen a milestone
636
    Reopen { title: String },
637
}
638
639
/// Labels to put on or take off an issue or proposal.
640
#[derive(clap::Args)]
641
struct LabelChange {
642
    number: i64,
643
    /// A label to add (repeatable)
644
    #[arg(long, short)]
645
    add: Vec<String>,
646
    /// A label to take off (repeatable)
647
    #[arg(long, short)]
648
    remove: Vec<String>,
649
}
650
651
impl LabelChange {
652
    /// The set after the change, from the one there now.
6530×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
6540×
        if self.add.is_empty() && self.remove.is_empty() {
6550×
            bail!("say what to change: --add NAME or --remove NAME");
6560×
        }
6570×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
6580×
        for a in &self.add {
6590×
            if !names.contains(a) {
6600×
                names.push(a.clone());
6610×
            }
662
        }
6630×
        Ok(names)
6640×
    }
665
}
666
6670×
fn label_names(labels: &[String]) -> String {
6680×
    if labels.is_empty() {
6690×
        ui::dim("no labels")
670
    } else {
6710×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
672
    }
6730×
}
674
675
#[derive(Subcommand)]
676
enum CoverageCmd {
677
    /// Upload an LCOV or Cobertura report measured on this machine, as the
678
    /// coverage of a bookmark's current state (default: the default
679
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
680
    /// not measured by a runner, and sets no check from it
681
    Upload {
682
        file: std::path::PathBuf,
683
        #[arg(long)]
684
        bookmark: Option<String>,
685
        /// A change's full hash
686
        #[arg(long, conflicts_with = "bookmark")]
687
        change: Option<String>,
688
    },
689
}
690
691
#[derive(Subcommand)]
692
enum RunCmd {
693
    /// Recent runs, newest first
694
    List {
695
        #[arg(long, default_value_t = 20)]
696
        limit: i64,
697
    },
698
    /// A run and its jobs
699
    View {
700
        number: i64,
701
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
702
        #[arg(long)]
703
        timings: bool,
704
    },
705
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
706
    Start {
707
        #[arg(long)]
708
        bookmark: Option<String>,
709
        /// A change's full hash
710
        #[arg(long, conflicts_with = "bookmark")]
711
        change: Option<String>,
712
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
713
        #[arg(long = "job", value_name = "NAME")]
714
        jobs: Vec<String>,
715
        /// Wait for the run and exit 1 unless it passes
716
        #[arg(long)]
717
        watch: bool,
718
    },
719
    /// Follow a run until it finishes; exit 1 unless it passes
720
    Watch { number: i64 },
721
    /// A job's log
722
    Log { number: i64, job: String },
723
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
724
    Report {
725
        number: i64,
726
        job: String,
727
        #[command(flatten)]
728
        pick: ReportPick,
729
    },
730
    /// Run a finished run's state again; with --job, only that job (and the
731
    /// jobs that depend on it) in the same run
732
    Rerun {
733
        number: i64,
734
        #[arg(long)]
735
        job: Option<String>,
736
    },
737
    /// Cancel a run still queued or running; its running jobs are stopped
738
    Cancel { number: i64 },
739
    /// Approve a job that waits for a person (oxygenflow#57)
740
    Approve {
741
        number: i64,
742
        #[arg(long)]
743
        job: String,
744
    },
745
    /// Reject a job that waits for a person: it ends cancelled
746
    Reject {
747
        number: i64,
748
        #[arg(long)]
749
        job: String,
750
    },
751
}
752
753
/// Which report of a job, and what of it to show.
754
#[derive(clap::Args)]
755
struct ReportPick {
756
    /// Which report, when the job published more than one
757
    #[arg(long)]
758
    name: Option<String>,
759
    /// What it holds: its metrics, context and files
760
    #[arg(long, conflicts_with = "file")]
761
    list: bool,
762
    /// One file of it (`data/frames.csv`), as published
763
    #[arg(long, value_name = "PATH")]
764
    file: Option<String>,
765
    /// Write the file here instead of to stdout
766
    #[arg(long, short, value_name = "FILE", requires = "file")]
767
    output: Option<std::path::PathBuf>,
768
}
769
770
#[derive(Subcommand)]
771
enum ReportCmd {
772
    /// The newest run of each report, newest first
773
    List {
774
        /// Only runs on this bookmark
775
        #[arg(long)]
776
        bookmark: Option<String>,
777
    },
778
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
779
    Show {
780
        report: String,
781
        #[arg(long, conflicts_with = "bookmark")]
782
        id: Option<i64>,
783
        #[arg(long)]
784
        bookmark: Option<String>,
785
        /// What it holds: its metrics, context and files
786
        #[arg(long, conflicts_with = "file")]
787
        list: bool,
788
        /// One file of it, as published
789
        #[arg(long, value_name = "PATH")]
790
        file: Option<String>,
791
        /// Write the file here instead of to stdout
792
        #[arg(long, short, value_name = "FILE", requires = "file")]
793
        output: Option<std::path::PathBuf>,
794
    },
795
}
796
797
#[derive(Subcommand)]
798
enum TagCmd {
799
    /// Tags, newest name first
800
    List,
801
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
802
    /// delegate (as `oxy tag create` and a push would be)
803
    Create {
804
        name: String,
805
        /// What to tag (default: the default bookmark)
806
        #[arg(long)]
807
        target: Option<String>,
808
        #[arg(long, short)]
809
        message: Option<String>,
810
    },
811
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
812
    /// their next fetch, and the name is never used again. Refused while a
813
    /// release uses the tag
814
    Delete {
815
        name: String,
816
        /// Why, recorded with the withdrawal
817
        #[arg(long, short)]
818
        reason: Option<String>,
819
    },
820
}
821
822
#[derive(Subcommand)]
823
enum ReleaseCmd {
824
    /// Releases, newest first
825
    List,
826
    /// Create a release on an existing tag
827
    Create {
828
        tag: String,
829
        #[arg(long, short)]
830
        title: Option<String>,
831
        /// Notes in Markdown (default: generated from the changes since the previous release)
832
        #[arg(long, short)]
833
        notes: Option<String>,
834
        #[arg(long)]
835
        prerelease: bool,
836
    },
837
    /// Change a release's title, notes or prerelease flag
838
    Edit {
839
        tag: String,
840
        #[arg(long, short)]
841
        title: Option<String>,
842
        /// New notes in Markdown ("-" reads them from stdin)
843
        #[arg(long, short)]
844
        notes: Option<String>,
845
        /// Mark it a prerelease (true) or not (false)
846
        #[arg(long)]
847
        prerelease: Option<bool>,
848
    },
849
    /// Attach files to a release
850
    Upload { tag: String, files: Vec<std::path::PathBuf> },
851
    /// The release's trust report: signatures, builds, receipts and audit
852
    Trust { tag: String },
853
}
854
85547×
fn main() {
856
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
857
    // other command-line tools do, instead of panicking on the failed
858
    // write (oxygenhub#92).
859
    #[cfg(unix)]
86047×
    unsafe {
86147×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
86247×
    }
86347×
    let cli = Cli::parse();
86447×
    ui::init(cli.plain);
86547×
    match run(cli) {
86640×
        Ok(code) => std::process::exit(code),
8677×
        Err(e) => {
8687×
            eprintln!("{} {e:#}", ui::bad("error:"));
8697×
            std::process::exit(2);
870
        }
871
    }
872
}
873
87419×
fn enc(s: &str) -> String {
87519×
    let mut out = String::new();
87686×
    for b in s.bytes() {
87786×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
87885×
            out.push(b as char);
87985×
        } else {
8801×
            out.push_str(&format!("%{b:02X}"));
8811×
        }
882
    }
88319×
    out
88419×
}
885
88647×
fn run(cli: Cli) -> Result<i32> {
88747×
    let cfg = Config::load()?;
8881×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
8891×
        return login(cfg, url, token.clone(), ca.clone());
89046×
    }
89146×
    let here = std::env::current_dir()?;
89246×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
89345×
    let c = Client::new(&t)?;
89445×
    let json = cli.json;
8950×
    match cli.cmd {
896
        Cmd::Auth { cmd: AuthCmd::Status } => {
8970×
            let me: serde_json::Value = c.get("/user")?;
8980×
            if json {
8990×
                println!("{me}");
9000×
            } else {
9010×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
9020×
            }
9030×
            Ok(0)
904
        }
9050×
        Cmd::Auth { .. } => unreachable!(),
9061×
        Cmd::Api { path, method, data } => {
9071×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
908
            // The method applies with or without a body (#75): without one, a
909
            // GET reads, anything else sends an empty object.
9101×
            let text = match data {
9110×
                Some(d) => c.send_text(
9120×
                    &method.to_uppercase(),
9130×
                    &path,
9140×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
9150×
                )?,
9161×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
9170×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
918
            };
9191×
            println!("{text}");
9201×
            Ok(0)
921
        }
922
        Cmd::Repo { cmd: RepoCmd::View } => {
9231×
            let path = t.repo_path()?;
9241×
            if json {
9250×
                println!("{}", c.get_text(&path)?);
9260×
                return Ok(0);
9271×
            }
9281×
            let r: serde_json::Value = c.get(&path)?;
9291×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
9301×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
9311×
                println!("{d}");
9321×
            }
9331×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
9341×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
9351×
            Ok(0)
936
        }
93715×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
9384×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
9393×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
9400×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
9410×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
9420×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
9430×
            let mut body = serde_json::json!({ "content": content });
9440×
            if let Some(b) = bookmark {
9450×
                body["bookmark"] = b.into();
9460×
            }
9470×
            if let Some(ch) = change {
9480×
                body["change"] = ch.into();
9490×
            }
9500×
            let base = t.repo_path()?;
9510×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
9520×
            if json {
9530×
                println!("{}", serde_json::to_string(&r)?);
954
            } else {
9550×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
9560×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
9570×
                println!(
958
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
9590×
                    ui::ok("✔"),
960
                    r.lines_hit,
961
                    r.lines_found,
962
                    r.files,
9630×
                    ui::dim(&r.url)
964
                );
9650×
                if r.dropped > 0 {
9660×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
9670×
                }
968
            }
9690×
            Ok(0)
970
        }
9714×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
9720×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
9730×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
9740×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
97510×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
9760×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
9770×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
9780×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
9797×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
980
    }
98147×
}
982
983
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
9842×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
9852×
    Ok(match v {
9860×
        None => None,
9872×
        Some("on") => Some(Some(true)),
9882×
        Some("off") => Some(Some(false)),
9892×
        Some("inherit") => Some(None),
9901×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
991
    })
9922×
}
993
994
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
9957×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
9967×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
9971×
    Ok(match kind {
9987×
        "site" if name.is_empty() => ("site".into(), String::new()),
9996×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
10005×
        "group" => {
10013×
            let g = all
10023×
                .groups
10033×
                .iter()
10043×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
10053×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
10063×
            ("group".into(), g.id.to_string())
1007
        }
10082×
        "runner" => {
10091×
            let r = all
10101×
                .runners
10111×
                .iter()
10121×
                .find(|r| r.id.to_string() == name || r.name == name)
10131×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
10140×
            ("runner".into(), r.id.to_string())
1015
        }
10161×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1017
    })
10187×
}
1019
10200×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
10210×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
10220×
    match cmd {
10230×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1024
        RunnerUpdatesCmd::Show => {
10250×
            println!(
1026
                "{} {}",
10270×
                ui::strong("Builds from"),
10280×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1029
            );
10300×
            for h in &all.holds {
10310×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
10320×
            }
10330×
            for s in &all.settings {
10340×
                let mut said = vec![];
10350×
                if let Some(u) = s.updates {
10360×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
10370×
                }
10380×
                if let Some(ch) = &s.channel {
10390×
                    said.push(format!("channel {ch}"));
10400×
                }
10410×
                if let Some(w) = &s.window {
10420×
                    said.push(format!("window {w} UTC"));
10430×
                }
10440×
                if let Some(d) = s.dry_run {
10450×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
10460×
                }
10470×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
10480×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1049
            }
10500×
            for g in &all.groups {
10510×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
10520×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
10530×
                if let Some(w) = g.wave {
10540×
                    what.push_str(&format!(", wave {w}"));
10550×
                }
10560×
                println!(
1057
                    "  group {} ({what}): {}",
10580×
                    ui::strong(&g.name),
10590×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1060
                );
1061
            }
10620×
            for r in &all.runners {
10630×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
10640×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1065
            }
1066
        }
10670×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
10680×
            let (scope, key) = update_scope(&scope, &all)?;
10690×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
10700×
                scope: scope.clone(),
10710×
                key: key.clone(),
10720×
                ..Default::default()
10730×
            });
10740×
            if let Some(u) = switch(updates.as_deref())? {
10750×
                s.updates = u;
10760×
            }
10770×
            if let Some(d) = switch(dry_run.as_deref())? {
10780×
                s.dry_run = d;
10790×
            }
10800×
            if let Some(ch) = channel {
10810×
                s.channel = Some(ch).filter(|c| c != "inherit");
10820×
            }
10830×
            if let Some(w) = window {
10840×
                s.window = Some(w).filter(|w| w != "inherit");
10850×
            }
10860×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
10870×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1088
        }
10890×
        RunnerUpdatesCmd::Lift { version } => {
10900×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
10910×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1092
        }
1093
    }
10940×
    Ok(0)
10950×
}
1096
1097
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
10987×
fn drop_id(s: &str) -> Result<String> {
10997×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1100144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
11011×
        bail!("{s:?} is not a drop's id or address");
11026×
    }
11036×
    Ok(id.to_ascii_lowercase())
11047×
}
1105
11062×
fn drop_line(d: &hub_api::Drop) -> String {
11072×
    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() };
11084×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
11092×
    format!(
1110
        "{} {} {}{}",
11112×
        ui::dim(&d.id),
11122×
        ui::strong(&title),
11132×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
11142×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1115
    )
11162×
}
1117
1118
/// `oh drop star|unstar` (oxygenhub#349).
11190×
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
11200×
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
11210×
    if json {
11220×
        println!("{}", serde_json::to_string(&s)?);
1123
    } else {
11240×
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1125
    }
11260×
    Ok(())
11270×
}
1128
11297×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
11307×
    match cmd {
11311×
        DropCmd::Create { files, secret, description, title } => {
11321×
            let mut out = Vec::with_capacity(files.len());
11332×
            for f in &files {
11342×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
11352×
                let content =
11362×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
11372×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1138
            }
11391×
            let new =
11401×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
11411×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
11421×
            if json {
11431×
                println!("{}", serde_json::to_string(&d)?);
1144
            } else {
11450×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
11460×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1147
            }
1148
        }
11492×
        DropCmd::List { user } => {
11502×
            let path = match &user {
11511×
                Some(u) => format!("/users/{}/drops", enc(u)),
11521×
                None => "/drops".to_string(),
1153
            };
11542×
            if json {
11551×
                println!("{}", c.get_text(&path)?);
11561×
                return Ok(0);
11571×
            }
11581×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
11591×
            if list.is_empty() {
11600×
                println!("{}", ui::dim("No drops."));
11611×
            }
11621×
            for d in &list {
11631×
                println!("{}", drop_line(d));
11641×
            }
1165
        }
11663×
        DropCmd::View { id, file } => {
11673×
            let path = format!("/drops/{}", drop_id(&id)?);
11683×
            if json && file.is_none() {
11690×
                println!("{}", c.get_text(&path)?);
11700×
                return Ok(0);
11713×
            }
11723×
            let d: hub_api::Drop = c.get(&path)?;
11732×
            if let Some(name) = file {
11742×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
11751×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
11761×
                print!("{content}");
11771×
                return Ok(0);
11781×
            }
11791×
            println!("{}", drop_line(&d));
11801×
            if !d.description.is_empty() {
11811×
                println!("{}", d.description);
11821×
            }
11831×
            println!("{}", ui::kv("url", &d.url));
11841×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
11852×
            for f in &d.files {
11862×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
11872×
                match &f.content {
11882×
                    Some(text) => {
11892×
                        print!("{text}");
11902×
                        if !text.ends_with('\n') && !text.is_empty() {
11910×
                            println!();
11922×
                        }
1193
                    }
11940×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1195
                }
1196
            }
1197
        }
11981×
        DropCmd::Delete { id } => {
11991×
            let id = drop_id(&id)?;
12001×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
12011×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1202
        }
12030×
        DropCmd::Fork { id } => {
12040×
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
12050×
            if json {
12060×
                println!("{}", serde_json::to_string(&d)?);
12070×
            } else {
12080×
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
12090×
            }
1210
        }
12110×
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
12120×
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
12130×
        DropCmd::Comments { id } => {
12140×
            let path = format!("/drops/{}/comments", drop_id(&id)?);
12150×
            if json {
12160×
                println!("{}", c.get_text(&path)?);
12170×
                return Ok(0);
12180×
            }
12190×
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
12200×
            if list.is_empty() {
12210×
                println!("{}", ui::dim("No comments."));
12220×
            }
12230×
            for m in &list {
12240×
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
12250×
                println!("{}\n", m.body);
12260×
            }
1227
        }
12280×
        DropCmd::Comment { id, message } => {
12290×
            let m: hub_api::DropComment =
12300×
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
12310×
            if json {
12320×
                println!("{}", serde_json::to_string(&m)?);
12330×
            } else {
12340×
                println!("{} commented (#{})", ui::ok("✔"), m.id);
12350×
            }
1236
        }
1237
    }
12384×
    Ok(0)
12397×
}
1240
1241
/// `30d`, `12h`, `90m` in milliseconds.
12420×
fn duration_ms(s: &str) -> Result<i64> {
12430×
    let s = s.trim();
12440×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
12450×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
12460×
    let per = match unit {
12470×
        "d" => 86_400_000,
12480×
        "h" => 3_600_000,
12490×
        "m" => 60_000,
12500×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1251
    };
12520×
    if n <= 0 {
12530×
        bail!("a grant must last some time");
12540×
    }
12550×
    Ok(n * per)
12560×
}
1257
12580×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1259
    use oxy_core::cert::{Grant, SignedGrant};
1260
    use oxy_core::identity::{Identity, Scope};
12610×
    match cmd {
12620×
        AgentCmd::Grant { name, scope, lasts } => {
12630×
            let home = oxy_core::repo::default_home();
12640×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
12650×
                format!(
1266
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
12670×
                    home.display()
1268
                )
12690×
            })?;
12700×
            let me: serde_json::Value = c.get("/user")?;
12710×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
12720×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
12730×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
12740×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
12750×
            let grant = Grant {
12760×
                grantor: me_id.hash(),
12770×
                subject: format!("agent:{name}@{username}"),
12780×
                issuer: hub.hash(),
12790×
                scope,
12800×
                not_before: (now - 60_000) as u64,
12810×
                expires: (now + duration_ms(&lasts)?) as u64,
1282
            };
12830×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
12840×
            let r: serde_json::Value =
12850×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
12860×
            if json {
12870×
                println!("{r}");
12880×
                return Ok(0);
12890×
            }
12900×
            println!(
1291
                "{} {} to act for you as {} ({}), until {}",
12920×
                ui::ok("✔ granted"),
12930×
                ui::strong(&name),
12940×
                r["subject"].as_str().unwrap_or(""),
12950×
                r["scope"].as_str().unwrap_or(""),
12960×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1297
            );
12980×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
12990×
            println!(
1300
                "  {}",
13010×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1302
            );
13030×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
13040×
            Ok(0)
1305
        }
1306
        AgentCmd::List => {
13070×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
13080×
            if json {
13090×
                println!("{}", serde_json::to_string(&grants)?);
13100×
                return Ok(0);
13110×
            }
13120×
            if grants.is_empty() {
13130×
                println!("{}", ui::dim("no agent grants"));
13140×
            }
13150×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
13160×
            for g in grants {
13170×
                let state = if g["revoked_ms"].is_i64() {
13180×
                    ui::bad("revoked")
13190×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
13200×
                    ui::dim("ended")
1321
                } else {
13220×
                    ui::ok("live")
1323
                };
13240×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
13250×
                println!(
1326
                    "#{:<4} {:<8} {} · {} · until {} · {}",
13270×
                    g["id"],
1328
                    state,
13290×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
13300×
                    g["scope"].as_str().unwrap_or(""),
13310×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
13320×
                    ui::dim(&used)
1333
                );
1334
            }
13350×
            Ok(0)
1336
        }
13370×
        AgentCmd::Revoke { id } => {
13380×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
13390×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
13400×
            Ok(0)
1341
        }
1342
    }
13430×
}
1344
13451×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
13461×
    let hub = url.trim_end_matches('/').to_string();
13471×
    let token = match token.as_deref() {
13481×
        Some("-") => {
13490×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
13500×
            let mut line = String::new();
13510×
            std::io::stdin().read_line(&mut line)?;
13520×
            line.trim().to_string()
1353
        }
13541×
        Some(t) => t.to_string(),
13550×
        None => device_sign_in(&hub, ca.clone())?,
1356
    };
13571×
    if token.is_empty() {
13580×
        bail!("no token given");
13591×
    }
13601×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
13611×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
13621×
    let account = me["username"].as_str().unwrap_or("?");
1363
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
13641×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
13651×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
13661×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
13671×
    cfg.default_hub = Some(hub.clone());
13681×
    cfg.save()?;
13691×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
13701×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
13711×
    Ok(0)
13721×
}
1373
1374
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1375
/// it on the web, and the token arrives here.
13760×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
13770×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
13780×
    let c = Client::new(&t)?;
13790×
    let host = std::fs::read_to_string("/etc/hostname")
13800×
        .ok()
13810×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
13820×
        .map(|h| h.trim().to_string())
13830×
        .filter(|h| !h.is_empty());
13840×
    let client = match host {
13850×
        Some(h) => format!("oh on {h}"),
13860×
        None => "oh".to_string(),
1387
    };
13880×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
13890×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
13900×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
13910×
    if code != 200 {
13920×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
13930×
    }
13940×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
13950×
    let user = v["user_code"].as_str().unwrap_or("?");
13960×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
13970×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
13980×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
13990×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
14000×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1401
    loop {
14020×
        std::thread::sleep(std::time::Duration::from_secs(interval));
14030×
        if std::time::Instant::now() > deadline {
14040×
            bail!("the code expired before it was approved; run oh auth login again");
14050×
        }
14060×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
14070×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
14080×
        if code == 200 {
14090×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
14100×
        }
14110×
        match v["error"].as_str() {
14120×
            Some("authorization_pending") => {}
14130×
            Some("slow_down") => interval += 5,
14140×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
14150×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
14160×
            _ => bail!("signing in: HTTP {code}: {body}"),
1417
        }
1418
    }
14190×
}
1420
14217×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
14227×
    match (body, file) {
14232×
        (Some(b), _) => Ok(b),
14241×
        (None, Some(f)) if f == "-" => {
14250×
            let mut s = String::new();
14260×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
14270×
            Ok(s)
1428
        }
14291×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
14304×
        (None, None) => Ok(String::new()),
1431
    }
14327×
}
1433
14343×
fn issue_line(i: &Issue) -> String {
14353×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
14363×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
14373×
    format!(
1438
        "{glyph} {} {}{}{}",
14393×
        ui::dim(&format!("#{}", i.number)),
1440
        i.title,
14413×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
14423×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1443
    )
14443×
}
1445
144615×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
144715×
    let base = t.repo_path()?;
144815×
    match cmd {
14493×
        IssueCmd::List { state } => {
14503×
            let path = format!("{base}/issues?state={}", enc(&state));
14513×
            if json {
14521×
                println!("{}", c.get_text(&path)?);
14531×
                return Ok(0);
14542×
            }
14552×
            let list: Vec<Issue> = c.get(&path)?;
14562×
            if list.is_empty() {
14571×
                println!("{}", ui::dim(&format!("No {state} issues.")));
14581×
            }
14592×
            for i in &list {
14602×
                println!("{}", issue_line(i));
14612×
            }
1462
        }
14632×
        IssueCmd::View { number } => {
14642×
            let path = format!("{base}/issues/{number}");
14652×
            if json {
14661×
                println!("{}", c.get_text(&path)?);
14671×
                return Ok(0);
14681×
            }
14691×
            let i: Issue = c.get(&path)?;
14701×
            println!("{}", issue_line(&i));
14711×
            if !i.body.trim().is_empty() {
14721×
                println!("\n{}\n", i.body.trim_end());
14731×
            }
14741×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
14752×
            for cm in comments {
14762×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
14772×
            }
14781×
            println!("{}", ui::dim(&i.url));
1479
        }
14803×
        IssueCmd::Create { title, body, body_file, label, project, column } => {
14813×
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
14823×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
14832×
            if json {
14840×
                println!("{}", serde_json::to_string(&i)?);
14852×
            } else {
14862×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
14872×
            }
14882×
            if let Some(n) = project {
14891×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
14901×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
14911×
                if !json {
14921×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
14931×
                }
14941×
            }
1495
        }
14961×
        IssueCmd::Close { number, reason } => {
14971×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
14981×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1499
        }
15000×
        IssueCmd::Reopen { number } => {
15010×
            let i: Issue =
15020×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
15030×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1504
        }
15053×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
15063×
            let body = match (&body, &body_file) {
15073×
                (None, None) => None,
15080×
                _ => Some(body_of(body, body_file)?),
1509
            };
15103×
            let labels = if no_labels {
15111×
                Some(Vec::new())
15122×
            } else if label.is_empty() {
15131×
                None
1514
            } else {
15151×
                Some(label)
1516
            };
15173×
            let assignees = if no_assignees {
15181×
                Some(Vec::new())
15192×
            } else if assignee.is_empty() {
15201×
                None
1521
            } else {
15221×
                Some(assignee)
1523
            };
15243×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
15251×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
15262×
            }
15272×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
15282×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
15292×
            if json {
15301×
                println!("{}", serde_json::to_string(&i)?);
15311×
            } else {
15321×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
15331×
            }
1534
        }
15350×
        IssueCmd::Label(change) => {
15360×
            let path = format!("{base}/issues/{}", change.number);
15370×
            let now: Issue = c.get(&path)?;
15380×
            let labels = change.apply(&now.labels)?;
15390×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
15400×
            let i: Issue = c.send("PATCH", &path, &edit)?;
15410×
            if json {
15420×
                println!("{}", serde_json::to_string(&i)?);
15430×
            } else {
15440×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
15450×
            }
1546
        }
15473×
        IssueCmd::Comment { number, body, body_file } => {
15483×
            let body = body_of(body, body_file)?;
15493×
            if body.trim().is_empty() {
15501×
                bail!("give the comment with --body or --body-file");
15512×
            }
15522×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
15532×
            println!("{} commented on #{number}", ui::ok("✔"));
1554
        }
1555
    }
155610×
    Ok(0)
155715×
}
1558
15591×
fn source_name(s: &hub_api::ProposalSource) -> String {
15601×
    match s {
15611×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
15620×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
15630×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1564
    }
15651×
}
1566
15671×
fn proposal_line(p: &Proposal) -> String {
15681×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
15691×
    let glyph = match state.as_str() {
15701×
        "open" => ui::ok("●"),
15710×
        "draft" => ui::dim("◌"),
15720×
        "landed" => ui::strong("✔"),
15730×
        _ => ui::dim("○"),
1574
    };
15751×
    format!(
1576
        "{glyph} {} {} {}{}",
15771×
        ui::dim(&format!("#{}", p.number)),
1578
        p.title,
15791×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
15801×
        ui::dim(&format!(" · {} · {state}", p.author))
1581
    )
15821×
}
1583
15844×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
15854×
    let base = t.repo_path()?;
15864×
    match cmd {
15870×
        ProposalCmd::List { state, limit } => {
15880×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
15890×
            if json {
15900×
                println!("{}", c.get_text(&path)?);
15910×
                return Ok(0);
15920×
            }
15930×
            let list: Vec<Proposal> = c.get(&path)?;
15940×
            if list.is_empty() {
15950×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
15960×
            }
15970×
            for p in &list {
15980×
                println!("{}", proposal_line(p));
15990×
            }
1600
        }
16011×
        ProposalCmd::View { number } => {
16021×
            let path = format!("{base}/proposals/{number}");
16031×
            if json {
16040×
                println!("{}", c.get_text(&path)?);
16050×
                return Ok(0);
16061×
            }
16071×
            let p: Proposal = c.get(&path)?;
16081×
            println!("{}", proposal_line(&p));
16091×
            if !p.body.trim().is_empty() {
16100×
                println!("\n{}\n", p.body.trim_end());
16111×
            }
16121×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
16131×
            for ch in &p.changes {
16141×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
16151×
            }
16161×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
16171×
            if p.landable {
16181×
                println!("{} can land", ui::ok("✔"));
16191×
            } else {
16200×
                for b in &p.blockers {
16210×
                    println!("{} {b}", ui::bad("✘"));
16220×
                }
1623
            }
16241×
            if p.conflicted {
16250×
                println!("{} landing it would leave conflicts", ui::bad("!"));
16261×
            }
16271×
            println!("{}", ui::dim(&p.url));
1628
        }
16291×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
16301×
            let target = match into {
16310×
                Some(i) => i,
16321×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1633
            };
16341×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
16351×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
16361×
            if json {
16370×
                println!("{}", serde_json::to_string(&p)?);
16381×
            } else {
16391×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
16401×
            }
1641
        }
16420×
        ProposalCmd::Edit { number, title, body, body_file } => {
16430×
            let body = match (&body, &body_file) {
16440×
                (None, None) => None,
16450×
                _ => Some(body_of(body, body_file)?),
1646
            };
16470×
            if title.is_none() && body.is_none() {
16480×
                bail!("say what to change: --title, --body or --body-file");
16490×
            }
16500×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
16510×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
16520×
            if json {
16530×
                println!("{}", serde_json::to_string(&p)?);
16540×
            } else {
16550×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
16560×
            }
1657
        }
16580×
        ProposalCmd::Label(change) => {
16590×
            let path = format!("{base}/proposals/{}", change.number);
16600×
            let now: Proposal = c.get(&path)?;
16610×
            let labels = change.apply(&now.labels)?;
16620×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
16630×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
16640×
            if json {
16650×
                println!("{}", serde_json::to_string(&p)?);
16660×
            } else {
16670×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
16680×
            }
1669
        }
16700×
        ProposalCmd::Comment { number, body, body_file } => {
16710×
            let body = body_of(body, body_file)?;
16720×
            if body.trim().is_empty() {
16730×
                bail!("give the comment with --body or --body-file");
16740×
            }
16750×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
16760×
            println!("{} commented on #{number}", ui::ok("✔"));
1677
        }
16780×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
16790×
            let path = format!("{base}/proposals/{number}/auto-land");
16800×
            let p: Proposal =
16810×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
16820×
            if json {
16830×
                println!("{}", serde_json::to_string(&p)?);
16840×
            } else if p.landed.is_some() {
16850×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
16860×
            } else if p.auto_land.is_some() {
16870×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
16880×
            } else {
16890×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
16900×
            }
1691
        }
16922×
        ProposalCmd::Land { number, over_checks, .. } => {
16932×
            let body = match &over_checks {
16940×
                Some(r) => serde_json::json!({ "over_checks": r }),
16952×
                None => serde_json::json!({}),
1696
            };
16972×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
16981×
            if json {
16990×
                println!("{}", serde_json::to_string(&p)?);
17001×
            } else {
17011×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
17021×
            }
1703
        }
17040×
        ProposalCmd::Close { number, message } => {
17050×
            if let Some(body) = message {
17060×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
17070×
            }
17080×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
17090×
            if json {
17100×
                println!("{}", serde_json::to_string(&p)?);
17110×
            } else {
17120×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
17130×
            }
1714
        }
17150×
        ProposalCmd::Reopen { number } => {
17160×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
17170×
            if json {
17180×
                println!("{}", serde_json::to_string(&p)?);
17190×
            } else {
17200×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
17210×
            }
1722
        }
17230×
        ProposalCmd::Ready { number, undo } => {
17240×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
17250×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
17260×
            if json {
17270×
                println!("{}", serde_json::to_string(&p)?);
17280×
            } else if undo {
17290×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
17300×
            } else {
17310×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
17320×
            }
1733
        }
17340×
        ProposalCmd::Checks { number } => {
17350×
            let path = format!("{base}/proposals/{number}/checks");
17360×
            if json {
17370×
                println!("{}", c.get_text(&path)?);
17380×
                return Ok(0);
17390×
            }
17400×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
17410×
            if checks.is_empty() {
17420×
                println!("{}", ui::dim("No checks yet."));
17430×
            }
17440×
            for ch in checks {
17450×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
17460×
            }
1747
        }
1748
    }
17493×
    Ok(0)
17504×
}
1751
17521×
fn run_line(r: &FlowRun) -> String {
17531×
    let what =
17541×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
17551×
    format!(
1756
        "{} {} {} {}",
17571×
        ui::status(&r.status),
17581×
        ui::dim(&format!("#{}", r.number)),
1759
        what,
17601×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1761
    )
17621×
}
1763
17641×
fn print_run(r: &FlowRun, timings: bool) {
17651×
    println!("{}", run_line(r));
17661×
    for j in &r.jobs {
17671×
        let dur = match (j.started_ms, j.finished_ms) {
17680×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
17691×
            _ => String::new(),
1770
        };
17711×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
17721×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1773
        // Why a queued job no runner can take waits (oxygenhub#28), and
1774
        // why a job ran where it did (oxygenflow#42).
17751×
        if j.status == "queued" && !j.waiting.is_empty() {
17760×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
17771×
        } else if !j.placed.is_empty() {
17780×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
17791×
        }
17801×
        if timings {
17810×
            let t = timing_line(j);
17820×
            if !t.is_empty() {
17830×
                println!("    {}", ui::dim(&t));
17840×
            }
17851×
        }
1786
    }
17871×
    if !r.error.is_empty() {
17880×
        println!("{}", ui::bad(&r.error));
17891×
    }
17901×
    println!("{}", ui::dim(&r.url));
17911×
}
1792
1793
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
17943×
fn took(ms: i64) -> String {
17953×
    match ms {
17963×
        ..=999 => format!("{ms} ms"),
17972×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
17981×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1799
    }
18003×
}
1801
1802
/// MiB as a person reads them.
18032×
fn mib(m: i64) -> String {
18042×
    if m >= 1024 {
18051×
        format!("{:.1} GiB", m as f64 / 1024.0)
1806
    } else {
18071×
        format!("{m} MiB")
1808
    }
18092×
}
1810
1811
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1812
/// phase its runner reported, and the most disk and memory it took.
18132×
fn timing_line(j: &FlowJob) -> String {
18142×
    let mut parts = vec![];
18152×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
18161×
        parts.push(format!("waited {}", took((s - q).max(0))));
18171×
    }
18182×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
18192×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
18202×
        .into_iter()
18214×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
18222×
        .collect();
18232×
    if !peaks.is_empty() {
18241×
        parts.push(format!("peak {}", peaks.join(", ")));
18251×
    }
18262×
    parts.join(" · ")
18272×
}
1828
1829
/// A report's path, its segments encoded and its slashes kept.
18301×
fn enc_path(path: &str) -> String {
18311×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
18321×
}
1833
1834
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1835
/// files are at `files(path)`. By default its report.toml; with `list`
1836
/// what it holds; with `file` one file, to stdout or `output`.
18370×
fn show_report(
18380×
    c: &Client,
18390×
    at: &str,
18400×
    files: impl Fn(&str) -> String,
18410×
    list: bool,
18420×
    file: Option<String>,
18430×
    output: Option<std::path::PathBuf>,
18440×
    json: bool,
18450×
) -> Result<()> {
1846
    use std::io::Write;
18470×
    if let Some(path) = file {
18480×
        let bytes = c.get_bytes(&files(&path))?;
18490×
        match output {
18500×
            Some(out) => {
18510×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
18520×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
1853
            }
18540×
            None => std::io::stdout().write_all(&bytes)?,
1855
        }
18560×
        return Ok(());
18570×
    }
18580×
    if json {
18590×
        println!("{}", c.get_text(at)?);
18600×
        return Ok(());
18610×
    }
18620×
    if !list {
18630×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
18640×
        return Ok(());
18650×
    }
18660×
    let r: Report = c.get(at)?;
18670×
    print_report(&r);
18680×
    if r.files_expired_ms.is_some() {
18690×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
18700×
    }
18710×
    for f in &r.manifest {
18720×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
18730×
    }
18740×
    println!("{}", ui::dim(&r.url));
18750×
    Ok(())
18760×
}
1877
1878
/// A report's heading, metrics and context.
18790×
fn print_report(r: &Report) {
18800×
    let from = match r.run {
18810×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
18820×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
1883
    };
18840×
    println!(
1885
        "{} {} {}",
18860×
        ui::strong(&r.name),
18870×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
18880×
        ui::dim(&format!("· {from} · {} files", r.files))
1889
    );
18900×
    if !r.summary.is_empty() {
18910×
        println!("  {}", r.summary);
18920×
    }
18930×
    for m in &r.metrics {
18940×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
18950×
        let mut notes = vec![];
18960×
        if !m.better.is_empty() {
18970×
            notes.push(format!("{} is better", m.better));
18980×
        }
18990×
        if let Some(a) = m.fail_above {
19000×
            notes.push(format!("fails above {a}"));
19010×
        }
19020×
        if let Some(b) = m.fail_below {
19030×
            notes.push(format!("fails below {b}"));
19040×
        }
19050×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
19060×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
1907
    }
19080×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
19090×
        let line: Vec<String> =
19100×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
19110×
        println!("  {}", ui::dim(&line.join(" ")));
19120×
    }
19130×
}
1914
1915
/// `oh report …` (oxygenhub#348).
19160×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
19170×
    let base = t.repo_path()?;
19180×
    match cmd {
19190×
        ReportCmd::List { bookmark } => {
19200×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
19210×
            if json {
19220×
                println!("{}", c.get_text(&path)?);
19230×
                return Ok(0);
19240×
            }
19250×
            let list: Vec<Report> = c.get(&path)?;
19260×
            if list.is_empty() {
19270×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
19280×
            }
19290×
            for r in &list {
19300×
                print_report(r);
19310×
            }
1932
        }
19330×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
19340×
            let at = format!("{base}/reports/{}", enc(&report));
19350×
            let query = match (id, bookmark) {
19360×
                (Some(id), _) => format!("?id={id}"),
19370×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
19380×
                (None, None) => String::new(),
1939
            };
19400×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
19410×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
1942
        }
1943
    }
19440×
    Ok(0)
19450×
}
1946
19470×
fn live(status: &str) -> bool {
19480×
    matches!(status, "queued" | "running")
19490×
}
1950
1951
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
19520×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
19530×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
19540×
    if json {
19550×
        println!("{done}");
19560×
    } else {
19570×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
19580×
    }
19590×
    Ok(())
19600×
}
1961
19620×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
19630×
    let path = format!("{base}/flow/runs/{number}");
19640×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1965
    loop {
19660×
        let r: FlowRun = c.get(&path)?;
19670×
        if !json {
19680×
            for j in &r.jobs {
19690×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
19700×
                if seen.get(&j.name) != Some(&shown) {
19710×
                    println!("{} {}", ui::status(&j.status), j.name);
19720×
                    if j.status == "queued" && !j.waiting.is_empty() {
19730×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
19740×
                    }
19750×
                    seen.insert(j.name.clone(), shown);
19760×
                }
1977
            }
19780×
        }
19790×
        if !live(&r.status) {
19800×
            if json {
19810×
                println!("{}", serde_json::to_string(&r)?);
19820×
            } else {
19830×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
19840×
            }
19850×
            return Ok(if r.status == "passed" { 0 } else { 1 });
19860×
        }
19870×
        std::thread::sleep(Duration::from_secs(3));
1988
    }
19890×
}
1990
19913×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
19923×
    let base = t.repo_path()?;
19930×
    match cmd {
19941×
        RunCmd::List { limit } => {
19951×
            let path = format!("{base}/flow/runs?limit={limit}");
19961×
            if json {
19971×
                println!("{}", c.get_text(&path)?);
19981×
                return Ok(0);
19990×
            }
20000×
            let runs: Vec<FlowRun> = c.get(&path)?;
20010×
            if runs.is_empty() {
20020×
                println!("{}", ui::dim("No runs yet."));
20030×
            }
20040×
            for r in &runs {
20050×
                println!("{}", run_line(r));
20060×
            }
2007
        }
20081×
        RunCmd::View { number, timings } => {
20091×
            let path = format!("{base}/flow/runs/{number}");
20101×
            if json {
20110×
                println!("{}", c.get_text(&path)?);
20120×
                return Ok(0);
20131×
            }
20141×
            print_run(&c.get(&path)?, timings);
2015
        }
20161×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
20171×
            let mut body = match (bookmark, change) {
20180×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
20190×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
20201×
                (None, None) => serde_json::json!({}),
2021
            };
20221×
            if !jobs.is_empty() {
20230×
                body["jobs"] = serde_json::json!(jobs);
20241×
            }
20251×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
20261×
            let n = started["number"].as_i64().context("the hub named no run")?;
20271×
            if !json || !follow {
20281×
                if json {
20290×
                    println!("{started}");
20301×
                } else {
20311×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
20321×
                }
20330×
            }
20341×
            if follow {
20350×
                return watch(c, &base, n, json);
20361×
            }
2037
        }
20380×
        RunCmd::Watch { number } => return watch(c, &base, number, json),
20390×
        RunCmd::Log { number, job } => {
20400×
            let mut after = 0;
2041
            loop {
20420×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
20430×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
20440×
                if lines.is_empty() {
20450×
                    break;
20460×
                }
20470×
                for l in &lines {
20480×
                    if json {
20490×
                        println!("{}", serde_json::to_string(l)?);
20500×
                    } else if l.stream == "flow" {
20510×
                        println!("{}", ui::dim(&l.text));
20520×
                    } else {
20530×
                        println!("{}", l.text);
20540×
                    }
2055
                }
20560×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2057
            }
2058
        }
20590×
        RunCmd::Report { number, job, pick } => {
20600×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
20610×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
20620×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
20630×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2064
        }
20650×
        RunCmd::Rerun { number, job: Some(job) } => {
20660×
            let queued: serde_json::Value =
20670×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
20680×
            if json {
20690×
                println!("{queued}");
20700×
            } else {
20710×
                let n = queued["queued"].as_i64().unwrap_or(1);
20720×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
20730×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2074
            }
2075
        }
20760×
        RunCmd::Rerun { number, job: None } => {
20770×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
20780×
            if json {
20790×
                println!("{started}");
20800×
            } else {
20810×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
20820×
            }
2083
        }
20840×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
20850×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
20860×
        RunCmd::Cancel { number } => {
20870×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
20880×
            if json {
20890×
                println!("{done}");
20900×
            } else {
20910×
                println!("{} cancelled run #{number}", ui::ok("✔"));
20920×
            }
2093
        }
2094
    }
20952×
    Ok(0)
20963×
}
2097
20980×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
20990×
    let base = t.repo_path()?;
21000×
    match cmd {
2101
        LabelCmd::List => {
21020×
            let path = format!("{base}/labels");
21030×
            if json {
21040×
                println!("{}", c.get_text(&path)?);
21050×
                return Ok(0);
21060×
            }
21070×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
21080×
            if labels.is_empty() {
21090×
                println!("{}", ui::dim("No labels."));
21100×
            }
21110×
            for l in labels {
21120×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
21130×
            }
2114
        }
21150×
        LabelCmd::Create { name, colour, description } => {
21160×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
21170×
            if json {
21180×
                println!("{}", serde_json::to_string(&l)?);
21190×
            } else {
21200×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
21210×
            }
2122
        }
21230×
        LabelCmd::Delete { name } => {
21240×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
21250×
            println!("{} deleted label {name}", ui::ok("✔"));
2126
        }
2127
    }
21280×
    Ok(0)
21290×
}
2130
21310×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
21320×
    let base = match (&org, site) {
21330×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
21340×
        (None, true) => "/admin/assistants".to_string(),
21350×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2136
    };
21370×
    match cmd {
2138
        AssistantCmd::List => {
21390×
            if json {
21400×
                println!("{}", c.get_text(&base)?);
21410×
                return Ok(0);
21420×
            }
21430×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
21440×
            if list.is_empty() {
21450×
                println!("{}", ui::dim("No assistants."));
21460×
            }
21470×
            for a in list {
21480×
                let state = if a.enabled && !a.off_above {
21490×
                    ui::ok("on")
21500×
                } else if a.off_above {
21510×
                    ui::dim("off above")
2152
                } else {
21530×
                    ui::dim("off")
2154
                };
21550×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
21560×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2157
            }
2158
        }
21590×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
21600×
            let token = match token_env {
21610×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
21620×
                None => String::new(),
2163
            };
21640×
            let body =
21650×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
21660×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
21670×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2168
        }
21690×
        AssistantCmd::Remove { name } => {
21700×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
21710×
            println!("{} removed {name}", ui::ok("✔"));
2172
        }
21730×
        AssistantCmd::Prompt { set } => {
21740×
            let p: hub_api::AssistantPrompt = match set {
21750×
                Some(path) => {
21760×
                    let text = if path.as_os_str() == "-" {
21770×
                        let mut s = String::new();
21780×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
21790×
                        s
2180
                    } else {
21810×
                        std::fs::read_to_string(&path)?
2182
                    };
21830×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2184
                }
21850×
                None => c.get(&format!("{base}/prompt"))?,
2186
            };
21870×
            if json {
21880×
                println!("{}", serde_json::to_string(&p)?);
21890×
                return Ok(0);
21900×
            }
21910×
            for (from, text) in &p.inherited {
21920×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
21930×
            }
21940×
            if p.prompt.is_empty() {
21950×
                println!("{}", ui::dim("No prompt of its own."));
21960×
            } else {
21970×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
21980×
            }
2199
        }
2200
    }
22010×
    Ok(0)
22020×
}
2203
22042×
fn project_line(p: &hub_api::Project) -> String {
22052×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
22062×
    let private = if p.public { "" } else { " · private" };
22072×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
22082×
}
2209
221010×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
221110×
    let owner = match owner {
22120×
        Some(o) => o,
221310×
        None => t.repo()?.0.to_string(),
2214
    };
221510×
    let base = format!("/projects/{}", enc(&owner));
221610×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
22171×
        let p: hub_api::Project =
22181×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
22191×
        if json {
22200×
            println!("{}", serde_json::to_string(&p)?);
22211×
        } else {
22221×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
22231×
        }
22241×
        Ok(())
22251×
    };
22264×
    match cmd {
2227
        ProjectCmd::List => {
22281×
            if json {
22290×
                println!("{}", c.get_text(&base)?);
22300×
                return Ok(0);
22311×
            }
22321×
            let list: Vec<hub_api::Project> = c.get(&base)?;
22331×
            if list.is_empty() {
22340×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
22351×
            }
22361×
            for p in &list {
22371×
                println!("{}", project_line(p));
22381×
            }
2239
        }
22403×
        ProjectCmd::View { number, archived } => {
22413×
            let path = format!("{base}/{number}");
22423×
            let cards = format!("{path}/cards?archived=true");
22433×
            if json {
22442×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
22452×
                return Ok(0);
22461×
            }
22471×
            let mut b: hub_api::Board = c.get(&path)?;
22481×
            if archived {
22490×
                b.columns = c.get(&cards)?;
22501×
            }
22511×
            println!("{}", project_line(&b.project));
22521×
            if !b.project.description.is_empty() {
22531×
                println!("{}", b.project.description);
22541×
            }
22553×
            for col in &b.columns {
22563×
                println!();
22573×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
22583×
                if col.cards.is_empty() {
22591×
                    println!("  {}", ui::dim("(empty)"));
22602×
                }
22613×
                for card in &col.cards {
22622×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
22632×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
22642×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
22652×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
22662×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
22672×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2268
                }
2269
            }
22701×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2271
        }
22721×
        ProjectCmd::Create { title, description, private } => {
22731×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
22741×
            if json {
22750×
                println!("{}", serde_json::to_string(&p)?);
22761×
            } else {
22771×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
22781×
            }
2279
        }
22801×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
22810×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
22820×
        ProjectCmd::Transfer { number, to } => {
22830×
            let p: hub_api::Project =
22840×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
22850×
            if json {
22860×
                println!("{}", serde_json::to_string(&p)?);
22870×
            } else {
22880×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
22890×
            }
2290
        }
22912×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2292
            // The hub names a card's issue as `repo#N` among the owner's
2293
            // repositories.
22942×
            let reference = match reference {
22951×
                None => String::new(),
22961×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
22970×
                    Some((o, rest)) if o == owner => rest.to_string(),
22980×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
22990×
                    None => r,
2300
                },
23011×
                Some(r) => {
23021×
                    let n = r.trim_start_matches('#');
23031×
                    if n.parse::<i64>().is_err() {
23040×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
23051×
                    }
23061×
                    format!("{}#{n}", t.repo()?.1)
2307
                }
2308
            };
23092×
            let note = note.unwrap_or_default();
23102×
            if reference.is_empty() && note.is_empty() {
23110×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
23122×
            }
23131×
            let card: hub_api::ProjectCard =
23142×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
23151×
            if json {
23160×
                println!("{}", serde_json::to_string(&card)?);
2317
            } else {
23181×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2319
            }
2320
        }
23211×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
23221×
            (Some(card), None) => {
23231×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
23241×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2325
            }
23260×
            (None, Some(from)) => {
23270×
                let r: hub_api::CardsMoved = c.send(
23280×
                    "POST",
23290×
                    &format!("{base}/{number}/cards/move"),
23300×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
23310×
                )?;
23320×
                if json {
23330×
                    println!("{}", serde_json::to_string(&r)?);
23340×
                    return Ok(0);
23350×
                }
23360×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
23370×
                for m in &r.moved {
23380×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2339
                }
23400×
                let verb = if dry_run { "would move" } else { "moved" };
23410×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2342
            }
23430×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2344
        },
23450×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
23460×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
23470×
                None => None,
23480×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2349
            };
23500×
            let r: hub_api::CardsArchived = c.send(
23510×
                "POST",
23520×
                &format!("{base}/{number}/cards/archive"),
23530×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
23540×
            )?;
23550×
            if json {
23560×
                println!("{}", serde_json::to_string(&r)?);
23570×
                return Ok(0);
23580×
            }
23590×
            let verb = if dry_run { "would archive" } else { "archived" };
23600×
            for a in &r.archived {
23610×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
23620×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2363
            }
23640×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2365
        }
23660×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
23670×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
23680×
            println!("{} card {card} restored", ui::ok("✔"));
2369
        }
23701×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
23711×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
23721×
            println!("{} card {card} removed", ui::ok("✔"));
2373
        }
2374
    }
23757×
    Ok(0)
237610×
}
2377
23780×
fn milestone_line(m: &hub_api::Milestone) -> String {
23790×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
23800×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
23810×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
23820×
}
2383
23840×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
23850×
    let base = t.repo_path()?;
23860×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
23870×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
23880×
        if json {
23890×
            println!("{}", serde_json::to_string(&m)?);
23900×
        } else {
23910×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
23920×
        }
23930×
        Ok(())
23940×
    };
23950×
    match cmd {
2396
        MilestoneCmd::List => {
23970×
            let path = format!("{base}/milestones");
23980×
            if json {
23990×
                println!("{}", c.get_text(&path)?);
24000×
                return Ok(0);
24010×
            }
24020×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
24030×
            if list.is_empty() {
24040×
                println!("{}", ui::dim("No milestones."));
24050×
            }
24060×
            for m in &list {
24070×
                println!("{}", milestone_line(m));
24080×
            }
2409
        }
24100×
        MilestoneCmd::Create { title, description, due } => {
24110×
            let m: hub_api::Milestone =
24120×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
24130×
            if json {
24140×
                println!("{}", serde_json::to_string(&m)?);
24150×
            } else {
24160×
                println!("{} milestone {}", ui::ok("✔"), m.title);
24170×
            }
2418
        }
24190×
        MilestoneCmd::Edit { title, rename, description, due } => {
24200×
            if rename.is_none() && description.is_none() && due.is_none() {
24210×
                bail!("say what to change: --rename, --description or --due");
24220×
            }
24230×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2424
        }
24250×
        MilestoneCmd::Close { title } => {
24260×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2427
        }
24280×
        MilestoneCmd::Reopen { title } => {
24290×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2430
        }
2431
    }
24320×
    Ok(0)
24330×
}
2434
24350×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
24360×
    let base = t.repo_path()?;
24370×
    match cmd {
2438
        TagCmd::List => {
24390×
            let path = format!("{base}/tags");
24400×
            if json {
24410×
                println!("{}", c.get_text(&path)?);
24420×
                return Ok(0);
24430×
            }
24440×
            let tags: Vec<Tag> = c.get(&path)?;
24450×
            if tags.is_empty() {
24460×
                println!("{}", ui::dim("no tags"));
24470×
            }
24480×
            for t in tags {
24490×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
24500×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
24510×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2452
            }
2453
        }
24540×
        TagCmd::Create { name, target, message } => {
24550×
            let new = hub_api::NewTag { name, target, message };
24560×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
24570×
            if json {
24580×
                println!("{}", serde_json::to_string(&made)?);
24590×
            } else {
24600×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
24610×
            }
2462
        }
24630×
        TagCmd::Delete { name, reason } => {
24640×
            let reason = reason.unwrap_or_default();
24650×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
24660×
            if json {
24670×
                println!("{}", serde_json::json!({ "withdrawn": name }));
24680×
            } else {
24690×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
24700×
            }
2471
        }
2472
    }
24730×
    Ok(0)
24740×
}
2475
24764×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
24774×
    let base = t.repo_path()?;
24784×
    match cmd {
2479
        ReleaseCmd::List => {
24801×
            let path = format!("{base}/releases");
24811×
            if json {
24821×
                println!("{}", c.get_text(&path)?);
24831×
                return Ok(0);
24840×
            }
24850×
            let list: Vec<Release> = c.get(&path)?;
24860×
            if list.is_empty() {
24870×
                println!("{}", ui::dim("No releases."));
24880×
            }
24890×
            for r in &list {
24900×
                println!(
2491
                    "{} {} {}{}",
24920×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
24930×
                    ui::strong(&r.tag),
2494
                    r.title,
24950×
                    ui::dim(&format!(
2496
                        " · {} asset{} · {}",
24970×
                        r.assets.len(),
24980×
                        if r.assets.len() == 1 { "" } else { "s" },
24990×
                        ui::ago(r.created_ms)
2500
                    ))
2501
                );
2502
            }
2503
        }
25041×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
25051×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
25061×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
25071×
            if json {
25080×
                println!("{}", serde_json::to_string(&r)?);
25091×
            } else {
25101×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
25111×
            }
2512
        }
25130×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
25140×
            let notes = match notes.as_deref() {
25150×
                Some("-") => Some(body_of(None, Some("-".into()))?),
25160×
                _ => notes,
2517
            };
25180×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
25190×
                bail!("say what to change: --title, --notes or --prerelease");
25200×
            }
25210×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
25220×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
25230×
            if json {
25240×
                println!("{}", serde_json::to_string(&r)?);
25250×
            } else {
25260×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
25270×
            }
2528
        }
25291×
        ReleaseCmd::Upload { tag, files } => {
25301×
            if files.is_empty() {
25310×
                bail!("name the files to attach");
25321×
            }
25331×
            for f in files {
25341×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
25351×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
25361×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
25371×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2538
            }
2539
        }
25401×
        ReleaseCmd::Trust { tag } => {
25411×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
25421×
            if json {
25430×
                println!("{}", c.get_text(&path)?);
25440×
                return Ok(0);
25451×
            }
25461×
            let r: serde_json::Value = c.get(&path)?;
25471×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
25481×
            let mut worst = 0;
25494×
            for ch in r["audit"].as_array().into_iter().flatten() {
25504×
                let v = ch["verdict"].as_str().unwrap_or("");
25514×
                worst = worst.max(match v {
25524×
                    "fail" => 2,
25534×
                    "warn" => 1,
25543×
                    _ => 0,
2555
                });
25564×
                let g = match v {
25574×
                    "pass" => ui::ok("✔"),
25581×
                    "warn" => ui::warn("!"),
25590×
                    _ => ui::bad("✘"),
2560
                };
25614×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2562
            }
25631×
            return Ok(if worst == 2 { 1 } else { 0 });
2564
        }
2565
    }
25662×
    Ok(0)
25674×
}
2568
2569
#[cfg(test)]
2570
mod tests {
2571
2572
    #[test]
25731×
    fn job_timings_and_report_commands_read_plainly() {
2574
        use clap::Parser;
25751×
        let job = hub_api::FlowJob {
25761×
            name: "perf".into(),
25771×
            status: "passed".into(),
25781×
            depends_on: vec![],
25791×
            runner: "earth-1".into(),
25801×
            exit_code: Some(0),
25811×
            error: String::new(),
25821×
            started_ms: Some(13_000),
25831×
            finished_ms: Some(200_000),
25841×
            log_lines: 10,
25851×
            waiting: String::new(),
25861×
            placed: String::new(),
25871×
            approval: String::new(),
25881×
            queued_ms: Some(1_000),
25891×
            ready_ms: Some(12_500),
25901×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
25911×
            peak_disk_mib: Some(2150),
25921×
            peak_memory_mib: Some(900),
25931×
        };
25941×
        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");
25951×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
25961×
        assert_eq!(super::timing_line(&bare), "");
25971×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2598
25991×
        let cli =
26001×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
26011×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
26021×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
26031×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
26041×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
26051×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
26061×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
26071×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
26081×
    }
2609
2610
    #[test]
26111×
    fn runner_update_scopes_resolve_by_name_or_id() {
26121×
        let all = hub_api::RunnerUpdates {
26131×
            repo: String::new(),
26141×
            settings: vec![],
26151×
            groups: vec![hub_api::RunnerGroup {
26161×
                id: 4,
26171×
                owner: "acme".into(),
26181×
                name: "canary".into(),
26191×
                percent: None,
26201×
                members: vec![],
26211×
                wave: None,
26221×
            }],
26231×
            runners: vec![],
26241×
            holds: vec![],
26251×
        };
26261×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
26271×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
26283×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
26293×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2630
        }
26311×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
26321×
        assert!(update_scope("everyone", &all).is_err());
26331×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
26341×
        assert!(switch(Some("yes")).is_err());
26351×
    }
2636
    use super::*;
2637
2638
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2639
    /// help says, and a drop is named by its id or its address.
2640
    #[test]
26411×
    fn drop_commands_parse() {
26421×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
26431×
        match cli.cmd {
26441×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
26451×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
26461×
                assert!(secret);
26471×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2648
            }
26490×
            _ => panic!("not drop create"),
2650
        }
26511×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
26521×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
26531×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
26541×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
26551×
                assert!(channel.is_none() && dry_run.is_none());
2656
            }
26570×
            _ => panic!("not runner-updates set"),
2658
        }
26591×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
26601×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
26611×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
26620×
            _ => panic!("not drop list"),
2663
        }
26641×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
26651×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
26661×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2667
            }
26680×
            _ => panic!("not drop view"),
2669
        }
26701×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
26714×
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
26724×
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2673
        }
26741×
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
26751×
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
26761×
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
26770×
            _ => panic!("not drop comment"),
2678
        }
26791×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
26801×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
26811×
        assert!(drop_id("andy/notes").is_err());
26821×
    }
2683
}