OXYGENHUB

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

672 of 1690 lines run, 49 of 263 functions · run #541 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
        /// Only the cards this filter keeps, as the board's filter bar takes it:
538
        /// words, repo:, assignee:, label:, milestone:, is:open|closed, age:>14d (#361)
539
        #[arg(long, short = 'q', conflicts_with = "view")]
540
        filter: Option<String>,
541
        /// A saved view of the board, by name: its filter (#361)
542
        #[arg(long)]
543
        view: Option<String>,
544
    },
545
    /// Create a board (owner, or an organisation's members)
546
    Create {
547
        title: String,
548
        #[arg(long, short, default_value = "")]
549
        description: String,
550
        /// Only the owner (or the organisation's members) can see it
551
        #[arg(long)]
552
        private: bool,
553
    },
554
    /// Close a board
555
    Close { number: i64 },
556
    /// Reopen a board
557
    Reopen { number: i64 },
558
    /// Move a board to another owner you may make boards under (an
559
    /// organisation, say); it takes the next number there
560
    Transfer {
561
        number: i64,
562
        /// The new owner
563
        #[arg(long)]
564
        to: String,
565
    },
566
    /// Cards on a board: add, move, archive, restore, remove
567
    Card {
568
        #[command(subcommand)]
569
        cmd: CardCmd,
570
    },
571
    /// A board's columns: add, rename, move, remove (#366)
572
    Column {
573
        #[command(subcommand)]
574
        cmd: ColumnCmd,
575
    },
576
}
577
578
#[derive(Subcommand)]
579
enum ColumnCmd {
580
    /// Add a column at the right
581
    Add {
582
        /// The board
583
        number: i64,
584
        name: String,
585
    },
586
    /// Rename a column (by name or id)
587
    Rename {
588
        /// The board
589
        number: i64,
590
        column: String,
591
        /// Its new name
592
        to: String,
593
    },
594
    /// Move a column: --to POSITION (1 is the leftmost), --left or --right
595
    Move {
596
        /// The board
597
        number: i64,
598
        column: String,
599
        /// Its place, counting from 1 at the left
600
        #[arg(long, conflicts_with_all = ["left", "right"], required_unless_present_any = ["left", "right"])]
601
        to: Option<i64>,
602
        /// One place to the left
603
        #[arg(long, conflicts_with = "right")]
604
        left: bool,
605
        /// One place to the right
606
        #[arg(long)]
607
        right: bool,
608
    },
609
    /// Remove a column; its cards go to the first remaining one
610
    Remove {
611
        /// The board
612
        number: i64,
613
        column: String,
614
    },
615
}
616
617
#[derive(Subcommand)]
618
enum CardCmd {
619
    /// Put an issue or proposal on a board (`12` or `#12` in this
620
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
621
    /// or a note with --note
622
    Add {
623
        number: i64,
624
        /// The issue or proposal; a number means this repository's
625
        reference: Option<String>,
626
        /// A note card instead
627
        #[arg(long, conflicts_with = "reference")]
628
        note: Option<String>,
629
        /// The column, by name or id (default: the first)
630
        #[arg(long, short)]
631
        column: Option<String>,
632
    },
633
    /// Move a card to another column (by name or id), or with --from every
634
    /// card of a column at once
635
    Move {
636
        number: i64,
637
        /// The card (its id); leave it out with --from
638
        card: Option<i64>,
639
        #[arg(long, short)]
640
        column: String,
641
        /// Move every card of this column (#289)
642
        #[arg(long, conflicts_with = "card")]
643
        from: Option<String>,
644
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
645
        #[arg(long, value_delimiter = ',', requires = "from")]
646
        except: Vec<String>,
647
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
648
        #[arg(long, value_delimiter = ',', requires = "from")]
649
        state: Vec<String>,
650
        /// With --from: say what would move, and move nothing
651
        #[arg(long, requires = "from")]
652
        dry_run: bool,
653
    },
654
    /// Archive a column's cards: off the board, kept and restorable (#293)
655
    Archive {
656
        number: i64,
657
        /// The column, by name or id
658
        #[arg(long)]
659
        from: String,
660
        /// Only cards that joined the column more than this long ago (14d, or 14)
661
        #[arg(long)]
662
        older: Option<String>,
663
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
664
        #[arg(long, value_delimiter = ',')]
665
        except: Vec<String>,
666
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
667
        #[arg(long, value_delimiter = ',')]
668
        state: Vec<String>,
669
        /// Say what would be archived, and archive nothing
670
        #[arg(long)]
671
        dry_run: bool,
672
    },
673
    /// Put an archived card back at the end of its column
674
    Restore { number: i64, card: i64 },
675
    /// Take a card off a board
676
    Remove { number: i64, card: i64 },
677
}
678
679
#[derive(Subcommand)]
680
enum MilestoneCmd {
681
    /// The repository's milestones
682
    List,
683
    /// Create a milestone, or change the one of that title (triage)
684
    Create {
685
        title: String,
686
        #[arg(long, short, default_value = "")]
687
        description: String,
688
        /// Due date, YYYY-MM-DD
689
        #[arg(long)]
690
        due: Option<String>,
691
    },
692
    /// Change a milestone's title, description or due date (triage)
693
    Edit {
694
        title: String,
695
        #[arg(long, short)]
696
        rename: Option<String>,
697
        #[arg(long, short)]
698
        description: Option<String>,
699
        /// Due date, YYYY-MM-DD ("" for none)
700
        #[arg(long)]
701
        due: Option<String>,
702
    },
703
    /// Close a milestone
704
    Close { title: String },
705
    /// Reopen a milestone
706
    Reopen { title: String },
707
}
708
709
/// Labels to put on or take off an issue or proposal.
710
#[derive(clap::Args)]
711
struct LabelChange {
712
    number: i64,
713
    /// A label to add (repeatable)
714
    #[arg(long, short)]
715
    add: Vec<String>,
716
    /// A label to take off (repeatable)
717
    #[arg(long, short)]
718
    remove: Vec<String>,
719
}
720
721
impl LabelChange {
722
    /// The set after the change, from the one there now.
7230×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
7240×
        if self.add.is_empty() && self.remove.is_empty() {
7250×
            bail!("say what to change: --add NAME or --remove NAME");
7260×
        }
7270×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
7280×
        for a in &self.add {
7290×
            if !names.contains(a) {
7300×
                names.push(a.clone());
7310×
            }
732
        }
7330×
        Ok(names)
7340×
    }
735
}
736
7370×
fn label_names(labels: &[String]) -> String {
7380×
    if labels.is_empty() {
7390×
        ui::dim("no labels")
740
    } else {
7410×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
742
    }
7430×
}
744
745
#[derive(Subcommand)]
746
enum CoverageCmd {
747
    /// Upload an LCOV or Cobertura report measured on this machine, as the
748
    /// coverage of a bookmark's current state (default: the default
749
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
750
    /// not measured by a runner, and sets no check from it
751
    Upload {
752
        file: std::path::PathBuf,
753
        #[arg(long)]
754
        bookmark: Option<String>,
755
        /// A change's full hash
756
        #[arg(long, conflicts_with = "bookmark")]
757
        change: Option<String>,
758
    },
759
}
760
761
#[derive(Subcommand)]
762
enum RunCmd {
763
    /// Recent runs, newest first
764
    List {
765
        #[arg(long, default_value_t = 20)]
766
        limit: i64,
767
    },
768
    /// A run and its jobs (default: the newest run)
769
    View {
770
        /// The run (default: the newest, or the newest of --bookmark)
771
        number: Option<i64>,
772
        /// With no number: the newest run of this bookmark
773
        #[arg(long, conflicts_with = "number")]
774
        bookmark: Option<String>,
775
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
776
        #[arg(long)]
777
        timings: bool,
778
    },
779
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
780
    Start {
781
        #[arg(long)]
782
        bookmark: Option<String>,
783
        /// A change's full hash
784
        #[arg(long, conflicts_with = "bookmark")]
785
        change: Option<String>,
786
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
787
        #[arg(long = "job", value_name = "NAME")]
788
        jobs: Vec<String>,
789
        /// Wait for the run and exit 1 unless it passes
790
        #[arg(long)]
791
        watch: bool,
792
    },
793
    /// Follow a run until it finishes (default: the newest run); exit 1 unless it passes
794
    Watch {
795
        /// The run (default: the newest, or the newest of --bookmark) (#367)
796
        number: Option<i64>,
797
        /// With no number: the newest run of this bookmark
798
        #[arg(long, conflicts_with = "number")]
799
        bookmark: Option<String>,
800
    },
801
    /// A job's log
802
    Log { number: i64, job: String },
803
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
804
    Report {
805
        number: i64,
806
        job: String,
807
        #[command(flatten)]
808
        pick: ReportPick,
809
    },
810
    /// Run a finished run's state again; with --job, only that job (and the
811
    /// jobs that depend on it) in the same run
812
    Rerun {
813
        number: i64,
814
        #[arg(long)]
815
        job: Option<String>,
816
    },
817
    /// Cancel a run still queued or running; its running jobs are stopped
818
    Cancel { number: i64 },
819
    /// Approve a job that waits for a person (oxygenflow#57)
820
    Approve {
821
        number: i64,
822
        #[arg(long)]
823
        job: String,
824
    },
825
    /// Reject a job that waits for a person: it ends cancelled
826
    Reject {
827
        number: i64,
828
        #[arg(long)]
829
        job: String,
830
    },
831
}
832
833
/// Which report of a job, and what of it to show.
834
#[derive(clap::Args)]
835
struct ReportPick {
836
    /// Which report, when the job published more than one
837
    #[arg(long)]
838
    name: Option<String>,
839
    /// What it holds: its metrics, context and files
840
    #[arg(long, conflicts_with = "file")]
841
    list: bool,
842
    /// One file of it (`data/frames.csv`), as published
843
    #[arg(long, value_name = "PATH")]
844
    file: Option<String>,
845
    /// Write the file here instead of to stdout
846
    #[arg(long, short, value_name = "FILE", requires = "file")]
847
    output: Option<std::path::PathBuf>,
848
}
849
850
#[derive(Subcommand)]
851
enum ReportCmd {
852
    /// The newest run of each report, newest first
853
    List {
854
        /// Only runs on this bookmark
855
        #[arg(long)]
856
        bookmark: Option<String>,
857
    },
858
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
859
    Show {
860
        report: String,
861
        #[arg(long, conflicts_with = "bookmark")]
862
        id: Option<i64>,
863
        #[arg(long)]
864
        bookmark: Option<String>,
865
        /// What it holds: its metrics, context and files
866
        #[arg(long, conflicts_with = "file")]
867
        list: bool,
868
        /// One file of it, as published
869
        #[arg(long, value_name = "PATH")]
870
        file: Option<String>,
871
        /// Write the file here instead of to stdout
872
        #[arg(long, short, value_name = "FILE", requires = "file")]
873
        output: Option<std::path::PathBuf>,
874
    },
875
}
876
877
#[derive(Subcommand)]
878
enum TagCmd {
879
    /// Tags, newest name first
880
    List,
881
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
882
    /// delegate (as `oxy tag create` and a push would be)
883
    Create {
884
        name: String,
885
        /// What to tag (default: the default bookmark)
886
        #[arg(long)]
887
        target: Option<String>,
888
        #[arg(long, short)]
889
        message: Option<String>,
890
    },
891
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
892
    /// their next fetch, and the name is never used again. Refused while a
893
    /// release uses the tag
894
    Delete {
895
        name: String,
896
        /// Why, recorded with the withdrawal
897
        #[arg(long, short)]
898
        reason: Option<String>,
899
    },
900
}
901
902
#[derive(Subcommand)]
903
enum ReleaseCmd {
904
    /// Releases, newest first
905
    List,
906
    /// Create a release on an existing tag
907
    Create {
908
        tag: String,
909
        #[arg(long, short)]
910
        title: Option<String>,
911
        /// Notes in Markdown (default: generated from the changes since the previous release)
912
        #[arg(long, short)]
913
        notes: Option<String>,
914
        #[arg(long)]
915
        prerelease: bool,
916
    },
917
    /// Change a release's title, notes or prerelease flag
918
    Edit {
919
        tag: String,
920
        #[arg(long, short)]
921
        title: Option<String>,
922
        /// New notes in Markdown ("-" reads them from stdin)
923
        #[arg(long, short)]
924
        notes: Option<String>,
925
        /// Mark it a prerelease (true) or not (false)
926
        #[arg(long)]
927
        prerelease: Option<bool>,
928
    },
929
    /// Attach files to a release
930
    Upload { tag: String, files: Vec<std::path::PathBuf> },
931
    /// The release's trust report: signatures, builds, receipts and audit
932
    Trust { tag: String },
933
}
934
93553×
fn main() {
936
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
937
    // other command-line tools do, instead of panicking on the failed
938
    // write (oxygenhub#92).
939
    #[cfg(unix)]
94053×
    unsafe {
94153×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
94253×
    }
94353×
    let cli = Cli::parse();
94453×
    ui::init(cli.plain);
94553×
    match run(cli) {
94645×
        Ok(code) => std::process::exit(code),
9478×
        Err(e) => {
9488×
            eprintln!("{} {e:#}", ui::bad("error:"));
9498×
            std::process::exit(2);
950
        }
951
    }
952
}
953
95422×
fn enc(s: &str) -> String {
95522×
    let mut out = String::new();
956109×
    for b in s.bytes() {
957109×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
958108×
            out.push(b as char);
959108×
        } else {
9601×
            out.push_str(&format!("%{b:02X}"));
9611×
        }
962
    }
96322×
    out
96422×
}
965
96653×
fn run(cli: Cli) -> Result<i32> {
96753×
    let cfg = Config::load()?;
9681×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
9691×
        return login(cfg, url, token.clone(), ca.clone());
97052×
    }
97152×
    let here = std::env::current_dir()?;
97252×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
97351×
    let c = Client::new(&t)?;
97451×
    let json = cli.json;
9750×
    match cli.cmd {
976
        Cmd::Auth { cmd: AuthCmd::Status } => {
9770×
            let me: serde_json::Value = c.get("/user")?;
9780×
            if json {
9790×
                println!("{me}");
9800×
            } else {
9810×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
9820×
            }
9830×
            Ok(0)
984
        }
9850×
        Cmd::Auth { .. } => unreachable!(),
9862×
        Cmd::Mcp { allow_write } => {
9872×
            t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?;
9882×
            mcp::serve(c, t, allow_write)
989
        }
9902×
        Cmd::Api { path, method, data } => {
9912×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
992
            // The method applies with or without a body (#75): without one, a
993
            // GET reads, anything else sends an empty object.
9942×
            let text = match data {
9950×
                Some(d) => c.send_text(
9960×
                    &method.to_uppercase(),
9970×
                    &path,
9980×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
9990×
                )?,
10002×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
10010×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
1002
            };
10032×
            println!("{text}");
10042×
            Ok(0)
1005
        }
1006
        Cmd::Repo { cmd: RepoCmd::View } => {
10071×
            let path = t.repo_path()?;
10081×
            if json {
10090×
                println!("{}", c.get_text(&path)?);
10100×
                return Ok(0);
10111×
            }
10121×
            let r: serde_json::Value = c.get(&path)?;
10131×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
10141×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
10151×
                println!("{d}");
10161×
            }
10171×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
10181×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
10191×
            Ok(0)
1020
        }
102118×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
10224×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
10233×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
10240×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
10250×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
10260×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
10270×
            let mut body = serde_json::json!({ "content": content });
10280×
            if let Some(b) = bookmark {
10290×
                body["bookmark"] = b.into();
10300×
            }
10310×
            if let Some(ch) = change {
10320×
                body["change"] = ch.into();
10330×
            }
10340×
            let base = t.repo_path()?;
10350×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
10360×
            if json {
10370×
                println!("{}", serde_json::to_string(&r)?);
1038
            } else {
10390×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
10400×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
10410×
                println!(
1042
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
10430×
                    ui::ok("✔"),
1044
                    r.lines_hit,
1045
                    r.lines_found,
1046
                    r.files,
10470×
                    ui::dim(&r.url)
1048
                );
10490×
                if r.dropped > 0 {
10500×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
10510×
                }
1052
            }
10530×
            Ok(0)
1054
        }
10554×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
10560×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
10570×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
10580×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
105910×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
10600×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
10610×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
10620×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
10637×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
1064
    }
106553×
}
1066
1067
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
10682×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
10692×
    Ok(match v {
10700×
        None => None,
10712×
        Some("on") => Some(Some(true)),
10722×
        Some("off") => Some(Some(false)),
10732×
        Some("inherit") => Some(None),
10741×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1075
    })
10762×
}
1077
1078
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
10797×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
10807×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
10811×
    Ok(match kind {
10827×
        "site" if name.is_empty() => ("site".into(), String::new()),
10836×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
10845×
        "group" => {
10853×
            let g = all
10863×
                .groups
10873×
                .iter()
10883×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
10893×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
10903×
            ("group".into(), g.id.to_string())
1091
        }
10922×
        "runner" => {
10931×
            let r = all
10941×
                .runners
10951×
                .iter()
10961×
                .find(|r| r.id.to_string() == name || r.name == name)
10971×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
10980×
            ("runner".into(), r.id.to_string())
1099
        }
11001×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1101
    })
11027×
}
1103
11040×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
11050×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
11060×
    match cmd {
11070×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1108
        RunnerUpdatesCmd::Show => {
11090×
            println!(
1110
                "{} {}",
11110×
                ui::strong("Builds from"),
11120×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1113
            );
11140×
            for h in &all.holds {
11150×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
11160×
            }
11170×
            for s in &all.settings {
11180×
                let mut said = vec![];
11190×
                if let Some(u) = s.updates {
11200×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
11210×
                }
11220×
                if let Some(ch) = &s.channel {
11230×
                    said.push(format!("channel {ch}"));
11240×
                }
11250×
                if let Some(w) = &s.window {
11260×
                    said.push(format!("window {w} UTC"));
11270×
                }
11280×
                if let Some(d) = s.dry_run {
11290×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
11300×
                }
11310×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
11320×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1133
            }
11340×
            for g in &all.groups {
11350×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
11360×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
11370×
                if let Some(w) = g.wave {
11380×
                    what.push_str(&format!(", wave {w}"));
11390×
                }
11400×
                println!(
1141
                    "  group {} ({what}): {}",
11420×
                    ui::strong(&g.name),
11430×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1144
                );
1145
            }
11460×
            for r in &all.runners {
11470×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
11480×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1149
            }
1150
        }
11510×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
11520×
            let (scope, key) = update_scope(&scope, &all)?;
11530×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
11540×
                scope: scope.clone(),
11550×
                key: key.clone(),
11560×
                ..Default::default()
11570×
            });
11580×
            if let Some(u) = switch(updates.as_deref())? {
11590×
                s.updates = u;
11600×
            }
11610×
            if let Some(d) = switch(dry_run.as_deref())? {
11620×
                s.dry_run = d;
11630×
            }
11640×
            if let Some(ch) = channel {
11650×
                s.channel = Some(ch).filter(|c| c != "inherit");
11660×
            }
11670×
            if let Some(w) = window {
11680×
                s.window = Some(w).filter(|w| w != "inherit");
11690×
            }
11700×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
11710×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1172
        }
11730×
        RunnerUpdatesCmd::Lift { version } => {
11740×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
11750×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1176
        }
1177
    }
11780×
    Ok(0)
11790×
}
1180
1181
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
11827×
fn drop_id(s: &str) -> Result<String> {
11837×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1184144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
11851×
        bail!("{s:?} is not a drop's id or address");
11866×
    }
11876×
    Ok(id.to_ascii_lowercase())
11887×
}
1189
11902×
fn drop_line(d: &hub_api::Drop) -> String {
11912×
    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() };
11924×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
11932×
    format!(
1194
        "{} {} {}{}",
11952×
        ui::dim(&d.id),
11962×
        ui::strong(&title),
11972×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
11982×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1199
    )
12002×
}
1201
1202
/// `oh drop star|unstar` (oxygenhub#349).
12030×
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
12040×
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
12050×
    if json {
12060×
        println!("{}", serde_json::to_string(&s)?);
1207
    } else {
12080×
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1209
    }
12100×
    Ok(())
12110×
}
1212
12137×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
12147×
    match cmd {
12151×
        DropCmd::Create { files, secret, description, title } => {
12161×
            let mut out = Vec::with_capacity(files.len());
12172×
            for f in &files {
12182×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
12192×
                let content =
12202×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
12212×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1222
            }
12231×
            let new =
12241×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
12251×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
12261×
            if json {
12271×
                println!("{}", serde_json::to_string(&d)?);
1228
            } else {
12290×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
12300×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1231
            }
1232
        }
12332×
        DropCmd::List { user } => {
12342×
            let path = match &user {
12351×
                Some(u) => format!("/users/{}/drops", enc(u)),
12361×
                None => "/drops".to_string(),
1237
            };
12382×
            if json {
12391×
                println!("{}", c.get_text(&path)?);
12401×
                return Ok(0);
12411×
            }
12421×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
12431×
            if list.is_empty() {
12440×
                println!("{}", ui::dim("No drops."));
12451×
            }
12461×
            for d in &list {
12471×
                println!("{}", drop_line(d));
12481×
            }
1249
        }
12503×
        DropCmd::View { id, file } => {
12513×
            let path = format!("/drops/{}", drop_id(&id)?);
12523×
            if json && file.is_none() {
12530×
                println!("{}", c.get_text(&path)?);
12540×
                return Ok(0);
12553×
            }
12563×
            let d: hub_api::Drop = c.get(&path)?;
12572×
            if let Some(name) = file {
12582×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
12591×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
12601×
                print!("{content}");
12611×
                return Ok(0);
12621×
            }
12631×
            println!("{}", drop_line(&d));
12641×
            if !d.description.is_empty() {
12651×
                println!("{}", d.description);
12661×
            }
12671×
            println!("{}", ui::kv("url", &d.url));
12681×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
12692×
            for f in &d.files {
12702×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
12712×
                match &f.content {
12722×
                    Some(text) => {
12732×
                        print!("{text}");
12742×
                        if !text.ends_with('\n') && !text.is_empty() {
12750×
                            println!();
12762×
                        }
1277
                    }
12780×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1279
                }
1280
            }
1281
        }
12821×
        DropCmd::Delete { id } => {
12831×
            let id = drop_id(&id)?;
12841×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
12851×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1286
        }
12870×
        DropCmd::Fork { id } => {
12880×
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
12890×
            if json {
12900×
                println!("{}", serde_json::to_string(&d)?);
12910×
            } else {
12920×
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
12930×
            }
1294
        }
12950×
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
12960×
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
12970×
        DropCmd::Comments { id } => {
12980×
            let path = format!("/drops/{}/comments", drop_id(&id)?);
12990×
            if json {
13000×
                println!("{}", c.get_text(&path)?);
13010×
                return Ok(0);
13020×
            }
13030×
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
13040×
            if list.is_empty() {
13050×
                println!("{}", ui::dim("No comments."));
13060×
            }
13070×
            for m in &list {
13080×
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
13090×
                println!("{}\n", m.body);
13100×
            }
1311
        }
13120×
        DropCmd::Comment { id, message } => {
13130×
            let m: hub_api::DropComment =
13140×
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
13150×
            if json {
13160×
                println!("{}", serde_json::to_string(&m)?);
13170×
            } else {
13180×
                println!("{} commented (#{})", ui::ok("✔"), m.id);
13190×
            }
1320
        }
1321
    }
13224×
    Ok(0)
13237×
}
1324
1325
/// `30d`, `12h`, `90m` in milliseconds.
13260×
fn duration_ms(s: &str) -> Result<i64> {
13270×
    let s = s.trim();
13280×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
13290×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
13300×
    let per = match unit {
13310×
        "d" => 86_400_000,
13320×
        "h" => 3_600_000,
13330×
        "m" => 60_000,
13340×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1335
    };
13360×
    if n <= 0 {
13370×
        bail!("a grant must last some time");
13380×
    }
13390×
    Ok(n * per)
13400×
}
1341
13420×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1343
    use oxy_core::cert::{Grant, SignedGrant};
1344
    use oxy_core::identity::{Identity, Scope};
13450×
    match cmd {
13460×
        AgentCmd::Grant { name, scope, lasts } => {
13470×
            let home = oxy_core::repo::default_home();
13480×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
13490×
                format!(
1350
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
13510×
                    home.display()
1352
                )
13530×
            })?;
13540×
            let me: serde_json::Value = c.get("/user")?;
13550×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
13560×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
13570×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
13580×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
13590×
            let grant = Grant {
13600×
                grantor: me_id.hash(),
13610×
                subject: format!("agent:{name}@{username}"),
13620×
                issuer: hub.hash(),
13630×
                scope,
13640×
                not_before: (now - 60_000) as u64,
13650×
                expires: (now + duration_ms(&lasts)?) as u64,
1366
            };
13670×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
13680×
            let r: serde_json::Value =
13690×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
13700×
            if json {
13710×
                println!("{r}");
13720×
                return Ok(0);
13730×
            }
13740×
            println!(
1375
                "{} {} to act for you as {} ({}), until {}",
13760×
                ui::ok("✔ granted"),
13770×
                ui::strong(&name),
13780×
                r["subject"].as_str().unwrap_or(""),
13790×
                r["scope"].as_str().unwrap_or(""),
13800×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1381
            );
13820×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
13830×
            println!(
1384
                "  {}",
13850×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1386
            );
13870×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
13880×
            Ok(0)
1389
        }
1390
        AgentCmd::List => {
13910×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
13920×
            if json {
13930×
                println!("{}", serde_json::to_string(&grants)?);
13940×
                return Ok(0);
13950×
            }
13960×
            if grants.is_empty() {
13970×
                println!("{}", ui::dim("no agent grants"));
13980×
            }
13990×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
14000×
            for g in grants {
14010×
                let state = if g["revoked_ms"].is_i64() {
14020×
                    ui::bad("revoked")
14030×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
14040×
                    ui::dim("ended")
1405
                } else {
14060×
                    ui::ok("live")
1407
                };
14080×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
14090×
                println!(
1410
                    "#{:<4} {:<8} {} · {} · until {} · {}",
14110×
                    g["id"],
1412
                    state,
14130×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
14140×
                    g["scope"].as_str().unwrap_or(""),
14150×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
14160×
                    ui::dim(&used)
1417
                );
1418
            }
14190×
            Ok(0)
1420
        }
14210×
        AgentCmd::Revoke { id } => {
14220×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
14230×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
14240×
            Ok(0)
1425
        }
1426
    }
14270×
}
1428
14291×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
14301×
    let hub = url.trim_end_matches('/').to_string();
14311×
    let token = match token.as_deref() {
14321×
        Some("-") => {
14330×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
14340×
            let mut line = String::new();
14350×
            std::io::stdin().read_line(&mut line)?;
14360×
            line.trim().to_string()
1437
        }
14381×
        Some(t) => t.to_string(),
14390×
        None => device_sign_in(&hub, ca.clone())?,
1440
    };
14411×
    if token.is_empty() {
14420×
        bail!("no token given");
14431×
    }
14441×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
14451×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
14461×
    let account = me["username"].as_str().unwrap_or("?");
1447
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
14481×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
14491×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
14501×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
14511×
    cfg.default_hub = Some(hub.clone());
14521×
    cfg.save()?;
14531×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
14541×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
14551×
    Ok(0)
14561×
}
1457
1458
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1459
/// it on the web, and the token arrives here.
14600×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
14610×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
14620×
    let c = Client::new(&t)?;
14630×
    let host = std::fs::read_to_string("/etc/hostname")
14640×
        .ok()
14650×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
14660×
        .map(|h| h.trim().to_string())
14670×
        .filter(|h| !h.is_empty());
14680×
    let client = match host {
14690×
        Some(h) => format!("oh on {h}"),
14700×
        None => "oh".to_string(),
1471
    };
14720×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
14730×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
14740×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
14750×
    if code != 200 {
14760×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
14770×
    }
14780×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
14790×
    let user = v["user_code"].as_str().unwrap_or("?");
14800×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
14810×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
14820×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
14830×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
14840×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1485
    loop {
14860×
        std::thread::sleep(std::time::Duration::from_secs(interval));
14870×
        if std::time::Instant::now() > deadline {
14880×
            bail!("the code expired before it was approved; run oh auth login again");
14890×
        }
14900×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
14910×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
14920×
        if code == 200 {
14930×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
14940×
        }
14950×
        match v["error"].as_str() {
14960×
            Some("authorization_pending") => {}
14970×
            Some("slow_down") => interval += 5,
14980×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
14990×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
15000×
            _ => bail!("signing in: HTTP {code}: {body}"),
1501
        }
1502
    }
15030×
}
1504
150510×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
150610×
    match (body, file) {
15073×
        (Some(b), _) => Ok(b),
15081×
        (None, Some(f)) if f == "-" => {
15090×
            let mut s = String::new();
15100×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
15110×
            Ok(s)
1512
        }
15131×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
15146×
        (None, None) => Ok(String::new()),
1515
    }
151610×
}
1517
15183×
fn issue_line(i: &Issue) -> String {
15193×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
15203×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
15213×
    format!(
1522
        "{glyph} {} {}{}{}",
15233×
        ui::dim(&format!("#{}", i.number)),
1524
        i.title,
15253×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
15263×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1527
    )
15283×
}
1529
153018×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
153118×
    let base = t.repo_path()?;
153218×
    match cmd {
15333×
        IssueCmd::List { state } => {
15343×
            let path = format!("{base}/issues?state={}", enc(&state));
15353×
            if json {
15361×
                println!("{}", c.get_text(&path)?);
15371×
                return Ok(0);
15382×
            }
15392×
            let list: Vec<Issue> = c.get(&path)?;
15402×
            if list.is_empty() {
15411×
                println!("{}", ui::dim(&format!("No {state} issues.")));
15421×
            }
15432×
            for i in &list {
15442×
                println!("{}", issue_line(i));
15452×
            }
1546
        }
15472×
        IssueCmd::View { number } => {
15482×
            let path = format!("{base}/issues/{number}");
15492×
            if json {
15501×
                println!("{}", c.get_text(&path)?);
15511×
                return Ok(0);
15521×
            }
15531×
            let i: Issue = c.get(&path)?;
15541×
            println!("{}", issue_line(&i));
15551×
            if !i.body.trim().is_empty() {
15561×
                println!("\n{}\n", i.body.trim_end());
15571×
            }
15581×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
15592×
            for cm in comments {
15602×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
15612×
            }
15621×
            println!("{}", ui::dim(&i.url));
1563
        }
15644×
        IssueCmd::Create { title, body, body_file, label, project, column, attach } => {
15654×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
15664×
            let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None };
15674×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
15683×
            if json {
15691×
                println!("{}", serde_json::to_string(&i)?);
15702×
            } else {
15712×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
15722×
            }
15733×
            if let Some(n) = project {
15741×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
15751×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
15761×
                if !json {
15771×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
15781×
                }
15792×
            }
1580
        }
15811×
        IssueCmd::Close { number, reason, comment } => {
15821×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
15831×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
15841×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1585
        }
15860×
        IssueCmd::Reopen { number, comment } => {
15870×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
15880×
            let i: Issue =
15890×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
15900×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1591
        }
15923×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
15933×
            let body = match (&body, &body_file) {
15943×
                (None, None) => None,
15950×
                _ => Some(body_of(body, body_file)?),
1596
            };
15973×
            let labels = if no_labels {
15981×
                Some(Vec::new())
15992×
            } else if label.is_empty() {
16001×
                None
1601
            } else {
16021×
                Some(label)
1603
            };
16043×
            let assignees = if no_assignees {
16051×
                Some(Vec::new())
16062×
            } else if assignee.is_empty() {
16071×
                None
1608
            } else {
16091×
                Some(assignee)
1610
            };
16113×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
16121×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
16132×
            }
16142×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
16152×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
16162×
            if json {
16171×
                println!("{}", serde_json::to_string(&i)?);
16181×
            } else {
16191×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
16201×
            }
1621
        }
16220×
        IssueCmd::Label(change) => {
16230×
            let path = format!("{base}/issues/{}", change.number);
16240×
            let now: Issue = c.get(&path)?;
16250×
            let labels = change.apply(&now.labels)?;
16260×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
16270×
            let i: Issue = c.send("PATCH", &path, &edit)?;
16280×
            if json {
16290×
                println!("{}", serde_json::to_string(&i)?);
16300×
            } else {
16310×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
16320×
            }
1633
        }
16345×
        IssueCmd::Comment { number, body, body_file, attach } => {
16355×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
16364×
            if body.trim().is_empty() {
16371×
                bail!("give the comment with --body, --body-file or --attach");
16383×
            }
16393×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
16403×
            println!("{} commented on #{number}", ui::ok("✔"));
1641
        }
1642
    }
164312×
    Ok(0)
164418×
}
1645
1646
/// A comment to post with a close or reopen (#368): saying why, in the
1647
/// same command.
1648
#[derive(clap::Args)]
1649
struct StateComment {
1650
    /// Say why, as a comment posted first
1651
    #[arg(long, short)]
1652
    body: Option<String>,
1653
    /// Read the comment from a file ("-" for stdin)
1654
    #[arg(long, short = 'F', conflicts_with = "body")]
1655
    body_file: Option<String>,
1656
    /// Attach a file to the comment (repeatable)
1657
    #[arg(long, short = 'a', value_name = "FILE")]
1658
    attach: Vec<std::path::PathBuf>,
1659
}
1660
1661
impl StateComment {
16621×
    fn post(self, c: &Client, base: &str, path: &str) -> Result<()> {
16631×
        if self.body.is_none() && self.body_file.is_none() && self.attach.is_empty() {
16641×
            return Ok(());
16650×
        }
16660×
        let body = with_attachments(c, base, body_of(self.body, self.body_file)?, &self.attach)?;
16670×
        if !body.trim().is_empty() {
16680×
            c.send_text("POST", path, &NewComment { body, path: None, line: None })?;
16690×
        }
16700×
        Ok(())
16711×
    }
1672
}
1673
1674
/// `number`, or the newest run (of `bookmark`, when given): what a push
1675
/// just started is what one usually wants to follow (#367).
16761×
fn run_or_newest(c: &Client, base: &str, number: Option<i64>, bookmark: Option<&str>) -> Result<i64> {
16771×
    if let Some(n) = number {
16781×
        return Ok(n);
16790×
    }
16800×
    let runs: Vec<FlowRun> = c.get(&format!("{base}/flow/runs?limit=100"))?;
16810×
    runs.iter().filter(|r| bookmark.is_none_or(|b| r.bookmark == b)).map(|r| r.number).max().with_context(|| match bookmark {
16820×
        Some(b) => format!("no runs of {b} among the latest 100"),
16830×
        None => "no runs yet".to_string(),
16840×
    })
16851×
}
1686
1687
/// `body` with each file attached to the repository and linked under it:
1688
/// an image shown in place, anything else a download (#350). Files are
1689
/// uploaded first, so a failed upload leaves nothing half made.
16909×
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> {
16919×
    if files.is_empty() {
16926×
        return Ok(body);
16933×
    }
16943×
    let mut links = Vec::new();
16954×
    for f in files {
16964×
        let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?;
16973×
        let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
16983×
        let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?;
16993×
        let a: hub_api::Attachment =
17003×
            serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?;
17013×
        links.push(a.markdown);
1702
    }
17032×
    let links = links.join("\n\n");
17042×
    Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) })
17059×
}
1706
17071×
fn source_name(s: &hub_api::ProposalSource) -> String {
17081×
    match s {
17091×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
17100×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
17110×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1712
    }
17131×
}
1714
17151×
fn proposal_line(p: &Proposal) -> String {
17161×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
17171×
    let glyph = match state.as_str() {
17181×
        "open" => ui::ok("●"),
17190×
        "draft" => ui::dim("◌"),
17200×
        "landed" => ui::strong("✔"),
17210×
        _ => ui::dim("○"),
1722
    };
17231×
    format!(
1724
        "{glyph} {} {} {}{}",
17251×
        ui::dim(&format!("#{}", p.number)),
1726
        p.title,
17271×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
17281×
        ui::dim(&format!(" · {} · {state}", p.author))
1729
    )
17301×
}
1731
17324×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
17334×
    let base = t.repo_path()?;
17344×
    match cmd {
17350×
        ProposalCmd::List { state, limit } => {
17360×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
17370×
            if json {
17380×
                println!("{}", c.get_text(&path)?);
17390×
                return Ok(0);
17400×
            }
17410×
            let list: Vec<Proposal> = c.get(&path)?;
17420×
            if list.is_empty() {
17430×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
17440×
            }
17450×
            for p in &list {
17460×
                println!("{}", proposal_line(p));
17470×
            }
1748
        }
17491×
        ProposalCmd::View { number } => {
17501×
            let path = format!("{base}/proposals/{number}");
17511×
            if json {
17520×
                println!("{}", c.get_text(&path)?);
17530×
                return Ok(0);
17541×
            }
17551×
            let p: Proposal = c.get(&path)?;
17561×
            println!("{}", proposal_line(&p));
17571×
            if !p.body.trim().is_empty() {
17580×
                println!("\n{}\n", p.body.trim_end());
17591×
            }
17601×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
17611×
            for ch in &p.changes {
17621×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
17631×
            }
17641×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
17651×
            if p.landable {
17661×
                println!("{} can land", ui::ok("✔"));
17671×
            } else {
17680×
                for b in &p.blockers {
17690×
                    println!("{} {b}", ui::bad("✘"));
17700×
                }
1771
            }
17721×
            if p.conflicted {
17730×
                println!("{} landing it would leave conflicts", ui::bad("!"));
17741×
            }
17751×
            println!("{}", ui::dim(&p.url));
1776
        }
17771×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
17781×
            let target = match into {
17790×
                Some(i) => i,
17801×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1781
            };
17821×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
17831×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
17841×
            if json {
17850×
                println!("{}", serde_json::to_string(&p)?);
17861×
            } else {
17871×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
17881×
            }
1789
        }
17900×
        ProposalCmd::Edit { number, title, body, body_file } => {
17910×
            let body = match (&body, &body_file) {
17920×
                (None, None) => None,
17930×
                _ => Some(body_of(body, body_file)?),
1794
            };
17950×
            if title.is_none() && body.is_none() {
17960×
                bail!("say what to change: --title, --body or --body-file");
17970×
            }
17980×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
17990×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
18000×
            if json {
18010×
                println!("{}", serde_json::to_string(&p)?);
18020×
            } else {
18030×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
18040×
            }
1805
        }
18060×
        ProposalCmd::Label(change) => {
18070×
            let path = format!("{base}/proposals/{}", change.number);
18080×
            let now: Proposal = c.get(&path)?;
18090×
            let labels = change.apply(&now.labels)?;
18100×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
18110×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
18120×
            if json {
18130×
                println!("{}", serde_json::to_string(&p)?);
18140×
            } else {
18150×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
18160×
            }
1817
        }
18180×
        ProposalCmd::Comment { number, body, body_file } => {
18190×
            let body = body_of(body, body_file)?;
18200×
            if body.trim().is_empty() {
18210×
                bail!("give the comment with --body or --body-file");
18220×
            }
18230×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
18240×
            println!("{} commented on #{number}", ui::ok("✔"));
1825
        }
18260×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
18270×
            let path = format!("{base}/proposals/{number}/auto-land");
18280×
            let p: Proposal =
18290×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
18300×
            if json {
18310×
                println!("{}", serde_json::to_string(&p)?);
18320×
            } else if p.landed.is_some() {
18330×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
18340×
            } else if p.auto_land.is_some() {
18350×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
18360×
            } else {
18370×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
18380×
            }
1839
        }
18402×
        ProposalCmd::Land { number, over_checks, .. } => {
18412×
            let body = match &over_checks {
18420×
                Some(r) => serde_json::json!({ "over_checks": r }),
18432×
                None => serde_json::json!({}),
1844
            };
18452×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
18461×
            if json {
18470×
                println!("{}", serde_json::to_string(&p)?);
18481×
            } else {
18491×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
18501×
            }
1851
        }
18520×
        ProposalCmd::Close { number, message } => {
18530×
            if let Some(body) = message {
18540×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
18550×
            }
18560×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
18570×
            if json {
18580×
                println!("{}", serde_json::to_string(&p)?);
18590×
            } else {
18600×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
18610×
            }
1862
        }
18630×
        ProposalCmd::Reopen { number } => {
18640×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
18650×
            if json {
18660×
                println!("{}", serde_json::to_string(&p)?);
18670×
            } else {
18680×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
18690×
            }
1870
        }
18710×
        ProposalCmd::Ready { number, undo } => {
18720×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
18730×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
18740×
            if json {
18750×
                println!("{}", serde_json::to_string(&p)?);
18760×
            } else if undo {
18770×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
18780×
            } else {
18790×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
18800×
            }
1881
        }
18820×
        ProposalCmd::Checks { number } => {
18830×
            let path = format!("{base}/proposals/{number}/checks");
18840×
            if json {
18850×
                println!("{}", c.get_text(&path)?);
18860×
                return Ok(0);
18870×
            }
18880×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
18890×
            if checks.is_empty() {
18900×
                println!("{}", ui::dim("No checks yet."));
18910×
            }
18920×
            for ch in checks {
18930×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
18940×
            }
1895
        }
1896
    }
18973×
    Ok(0)
18984×
}
1899
19001×
fn run_line(r: &FlowRun) -> String {
19011×
    let what =
19021×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
19031×
    format!(
1904
        "{} {} {} {}",
19051×
        ui::status(&r.status),
19061×
        ui::dim(&format!("#{}", r.number)),
1907
        what,
19081×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1909
    )
19101×
}
1911
19121×
fn print_run(r: &FlowRun, timings: bool) {
19131×
    println!("{}", run_line(r));
19141×
    for j in &r.jobs {
19151×
        let dur = match (j.started_ms, j.finished_ms) {
19160×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
19171×
            _ => String::new(),
1918
        };
19191×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
19201×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1921
        // Why a queued job no runner can take waits (oxygenhub#28), and
1922
        // why a job ran where it did (oxygenflow#42).
19231×
        if j.status == "queued" && !j.waiting.is_empty() {
19240×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
19251×
        } else if !j.placed.is_empty() {
19260×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
19271×
        }
19281×
        if timings {
19290×
            let t = timing_line(j);
19300×
            if !t.is_empty() {
19310×
                println!("    {}", ui::dim(&t));
19320×
            }
19331×
        }
1934
    }
19351×
    if !r.error.is_empty() {
19360×
        println!("{}", ui::bad(&r.error));
19371×
    }
19381×
    println!("{}", ui::dim(&r.url));
19391×
}
1940
1941
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
19423×
fn took(ms: i64) -> String {
19433×
    match ms {
19443×
        ..=999 => format!("{ms} ms"),
19452×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
19461×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1947
    }
19483×
}
1949
1950
/// MiB as a person reads them.
19512×
fn mib(m: i64) -> String {
19522×
    if m >= 1024 {
19531×
        format!("{:.1} GiB", m as f64 / 1024.0)
1954
    } else {
19551×
        format!("{m} MiB")
1956
    }
19572×
}
1958
1959
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1960
/// phase its runner reported, and the most disk and memory it took.
19612×
fn timing_line(j: &FlowJob) -> String {
19622×
    let mut parts = vec![];
19632×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
19641×
        parts.push(format!("waited {}", took((s - q).max(0))));
19651×
    }
19662×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
19672×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
19682×
        .into_iter()
19694×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
19702×
        .collect();
19712×
    if !peaks.is_empty() {
19721×
        parts.push(format!("peak {}", peaks.join(", ")));
19731×
    }
19742×
    parts.join(" · ")
19752×
}
1976
1977
/// A report's path, its segments encoded and its slashes kept.
19781×
fn enc_path(path: &str) -> String {
19791×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
19801×
}
1981
1982
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1983
/// files are at `files(path)`. By default its report.toml; with `list`
1984
/// what it holds; with `file` one file, to stdout or `output`.
19850×
fn show_report(
19860×
    c: &Client,
19870×
    at: &str,
19880×
    files: impl Fn(&str) -> String,
19890×
    list: bool,
19900×
    file: Option<String>,
19910×
    output: Option<std::path::PathBuf>,
19920×
    json: bool,
19930×
) -> Result<()> {
1994
    use std::io::Write;
19950×
    if let Some(path) = file {
19960×
        let bytes = c.get_bytes(&files(&path))?;
19970×
        match output {
19980×
            Some(out) => {
19990×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
20000×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
2001
            }
20020×
            None => std::io::stdout().write_all(&bytes)?,
2003
        }
20040×
        return Ok(());
20050×
    }
20060×
    if json {
20070×
        println!("{}", c.get_text(at)?);
20080×
        return Ok(());
20090×
    }
20100×
    if !list {
20110×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
20120×
        return Ok(());
20130×
    }
20140×
    let r: Report = c.get(at)?;
20150×
    print_report(&r);
20160×
    if r.files_expired_ms.is_some() {
20170×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
20180×
    }
20190×
    for f in &r.manifest {
20200×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
20210×
    }
20220×
    println!("{}", ui::dim(&r.url));
20230×
    Ok(())
20240×
}
2025
2026
/// A report's heading, metrics and context.
20270×
fn print_report(r: &Report) {
20280×
    let from = match r.run {
20290×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
20300×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
2031
    };
20320×
    println!(
2033
        "{} {} {}",
20340×
        ui::strong(&r.name),
20350×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
20360×
        ui::dim(&format!("· {from} · {} files", r.files))
2037
    );
20380×
    if !r.summary.is_empty() {
20390×
        println!("  {}", r.summary);
20400×
    }
20410×
    for m in &r.metrics {
20420×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
20430×
        let mut notes = vec![];
20440×
        if !m.better.is_empty() {
20450×
            notes.push(format!("{} is better", m.better));
20460×
        }
20470×
        if let Some(a) = m.fail_above {
20480×
            notes.push(format!("fails above {a}"));
20490×
        }
20500×
        if let Some(b) = m.fail_below {
20510×
            notes.push(format!("fails below {b}"));
20520×
        }
20530×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
20540×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
2055
    }
20560×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
20570×
        let line: Vec<String> =
20580×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
20590×
        println!("  {}", ui::dim(&line.join(" ")));
20600×
    }
20610×
}
2062
2063
/// `oh report …` (oxygenhub#348).
20640×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
20650×
    let base = t.repo_path()?;
20660×
    match cmd {
20670×
        ReportCmd::List { bookmark } => {
20680×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
20690×
            if json {
20700×
                println!("{}", c.get_text(&path)?);
20710×
                return Ok(0);
20720×
            }
20730×
            let list: Vec<Report> = c.get(&path)?;
20740×
            if list.is_empty() {
20750×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
20760×
            }
20770×
            for r in &list {
20780×
                print_report(r);
20790×
            }
2080
        }
20810×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
20820×
            let at = format!("{base}/reports/{}", enc(&report));
20830×
            let query = match (id, bookmark) {
20840×
                (Some(id), _) => format!("?id={id}"),
20850×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
20860×
                (None, None) => String::new(),
2087
            };
20880×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
20890×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
2090
        }
2091
    }
20920×
    Ok(0)
20930×
}
2094
20950×
fn live(status: &str) -> bool {
20960×
    matches!(status, "queued" | "running")
20970×
}
2098
2099
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
21000×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
21010×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
21020×
    if json {
21030×
        println!("{done}");
21040×
    } else {
21050×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
21060×
    }
21070×
    Ok(())
21080×
}
2109
21100×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
21110×
    let path = format!("{base}/flow/runs/{number}");
21120×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2113
    loop {
21140×
        let r: FlowRun = c.get(&path)?;
21150×
        if !json {
21160×
            for j in &r.jobs {
21170×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
21180×
                if seen.get(&j.name) != Some(&shown) {
21190×
                    println!("{} {}", ui::status(&j.status), j.name);
21200×
                    if j.status == "queued" && !j.waiting.is_empty() {
21210×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
21220×
                    }
21230×
                    seen.insert(j.name.clone(), shown);
21240×
                }
2125
            }
21260×
        }
21270×
        if !live(&r.status) {
21280×
            if json {
21290×
                println!("{}", serde_json::to_string(&r)?);
21300×
            } else {
21310×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
21320×
            }
21330×
            return Ok(if r.status == "passed" { 0 } else { 1 });
21340×
        }
21350×
        std::thread::sleep(Duration::from_secs(3));
2136
    }
21370×
}
2138
21393×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
21403×
    let base = t.repo_path()?;
21410×
    match cmd {
21421×
        RunCmd::List { limit } => {
21431×
            let path = format!("{base}/flow/runs?limit={limit}");
21441×
            if json {
21451×
                println!("{}", c.get_text(&path)?);
21461×
                return Ok(0);
21470×
            }
21480×
            let runs: Vec<FlowRun> = c.get(&path)?;
21490×
            if runs.is_empty() {
21500×
                println!("{}", ui::dim("No runs yet."));
21510×
            }
21520×
            for r in &runs {
21530×
                println!("{}", run_line(r));
21540×
            }
2155
        }
21561×
        RunCmd::View { number, bookmark, timings } => {
21571×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
21581×
            let path = format!("{base}/flow/runs/{number}");
21591×
            if json {
21600×
                println!("{}", c.get_text(&path)?);
21610×
                return Ok(0);
21621×
            }
21631×
            print_run(&c.get(&path)?, timings);
2164
        }
21651×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
21661×
            let mut body = match (bookmark, change) {
21670×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
21680×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
21691×
                (None, None) => serde_json::json!({}),
2170
            };
21711×
            if !jobs.is_empty() {
21720×
                body["jobs"] = serde_json::json!(jobs);
21731×
            }
21741×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
21751×
            let n = started["number"].as_i64().context("the hub named no run")?;
21761×
            if !json || !follow {
21771×
                if json {
21780×
                    println!("{started}");
21791×
                } else {
21801×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
21811×
                }
21820×
            }
21831×
            if follow {
21840×
                return watch(c, &base, n, json);
21851×
            }
2186
        }
21870×
        RunCmd::Watch { number, bookmark } => {
21880×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
21890×
            return watch(c, &base, number, json);
2190
        }
21910×
        RunCmd::Log { number, job } => {
21920×
            let mut after = 0;
2193
            loop {
21940×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
21950×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
21960×
                if lines.is_empty() {
21970×
                    break;
21980×
                }
21990×
                for l in &lines {
22000×
                    if json {
22010×
                        println!("{}", serde_json::to_string(l)?);
22020×
                    } else if l.stream == "flow" {
22030×
                        println!("{}", ui::dim(&l.text));
22040×
                    } else {
22050×
                        println!("{}", l.text);
22060×
                    }
2207
                }
22080×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2209
            }
2210
        }
22110×
        RunCmd::Report { number, job, pick } => {
22120×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
22130×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
22140×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
22150×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2216
        }
22170×
        RunCmd::Rerun { number, job: Some(job) } => {
22180×
            let queued: serde_json::Value =
22190×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
22200×
            if json {
22210×
                println!("{queued}");
22220×
            } else {
22230×
                let n = queued["queued"].as_i64().unwrap_or(1);
22240×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
22250×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2226
            }
2227
        }
22280×
        RunCmd::Rerun { number, job: None } => {
22290×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
22300×
            if json {
22310×
                println!("{started}");
22320×
            } else {
22330×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
22340×
            }
2235
        }
22360×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
22370×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
22380×
        RunCmd::Cancel { number } => {
22390×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
22400×
            if json {
22410×
                println!("{done}");
22420×
            } else {
22430×
                println!("{} cancelled run #{number}", ui::ok("✔"));
22440×
            }
2245
        }
2246
    }
22472×
    Ok(0)
22483×
}
2249
22500×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
22510×
    let base = t.repo_path()?;
22520×
    match cmd {
2253
        LabelCmd::List => {
22540×
            let path = format!("{base}/labels");
22550×
            if json {
22560×
                println!("{}", c.get_text(&path)?);
22570×
                return Ok(0);
22580×
            }
22590×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
22600×
            if labels.is_empty() {
22610×
                println!("{}", ui::dim("No labels."));
22620×
            }
22630×
            for l in labels {
22640×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
22650×
            }
2266
        }
22670×
        LabelCmd::Create { name, colour, description } => {
22680×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
22690×
            if json {
22700×
                println!("{}", serde_json::to_string(&l)?);
22710×
            } else {
22720×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
22730×
            }
2274
        }
22750×
        LabelCmd::Delete { name } => {
22760×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
22770×
            println!("{} deleted label {name}", ui::ok("✔"));
2278
        }
2279
    }
22800×
    Ok(0)
22810×
}
2282
22830×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
22840×
    let base = match (&org, site) {
22850×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
22860×
        (None, true) => "/admin/assistants".to_string(),
22870×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2288
    };
22890×
    match cmd {
2290
        AssistantCmd::List => {
22910×
            if json {
22920×
                println!("{}", c.get_text(&base)?);
22930×
                return Ok(0);
22940×
            }
22950×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
22960×
            if list.is_empty() {
22970×
                println!("{}", ui::dim("No assistants."));
22980×
            }
22990×
            for a in list {
23000×
                let state = if a.enabled && !a.off_above {
23010×
                    ui::ok("on")
23020×
                } else if a.off_above {
23030×
                    ui::dim("off above")
2304
                } else {
23050×
                    ui::dim("off")
2306
                };
23070×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
23080×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2309
            }
2310
        }
23110×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
23120×
            let token = match token_env {
23130×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
23140×
                None => String::new(),
2315
            };
23160×
            let body =
23170×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
23180×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
23190×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2320
        }
23210×
        AssistantCmd::Remove { name } => {
23220×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
23230×
            println!("{} removed {name}", ui::ok("✔"));
2324
        }
23250×
        AssistantCmd::Prompt { set } => {
23260×
            let p: hub_api::AssistantPrompt = match set {
23270×
                Some(path) => {
23280×
                    let text = if path.as_os_str() == "-" {
23290×
                        let mut s = String::new();
23300×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
23310×
                        s
2332
                    } else {
23330×
                        std::fs::read_to_string(&path)?
2334
                    };
23350×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2336
                }
23370×
                None => c.get(&format!("{base}/prompt"))?,
2338
            };
23390×
            if json {
23400×
                println!("{}", serde_json::to_string(&p)?);
23410×
                return Ok(0);
23420×
            }
23430×
            for (from, text) in &p.inherited {
23440×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
23450×
            }
23460×
            if p.prompt.is_empty() {
23470×
                println!("{}", ui::dim("No prompt of its own."));
23480×
            } else {
23490×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
23500×
            }
2351
        }
2352
    }
23530×
    Ok(0)
23540×
}
2355
23562×
fn project_line(p: &hub_api::Project) -> String {
23572×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
23582×
    let private = if p.public { "" } else { " · private" };
23592×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
23602×
}
2361
236210×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
236310×
    let owner = match owner {
23640×
        Some(o) => o,
236510×
        None => t.repo()?.0.to_string(),
2366
    };
236710×
    let base = format!("/projects/{}", enc(&owner));
236810×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
23691×
        let p: hub_api::Project =
23701×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
23711×
        if json {
23720×
            println!("{}", serde_json::to_string(&p)?);
23731×
        } else {
23741×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
23751×
        }
23761×
        Ok(())
23771×
    };
23784×
    match cmd {
2379
        ProjectCmd::List => {
23801×
            if json {
23810×
                println!("{}", c.get_text(&base)?);
23820×
                return Ok(0);
23831×
            }
23841×
            let list: Vec<hub_api::Project> = c.get(&base)?;
23851×
            if list.is_empty() {
23860×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
23871×
            }
23881×
            for p in &list {
23891×
                println!("{}", project_line(p));
23901×
            }
2391
        }
23923×
        ProjectCmd::View { number, archived, filter, view } => {
23933×
            let cards = format!("{base}/{number}/cards?archived=true");
23943×
            let path = match (&filter, &view) {
23950×
                (Some(q), _) => format!("{base}/{number}?q={}", enc(q)),
23960×
                (None, Some(v)) => format!("{base}/{number}?view={}", enc(v)),
23973×
                (None, None) => format!("{base}/{number}"),
2398
            };
23993×
            if json {
24002×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
24012×
                return Ok(0);
24021×
            }
24031×
            let mut b: hub_api::Board = c.get(&path)?;
24041×
            if archived {
24050×
                b.columns = c.get(&cards)?;
24061×
            }
24071×
            println!("{}", project_line(&b.project));
24081×
            if !b.project.description.is_empty() {
24091×
                println!("{}", b.project.description);
24101×
            }
24111×
            if !b.filter.is_empty() {
24120×
                println!("{}", ui::dim(&format!("filter: {}", b.filter)));
24131×
            }
24141×
            if !b.views.is_empty() && filter.is_none() && view.is_none() {
24150×
                let names: Vec<&str> = b.views.iter().map(|v| v.name.as_str()).collect();
24160×
                println!("{}", ui::dim(&format!("views: {} (oh project view {number} --view NAME)", names.join(", "))));
24171×
            }
24183×
            for col in &b.columns {
24193×
                println!();
24203×
                let wip = match col.wip_limit {
24210×
                    Some(w) if col.cards.len() as i64 > w => format!(" · over its limit of {w}"),
24220×
                    Some(w) => format!(" · limit {w}"),
24233×
                    None => String::new(),
2424
                };
24253×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}{wip}", col.cards.len(), col.id)));
24263×
                if col.cards.is_empty() {
24271×
                    println!("  {}", ui::dim("(empty)"));
24282×
                }
24293×
                for card in &col.cards {
24302×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
24312×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
24322×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
24332×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
24342×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
24352×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2436
                }
2437
            }
24381×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2439
        }
24401×
        ProjectCmd::Create { title, description, private } => {
24411×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
24421×
            if json {
24430×
                println!("{}", serde_json::to_string(&p)?);
24441×
            } else {
24451×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
24461×
            }
2447
        }
24480×
        ProjectCmd::Column { cmd } => {
24490×
            let col_path = |number: i64, column: &str| format!("{base}/{number}/columns/{}", enc(column));
24500×
            let (number, b, what): (i64, hub_api::Board, String) = match cmd {
24510×
                ColumnCmd::Add { number, name } => {
24520×
                    let b = c.send("POST", &format!("{base}/{number}/columns"), &hub_api::NewColumn { name: name.clone() })?;
24530×
                    (number, b, format!("added column {name}"))
2454
                }
24550×
                ColumnCmd::Rename { number, column, to } => {
24560×
                    let edit = hub_api::ColumnEdit { name: Some(to.clone()), position: None };
24570×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("renamed column {column} to {to}"))
2458
                }
24590×
                ColumnCmd::Move { number, column, to, left, right } => {
24600×
                    let position = match to {
24610×
                        Some(n) => n - 1,
2462
                        None => {
24630×
                            let now: hub_api::Board = c.get(&format!("{base}/{number}"))?;
24640×
                            let at = now
24650×
                                .columns
24660×
                                .iter()
24670×
                                .position(|col| col.id.to_string() == column || col.name.eq_ignore_ascii_case(&column))
24680×
                                .with_context(|| format!("no column {column} on board {number}"))?
2469
                                as i64;
24700×
                            if left {
24710×
                                (at - 1).max(0)
2472
                            } else {
24730×
                                debug_assert!(right);
24740×
                                at + 1
2475
                            }
2476
                        }
2477
                    };
24780×
                    let edit = hub_api::ColumnEdit { name: None, position: Some(position) };
24790×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("moved column {column}"))
2480
                }
24810×
                ColumnCmd::Remove { number, column } => {
24820×
                    (number, c.send("DELETE", &col_path(number, &column), &serde_json::json!({}))?, format!("removed column {column}"))
2483
                }
2484
            };
24850×
            if json {
24860×
                println!("{}", serde_json::to_string(&b)?);
2487
            } else {
24880×
                let order: Vec<&str> = b.columns.iter().map(|col| col.name.as_str()).collect();
24890×
                println!("{} {what} on board {number}: {}", ui::ok("✔"), ui::dim(&order.join(" · ")));
2490
            }
2491
        }
24921×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
24930×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
24940×
        ProjectCmd::Transfer { number, to } => {
24950×
            let p: hub_api::Project =
24960×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
24970×
            if json {
24980×
                println!("{}", serde_json::to_string(&p)?);
24990×
            } else {
25000×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
25010×
            }
2502
        }
25032×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2504
            // The hub names a card's issue as `repo#N` among the owner's
2505
            // repositories.
25062×
            let reference = match reference {
25071×
                None => String::new(),
25081×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
25090×
                    Some((o, rest)) if o == owner => rest.to_string(),
25100×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
25110×
                    None => r,
2512
                },
25131×
                Some(r) => {
25141×
                    let n = r.trim_start_matches('#');
25151×
                    if n.parse::<i64>().is_err() {
25160×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
25171×
                    }
25181×
                    format!("{}#{n}", t.repo()?.1)
2519
                }
2520
            };
25212×
            let note = note.unwrap_or_default();
25222×
            if reference.is_empty() && note.is_empty() {
25230×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
25242×
            }
25251×
            let card: hub_api::ProjectCard =
25262×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
25271×
            if json {
25280×
                println!("{}", serde_json::to_string(&card)?);
2529
            } else {
25301×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2531
            }
2532
        }
25331×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
25341×
            (Some(card), None) => {
25351×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
25361×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2537
            }
25380×
            (None, Some(from)) => {
25390×
                let r: hub_api::CardsMoved = c.send(
25400×
                    "POST",
25410×
                    &format!("{base}/{number}/cards/move"),
25420×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
25430×
                )?;
25440×
                if json {
25450×
                    println!("{}", serde_json::to_string(&r)?);
25460×
                    return Ok(0);
25470×
                }
25480×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
25490×
                for m in &r.moved {
25500×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2551
                }
25520×
                let verb = if dry_run { "would move" } else { "moved" };
25530×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2554
            }
25550×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2556
        },
25570×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
25580×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
25590×
                None => None,
25600×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2561
            };
25620×
            let r: hub_api::CardsArchived = c.send(
25630×
                "POST",
25640×
                &format!("{base}/{number}/cards/archive"),
25650×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
25660×
            )?;
25670×
            if json {
25680×
                println!("{}", serde_json::to_string(&r)?);
25690×
                return Ok(0);
25700×
            }
25710×
            let verb = if dry_run { "would archive" } else { "archived" };
25720×
            for a in &r.archived {
25730×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
25740×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2575
            }
25760×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2577
        }
25780×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
25790×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
25800×
            println!("{} card {card} restored", ui::ok("✔"));
2581
        }
25821×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
25831×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
25841×
            println!("{} card {card} removed", ui::ok("✔"));
2585
        }
2586
    }
25877×
    Ok(0)
258810×
}
2589
25900×
fn milestone_line(m: &hub_api::Milestone) -> String {
25910×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
25920×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
25930×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
25940×
}
2595
25960×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
25970×
    let base = t.repo_path()?;
25980×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
25990×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
26000×
        if json {
26010×
            println!("{}", serde_json::to_string(&m)?);
26020×
        } else {
26030×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
26040×
        }
26050×
        Ok(())
26060×
    };
26070×
    match cmd {
2608
        MilestoneCmd::List => {
26090×
            let path = format!("{base}/milestones");
26100×
            if json {
26110×
                println!("{}", c.get_text(&path)?);
26120×
                return Ok(0);
26130×
            }
26140×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
26150×
            if list.is_empty() {
26160×
                println!("{}", ui::dim("No milestones."));
26170×
            }
26180×
            for m in &list {
26190×
                println!("{}", milestone_line(m));
26200×
            }
2621
        }
26220×
        MilestoneCmd::Create { title, description, due } => {
26230×
            let m: hub_api::Milestone =
26240×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
26250×
            if json {
26260×
                println!("{}", serde_json::to_string(&m)?);
26270×
            } else {
26280×
                println!("{} milestone {}", ui::ok("✔"), m.title);
26290×
            }
2630
        }
26310×
        MilestoneCmd::Edit { title, rename, description, due } => {
26320×
            if rename.is_none() && description.is_none() && due.is_none() {
26330×
                bail!("say what to change: --rename, --description or --due");
26340×
            }
26350×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2636
        }
26370×
        MilestoneCmd::Close { title } => {
26380×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2639
        }
26400×
        MilestoneCmd::Reopen { title } => {
26410×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2642
        }
2643
    }
26440×
    Ok(0)
26450×
}
2646
26470×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
26480×
    let base = t.repo_path()?;
26490×
    match cmd {
2650
        TagCmd::List => {
26510×
            let path = format!("{base}/tags");
26520×
            if json {
26530×
                println!("{}", c.get_text(&path)?);
26540×
                return Ok(0);
26550×
            }
26560×
            let tags: Vec<Tag> = c.get(&path)?;
26570×
            if tags.is_empty() {
26580×
                println!("{}", ui::dim("no tags"));
26590×
            }
26600×
            for t in tags {
26610×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
26620×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
26630×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2664
            }
2665
        }
26660×
        TagCmd::Create { name, target, message } => {
26670×
            let new = hub_api::NewTag { name, target, message };
26680×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
26690×
            if json {
26700×
                println!("{}", serde_json::to_string(&made)?);
26710×
            } else {
26720×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
26730×
            }
2674
        }
26750×
        TagCmd::Delete { name, reason } => {
26760×
            let reason = reason.unwrap_or_default();
26770×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
26780×
            if json {
26790×
                println!("{}", serde_json::json!({ "withdrawn": name }));
26800×
            } else {
26810×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
26820×
            }
2683
        }
2684
    }
26850×
    Ok(0)
26860×
}
2687
26884×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
26894×
    let base = t.repo_path()?;
26904×
    match cmd {
2691
        ReleaseCmd::List => {
26921×
            let path = format!("{base}/releases");
26931×
            if json {
26941×
                println!("{}", c.get_text(&path)?);
26951×
                return Ok(0);
26960×
            }
26970×
            let list: Vec<Release> = c.get(&path)?;
26980×
            if list.is_empty() {
26990×
                println!("{}", ui::dim("No releases."));
27000×
            }
27010×
            for r in &list {
27020×
                println!(
2703
                    "{} {} {}{}",
27040×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
27050×
                    ui::strong(&r.tag),
2706
                    r.title,
27070×
                    ui::dim(&format!(
2708
                        " · {} asset{} · {}",
27090×
                        r.assets.len(),
27100×
                        if r.assets.len() == 1 { "" } else { "s" },
27110×
                        ui::ago(r.created_ms)
2712
                    ))
2713
                );
2714
            }
2715
        }
27161×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
27171×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
27181×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
27191×
            if json {
27200×
                println!("{}", serde_json::to_string(&r)?);
27211×
            } else {
27221×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
27231×
            }
2724
        }
27250×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
27260×
            let notes = match notes.as_deref() {
27270×
                Some("-") => Some(body_of(None, Some("-".into()))?),
27280×
                _ => notes,
2729
            };
27300×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
27310×
                bail!("say what to change: --title, --notes or --prerelease");
27320×
            }
27330×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
27340×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
27350×
            if json {
27360×
                println!("{}", serde_json::to_string(&r)?);
27370×
            } else {
27380×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
27390×
            }
2740
        }
27411×
        ReleaseCmd::Upload { tag, files } => {
27421×
            if files.is_empty() {
27430×
                bail!("name the files to attach");
27441×
            }
27451×
            for f in files {
27461×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
27471×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
27481×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
27491×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2750
            }
2751
        }
27521×
        ReleaseCmd::Trust { tag } => {
27531×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
27541×
            if json {
27550×
                println!("{}", c.get_text(&path)?);
27560×
                return Ok(0);
27571×
            }
27581×
            let r: serde_json::Value = c.get(&path)?;
27591×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
27601×
            let mut worst = 0;
27614×
            for ch in r["audit"].as_array().into_iter().flatten() {
27624×
                let v = ch["verdict"].as_str().unwrap_or("");
27634×
                worst = worst.max(match v {
27644×
                    "fail" => 2,
27654×
                    "warn" => 1,
27663×
                    _ => 0,
2767
                });
27684×
                let g = match v {
27694×
                    "pass" => ui::ok("✔"),
27701×
                    "warn" => ui::warn("!"),
27710×
                    _ => ui::bad("✘"),
2772
                };
27734×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2774
            }
27751×
            return Ok(if worst == 2 { 1 } else { 0 });
2776
        }
2777
    }
27782×
    Ok(0)
27794×
}
2780
2781
#[cfg(test)]
2782
mod tests {
2783
2784
    #[test]
27851×
    fn job_timings_and_report_commands_read_plainly() {
2786
        use clap::Parser;
27871×
        let job = hub_api::FlowJob {
27881×
            name: "perf".into(),
27891×
            status: "passed".into(),
27901×
            depends_on: vec![],
27911×
            runner: "earth-1".into(),
27921×
            exit_code: Some(0),
27931×
            error: String::new(),
27941×
            started_ms: Some(13_000),
27951×
            finished_ms: Some(200_000),
27961×
            log_lines: 10,
27971×
            waiting: String::new(),
27981×
            placed: String::new(),
27991×
            approval: String::new(),
28001×
            queued_ms: Some(1_000),
28011×
            ready_ms: Some(12_500),
28021×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
28031×
            peak_disk_mib: Some(2150),
28041×
            peak_memory_mib: Some(900),
28051×
        };
28061×
        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");
28071×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
28081×
        assert_eq!(super::timing_line(&bare), "");
28091×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2810
28111×
        let cli =
28121×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
28131×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
28141×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
28151×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
28161×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
28171×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
28181×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
28191×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
28201×
    }
2821
2822
    #[test]
28231×
    fn runner_update_scopes_resolve_by_name_or_id() {
28241×
        let all = hub_api::RunnerUpdates {
28251×
            repo: String::new(),
28261×
            settings: vec![],
28271×
            groups: vec![hub_api::RunnerGroup {
28281×
                id: 4,
28291×
                owner: "acme".into(),
28301×
                name: "canary".into(),
28311×
                percent: None,
28321×
                members: vec![],
28331×
                wave: None,
28341×
            }],
28351×
            runners: vec![],
28361×
            holds: vec![],
28371×
        };
28381×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
28391×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
28403×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
28413×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2842
        }
28431×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
28441×
        assert!(update_scope("everyone", &all).is_err());
28451×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
28461×
        assert!(switch(Some("yes")).is_err());
28471×
    }
2848
    use super::*;
2849
2850
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2851
    /// help says, and a drop is named by its id or its address.
2852
    #[test]
28531×
    fn drop_commands_parse() {
28541×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
28551×
        match cli.cmd {
28561×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
28571×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
28581×
                assert!(secret);
28591×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2860
            }
28610×
            _ => panic!("not drop create"),
2862
        }
28631×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
28641×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
28651×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
28661×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
28671×
                assert!(channel.is_none() && dry_run.is_none());
2868
            }
28690×
            _ => panic!("not runner-updates set"),
2870
        }
28711×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
28721×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
28731×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
28740×
            _ => panic!("not drop list"),
2875
        }
28761×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
28771×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
28781×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2879
            }
28800×
            _ => panic!("not drop view"),
2881
        }
28821×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
28834×
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
28844×
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2885
        }
28861×
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
28871×
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
28881×
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
28890×
            _ => panic!("not drop comment"),
2890
        }
28911×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
28921×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
28931×
        assert!(drop_id("andy/notes").is_err());
28941×
    }
2895
}