OXYGENHUB

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

665 of 1675 lines run, 49 of 261 functions · run #538 on main · run missed

1
//! `oh`: OxygenHub from the command line, as `gh` is for GitHub. It talks
2
//! to the hub's JSON API (hub spec §12) as the checkout's remote does:
3
//! same hub, same token, same CA.
4
5
mod client;
6
mod mcp;
7
mod target;
8
mod ui;
9
10
use anyhow::{bail, Context, Result};
11
use clap::{Parser, Subcommand};
12
use client::Client;
13
use hub_api::{
14
    FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag,
15
};
16
use std::time::Duration;
17
use target::{Choice, Config, Target};
18
19
#[derive(Parser)]
20
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")]
21
struct Cli {
22
    /// The repository, when not inside an Oxygen checkout
23
    #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")]
24
    repo: Option<String>,
25
    /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved)
26
    #[arg(long, global = true, value_name = "URL")]
27
    hub: Option<String>,
28
    /// Which of the checkout's remotes to use (default: origin, or the only one)
29
    #[arg(long, global = true)]
30
    remote: Option<String>,
31
    /// Machine-readable output: the API's JSON, unchanged
32
    #[arg(long, global = true)]
33
    json: bool,
34
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
35
    #[arg(long, global = true)]
36
    plain: bool,
37
    #[command(subcommand)]
38
    cmd: Cmd,
39
}
40
41
#[derive(Subcommand)]
42
enum Cmd {
43
    /// Sign in to a hub, or show who you are signed in as
44
    Auth {
45
        #[command(subcommand)]
46
        cmd: AuthCmd,
47
    },
48
    /// The repository
49
    Repo {
50
        #[command(subcommand)]
51
        cmd: RepoCmd,
52
    },
53
    /// Issues
54
    Issue {
55
        #[command(subcommand)]
56
        cmd: IssueCmd,
57
    },
58
    /// Proposals (pull requests)
59
    Proposal {
60
        #[command(subcommand)]
61
        cmd: ProposalCmd,
62
    },
63
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
64
    Coverage {
65
        #[command(subcommand)]
66
        cmd: CoverageCmd,
67
    },
68
    /// OxygenFlow runs
69
    Run {
70
        #[command(subcommand)]
71
        cmd: RunCmd,
72
    },
73
    /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348)
74
    Report {
75
        #[command(subcommand)]
76
        cmd: ReportCmd,
77
    },
78
    /// Releases
79
    Release {
80
        #[command(subcommand)]
81
        cmd: ReleaseCmd,
82
    },
83
    /// Tags: list, create, withdraw
84
    Tag {
85
        #[command(subcommand)]
86
        cmd: TagCmd,
87
    },
88
    /// The repository's labels
89
    Label {
90
        #[command(subcommand)]
91
        cmd: LabelCmd,
92
    },
93
    /// Milestones: list, create, edit, close
94
    Milestone {
95
        #[command(subcommand)]
96
        cmd: MilestoneCmd,
97
    },
98
    /// Project boards of the repository's owner (or --owner): list,
99
    /// create, view, and cards
100
    Project {
101
        #[command(subcommand)]
102
        cmd: ProjectCmd,
103
        /// A user or organisation other than the repository's owner
104
        #[arg(long, global = true)]
105
        owner: Option<String>,
106
    },
107
    /// AI assistants of the repository (its admins), or with --org or
108
    /// --site of an organisation or the site
109
    Assistant {
110
        #[command(subcommand)]
111
        cmd: AssistantCmd,
112
        /// An organisation's assistants instead of the repository's
113
        #[arg(long, global = true)]
114
        org: Option<String>,
115
        /// The site's assistants (administrators)
116
        #[arg(long, global = true, conflicts_with = "org")]
117
        site: bool,
118
    },
119
    /// Agents that act for you without a key of their own (keyless
120
    /// signing): grant, list, revoke
121
    Agent {
122
        #[command(subcommand)]
123
        cmd: AgentCmd,
124
    },
125
    /// Drops: small snippets of files, each its own repository, never
126
    /// listed among your repositories (oxygenhub#279)
127
    Drop {
128
        #[command(subcommand)]
129
        cmd: DropCmd,
130
    },
131
    /// Runners that update themselves (site administrators; oxygenhub#322):
132
    /// where builds come from, who takes them, what is held back
133
    #[command(name = "runner-updates")]
134
    RunnerUpdates {
135
        #[command(subcommand)]
136
        cmd: Option<RunnerUpdatesCmd>,
137
    },
138
    /// Serve this repository's hub to an AI agent over the Model Context Protocol (stdio); read-only unless --allow-write
139
    Mcp {
140
        /// Also offer tools that change the hub: create, comment on and close issues, comment on proposals, re-run Flow runs
141
        #[arg(long)]
142
        allow_write: bool,
143
    },
144
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
145
    Api {
146
        /// A path under /api/v1
147
        path: String,
148
        /// The method
149
        #[arg(long, short = 'X', default_value = "GET")]
150
        method: String,
151
        /// A JSON body
152
        #[arg(long, short = 'd')]
153
        data: Option<String>,
154
    },
155
}
156
157
#[derive(Subcommand)]
158
enum AgentCmd {
159
    /// Let an agent act for you: your oxy key (the one your oxy home names
160
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
161
    /// the agent a token it exchanges for ten-minute certificates. The
162
    /// token is printed once: give it to the agent (`oxy auth grant`)
163
    Grant {
164
        /// The agent's name, as in agent:NAME@YOU
165
        name: String,
166
        /// What its keys may do for you: changes, seal, refs
167
        #[arg(long, default_value = "changes,seal,refs")]
168
        scope: String,
169
        /// How long the grant lasts: 30d, 12h, 90m
170
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
171
        lasts: String,
172
    },
173
    /// Your grants, live and past
174
    List,
175
    /// Stop a grant at once: no more certificates under it
176
    Revoke { id: i64 },
177
}
178
179
#[derive(Subcommand)]
180
enum DropCmd {
181
    /// Make a drop of these files, signed by the hub as your delegate
182
    Create {
183
        /// The files (their names in the drop are their file names)
184
        #[arg(required = true)]
185
        files: Vec<std::path::PathBuf>,
186
        /// Unlisted: readable by anyone with its address, listed nowhere
187
        #[arg(long)]
188
        secret: bool,
189
        /// A description
190
        #[arg(long, short = 'd', value_name = "TEXT")]
191
        description: Option<String>,
192
        /// A title (default: the first file's name)
193
        #[arg(long, short = 't')]
194
        title: Option<String>,
195
    },
196
    /// Your drops, or someone's public ones
197
    List {
198
        /// Whose drops
199
        #[arg(long, short = 'u', value_name = "NAME")]
200
        user: Option<String>,
201
    },
202
    /// A drop's files, printed (by id or address)
203
    View {
204
        /// The drop's id, or its address
205
        id: String,
206
        /// Print only this file's content
207
        #[arg(long, short = 'f', value_name = "NAME")]
208
        file: Option<String>,
209
    },
210
    /// Delete a drop and its history
211
    Delete {
212
        /// The drop's id, or its address
213
        id: String,
214
    },
215
    /// A copy of someone's drop, history and all, as a drop of yours
216
    Fork {
217
        /// The drop's id, or its address
218
        id: String,
219
    },
220
    /// Star a drop
221
    Star {
222
        /// The drop's id, or its address
223
        id: String,
224
    },
225
    /// Take your star back
226
    Unstar {
227
        /// The drop's id, or its address
228
        id: String,
229
    },
230
    /// A drop's comments, oldest first
231
    Comments {
232
        /// The drop's id, or its address
233
        id: String,
234
    },
235
    /// Comment on a drop (Markdown); its owner is told
236
    Comment {
237
        /// The drop's id, or its address
238
        id: String,
239
        /// What to say
240
        #[arg(long, short = 'm')]
241
        message: String,
242
    },
243
}
244
245
#[derive(Subcommand)]
246
enum RunnerUpdatesCmd {
247
    /// Every level's settings, the test groups, each runner's policy and what it is offered (the default)
248
    Show,
249
    /// Change one level's settings; what is not given stays as it is
250
    Set {
251
        /// `site`, `owner:NAME`, `group:NAME` (or `group:OWNER/NAME`, `group:ID`), `runner:NAME` (or `runner:ID`)
252
        scope: String,
253
        /// `on`, `off` or `inherit`
254
        #[arg(long)]
255
        updates: Option<String>,
256
        /// `stable`, `canary`, a version, or `inherit`
257
        #[arg(long)]
258
        channel: Option<String>,
259
        /// Hours (UTC) updates may start in, `02-05`, or `inherit`
260
        #[arg(long)]
261
        window: Option<String>,
262
        /// `on`, `off` or `inherit`
263
        #[arg(long)]
264
        dry_run: Option<String>,
265
    },
266
    /// Offer a held build again (it rolled back on a runner)
267
    Lift { version: String },
268
}
269
270
#[derive(Subcommand)]
271
enum AuthCmd {
272
    /// Sign in to a hub and make it the default: approve a code on the web
273
    /// (device sign-in), or give a token
274
    Login {
275
        /// The hub, e.g. https://oxygenhub.io
276
        #[arg(long = "with-hub", value_name = "URL")]
277
        url: String,
278
        /// An API token from the hub's Settings → Tokens, instead of
279
        /// approving a code ("-" reads it from stdin)
280
        #[arg(long)]
281
        token: Option<String>,
282
        /// The hub's CA certificate, when self-signed
283
        #[arg(long)]
284
        ca: Option<std::path::PathBuf>,
285
    },
286
    /// Who the token in use belongs to
287
    Status,
288
}
289
290
#[derive(Subcommand)]
291
enum RepoCmd {
292
    /// Name, description, visibility and default bookmark
293
    View,
294
}
295
296
#[derive(Subcommand)]
297
enum IssueCmd {
298
    /// Put labels on an issue or take them off (triage)
299
    Label(LabelChange),
300
    /// Open issues (or --state closed|all)
301
    List {
302
        #[arg(long, default_value = "open")]
303
        state: String,
304
    },
305
    /// One issue with its comments
306
    View { number: i64 },
307
    /// Open an issue
308
    Create {
309
        #[arg(long, short)]
310
        title: String,
311
        #[arg(long, short)]
312
        body: Option<String>,
313
        /// Read the body from a file ("-" for stdin)
314
        #[arg(long, short = 'F')]
315
        body_file: Option<String>,
316
        /// A label (repeatable)
317
        #[arg(long, short)]
318
        label: Vec<String>,
319
        /// Also put it on this board of the repository's owner
320
        #[arg(long, short)]
321
        project: Option<i64>,
322
        /// The board's column for it, by name (default: the first)
323
        #[arg(long, requires = "project")]
324
        column: Option<String>,
325
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
326
        #[arg(long, short = 'a', value_name = "FILE")]
327
        attach: Vec<std::path::PathBuf>,
328
    },
329
    /// Close an issue, with an optional comment saying why
330
    Close {
331
        number: i64,
332
        /// `completed` or `not_planned`
333
        #[arg(long, default_value = "completed")]
334
        reason: String,
335
        #[command(flatten)]
336
        comment: StateComment,
337
    },
338
    /// Reopen an issue, with an optional comment saying why
339
    Reopen {
340
        number: i64,
341
        #[command(flatten)]
342
        comment: StateComment,
343
    },
344
    /// Change an issue's title or body (its author or triage), or its
345
    /// labels, assignees or milestone as whole sets (triage)
346
    Edit {
347
        number: i64,
348
        #[arg(long, short)]
349
        title: Option<String>,
350
        #[arg(long, short)]
351
        body: Option<String>,
352
        /// Read the body from a file ("-" for stdin)
353
        #[arg(long, short = 'F', conflicts_with = "body")]
354
        body_file: Option<String>,
355
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
356
        #[arg(long, short)]
357
        label: Vec<String>,
358
        /// Clear its labels
359
        #[arg(long, conflicts_with = "label")]
360
        no_labels: bool,
361
        /// The users it should be assigned to (repeatable)
362
        #[arg(long, short)]
363
        assignee: Vec<String>,
364
        /// Take everyone off it
365
        #[arg(long, conflicts_with = "assignee")]
366
        no_assignees: bool,
367
        /// A milestone's title ("" takes it out of its milestone)
368
        #[arg(long, short)]
369
        milestone: Option<String>,
370
    },
371
    /// Comment on an issue
372
    Comment {
373
        number: i64,
374
        #[arg(long, short)]
375
        body: Option<String>,
376
        /// Read the body from a file ("-" for stdin), as proposal comment
377
        /// does (#260)
378
        #[arg(long, short = 'F', conflicts_with = "body")]
379
        body_file: Option<String>,
380
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
381
        #[arg(long, short = 'a', value_name = "FILE")]
382
        attach: Vec<std::path::PathBuf>,
383
    },
384
}
385
386
#[derive(Subcommand)]
387
enum ProposalCmd {
388
    /// Open proposals (or --state draft|landed|closed|all), newest first
389
    List {
390
        #[arg(long, default_value = "open")]
391
        state: String,
392
        /// At most this many
393
        #[arg(long, default_value_t = 30)]
394
        limit: usize,
395
    },
396
    /// One proposal: its changes, approvals and whether it can land
397
    View { number: i64 },
398
    /// Propose a bookmark's changes for another bookmark
399
    Create {
400
        #[arg(long, short)]
401
        title: 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
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
408
        #[arg(long)]
409
        from: String,
410
        /// The bookmark to land them on (default: the repository's default bookmark)
411
        #[arg(long)]
412
        into: Option<String>,
413
        #[arg(long)]
414
        draft: bool,
415
    },
416
    /// Change a proposal's title or description (its author or a maintainer)
417
    Edit {
418
        number: i64,
419
        #[arg(long, short)]
420
        title: Option<String>,
421
        #[arg(long, short)]
422
        body: Option<String>,
423
        /// Read the body from a file ("-" for stdin)
424
        #[arg(long, short = 'F', conflicts_with = "body")]
425
        body_file: Option<String>,
426
    },
427
    /// Put labels on a proposal or take them off (triage)
428
    Label(LabelChange),
429
    /// Comment on a proposal's conversation
430
    Comment {
431
        number: i64,
432
        #[arg(long, short)]
433
        body: Option<String>,
434
        /// Read the comment from a file ("-" for stdin)
435
        #[arg(long, short = 'F', conflicts_with = "body")]
436
        body_file: Option<String>,
437
    },
438
    /// The checks on a proposal's projected state
439
    Checks { number: i64 },
440
    /// Land a proposal on its target, as the page's Land button does
441
    Land {
442
        number: i64,
443
        /// Land before its required checks pass, saying why (maintainers;
444
        /// recorded and audited, #261)
445
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
446
        over_checks: Option<String>,
447
        /// Land it by itself once its checks pass (#261); with --off, don't
448
        #[arg(long)]
449
        when_ready: bool,
450
        /// With --when-ready: turn it off
451
        #[arg(long, requires = "when_ready")]
452
        off: bool,
453
    },
454
    /// Close a proposal without landing it, with an optional comment
455
    Close {
456
        number: i64,
457
        /// Say why, as a comment before it closes
458
        #[arg(long, short = 'm')]
459
        message: Option<String>,
460
    },
461
    /// Reopen a closed proposal
462
    Reopen { number: i64 },
463
    /// Take a draft proposal out of draft, ready for review (its author or triage)
464
    Ready {
465
        number: i64,
466
        /// Turn an open proposal back into a draft instead
467
        #[arg(long)]
468
        undo: bool,
469
    },
470
}
471
472
#[derive(Subcommand)]
473
enum AssistantCmd {
474
    /// The assistants this level sees, its own and those inherited
475
    List,
476
    /// Add an assistant, or change the one of that name
477
    Add {
478
        /// How it shows on reviews (default: the provider's name)
479
        #[arg(long, default_value = "")]
480
        name: String,
481
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
482
        #[arg(long, default_value = "")]
483
        preset: String,
484
        /// The endpoint, when no preset or another one
485
        #[arg(long, default_value = "")]
486
        endpoint: String,
487
        /// chat-completions or anthropic-messages
488
        #[arg(long, default_value = "")]
489
        api: String,
490
        /// One the endpoint lists (`oh assistant models` shows them)
491
        #[arg(long)]
492
        model: String,
493
        /// The API key, read from this environment variable (never typed on the command line)
494
        #[arg(long, value_name = "VAR")]
495
        token_env: Option<String>,
496
        /// Add it turned off
497
        #[arg(long)]
498
        off: bool,
499
    },
500
    /// Remove this level's assistant of that name
501
    Remove { name: String },
502
    /// Show this level's prompt, and those it inherits
503
    Prompt {
504
        /// Set it from this file (`-` for standard input; an empty file clears it)
505
        #[arg(long, value_name = "FILE")]
506
        set: Option<std::path::PathBuf>,
507
    },
508
}
509
510
#[derive(Subcommand)]
511
enum LabelCmd {
512
    /// The repository's labels
513
    List,
514
    /// Create a label, or change the one of that name (triage)
515
    Create {
516
        name: String,
517
        /// `#rrggbb` (default: one the hub picks)
518
        #[arg(long)]
519
        colour: Option<String>,
520
        #[arg(long, short, default_value = "")]
521
        description: String,
522
    },
523
    /// Delete a label, taking it off every issue and proposal (triage)
524
    Delete { name: String },
525
}
526
527
#[derive(Subcommand)]
528
enum ProjectCmd {
529
    /// The owner's boards
530
    List,
531
    /// One board: its columns and cards
532
    View {
533
        number: i64,
534
        /// Its archived cards instead (#293)
535
        #[arg(long)]
536
        archived: bool,
537
    },
538
    /// Create a board (owner, or an organisation's members)
539
    Create {
540
        title: String,
541
        #[arg(long, short, default_value = "")]
542
        description: String,
543
        /// Only the owner (or the organisation's members) can see it
544
        #[arg(long)]
545
        private: bool,
546
    },
547
    /// Close a board
548
    Close { number: i64 },
549
    /// Reopen a board
550
    Reopen { number: i64 },
551
    /// Move a board to another owner you may make boards under (an
552
    /// organisation, say); it takes the next number there
553
    Transfer {
554
        number: i64,
555
        /// The new owner
556
        #[arg(long)]
557
        to: String,
558
    },
559
    /// Cards on a board: add, move, archive, restore, remove
560
    Card {
561
        #[command(subcommand)]
562
        cmd: CardCmd,
563
    },
564
    /// A board's columns: add, rename, move, remove (#366)
565
    Column {
566
        #[command(subcommand)]
567
        cmd: ColumnCmd,
568
    },
569
}
570
571
#[derive(Subcommand)]
572
enum ColumnCmd {
573
    /// Add a column at the right
574
    Add {
575
        /// The board
576
        number: i64,
577
        name: String,
578
    },
579
    /// Rename a column (by name or id)
580
    Rename {
581
        /// The board
582
        number: i64,
583
        column: String,
584
        /// Its new name
585
        to: String,
586
    },
587
    /// Move a column: --to POSITION (1 is the leftmost), --left or --right
588
    Move {
589
        /// The board
590
        number: i64,
591
        column: String,
592
        /// Its place, counting from 1 at the left
593
        #[arg(long, conflicts_with_all = ["left", "right"], required_unless_present_any = ["left", "right"])]
594
        to: Option<i64>,
595
        /// One place to the left
596
        #[arg(long, conflicts_with = "right")]
597
        left: bool,
598
        /// One place to the right
599
        #[arg(long)]
600
        right: bool,
601
    },
602
    /// Remove a column; its cards go to the first remaining one
603
    Remove {
604
        /// The board
605
        number: i64,
606
        column: String,
607
    },
608
}
609
610
#[derive(Subcommand)]
611
enum CardCmd {
612
    /// Put an issue or proposal on a board (`12` or `#12` in this
613
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
614
    /// or a note with --note
615
    Add {
616
        number: i64,
617
        /// The issue or proposal; a number means this repository's
618
        reference: Option<String>,
619
        /// A note card instead
620
        #[arg(long, conflicts_with = "reference")]
621
        note: Option<String>,
622
        /// The column, by name or id (default: the first)
623
        #[arg(long, short)]
624
        column: Option<String>,
625
    },
626
    /// Move a card to another column (by name or id), or with --from every
627
    /// card of a column at once
628
    Move {
629
        number: i64,
630
        /// The card (its id); leave it out with --from
631
        card: Option<i64>,
632
        #[arg(long, short)]
633
        column: String,
634
        /// Move every card of this column (#289)
635
        #[arg(long, conflicts_with = "card")]
636
        from: Option<String>,
637
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
638
        #[arg(long, value_delimiter = ',', requires = "from")]
639
        except: Vec<String>,
640
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
641
        #[arg(long, value_delimiter = ',', requires = "from")]
642
        state: Vec<String>,
643
        /// With --from: say what would move, and move nothing
644
        #[arg(long, requires = "from")]
645
        dry_run: bool,
646
    },
647
    /// Archive a column's cards: off the board, kept and restorable (#293)
648
    Archive {
649
        number: i64,
650
        /// The column, by name or id
651
        #[arg(long)]
652
        from: String,
653
        /// Only cards that joined the column more than this long ago (14d, or 14)
654
        #[arg(long)]
655
        older: Option<String>,
656
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
657
        #[arg(long, value_delimiter = ',')]
658
        except: Vec<String>,
659
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
660
        #[arg(long, value_delimiter = ',')]
661
        state: Vec<String>,
662
        /// Say what would be archived, and archive nothing
663
        #[arg(long)]
664
        dry_run: bool,
665
    },
666
    /// Put an archived card back at the end of its column
667
    Restore { number: i64, card: i64 },
668
    /// Take a card off a board
669
    Remove { number: i64, card: i64 },
670
}
671
672
#[derive(Subcommand)]
673
enum MilestoneCmd {
674
    /// The repository's milestones
675
    List,
676
    /// Create a milestone, or change the one of that title (triage)
677
    Create {
678
        title: String,
679
        #[arg(long, short, default_value = "")]
680
        description: String,
681
        /// Due date, YYYY-MM-DD
682
        #[arg(long)]
683
        due: Option<String>,
684
    },
685
    /// Change a milestone's title, description or due date (triage)
686
    Edit {
687
        title: String,
688
        #[arg(long, short)]
689
        rename: Option<String>,
690
        #[arg(long, short)]
691
        description: Option<String>,
692
        /// Due date, YYYY-MM-DD ("" for none)
693
        #[arg(long)]
694
        due: Option<String>,
695
    },
696
    /// Close a milestone
697
    Close { title: String },
698
    /// Reopen a milestone
699
    Reopen { title: String },
700
}
701
702
/// Labels to put on or take off an issue or proposal.
703
#[derive(clap::Args)]
704
struct LabelChange {
705
    number: i64,
706
    /// A label to add (repeatable)
707
    #[arg(long, short)]
708
    add: Vec<String>,
709
    /// A label to take off (repeatable)
710
    #[arg(long, short)]
711
    remove: Vec<String>,
712
}
713
714
impl LabelChange {
715
    /// The set after the change, from the one there now.
7160×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
7170×
        if self.add.is_empty() && self.remove.is_empty() {
7180×
            bail!("say what to change: --add NAME or --remove NAME");
7190×
        }
7200×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
7210×
        for a in &self.add {
7220×
            if !names.contains(a) {
7230×
                names.push(a.clone());
7240×
            }
725
        }
7260×
        Ok(names)
7270×
    }
728
}
729
7300×
fn label_names(labels: &[String]) -> String {
7310×
    if labels.is_empty() {
7320×
        ui::dim("no labels")
733
    } else {
7340×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
735
    }
7360×
}
737
738
#[derive(Subcommand)]
739
enum CoverageCmd {
740
    /// Upload an LCOV or Cobertura report measured on this machine, as the
741
    /// coverage of a bookmark's current state (default: the default
742
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
743
    /// not measured by a runner, and sets no check from it
744
    Upload {
745
        file: std::path::PathBuf,
746
        #[arg(long)]
747
        bookmark: Option<String>,
748
        /// A change's full hash
749
        #[arg(long, conflicts_with = "bookmark")]
750
        change: Option<String>,
751
    },
752
}
753
754
#[derive(Subcommand)]
755
enum RunCmd {
756
    /// Recent runs, newest first
757
    List {
758
        #[arg(long, default_value_t = 20)]
759
        limit: i64,
760
    },
761
    /// A run and its jobs (default: the newest run)
762
    View {
763
        /// The run (default: the newest, or the newest of --bookmark)
764
        number: Option<i64>,
765
        /// With no number: the newest run of this bookmark
766
        #[arg(long, conflicts_with = "number")]
767
        bookmark: Option<String>,
768
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
769
        #[arg(long)]
770
        timings: bool,
771
    },
772
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
773
    Start {
774
        #[arg(long)]
775
        bookmark: Option<String>,
776
        /// A change's full hash
777
        #[arg(long, conflicts_with = "bookmark")]
778
        change: Option<String>,
779
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
780
        #[arg(long = "job", value_name = "NAME")]
781
        jobs: Vec<String>,
782
        /// Wait for the run and exit 1 unless it passes
783
        #[arg(long)]
784
        watch: bool,
785
    },
786
    /// Follow a run until it finishes (default: the newest run); exit 1 unless it passes
787
    Watch {
788
        /// The run (default: the newest, or the newest of --bookmark) (#367)
789
        number: Option<i64>,
790
        /// With no number: the newest run of this bookmark
791
        #[arg(long, conflicts_with = "number")]
792
        bookmark: Option<String>,
793
    },
794
    /// A job's log
795
    Log { number: i64, job: String },
796
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
797
    Report {
798
        number: i64,
799
        job: String,
800
        #[command(flatten)]
801
        pick: ReportPick,
802
    },
803
    /// Run a finished run's state again; with --job, only that job (and the
804
    /// jobs that depend on it) in the same run
805
    Rerun {
806
        number: i64,
807
        #[arg(long)]
808
        job: Option<String>,
809
    },
810
    /// Cancel a run still queued or running; its running jobs are stopped
811
    Cancel { number: i64 },
812
    /// Approve a job that waits for a person (oxygenflow#57)
813
    Approve {
814
        number: i64,
815
        #[arg(long)]
816
        job: String,
817
    },
818
    /// Reject a job that waits for a person: it ends cancelled
819
    Reject {
820
        number: i64,
821
        #[arg(long)]
822
        job: String,
823
    },
824
}
825
826
/// Which report of a job, and what of it to show.
827
#[derive(clap::Args)]
828
struct ReportPick {
829
    /// Which report, when the job published more than one
830
    #[arg(long)]
831
    name: Option<String>,
832
    /// What it holds: its metrics, context and files
833
    #[arg(long, conflicts_with = "file")]
834
    list: bool,
835
    /// One file of it (`data/frames.csv`), as published
836
    #[arg(long, value_name = "PATH")]
837
    file: Option<String>,
838
    /// Write the file here instead of to stdout
839
    #[arg(long, short, value_name = "FILE", requires = "file")]
840
    output: Option<std::path::PathBuf>,
841
}
842
843
#[derive(Subcommand)]
844
enum ReportCmd {
845
    /// The newest run of each report, newest first
846
    List {
847
        /// Only runs on this bookmark
848
        #[arg(long)]
849
        bookmark: Option<String>,
850
    },
851
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
852
    Show {
853
        report: String,
854
        #[arg(long, conflicts_with = "bookmark")]
855
        id: Option<i64>,
856
        #[arg(long)]
857
        bookmark: Option<String>,
858
        /// What it holds: its metrics, context and files
859
        #[arg(long, conflicts_with = "file")]
860
        list: bool,
861
        /// One file of it, as published
862
        #[arg(long, value_name = "PATH")]
863
        file: Option<String>,
864
        /// Write the file here instead of to stdout
865
        #[arg(long, short, value_name = "FILE", requires = "file")]
866
        output: Option<std::path::PathBuf>,
867
    },
868
}
869
870
#[derive(Subcommand)]
871
enum TagCmd {
872
    /// Tags, newest name first
873
    List,
874
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
875
    /// delegate (as `oxy tag create` and a push would be)
876
    Create {
877
        name: String,
878
        /// What to tag (default: the default bookmark)
879
        #[arg(long)]
880
        target: Option<String>,
881
        #[arg(long, short)]
882
        message: Option<String>,
883
    },
884
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
885
    /// their next fetch, and the name is never used again. Refused while a
886
    /// release uses the tag
887
    Delete {
888
        name: String,
889
        /// Why, recorded with the withdrawal
890
        #[arg(long, short)]
891
        reason: Option<String>,
892
    },
893
}
894
895
#[derive(Subcommand)]
896
enum ReleaseCmd {
897
    /// Releases, newest first
898
    List,
899
    /// Create a release on an existing tag
900
    Create {
901
        tag: String,
902
        #[arg(long, short)]
903
        title: Option<String>,
904
        /// Notes in Markdown (default: generated from the changes since the previous release)
905
        #[arg(long, short)]
906
        notes: Option<String>,
907
        #[arg(long)]
908
        prerelease: bool,
909
    },
910
    /// Change a release's title, notes or prerelease flag
911
    Edit {
912
        tag: String,
913
        #[arg(long, short)]
914
        title: Option<String>,
915
        /// New notes in Markdown ("-" reads them from stdin)
916
        #[arg(long, short)]
917
        notes: Option<String>,
918
        /// Mark it a prerelease (true) or not (false)
919
        #[arg(long)]
920
        prerelease: Option<bool>,
921
    },
922
    /// Attach files to a release
923
    Upload { tag: String, files: Vec<std::path::PathBuf> },
924
    /// The release's trust report: signatures, builds, receipts and audit
925
    Trust { tag: String },
926
}
927
92853×
fn main() {
929
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
930
    // other command-line tools do, instead of panicking on the failed
931
    // write (oxygenhub#92).
932
    #[cfg(unix)]
93353×
    unsafe {
93453×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
93553×
    }
93653×
    let cli = Cli::parse();
93753×
    ui::init(cli.plain);
93853×
    match run(cli) {
93945×
        Ok(code) => std::process::exit(code),
9408×
        Err(e) => {
9418×
            eprintln!("{} {e:#}", ui::bad("error:"));
9428×
            std::process::exit(2);
943
        }
944
    }
945
}
946
94722×
fn enc(s: &str) -> String {
94822×
    let mut out = String::new();
949109×
    for b in s.bytes() {
950109×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
951108×
            out.push(b as char);
952108×
        } else {
9531×
            out.push_str(&format!("%{b:02X}"));
9541×
        }
955
    }
95622×
    out
95722×
}
958
95953×
fn run(cli: Cli) -> Result<i32> {
96053×
    let cfg = Config::load()?;
9611×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
9621×
        return login(cfg, url, token.clone(), ca.clone());
96352×
    }
96452×
    let here = std::env::current_dir()?;
96552×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
96651×
    let c = Client::new(&t)?;
96751×
    let json = cli.json;
9680×
    match cli.cmd {
969
        Cmd::Auth { cmd: AuthCmd::Status } => {
9700×
            let me: serde_json::Value = c.get("/user")?;
9710×
            if json {
9720×
                println!("{me}");
9730×
            } else {
9740×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
9750×
            }
9760×
            Ok(0)
977
        }
9780×
        Cmd::Auth { .. } => unreachable!(),
9792×
        Cmd::Mcp { allow_write } => {
9802×
            t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?;
9812×
            mcp::serve(c, t, allow_write)
982
        }
9832×
        Cmd::Api { path, method, data } => {
9842×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
985
            // The method applies with or without a body (#75): without one, a
986
            // GET reads, anything else sends an empty object.
9872×
            let text = match data {
9880×
                Some(d) => c.send_text(
9890×
                    &method.to_uppercase(),
9900×
                    &path,
9910×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
9920×
                )?,
9932×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
9940×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
995
            };
9962×
            println!("{text}");
9972×
            Ok(0)
998
        }
999
        Cmd::Repo { cmd: RepoCmd::View } => {
10001×
            let path = t.repo_path()?;
10011×
            if json {
10020×
                println!("{}", c.get_text(&path)?);
10030×
                return Ok(0);
10041×
            }
10051×
            let r: serde_json::Value = c.get(&path)?;
10061×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
10071×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
10081×
                println!("{d}");
10091×
            }
10101×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
10111×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
10121×
            Ok(0)
1013
        }
101418×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
10154×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
10163×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
10170×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
10180×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
10190×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
10200×
            let mut body = serde_json::json!({ "content": content });
10210×
            if let Some(b) = bookmark {
10220×
                body["bookmark"] = b.into();
10230×
            }
10240×
            if let Some(ch) = change {
10250×
                body["change"] = ch.into();
10260×
            }
10270×
            let base = t.repo_path()?;
10280×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
10290×
            if json {
10300×
                println!("{}", serde_json::to_string(&r)?);
1031
            } else {
10320×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
10330×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
10340×
                println!(
1035
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
10360×
                    ui::ok("✔"),
1037
                    r.lines_hit,
1038
                    r.lines_found,
1039
                    r.files,
10400×
                    ui::dim(&r.url)
1041
                );
10420×
                if r.dropped > 0 {
10430×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
10440×
                }
1045
            }
10460×
            Ok(0)
1047
        }
10484×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
10490×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
10500×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
10510×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
105210×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
10530×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
10540×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
10550×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
10567×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
1057
    }
105853×
}
1059
1060
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
10612×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
10622×
    Ok(match v {
10630×
        None => None,
10642×
        Some("on") => Some(Some(true)),
10652×
        Some("off") => Some(Some(false)),
10662×
        Some("inherit") => Some(None),
10671×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1068
    })
10692×
}
1070
1071
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
10727×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
10737×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
10741×
    Ok(match kind {
10757×
        "site" if name.is_empty() => ("site".into(), String::new()),
10766×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
10775×
        "group" => {
10783×
            let g = all
10793×
                .groups
10803×
                .iter()
10813×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
10823×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
10833×
            ("group".into(), g.id.to_string())
1084
        }
10852×
        "runner" => {
10861×
            let r = all
10871×
                .runners
10881×
                .iter()
10891×
                .find(|r| r.id.to_string() == name || r.name == name)
10901×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
10910×
            ("runner".into(), r.id.to_string())
1092
        }
10931×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1094
    })
10957×
}
1096
10970×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
10980×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
10990×
    match cmd {
11000×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1101
        RunnerUpdatesCmd::Show => {
11020×
            println!(
1103
                "{} {}",
11040×
                ui::strong("Builds from"),
11050×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1106
            );
11070×
            for h in &all.holds {
11080×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
11090×
            }
11100×
            for s in &all.settings {
11110×
                let mut said = vec![];
11120×
                if let Some(u) = s.updates {
11130×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
11140×
                }
11150×
                if let Some(ch) = &s.channel {
11160×
                    said.push(format!("channel {ch}"));
11170×
                }
11180×
                if let Some(w) = &s.window {
11190×
                    said.push(format!("window {w} UTC"));
11200×
                }
11210×
                if let Some(d) = s.dry_run {
11220×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
11230×
                }
11240×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
11250×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1126
            }
11270×
            for g in &all.groups {
11280×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
11290×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
11300×
                if let Some(w) = g.wave {
11310×
                    what.push_str(&format!(", wave {w}"));
11320×
                }
11330×
                println!(
1134
                    "  group {} ({what}): {}",
11350×
                    ui::strong(&g.name),
11360×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1137
                );
1138
            }
11390×
            for r in &all.runners {
11400×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
11410×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1142
            }
1143
        }
11440×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
11450×
            let (scope, key) = update_scope(&scope, &all)?;
11460×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
11470×
                scope: scope.clone(),
11480×
                key: key.clone(),
11490×
                ..Default::default()
11500×
            });
11510×
            if let Some(u) = switch(updates.as_deref())? {
11520×
                s.updates = u;
11530×
            }
11540×
            if let Some(d) = switch(dry_run.as_deref())? {
11550×
                s.dry_run = d;
11560×
            }
11570×
            if let Some(ch) = channel {
11580×
                s.channel = Some(ch).filter(|c| c != "inherit");
11590×
            }
11600×
            if let Some(w) = window {
11610×
                s.window = Some(w).filter(|w| w != "inherit");
11620×
            }
11630×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
11640×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1165
        }
11660×
        RunnerUpdatesCmd::Lift { version } => {
11670×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
11680×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1169
        }
1170
    }
11710×
    Ok(0)
11720×
}
1173
1174
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
11757×
fn drop_id(s: &str) -> Result<String> {
11767×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1177144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
11781×
        bail!("{s:?} is not a drop's id or address");
11796×
    }
11806×
    Ok(id.to_ascii_lowercase())
11817×
}
1182
11832×
fn drop_line(d: &hub_api::Drop) -> String {
11842×
    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() };
11854×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
11862×
    format!(
1187
        "{} {} {}{}",
11882×
        ui::dim(&d.id),
11892×
        ui::strong(&title),
11902×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
11912×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1192
    )
11932×
}
1194
1195
/// `oh drop star|unstar` (oxygenhub#349).
11960×
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
11970×
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
11980×
    if json {
11990×
        println!("{}", serde_json::to_string(&s)?);
1200
    } else {
12010×
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1202
    }
12030×
    Ok(())
12040×
}
1205
12067×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
12077×
    match cmd {
12081×
        DropCmd::Create { files, secret, description, title } => {
12091×
            let mut out = Vec::with_capacity(files.len());
12102×
            for f in &files {
12112×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
12122×
                let content =
12132×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
12142×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1215
            }
12161×
            let new =
12171×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
12181×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
12191×
            if json {
12201×
                println!("{}", serde_json::to_string(&d)?);
1221
            } else {
12220×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
12230×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1224
            }
1225
        }
12262×
        DropCmd::List { user } => {
12272×
            let path = match &user {
12281×
                Some(u) => format!("/users/{}/drops", enc(u)),
12291×
                None => "/drops".to_string(),
1230
            };
12312×
            if json {
12321×
                println!("{}", c.get_text(&path)?);
12331×
                return Ok(0);
12341×
            }
12351×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
12361×
            if list.is_empty() {
12370×
                println!("{}", ui::dim("No drops."));
12381×
            }
12391×
            for d in &list {
12401×
                println!("{}", drop_line(d));
12411×
            }
1242
        }
12433×
        DropCmd::View { id, file } => {
12443×
            let path = format!("/drops/{}", drop_id(&id)?);
12453×
            if json && file.is_none() {
12460×
                println!("{}", c.get_text(&path)?);
12470×
                return Ok(0);
12483×
            }
12493×
            let d: hub_api::Drop = c.get(&path)?;
12502×
            if let Some(name) = file {
12512×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
12521×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
12531×
                print!("{content}");
12541×
                return Ok(0);
12551×
            }
12561×
            println!("{}", drop_line(&d));
12571×
            if !d.description.is_empty() {
12581×
                println!("{}", d.description);
12591×
            }
12601×
            println!("{}", ui::kv("url", &d.url));
12611×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
12622×
            for f in &d.files {
12632×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
12642×
                match &f.content {
12652×
                    Some(text) => {
12662×
                        print!("{text}");
12672×
                        if !text.ends_with('\n') && !text.is_empty() {
12680×
                            println!();
12692×
                        }
1270
                    }
12710×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1272
                }
1273
            }
1274
        }
12751×
        DropCmd::Delete { id } => {
12761×
            let id = drop_id(&id)?;
12771×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
12781×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1279
        }
12800×
        DropCmd::Fork { id } => {
12810×
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
12820×
            if json {
12830×
                println!("{}", serde_json::to_string(&d)?);
12840×
            } else {
12850×
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
12860×
            }
1287
        }
12880×
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
12890×
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
12900×
        DropCmd::Comments { id } => {
12910×
            let path = format!("/drops/{}/comments", drop_id(&id)?);
12920×
            if json {
12930×
                println!("{}", c.get_text(&path)?);
12940×
                return Ok(0);
12950×
            }
12960×
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
12970×
            if list.is_empty() {
12980×
                println!("{}", ui::dim("No comments."));
12990×
            }
13000×
            for m in &list {
13010×
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
13020×
                println!("{}\n", m.body);
13030×
            }
1304
        }
13050×
        DropCmd::Comment { id, message } => {
13060×
            let m: hub_api::DropComment =
13070×
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
13080×
            if json {
13090×
                println!("{}", serde_json::to_string(&m)?);
13100×
            } else {
13110×
                println!("{} commented (#{})", ui::ok("✔"), m.id);
13120×
            }
1313
        }
1314
    }
13154×
    Ok(0)
13167×
}
1317
1318
/// `30d`, `12h`, `90m` in milliseconds.
13190×
fn duration_ms(s: &str) -> Result<i64> {
13200×
    let s = s.trim();
13210×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
13220×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
13230×
    let per = match unit {
13240×
        "d" => 86_400_000,
13250×
        "h" => 3_600_000,
13260×
        "m" => 60_000,
13270×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1328
    };
13290×
    if n <= 0 {
13300×
        bail!("a grant must last some time");
13310×
    }
13320×
    Ok(n * per)
13330×
}
1334
13350×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1336
    use oxy_core::cert::{Grant, SignedGrant};
1337
    use oxy_core::identity::{Identity, Scope};
13380×
    match cmd {
13390×
        AgentCmd::Grant { name, scope, lasts } => {
13400×
            let home = oxy_core::repo::default_home();
13410×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
13420×
                format!(
1343
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
13440×
                    home.display()
1345
                )
13460×
            })?;
13470×
            let me: serde_json::Value = c.get("/user")?;
13480×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
13490×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
13500×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
13510×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
13520×
            let grant = Grant {
13530×
                grantor: me_id.hash(),
13540×
                subject: format!("agent:{name}@{username}"),
13550×
                issuer: hub.hash(),
13560×
                scope,
13570×
                not_before: (now - 60_000) as u64,
13580×
                expires: (now + duration_ms(&lasts)?) as u64,
1359
            };
13600×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
13610×
            let r: serde_json::Value =
13620×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
13630×
            if json {
13640×
                println!("{r}");
13650×
                return Ok(0);
13660×
            }
13670×
            println!(
1368
                "{} {} to act for you as {} ({}), until {}",
13690×
                ui::ok("✔ granted"),
13700×
                ui::strong(&name),
13710×
                r["subject"].as_str().unwrap_or(""),
13720×
                r["scope"].as_str().unwrap_or(""),
13730×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1374
            );
13750×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
13760×
            println!(
1377
                "  {}",
13780×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1379
            );
13800×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
13810×
            Ok(0)
1382
        }
1383
        AgentCmd::List => {
13840×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
13850×
            if json {
13860×
                println!("{}", serde_json::to_string(&grants)?);
13870×
                return Ok(0);
13880×
            }
13890×
            if grants.is_empty() {
13900×
                println!("{}", ui::dim("no agent grants"));
13910×
            }
13920×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
13930×
            for g in grants {
13940×
                let state = if g["revoked_ms"].is_i64() {
13950×
                    ui::bad("revoked")
13960×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
13970×
                    ui::dim("ended")
1398
                } else {
13990×
                    ui::ok("live")
1400
                };
14010×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
14020×
                println!(
1403
                    "#{:<4} {:<8} {} · {} · until {} · {}",
14040×
                    g["id"],
1405
                    state,
14060×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
14070×
                    g["scope"].as_str().unwrap_or(""),
14080×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
14090×
                    ui::dim(&used)
1410
                );
1411
            }
14120×
            Ok(0)
1413
        }
14140×
        AgentCmd::Revoke { id } => {
14150×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
14160×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
14170×
            Ok(0)
1418
        }
1419
    }
14200×
}
1421
14221×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
14231×
    let hub = url.trim_end_matches('/').to_string();
14241×
    let token = match token.as_deref() {
14251×
        Some("-") => {
14260×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
14270×
            let mut line = String::new();
14280×
            std::io::stdin().read_line(&mut line)?;
14290×
            line.trim().to_string()
1430
        }
14311×
        Some(t) => t.to_string(),
14320×
        None => device_sign_in(&hub, ca.clone())?,
1433
    };
14341×
    if token.is_empty() {
14350×
        bail!("no token given");
14361×
    }
14371×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
14381×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
14391×
    let account = me["username"].as_str().unwrap_or("?");
1440
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
14411×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
14421×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
14431×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
14441×
    cfg.default_hub = Some(hub.clone());
14451×
    cfg.save()?;
14461×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
14471×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
14481×
    Ok(0)
14491×
}
1450
1451
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1452
/// it on the web, and the token arrives here.
14530×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
14540×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
14550×
    let c = Client::new(&t)?;
14560×
    let host = std::fs::read_to_string("/etc/hostname")
14570×
        .ok()
14580×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
14590×
        .map(|h| h.trim().to_string())
14600×
        .filter(|h| !h.is_empty());
14610×
    let client = match host {
14620×
        Some(h) => format!("oh on {h}"),
14630×
        None => "oh".to_string(),
1464
    };
14650×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
14660×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
14670×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
14680×
    if code != 200 {
14690×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
14700×
    }
14710×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
14720×
    let user = v["user_code"].as_str().unwrap_or("?");
14730×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
14740×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
14750×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
14760×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
14770×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1478
    loop {
14790×
        std::thread::sleep(std::time::Duration::from_secs(interval));
14800×
        if std::time::Instant::now() > deadline {
14810×
            bail!("the code expired before it was approved; run oh auth login again");
14820×
        }
14830×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
14840×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
14850×
        if code == 200 {
14860×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
14870×
        }
14880×
        match v["error"].as_str() {
14890×
            Some("authorization_pending") => {}
14900×
            Some("slow_down") => interval += 5,
14910×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
14920×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
14930×
            _ => bail!("signing in: HTTP {code}: {body}"),
1494
        }
1495
    }
14960×
}
1497
149810×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
149910×
    match (body, file) {
15003×
        (Some(b), _) => Ok(b),
15011×
        (None, Some(f)) if f == "-" => {
15020×
            let mut s = String::new();
15030×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
15040×
            Ok(s)
1505
        }
15061×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
15076×
        (None, None) => Ok(String::new()),
1508
    }
150910×
}
1510
15113×
fn issue_line(i: &Issue) -> String {
15123×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
15133×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
15143×
    format!(
1515
        "{glyph} {} {}{}{}",
15163×
        ui::dim(&format!("#{}", i.number)),
1517
        i.title,
15183×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
15193×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1520
    )
15213×
}
1522
152318×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
152418×
    let base = t.repo_path()?;
152518×
    match cmd {
15263×
        IssueCmd::List { state } => {
15273×
            let path = format!("{base}/issues?state={}", enc(&state));
15283×
            if json {
15291×
                println!("{}", c.get_text(&path)?);
15301×
                return Ok(0);
15312×
            }
15322×
            let list: Vec<Issue> = c.get(&path)?;
15332×
            if list.is_empty() {
15341×
                println!("{}", ui::dim(&format!("No {state} issues.")));
15351×
            }
15362×
            for i in &list {
15372×
                println!("{}", issue_line(i));
15382×
            }
1539
        }
15402×
        IssueCmd::View { number } => {
15412×
            let path = format!("{base}/issues/{number}");
15422×
            if json {
15431×
                println!("{}", c.get_text(&path)?);
15441×
                return Ok(0);
15451×
            }
15461×
            let i: Issue = c.get(&path)?;
15471×
            println!("{}", issue_line(&i));
15481×
            if !i.body.trim().is_empty() {
15491×
                println!("\n{}\n", i.body.trim_end());
15501×
            }
15511×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
15522×
            for cm in comments {
15532×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
15542×
            }
15551×
            println!("{}", ui::dim(&i.url));
1556
        }
15574×
        IssueCmd::Create { title, body, body_file, label, project, column, attach } => {
15584×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
15594×
            let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None };
15604×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
15613×
            if json {
15621×
                println!("{}", serde_json::to_string(&i)?);
15632×
            } else {
15642×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
15652×
            }
15663×
            if let Some(n) = project {
15671×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
15681×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
15691×
                if !json {
15701×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
15711×
                }
15722×
            }
1573
        }
15741×
        IssueCmd::Close { number, reason, comment } => {
15751×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
15761×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
15771×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1578
        }
15790×
        IssueCmd::Reopen { number, comment } => {
15800×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
15810×
            let i: Issue =
15820×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
15830×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1584
        }
15853×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
15863×
            let body = match (&body, &body_file) {
15873×
                (None, None) => None,
15880×
                _ => Some(body_of(body, body_file)?),
1589
            };
15903×
            let labels = if no_labels {
15911×
                Some(Vec::new())
15922×
            } else if label.is_empty() {
15931×
                None
1594
            } else {
15951×
                Some(label)
1596
            };
15973×
            let assignees = if no_assignees {
15981×
                Some(Vec::new())
15992×
            } else if assignee.is_empty() {
16001×
                None
1601
            } else {
16021×
                Some(assignee)
1603
            };
16043×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
16051×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
16062×
            }
16072×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
16082×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
16092×
            if json {
16101×
                println!("{}", serde_json::to_string(&i)?);
16111×
            } else {
16121×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
16131×
            }
1614
        }
16150×
        IssueCmd::Label(change) => {
16160×
            let path = format!("{base}/issues/{}", change.number);
16170×
            let now: Issue = c.get(&path)?;
16180×
            let labels = change.apply(&now.labels)?;
16190×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
16200×
            let i: Issue = c.send("PATCH", &path, &edit)?;
16210×
            if json {
16220×
                println!("{}", serde_json::to_string(&i)?);
16230×
            } else {
16240×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
16250×
            }
1626
        }
16275×
        IssueCmd::Comment { number, body, body_file, attach } => {
16285×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
16294×
            if body.trim().is_empty() {
16301×
                bail!("give the comment with --body, --body-file or --attach");
16313×
            }
16323×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
16333×
            println!("{} commented on #{number}", ui::ok("✔"));
1634
        }
1635
    }
163612×
    Ok(0)
163718×
}
1638
1639
/// A comment to post with a close or reopen (#368): saying why, in the
1640
/// same command.
1641
#[derive(clap::Args)]
1642
struct StateComment {
1643
    /// Say why, as a comment posted first
1644
    #[arg(long, short)]
1645
    body: Option<String>,
1646
    /// Read the comment from a file ("-" for stdin)
1647
    #[arg(long, short = 'F', conflicts_with = "body")]
1648
    body_file: Option<String>,
1649
    /// Attach a file to the comment (repeatable)
1650
    #[arg(long, short = 'a', value_name = "FILE")]
1651
    attach: Vec<std::path::PathBuf>,
1652
}
1653
1654
impl StateComment {
16551×
    fn post(self, c: &Client, base: &str, path: &str) -> Result<()> {
16561×
        if self.body.is_none() && self.body_file.is_none() && self.attach.is_empty() {
16571×
            return Ok(());
16580×
        }
16590×
        let body = with_attachments(c, base, body_of(self.body, self.body_file)?, &self.attach)?;
16600×
        if !body.trim().is_empty() {
16610×
            c.send_text("POST", path, &NewComment { body, path: None, line: None })?;
16620×
        }
16630×
        Ok(())
16641×
    }
1665
}
1666
1667
/// `number`, or the newest run (of `bookmark`, when given): what a push
1668
/// just started is what one usually wants to follow (#367).
16691×
fn run_or_newest(c: &Client, base: &str, number: Option<i64>, bookmark: Option<&str>) -> Result<i64> {
16701×
    if let Some(n) = number {
16711×
        return Ok(n);
16720×
    }
16730×
    let runs: Vec<FlowRun> = c.get(&format!("{base}/flow/runs?limit=100"))?;
16740×
    runs.iter().filter(|r| bookmark.is_none_or(|b| r.bookmark == b)).map(|r| r.number).max().with_context(|| match bookmark {
16750×
        Some(b) => format!("no runs of {b} among the latest 100"),
16760×
        None => "no runs yet".to_string(),
16770×
    })
16781×
}
1679
1680
/// `body` with each file attached to the repository and linked under it:
1681
/// an image shown in place, anything else a download (#350). Files are
1682
/// uploaded first, so a failed upload leaves nothing half made.
16839×
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> {
16849×
    if files.is_empty() {
16856×
        return Ok(body);
16863×
    }
16873×
    let mut links = Vec::new();
16884×
    for f in files {
16894×
        let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?;
16903×
        let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
16913×
        let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?;
16923×
        let a: hub_api::Attachment =
16933×
            serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?;
16943×
        links.push(a.markdown);
1695
    }
16962×
    let links = links.join("\n\n");
16972×
    Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) })
16989×
}
1699
17001×
fn source_name(s: &hub_api::ProposalSource) -> String {
17011×
    match s {
17021×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
17030×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
17040×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1705
    }
17061×
}
1707
17081×
fn proposal_line(p: &Proposal) -> String {
17091×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
17101×
    let glyph = match state.as_str() {
17111×
        "open" => ui::ok("●"),
17120×
        "draft" => ui::dim("◌"),
17130×
        "landed" => ui::strong("✔"),
17140×
        _ => ui::dim("○"),
1715
    };
17161×
    format!(
1717
        "{glyph} {} {} {}{}",
17181×
        ui::dim(&format!("#{}", p.number)),
1719
        p.title,
17201×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
17211×
        ui::dim(&format!(" · {} · {state}", p.author))
1722
    )
17231×
}
1724
17254×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
17264×
    let base = t.repo_path()?;
17274×
    match cmd {
17280×
        ProposalCmd::List { state, limit } => {
17290×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
17300×
            if json {
17310×
                println!("{}", c.get_text(&path)?);
17320×
                return Ok(0);
17330×
            }
17340×
            let list: Vec<Proposal> = c.get(&path)?;
17350×
            if list.is_empty() {
17360×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
17370×
            }
17380×
            for p in &list {
17390×
                println!("{}", proposal_line(p));
17400×
            }
1741
        }
17421×
        ProposalCmd::View { number } => {
17431×
            let path = format!("{base}/proposals/{number}");
17441×
            if json {
17450×
                println!("{}", c.get_text(&path)?);
17460×
                return Ok(0);
17471×
            }
17481×
            let p: Proposal = c.get(&path)?;
17491×
            println!("{}", proposal_line(&p));
17501×
            if !p.body.trim().is_empty() {
17510×
                println!("\n{}\n", p.body.trim_end());
17521×
            }
17531×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
17541×
            for ch in &p.changes {
17551×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
17561×
            }
17571×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
17581×
            if p.landable {
17591×
                println!("{} can land", ui::ok("✔"));
17601×
            } else {
17610×
                for b in &p.blockers {
17620×
                    println!("{} {b}", ui::bad("✘"));
17630×
                }
1764
            }
17651×
            if p.conflicted {
17660×
                println!("{} landing it would leave conflicts", ui::bad("!"));
17671×
            }
17681×
            println!("{}", ui::dim(&p.url));
1769
        }
17701×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
17711×
            let target = match into {
17720×
                Some(i) => i,
17731×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1774
            };
17751×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
17761×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
17771×
            if json {
17780×
                println!("{}", serde_json::to_string(&p)?);
17791×
            } else {
17801×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
17811×
            }
1782
        }
17830×
        ProposalCmd::Edit { number, title, body, body_file } => {
17840×
            let body = match (&body, &body_file) {
17850×
                (None, None) => None,
17860×
                _ => Some(body_of(body, body_file)?),
1787
            };
17880×
            if title.is_none() && body.is_none() {
17890×
                bail!("say what to change: --title, --body or --body-file");
17900×
            }
17910×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
17920×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
17930×
            if json {
17940×
                println!("{}", serde_json::to_string(&p)?);
17950×
            } else {
17960×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
17970×
            }
1798
        }
17990×
        ProposalCmd::Label(change) => {
18000×
            let path = format!("{base}/proposals/{}", change.number);
18010×
            let now: Proposal = c.get(&path)?;
18020×
            let labels = change.apply(&now.labels)?;
18030×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
18040×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
18050×
            if json {
18060×
                println!("{}", serde_json::to_string(&p)?);
18070×
            } else {
18080×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
18090×
            }
1810
        }
18110×
        ProposalCmd::Comment { number, body, body_file } => {
18120×
            let body = body_of(body, body_file)?;
18130×
            if body.trim().is_empty() {
18140×
                bail!("give the comment with --body or --body-file");
18150×
            }
18160×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
18170×
            println!("{} commented on #{number}", ui::ok("✔"));
1818
        }
18190×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
18200×
            let path = format!("{base}/proposals/{number}/auto-land");
18210×
            let p: Proposal =
18220×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
18230×
            if json {
18240×
                println!("{}", serde_json::to_string(&p)?);
18250×
            } else if p.landed.is_some() {
18260×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
18270×
            } else if p.auto_land.is_some() {
18280×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
18290×
            } else {
18300×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
18310×
            }
1832
        }
18332×
        ProposalCmd::Land { number, over_checks, .. } => {
18342×
            let body = match &over_checks {
18350×
                Some(r) => serde_json::json!({ "over_checks": r }),
18362×
                None => serde_json::json!({}),
1837
            };
18382×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
18391×
            if json {
18400×
                println!("{}", serde_json::to_string(&p)?);
18411×
            } else {
18421×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
18431×
            }
1844
        }
18450×
        ProposalCmd::Close { number, message } => {
18460×
            if let Some(body) = message {
18470×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
18480×
            }
18490×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
18500×
            if json {
18510×
                println!("{}", serde_json::to_string(&p)?);
18520×
            } else {
18530×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
18540×
            }
1855
        }
18560×
        ProposalCmd::Reopen { number } => {
18570×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
18580×
            if json {
18590×
                println!("{}", serde_json::to_string(&p)?);
18600×
            } else {
18610×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
18620×
            }
1863
        }
18640×
        ProposalCmd::Ready { number, undo } => {
18650×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
18660×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
18670×
            if json {
18680×
                println!("{}", serde_json::to_string(&p)?);
18690×
            } else if undo {
18700×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
18710×
            } else {
18720×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
18730×
            }
1874
        }
18750×
        ProposalCmd::Checks { number } => {
18760×
            let path = format!("{base}/proposals/{number}/checks");
18770×
            if json {
18780×
                println!("{}", c.get_text(&path)?);
18790×
                return Ok(0);
18800×
            }
18810×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
18820×
            if checks.is_empty() {
18830×
                println!("{}", ui::dim("No checks yet."));
18840×
            }
18850×
            for ch in checks {
18860×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
18870×
            }
1888
        }
1889
    }
18903×
    Ok(0)
18914×
}
1892
18931×
fn run_line(r: &FlowRun) -> String {
18941×
    let what =
18951×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
18961×
    format!(
1897
        "{} {} {} {}",
18981×
        ui::status(&r.status),
18991×
        ui::dim(&format!("#{}", r.number)),
1900
        what,
19011×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1902
    )
19031×
}
1904
19051×
fn print_run(r: &FlowRun, timings: bool) {
19061×
    println!("{}", run_line(r));
19071×
    for j in &r.jobs {
19081×
        let dur = match (j.started_ms, j.finished_ms) {
19090×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
19101×
            _ => String::new(),
1911
        };
19121×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
19131×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1914
        // Why a queued job no runner can take waits (oxygenhub#28), and
1915
        // why a job ran where it did (oxygenflow#42).
19161×
        if j.status == "queued" && !j.waiting.is_empty() {
19170×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
19181×
        } else if !j.placed.is_empty() {
19190×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
19201×
        }
19211×
        if timings {
19220×
            let t = timing_line(j);
19230×
            if !t.is_empty() {
19240×
                println!("    {}", ui::dim(&t));
19250×
            }
19261×
        }
1927
    }
19281×
    if !r.error.is_empty() {
19290×
        println!("{}", ui::bad(&r.error));
19301×
    }
19311×
    println!("{}", ui::dim(&r.url));
19321×
}
1933
1934
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
19353×
fn took(ms: i64) -> String {
19363×
    match ms {
19373×
        ..=999 => format!("{ms} ms"),
19382×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
19391×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1940
    }
19413×
}
1942
1943
/// MiB as a person reads them.
19442×
fn mib(m: i64) -> String {
19452×
    if m >= 1024 {
19461×
        format!("{:.1} GiB", m as f64 / 1024.0)
1947
    } else {
19481×
        format!("{m} MiB")
1949
    }
19502×
}
1951
1952
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1953
/// phase its runner reported, and the most disk and memory it took.
19542×
fn timing_line(j: &FlowJob) -> String {
19552×
    let mut parts = vec![];
19562×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
19571×
        parts.push(format!("waited {}", took((s - q).max(0))));
19581×
    }
19592×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
19602×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
19612×
        .into_iter()
19624×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
19632×
        .collect();
19642×
    if !peaks.is_empty() {
19651×
        parts.push(format!("peak {}", peaks.join(", ")));
19661×
    }
19672×
    parts.join(" · ")
19682×
}
1969
1970
/// A report's path, its segments encoded and its slashes kept.
19711×
fn enc_path(path: &str) -> String {
19721×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
19731×
}
1974
1975
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1976
/// files are at `files(path)`. By default its report.toml; with `list`
1977
/// what it holds; with `file` one file, to stdout or `output`.
19780×
fn show_report(
19790×
    c: &Client,
19800×
    at: &str,
19810×
    files: impl Fn(&str) -> String,
19820×
    list: bool,
19830×
    file: Option<String>,
19840×
    output: Option<std::path::PathBuf>,
19850×
    json: bool,
19860×
) -> Result<()> {
1987
    use std::io::Write;
19880×
    if let Some(path) = file {
19890×
        let bytes = c.get_bytes(&files(&path))?;
19900×
        match output {
19910×
            Some(out) => {
19920×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
19930×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
1994
            }
19950×
            None => std::io::stdout().write_all(&bytes)?,
1996
        }
19970×
        return Ok(());
19980×
    }
19990×
    if json {
20000×
        println!("{}", c.get_text(at)?);
20010×
        return Ok(());
20020×
    }
20030×
    if !list {
20040×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
20050×
        return Ok(());
20060×
    }
20070×
    let r: Report = c.get(at)?;
20080×
    print_report(&r);
20090×
    if r.files_expired_ms.is_some() {
20100×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
20110×
    }
20120×
    for f in &r.manifest {
20130×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
20140×
    }
20150×
    println!("{}", ui::dim(&r.url));
20160×
    Ok(())
20170×
}
2018
2019
/// A report's heading, metrics and context.
20200×
fn print_report(r: &Report) {
20210×
    let from = match r.run {
20220×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
20230×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
2024
    };
20250×
    println!(
2026
        "{} {} {}",
20270×
        ui::strong(&r.name),
20280×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
20290×
        ui::dim(&format!("· {from} · {} files", r.files))
2030
    );
20310×
    if !r.summary.is_empty() {
20320×
        println!("  {}", r.summary);
20330×
    }
20340×
    for m in &r.metrics {
20350×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
20360×
        let mut notes = vec![];
20370×
        if !m.better.is_empty() {
20380×
            notes.push(format!("{} is better", m.better));
20390×
        }
20400×
        if let Some(a) = m.fail_above {
20410×
            notes.push(format!("fails above {a}"));
20420×
        }
20430×
        if let Some(b) = m.fail_below {
20440×
            notes.push(format!("fails below {b}"));
20450×
        }
20460×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
20470×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
2048
    }
20490×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
20500×
        let line: Vec<String> =
20510×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
20520×
        println!("  {}", ui::dim(&line.join(" ")));
20530×
    }
20540×
}
2055
2056
/// `oh report …` (oxygenhub#348).
20570×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
20580×
    let base = t.repo_path()?;
20590×
    match cmd {
20600×
        ReportCmd::List { bookmark } => {
20610×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
20620×
            if json {
20630×
                println!("{}", c.get_text(&path)?);
20640×
                return Ok(0);
20650×
            }
20660×
            let list: Vec<Report> = c.get(&path)?;
20670×
            if list.is_empty() {
20680×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
20690×
            }
20700×
            for r in &list {
20710×
                print_report(r);
20720×
            }
2073
        }
20740×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
20750×
            let at = format!("{base}/reports/{}", enc(&report));
20760×
            let query = match (id, bookmark) {
20770×
                (Some(id), _) => format!("?id={id}"),
20780×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
20790×
                (None, None) => String::new(),
2080
            };
20810×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
20820×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
2083
        }
2084
    }
20850×
    Ok(0)
20860×
}
2087
20880×
fn live(status: &str) -> bool {
20890×
    matches!(status, "queued" | "running")
20900×
}
2091
2092
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
20930×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
20940×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
20950×
    if json {
20960×
        println!("{done}");
20970×
    } else {
20980×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
20990×
    }
21000×
    Ok(())
21010×
}
2102
21030×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
21040×
    let path = format!("{base}/flow/runs/{number}");
21050×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2106
    loop {
21070×
        let r: FlowRun = c.get(&path)?;
21080×
        if !json {
21090×
            for j in &r.jobs {
21100×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
21110×
                if seen.get(&j.name) != Some(&shown) {
21120×
                    println!("{} {}", ui::status(&j.status), j.name);
21130×
                    if j.status == "queued" && !j.waiting.is_empty() {
21140×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
21150×
                    }
21160×
                    seen.insert(j.name.clone(), shown);
21170×
                }
2118
            }
21190×
        }
21200×
        if !live(&r.status) {
21210×
            if json {
21220×
                println!("{}", serde_json::to_string(&r)?);
21230×
            } else {
21240×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
21250×
            }
21260×
            return Ok(if r.status == "passed" { 0 } else { 1 });
21270×
        }
21280×
        std::thread::sleep(Duration::from_secs(3));
2129
    }
21300×
}
2131
21323×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
21333×
    let base = t.repo_path()?;
21340×
    match cmd {
21351×
        RunCmd::List { limit } => {
21361×
            let path = format!("{base}/flow/runs?limit={limit}");
21371×
            if json {
21381×
                println!("{}", c.get_text(&path)?);
21391×
                return Ok(0);
21400×
            }
21410×
            let runs: Vec<FlowRun> = c.get(&path)?;
21420×
            if runs.is_empty() {
21430×
                println!("{}", ui::dim("No runs yet."));
21440×
            }
21450×
            for r in &runs {
21460×
                println!("{}", run_line(r));
21470×
            }
2148
        }
21491×
        RunCmd::View { number, bookmark, timings } => {
21501×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
21511×
            let path = format!("{base}/flow/runs/{number}");
21521×
            if json {
21530×
                println!("{}", c.get_text(&path)?);
21540×
                return Ok(0);
21551×
            }
21561×
            print_run(&c.get(&path)?, timings);
2157
        }
21581×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
21591×
            let mut body = match (bookmark, change) {
21600×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
21610×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
21621×
                (None, None) => serde_json::json!({}),
2163
            };
21641×
            if !jobs.is_empty() {
21650×
                body["jobs"] = serde_json::json!(jobs);
21661×
            }
21671×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
21681×
            let n = started["number"].as_i64().context("the hub named no run")?;
21691×
            if !json || !follow {
21701×
                if json {
21710×
                    println!("{started}");
21721×
                } else {
21731×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
21741×
                }
21750×
            }
21761×
            if follow {
21770×
                return watch(c, &base, n, json);
21781×
            }
2179
        }
21800×
        RunCmd::Watch { number, bookmark } => {
21810×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
21820×
            return watch(c, &base, number, json);
2183
        }
21840×
        RunCmd::Log { number, job } => {
21850×
            let mut after = 0;
2186
            loop {
21870×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
21880×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
21890×
                if lines.is_empty() {
21900×
                    break;
21910×
                }
21920×
                for l in &lines {
21930×
                    if json {
21940×
                        println!("{}", serde_json::to_string(l)?);
21950×
                    } else if l.stream == "flow" {
21960×
                        println!("{}", ui::dim(&l.text));
21970×
                    } else {
21980×
                        println!("{}", l.text);
21990×
                    }
2200
                }
22010×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2202
            }
2203
        }
22040×
        RunCmd::Report { number, job, pick } => {
22050×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
22060×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
22070×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
22080×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2209
        }
22100×
        RunCmd::Rerun { number, job: Some(job) } => {
22110×
            let queued: serde_json::Value =
22120×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
22130×
            if json {
22140×
                println!("{queued}");
22150×
            } else {
22160×
                let n = queued["queued"].as_i64().unwrap_or(1);
22170×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
22180×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2219
            }
2220
        }
22210×
        RunCmd::Rerun { number, job: None } => {
22220×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
22230×
            if json {
22240×
                println!("{started}");
22250×
            } else {
22260×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
22270×
            }
2228
        }
22290×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
22300×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
22310×
        RunCmd::Cancel { number } => {
22320×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
22330×
            if json {
22340×
                println!("{done}");
22350×
            } else {
22360×
                println!("{} cancelled run #{number}", ui::ok("✔"));
22370×
            }
2238
        }
2239
    }
22402×
    Ok(0)
22413×
}
2242
22430×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
22440×
    let base = t.repo_path()?;
22450×
    match cmd {
2246
        LabelCmd::List => {
22470×
            let path = format!("{base}/labels");
22480×
            if json {
22490×
                println!("{}", c.get_text(&path)?);
22500×
                return Ok(0);
22510×
            }
22520×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
22530×
            if labels.is_empty() {
22540×
                println!("{}", ui::dim("No labels."));
22550×
            }
22560×
            for l in labels {
22570×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
22580×
            }
2259
        }
22600×
        LabelCmd::Create { name, colour, description } => {
22610×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
22620×
            if json {
22630×
                println!("{}", serde_json::to_string(&l)?);
22640×
            } else {
22650×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
22660×
            }
2267
        }
22680×
        LabelCmd::Delete { name } => {
22690×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
22700×
            println!("{} deleted label {name}", ui::ok("✔"));
2271
        }
2272
    }
22730×
    Ok(0)
22740×
}
2275
22760×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
22770×
    let base = match (&org, site) {
22780×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
22790×
        (None, true) => "/admin/assistants".to_string(),
22800×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2281
    };
22820×
    match cmd {
2283
        AssistantCmd::List => {
22840×
            if json {
22850×
                println!("{}", c.get_text(&base)?);
22860×
                return Ok(0);
22870×
            }
22880×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
22890×
            if list.is_empty() {
22900×
                println!("{}", ui::dim("No assistants."));
22910×
            }
22920×
            for a in list {
22930×
                let state = if a.enabled && !a.off_above {
22940×
                    ui::ok("on")
22950×
                } else if a.off_above {
22960×
                    ui::dim("off above")
2297
                } else {
22980×
                    ui::dim("off")
2299
                };
23000×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
23010×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2302
            }
2303
        }
23040×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
23050×
            let token = match token_env {
23060×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
23070×
                None => String::new(),
2308
            };
23090×
            let body =
23100×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
23110×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
23120×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2313
        }
23140×
        AssistantCmd::Remove { name } => {
23150×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
23160×
            println!("{} removed {name}", ui::ok("✔"));
2317
        }
23180×
        AssistantCmd::Prompt { set } => {
23190×
            let p: hub_api::AssistantPrompt = match set {
23200×
                Some(path) => {
23210×
                    let text = if path.as_os_str() == "-" {
23220×
                        let mut s = String::new();
23230×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
23240×
                        s
2325
                    } else {
23260×
                        std::fs::read_to_string(&path)?
2327
                    };
23280×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2329
                }
23300×
                None => c.get(&format!("{base}/prompt"))?,
2331
            };
23320×
            if json {
23330×
                println!("{}", serde_json::to_string(&p)?);
23340×
                return Ok(0);
23350×
            }
23360×
            for (from, text) in &p.inherited {
23370×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
23380×
            }
23390×
            if p.prompt.is_empty() {
23400×
                println!("{}", ui::dim("No prompt of its own."));
23410×
            } else {
23420×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
23430×
            }
2344
        }
2345
    }
23460×
    Ok(0)
23470×
}
2348
23492×
fn project_line(p: &hub_api::Project) -> String {
23502×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
23512×
    let private = if p.public { "" } else { " · private" };
23522×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
23532×
}
2354
235510×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
235610×
    let owner = match owner {
23570×
        Some(o) => o,
235810×
        None => t.repo()?.0.to_string(),
2359
    };
236010×
    let base = format!("/projects/{}", enc(&owner));
236110×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
23621×
        let p: hub_api::Project =
23631×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
23641×
        if json {
23650×
            println!("{}", serde_json::to_string(&p)?);
23661×
        } else {
23671×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
23681×
        }
23691×
        Ok(())
23701×
    };
23714×
    match cmd {
2372
        ProjectCmd::List => {
23731×
            if json {
23740×
                println!("{}", c.get_text(&base)?);
23750×
                return Ok(0);
23761×
            }
23771×
            let list: Vec<hub_api::Project> = c.get(&base)?;
23781×
            if list.is_empty() {
23790×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
23801×
            }
23811×
            for p in &list {
23821×
                println!("{}", project_line(p));
23831×
            }
2384
        }
23853×
        ProjectCmd::View { number, archived } => {
23863×
            let path = format!("{base}/{number}");
23873×
            let cards = format!("{path}/cards?archived=true");
23883×
            if json {
23892×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
23902×
                return Ok(0);
23911×
            }
23921×
            let mut b: hub_api::Board = c.get(&path)?;
23931×
            if archived {
23940×
                b.columns = c.get(&cards)?;
23951×
            }
23961×
            println!("{}", project_line(&b.project));
23971×
            if !b.project.description.is_empty() {
23981×
                println!("{}", b.project.description);
23991×
            }
24003×
            for col in &b.columns {
24013×
                println!();
24023×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
24033×
                if col.cards.is_empty() {
24041×
                    println!("  {}", ui::dim("(empty)"));
24052×
                }
24063×
                for card in &col.cards {
24072×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
24082×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
24092×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
24102×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
24112×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
24122×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2413
                }
2414
            }
24151×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2416
        }
24171×
        ProjectCmd::Create { title, description, private } => {
24181×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
24191×
            if json {
24200×
                println!("{}", serde_json::to_string(&p)?);
24211×
            } else {
24221×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
24231×
            }
2424
        }
24250×
        ProjectCmd::Column { cmd } => {
24260×
            let col_path = |number: i64, column: &str| format!("{base}/{number}/columns/{}", enc(column));
24270×
            let (number, b, what): (i64, hub_api::Board, String) = match cmd {
24280×
                ColumnCmd::Add { number, name } => {
24290×
                    let b = c.send("POST", &format!("{base}/{number}/columns"), &hub_api::NewColumn { name: name.clone() })?;
24300×
                    (number, b, format!("added column {name}"))
2431
                }
24320×
                ColumnCmd::Rename { number, column, to } => {
24330×
                    let edit = hub_api::ColumnEdit { name: Some(to.clone()), position: None };
24340×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("renamed column {column} to {to}"))
2435
                }
24360×
                ColumnCmd::Move { number, column, to, left, right } => {
24370×
                    let position = match to {
24380×
                        Some(n) => n - 1,
2439
                        None => {
24400×
                            let now: hub_api::Board = c.get(&format!("{base}/{number}"))?;
24410×
                            let at = now
24420×
                                .columns
24430×
                                .iter()
24440×
                                .position(|col| col.id.to_string() == column || col.name.eq_ignore_ascii_case(&column))
24450×
                                .with_context(|| format!("no column {column} on board {number}"))?
2446
                                as i64;
24470×
                            if left {
24480×
                                (at - 1).max(0)
2449
                            } else {
24500×
                                debug_assert!(right);
24510×
                                at + 1
2452
                            }
2453
                        }
2454
                    };
24550×
                    let edit = hub_api::ColumnEdit { name: None, position: Some(position) };
24560×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("moved column {column}"))
2457
                }
24580×
                ColumnCmd::Remove { number, column } => {
24590×
                    (number, c.send("DELETE", &col_path(number, &column), &serde_json::json!({}))?, format!("removed column {column}"))
2460
                }
2461
            };
24620×
            if json {
24630×
                println!("{}", serde_json::to_string(&b)?);
2464
            } else {
24650×
                let order: Vec<&str> = b.columns.iter().map(|col| col.name.as_str()).collect();
24660×
                println!("{} {what} on board {number}: {}", ui::ok("✔"), ui::dim(&order.join(" · ")));
2467
            }
2468
        }
24691×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
24700×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
24710×
        ProjectCmd::Transfer { number, to } => {
24720×
            let p: hub_api::Project =
24730×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
24740×
            if json {
24750×
                println!("{}", serde_json::to_string(&p)?);
24760×
            } else {
24770×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
24780×
            }
2479
        }
24802×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2481
            // The hub names a card's issue as `repo#N` among the owner's
2482
            // repositories.
24832×
            let reference = match reference {
24841×
                None => String::new(),
24851×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
24860×
                    Some((o, rest)) if o == owner => rest.to_string(),
24870×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
24880×
                    None => r,
2489
                },
24901×
                Some(r) => {
24911×
                    let n = r.trim_start_matches('#');
24921×
                    if n.parse::<i64>().is_err() {
24930×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
24941×
                    }
24951×
                    format!("{}#{n}", t.repo()?.1)
2496
                }
2497
            };
24982×
            let note = note.unwrap_or_default();
24992×
            if reference.is_empty() && note.is_empty() {
25000×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
25012×
            }
25021×
            let card: hub_api::ProjectCard =
25032×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
25041×
            if json {
25050×
                println!("{}", serde_json::to_string(&card)?);
2506
            } else {
25071×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2508
            }
2509
        }
25101×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
25111×
            (Some(card), None) => {
25121×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
25131×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2514
            }
25150×
            (None, Some(from)) => {
25160×
                let r: hub_api::CardsMoved = c.send(
25170×
                    "POST",
25180×
                    &format!("{base}/{number}/cards/move"),
25190×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
25200×
                )?;
25210×
                if json {
25220×
                    println!("{}", serde_json::to_string(&r)?);
25230×
                    return Ok(0);
25240×
                }
25250×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
25260×
                for m in &r.moved {
25270×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2528
                }
25290×
                let verb = if dry_run { "would move" } else { "moved" };
25300×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2531
            }
25320×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2533
        },
25340×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
25350×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
25360×
                None => None,
25370×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2538
            };
25390×
            let r: hub_api::CardsArchived = c.send(
25400×
                "POST",
25410×
                &format!("{base}/{number}/cards/archive"),
25420×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
25430×
            )?;
25440×
            if json {
25450×
                println!("{}", serde_json::to_string(&r)?);
25460×
                return Ok(0);
25470×
            }
25480×
            let verb = if dry_run { "would archive" } else { "archived" };
25490×
            for a in &r.archived {
25500×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
25510×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2552
            }
25530×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2554
        }
25550×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
25560×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
25570×
            println!("{} card {card} restored", ui::ok("✔"));
2558
        }
25591×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
25601×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
25611×
            println!("{} card {card} removed", ui::ok("✔"));
2562
        }
2563
    }
25647×
    Ok(0)
256510×
}
2566
25670×
fn milestone_line(m: &hub_api::Milestone) -> String {
25680×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
25690×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
25700×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
25710×
}
2572
25730×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
25740×
    let base = t.repo_path()?;
25750×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
25760×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
25770×
        if json {
25780×
            println!("{}", serde_json::to_string(&m)?);
25790×
        } else {
25800×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
25810×
        }
25820×
        Ok(())
25830×
    };
25840×
    match cmd {
2585
        MilestoneCmd::List => {
25860×
            let path = format!("{base}/milestones");
25870×
            if json {
25880×
                println!("{}", c.get_text(&path)?);
25890×
                return Ok(0);
25900×
            }
25910×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
25920×
            if list.is_empty() {
25930×
                println!("{}", ui::dim("No milestones."));
25940×
            }
25950×
            for m in &list {
25960×
                println!("{}", milestone_line(m));
25970×
            }
2598
        }
25990×
        MilestoneCmd::Create { title, description, due } => {
26000×
            let m: hub_api::Milestone =
26010×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
26020×
            if json {
26030×
                println!("{}", serde_json::to_string(&m)?);
26040×
            } else {
26050×
                println!("{} milestone {}", ui::ok("✔"), m.title);
26060×
            }
2607
        }
26080×
        MilestoneCmd::Edit { title, rename, description, due } => {
26090×
            if rename.is_none() && description.is_none() && due.is_none() {
26100×
                bail!("say what to change: --rename, --description or --due");
26110×
            }
26120×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2613
        }
26140×
        MilestoneCmd::Close { title } => {
26150×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2616
        }
26170×
        MilestoneCmd::Reopen { title } => {
26180×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2619
        }
2620
    }
26210×
    Ok(0)
26220×
}
2623
26240×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
26250×
    let base = t.repo_path()?;
26260×
    match cmd {
2627
        TagCmd::List => {
26280×
            let path = format!("{base}/tags");
26290×
            if json {
26300×
                println!("{}", c.get_text(&path)?);
26310×
                return Ok(0);
26320×
            }
26330×
            let tags: Vec<Tag> = c.get(&path)?;
26340×
            if tags.is_empty() {
26350×
                println!("{}", ui::dim("no tags"));
26360×
            }
26370×
            for t in tags {
26380×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
26390×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
26400×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2641
            }
2642
        }
26430×
        TagCmd::Create { name, target, message } => {
26440×
            let new = hub_api::NewTag { name, target, message };
26450×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
26460×
            if json {
26470×
                println!("{}", serde_json::to_string(&made)?);
26480×
            } else {
26490×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
26500×
            }
2651
        }
26520×
        TagCmd::Delete { name, reason } => {
26530×
            let reason = reason.unwrap_or_default();
26540×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
26550×
            if json {
26560×
                println!("{}", serde_json::json!({ "withdrawn": name }));
26570×
            } else {
26580×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
26590×
            }
2660
        }
2661
    }
26620×
    Ok(0)
26630×
}
2664
26654×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
26664×
    let base = t.repo_path()?;
26674×
    match cmd {
2668
        ReleaseCmd::List => {
26691×
            let path = format!("{base}/releases");
26701×
            if json {
26711×
                println!("{}", c.get_text(&path)?);
26721×
                return Ok(0);
26730×
            }
26740×
            let list: Vec<Release> = c.get(&path)?;
26750×
            if list.is_empty() {
26760×
                println!("{}", ui::dim("No releases."));
26770×
            }
26780×
            for r in &list {
26790×
                println!(
2680
                    "{} {} {}{}",
26810×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
26820×
                    ui::strong(&r.tag),
2683
                    r.title,
26840×
                    ui::dim(&format!(
2685
                        " · {} asset{} · {}",
26860×
                        r.assets.len(),
26870×
                        if r.assets.len() == 1 { "" } else { "s" },
26880×
                        ui::ago(r.created_ms)
2689
                    ))
2690
                );
2691
            }
2692
        }
26931×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
26941×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
26951×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
26961×
            if json {
26970×
                println!("{}", serde_json::to_string(&r)?);
26981×
            } else {
26991×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
27001×
            }
2701
        }
27020×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
27030×
            let notes = match notes.as_deref() {
27040×
                Some("-") => Some(body_of(None, Some("-".into()))?),
27050×
                _ => notes,
2706
            };
27070×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
27080×
                bail!("say what to change: --title, --notes or --prerelease");
27090×
            }
27100×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
27110×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
27120×
            if json {
27130×
                println!("{}", serde_json::to_string(&r)?);
27140×
            } else {
27150×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
27160×
            }
2717
        }
27181×
        ReleaseCmd::Upload { tag, files } => {
27191×
            if files.is_empty() {
27200×
                bail!("name the files to attach");
27211×
            }
27221×
            for f in files {
27231×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
27241×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
27251×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
27261×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2727
            }
2728
        }
27291×
        ReleaseCmd::Trust { tag } => {
27301×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
27311×
            if json {
27320×
                println!("{}", c.get_text(&path)?);
27330×
                return Ok(0);
27341×
            }
27351×
            let r: serde_json::Value = c.get(&path)?;
27361×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
27371×
            let mut worst = 0;
27384×
            for ch in r["audit"].as_array().into_iter().flatten() {
27394×
                let v = ch["verdict"].as_str().unwrap_or("");
27404×
                worst = worst.max(match v {
27414×
                    "fail" => 2,
27424×
                    "warn" => 1,
27433×
                    _ => 0,
2744
                });
27454×
                let g = match v {
27464×
                    "pass" => ui::ok("✔"),
27471×
                    "warn" => ui::warn("!"),
27480×
                    _ => ui::bad("✘"),
2749
                };
27504×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2751
            }
27521×
            return Ok(if worst == 2 { 1 } else { 0 });
2753
        }
2754
    }
27552×
    Ok(0)
27564×
}
2757
2758
#[cfg(test)]
2759
mod tests {
2760
2761
    #[test]
27621×
    fn job_timings_and_report_commands_read_plainly() {
2763
        use clap::Parser;
27641×
        let job = hub_api::FlowJob {
27651×
            name: "perf".into(),
27661×
            status: "passed".into(),
27671×
            depends_on: vec![],
27681×
            runner: "earth-1".into(),
27691×
            exit_code: Some(0),
27701×
            error: String::new(),
27711×
            started_ms: Some(13_000),
27721×
            finished_ms: Some(200_000),
27731×
            log_lines: 10,
27741×
            waiting: String::new(),
27751×
            placed: String::new(),
27761×
            approval: String::new(),
27771×
            queued_ms: Some(1_000),
27781×
            ready_ms: Some(12_500),
27791×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
27801×
            peak_disk_mib: Some(2150),
27811×
            peak_memory_mib: Some(900),
27821×
        };
27831×
        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");
27841×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
27851×
        assert_eq!(super::timing_line(&bare), "");
27861×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2787
27881×
        let cli =
27891×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
27901×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
27911×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
27921×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
27931×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
27941×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
27951×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
27961×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
27971×
    }
2798
2799
    #[test]
28001×
    fn runner_update_scopes_resolve_by_name_or_id() {
28011×
        let all = hub_api::RunnerUpdates {
28021×
            repo: String::new(),
28031×
            settings: vec![],
28041×
            groups: vec![hub_api::RunnerGroup {
28051×
                id: 4,
28061×
                owner: "acme".into(),
28071×
                name: "canary".into(),
28081×
                percent: None,
28091×
                members: vec![],
28101×
                wave: None,
28111×
            }],
28121×
            runners: vec![],
28131×
            holds: vec![],
28141×
        };
28151×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
28161×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
28173×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
28183×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2819
        }
28201×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
28211×
        assert!(update_scope("everyone", &all).is_err());
28221×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
28231×
        assert!(switch(Some("yes")).is_err());
28241×
    }
2825
    use super::*;
2826
2827
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2828
    /// help says, and a drop is named by its id or its address.
2829
    #[test]
28301×
    fn drop_commands_parse() {
28311×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
28321×
        match cli.cmd {
28331×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
28341×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
28351×
                assert!(secret);
28361×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2837
            }
28380×
            _ => panic!("not drop create"),
2839
        }
28401×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
28411×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
28421×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
28431×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
28441×
                assert!(channel.is_none() && dry_run.is_none());
2845
            }
28460×
            _ => panic!("not runner-updates set"),
2847
        }
28481×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
28491×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
28501×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
28510×
            _ => panic!("not drop list"),
2852
        }
28531×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
28541×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
28551×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2856
            }
28570×
            _ => panic!("not drop view"),
2858
        }
28591×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
28604×
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
28614×
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2862
        }
28631×
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
28641×
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
28651×
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
28660×
            _ => panic!("not drop comment"),
2867
        }
28681×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
28691×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
28701×
        assert!(drop_id("andy/notes").is_err());
28711×
    }
2872
}