OXYGENHUB

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

672 of 1726 lines run, 49 of 265 functions · run #542 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 charts from its own history: forecasts, cycle time,
572
    /// throughput (#357)
573
    Charts {
574
        /// The board
575
        number: i64,
576
        /// Forecast only the cards this filter keeps (words, repo:, label:, milestone:…)
577
        #[arg(long, short = 'q')]
578
        filter: Option<String>,
579
    },
580
    /// A board's columns: add, rename, move, remove (#366)
581
    Column {
582
        #[command(subcommand)]
583
        cmd: ColumnCmd,
584
    },
585
}
586
587
#[derive(Subcommand)]
588
enum ColumnCmd {
589
    /// Add a column at the right
590
    Add {
591
        /// The board
592
        number: i64,
593
        name: String,
594
    },
595
    /// Rename a column (by name or id)
596
    Rename {
597
        /// The board
598
        number: i64,
599
        column: String,
600
        /// Its new name
601
        to: String,
602
    },
603
    /// Move a column: --to POSITION (1 is the leftmost), --left or --right
604
    Move {
605
        /// The board
606
        number: i64,
607
        column: String,
608
        /// Its place, counting from 1 at the left
609
        #[arg(long, conflicts_with_all = ["left", "right"], required_unless_present_any = ["left", "right"])]
610
        to: Option<i64>,
611
        /// One place to the left
612
        #[arg(long, conflicts_with = "right")]
613
        left: bool,
614
        /// One place to the right
615
        #[arg(long)]
616
        right: bool,
617
    },
618
    /// Remove a column; its cards go to the first remaining one
619
    Remove {
620
        /// The board
621
        number: i64,
622
        column: String,
623
    },
624
}
625
626
#[derive(Subcommand)]
627
enum CardCmd {
628
    /// Put an issue or proposal on a board (`12` or `#12` in this
629
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
630
    /// or a note with --note
631
    Add {
632
        number: i64,
633
        /// The issue or proposal; a number means this repository's
634
        reference: Option<String>,
635
        /// A note card instead
636
        #[arg(long, conflicts_with = "reference")]
637
        note: Option<String>,
638
        /// The column, by name or id (default: the first)
639
        #[arg(long, short)]
640
        column: Option<String>,
641
    },
642
    /// Move a card to another column (by name or id), or with --from every
643
    /// card of a column at once
644
    Move {
645
        number: i64,
646
        /// The card (its id); leave it out with --from
647
        card: Option<i64>,
648
        #[arg(long, short)]
649
        column: String,
650
        /// Move every card of this column (#289)
651
        #[arg(long, conflicts_with = "card")]
652
        from: Option<String>,
653
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
654
        #[arg(long, value_delimiter = ',', requires = "from")]
655
        except: Vec<String>,
656
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
657
        #[arg(long, value_delimiter = ',', requires = "from")]
658
        state: Vec<String>,
659
        /// With --from: say what would move, and move nothing
660
        #[arg(long, requires = "from")]
661
        dry_run: bool,
662
    },
663
    /// Archive a column's cards: off the board, kept and restorable (#293)
664
    Archive {
665
        number: i64,
666
        /// The column, by name or id
667
        #[arg(long)]
668
        from: String,
669
        /// Only cards that joined the column more than this long ago (14d, or 14)
670
        #[arg(long)]
671
        older: Option<String>,
672
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
673
        #[arg(long, value_delimiter = ',')]
674
        except: Vec<String>,
675
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
676
        #[arg(long, value_delimiter = ',')]
677
        state: Vec<String>,
678
        /// Say what would be archived, and archive nothing
679
        #[arg(long)]
680
        dry_run: bool,
681
    },
682
    /// Put an archived card back at the end of its column
683
    Restore { number: i64, card: i64 },
684
    /// Take a card off a board
685
    Remove { number: i64, card: i64 },
686
}
687
688
#[derive(Subcommand)]
689
enum MilestoneCmd {
690
    /// The repository's milestones
691
    List,
692
    /// Create a milestone, or change the one of that title (triage)
693
    Create {
694
        title: String,
695
        #[arg(long, short, default_value = "")]
696
        description: String,
697
        /// Due date, YYYY-MM-DD
698
        #[arg(long)]
699
        due: Option<String>,
700
    },
701
    /// Change a milestone's title, description or due date (triage)
702
    Edit {
703
        title: String,
704
        #[arg(long, short)]
705
        rename: Option<String>,
706
        #[arg(long, short)]
707
        description: Option<String>,
708
        /// Due date, YYYY-MM-DD ("" for none)
709
        #[arg(long)]
710
        due: Option<String>,
711
    },
712
    /// Close a milestone
713
    Close { title: String },
714
    /// Reopen a milestone
715
    Reopen { title: String },
716
}
717
718
/// Labels to put on or take off an issue or proposal.
719
#[derive(clap::Args)]
720
struct LabelChange {
721
    number: i64,
722
    /// A label to add (repeatable)
723
    #[arg(long, short)]
724
    add: Vec<String>,
725
    /// A label to take off (repeatable)
726
    #[arg(long, short)]
727
    remove: Vec<String>,
728
}
729
730
impl LabelChange {
731
    /// The set after the change, from the one there now.
7320×
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
7330×
        if self.add.is_empty() && self.remove.is_empty() {
7340×
            bail!("say what to change: --add NAME or --remove NAME");
7350×
        }
7360×
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
7370×
        for a in &self.add {
7380×
            if !names.contains(a) {
7390×
                names.push(a.clone());
7400×
            }
741
        }
7420×
        Ok(names)
7430×
    }
744
}
745
7460×
fn label_names(labels: &[String]) -> String {
7470×
    if labels.is_empty() {
7480×
        ui::dim("no labels")
749
    } else {
7500×
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
751
    }
7520×
}
753
754
#[derive(Subcommand)]
755
enum CoverageCmd {
756
    /// Upload an LCOV or Cobertura report measured on this machine, as the
757
    /// coverage of a bookmark's current state (default: the default
758
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
759
    /// not measured by a runner, and sets no check from it
760
    Upload {
761
        file: std::path::PathBuf,
762
        #[arg(long)]
763
        bookmark: Option<String>,
764
        /// A change's full hash
765
        #[arg(long, conflicts_with = "bookmark")]
766
        change: Option<String>,
767
    },
768
}
769
770
#[derive(Subcommand)]
771
enum RunCmd {
772
    /// Recent runs, newest first
773
    List {
774
        #[arg(long, default_value_t = 20)]
775
        limit: i64,
776
    },
777
    /// A run and its jobs (default: the newest run)
778
    View {
779
        /// The run (default: the newest, or the newest of --bookmark)
780
        number: Option<i64>,
781
        /// With no number: the newest run of this bookmark
782
        #[arg(long, conflicts_with = "number")]
783
        bookmark: Option<String>,
784
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
785
        #[arg(long)]
786
        timings: bool,
787
    },
788
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
789
    Start {
790
        #[arg(long)]
791
        bookmark: Option<String>,
792
        /// A change's full hash
793
        #[arg(long, conflicts_with = "bookmark")]
794
        change: Option<String>,
795
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
796
        #[arg(long = "job", value_name = "NAME")]
797
        jobs: Vec<String>,
798
        /// Wait for the run and exit 1 unless it passes
799
        #[arg(long)]
800
        watch: bool,
801
    },
802
    /// Follow a run until it finishes (default: the newest run); exit 1 unless it passes
803
    Watch {
804
        /// The run (default: the newest, or the newest of --bookmark) (#367)
805
        number: Option<i64>,
806
        /// With no number: the newest run of this bookmark
807
        #[arg(long, conflicts_with = "number")]
808
        bookmark: Option<String>,
809
    },
810
    /// A job's log
811
    Log { number: i64, job: String },
812
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
813
    Report {
814
        number: i64,
815
        job: String,
816
        #[command(flatten)]
817
        pick: ReportPick,
818
    },
819
    /// Run a finished run's state again; with --job, only that job (and the
820
    /// jobs that depend on it) in the same run
821
    Rerun {
822
        number: i64,
823
        #[arg(long)]
824
        job: Option<String>,
825
    },
826
    /// Cancel a run still queued or running; its running jobs are stopped
827
    Cancel { number: i64 },
828
    /// Approve a job that waits for a person (oxygenflow#57)
829
    Approve {
830
        number: i64,
831
        #[arg(long)]
832
        job: String,
833
    },
834
    /// Reject a job that waits for a person: it ends cancelled
835
    Reject {
836
        number: i64,
837
        #[arg(long)]
838
        job: String,
839
    },
840
}
841
842
/// Which report of a job, and what of it to show.
843
#[derive(clap::Args)]
844
struct ReportPick {
845
    /// Which report, when the job published more than one
846
    #[arg(long)]
847
    name: Option<String>,
848
    /// What it holds: its metrics, context and files
849
    #[arg(long, conflicts_with = "file")]
850
    list: bool,
851
    /// One file of it (`data/frames.csv`), as published
852
    #[arg(long, value_name = "PATH")]
853
    file: Option<String>,
854
    /// Write the file here instead of to stdout
855
    #[arg(long, short, value_name = "FILE", requires = "file")]
856
    output: Option<std::path::PathBuf>,
857
}
858
859
#[derive(Subcommand)]
860
enum ReportCmd {
861
    /// The newest run of each report, newest first
862
    List {
863
        /// Only runs on this bookmark
864
        #[arg(long)]
865
        bookmark: Option<String>,
866
    },
867
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
868
    Show {
869
        report: String,
870
        #[arg(long, conflicts_with = "bookmark")]
871
        id: Option<i64>,
872
        #[arg(long)]
873
        bookmark: Option<String>,
874
        /// What it holds: its metrics, context and files
875
        #[arg(long, conflicts_with = "file")]
876
        list: bool,
877
        /// One file of it, as published
878
        #[arg(long, value_name = "PATH")]
879
        file: Option<String>,
880
        /// Write the file here instead of to stdout
881
        #[arg(long, short, value_name = "FILE", requires = "file")]
882
        output: Option<std::path::PathBuf>,
883
    },
884
}
885
886
#[derive(Subcommand)]
887
enum TagCmd {
888
    /// Tags, newest name first
889
    List,
890
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
891
    /// delegate (as `oxy tag create` and a push would be)
892
    Create {
893
        name: String,
894
        /// What to tag (default: the default bookmark)
895
        #[arg(long)]
896
        target: Option<String>,
897
        #[arg(long, short)]
898
        message: Option<String>,
899
    },
900
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
901
    /// their next fetch, and the name is never used again. Refused while a
902
    /// release uses the tag
903
    Delete {
904
        name: String,
905
        /// Why, recorded with the withdrawal
906
        #[arg(long, short)]
907
        reason: Option<String>,
908
    },
909
}
910
911
#[derive(Subcommand)]
912
enum ReleaseCmd {
913
    /// Releases, newest first
914
    List,
915
    /// Create a release on an existing tag
916
    Create {
917
        tag: String,
918
        #[arg(long, short)]
919
        title: Option<String>,
920
        /// Notes in Markdown (default: generated from the changes since the previous release)
921
        #[arg(long, short)]
922
        notes: Option<String>,
923
        #[arg(long)]
924
        prerelease: bool,
925
    },
926
    /// Change a release's title, notes or prerelease flag
927
    Edit {
928
        tag: String,
929
        #[arg(long, short)]
930
        title: Option<String>,
931
        /// New notes in Markdown ("-" reads them from stdin)
932
        #[arg(long, short)]
933
        notes: Option<String>,
934
        /// Mark it a prerelease (true) or not (false)
935
        #[arg(long)]
936
        prerelease: Option<bool>,
937
    },
938
    /// Attach files to a release
939
    Upload { tag: String, files: Vec<std::path::PathBuf> },
940
    /// The release's trust report: signatures, builds, receipts and audit
941
    Trust { tag: String },
942
}
943
94453×
fn main() {
945
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
946
    // other command-line tools do, instead of panicking on the failed
947
    // write (oxygenhub#92).
948
    #[cfg(unix)]
94953×
    unsafe {
95053×
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
95153×
    }
95253×
    let cli = Cli::parse();
95353×
    ui::init(cli.plain);
95453×
    match run(cli) {
95545×
        Ok(code) => std::process::exit(code),
9568×
        Err(e) => {
9578×
            eprintln!("{} {e:#}", ui::bad("error:"));
9588×
            std::process::exit(2);
959
        }
960
    }
961
}
962
96322×
fn enc(s: &str) -> String {
96422×
    let mut out = String::new();
965109×
    for b in s.bytes() {
966109×
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
967108×
            out.push(b as char);
968108×
        } else {
9691×
            out.push_str(&format!("%{b:02X}"));
9701×
        }
971
    }
97222×
    out
97322×
}
974
97553×
fn run(cli: Cli) -> Result<i32> {
97653×
    let cfg = Config::load()?;
9771×
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
9781×
        return login(cfg, url, token.clone(), ca.clone());
97952×
    }
98052×
    let here = std::env::current_dir()?;
98152×
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
98251×
    let c = Client::new(&t)?;
98351×
    let json = cli.json;
9840×
    match cli.cmd {
985
        Cmd::Auth { cmd: AuthCmd::Status } => {
9860×
            let me: serde_json::Value = c.get("/user")?;
9870×
            if json {
9880×
                println!("{me}");
9890×
            } else {
9900×
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
9910×
            }
9920×
            Ok(0)
993
        }
9940×
        Cmd::Auth { .. } => unreachable!(),
9952×
        Cmd::Mcp { allow_write } => {
9962×
            t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?;
9972×
            mcp::serve(c, t, allow_write)
998
        }
9992×
        Cmd::Api { path, method, data } => {
10002×
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
1001
            // The method applies with or without a body (#75): without one, a
1002
            // GET reads, anything else sends an empty object.
10032×
            let text = match data {
10040×
                Some(d) => c.send_text(
10050×
                    &method.to_uppercase(),
10060×
                    &path,
10070×
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
10080×
                )?,
10092×
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
10100×
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
1011
            };
10122×
            println!("{text}");
10132×
            Ok(0)
1014
        }
1015
        Cmd::Repo { cmd: RepoCmd::View } => {
10161×
            let path = t.repo_path()?;
10171×
            if json {
10180×
                println!("{}", c.get_text(&path)?);
10190×
                return Ok(0);
10201×
            }
10211×
            let r: serde_json::Value = c.get(&path)?;
10221×
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
10231×
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
10241×
                println!("{d}");
10251×
            }
10261×
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
10271×
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
10281×
            Ok(0)
1029
        }
103018×
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
10314×
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
10323×
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
10330×
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
10340×
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
10350×
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
10360×
            let mut body = serde_json::json!({ "content": content });
10370×
            if let Some(b) = bookmark {
10380×
                body["bookmark"] = b.into();
10390×
            }
10400×
            if let Some(ch) = change {
10410×
                body["change"] = ch.into();
10420×
            }
10430×
            let base = t.repo_path()?;
10440×
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
10450×
            if json {
10460×
                println!("{}", serde_json::to_string(&r)?);
1047
            } else {
10480×
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
10490×
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
10500×
                println!(
1051
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
10520×
                    ui::ok("✔"),
1053
                    r.lines_hit,
1054
                    r.lines_found,
1055
                    r.files,
10560×
                    ui::dim(&r.url)
1057
                );
10580×
                if r.dropped > 0 {
10590×
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
10600×
                }
1061
            }
10620×
            Ok(0)
1063
        }
10644×
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
10650×
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
10660×
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
10670×
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
106810×
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
10690×
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
10700×
        Cmd::Agent { cmd } => agent(&c, cmd, json),
10710×
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
10727×
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
1073
    }
107453×
}
1075
1076
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
10772×
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
10782×
    Ok(match v {
10790×
        None => None,
10802×
        Some("on") => Some(Some(true)),
10812×
        Some("off") => Some(Some(false)),
10822×
        Some("inherit") => Some(None),
10831×
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1084
    })
10852×
}
1086
1087
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
10887×
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
10897×
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
10901×
    Ok(match kind {
10917×
        "site" if name.is_empty() => ("site".into(), String::new()),
10926×
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
10935×
        "group" => {
10943×
            let g = all
10953×
                .groups
10963×
                .iter()
10973×
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
10983×
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
10993×
            ("group".into(), g.id.to_string())
1100
        }
11012×
        "runner" => {
11021×
            let r = all
11031×
                .runners
11041×
                .iter()
11051×
                .find(|r| r.id.to_string() == name || r.name == name)
11061×
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
11070×
            ("runner".into(), r.id.to_string())
1108
        }
11091×
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1110
    })
11117×
}
1112
11130×
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
11140×
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
11150×
    match cmd {
11160×
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1117
        RunnerUpdatesCmd::Show => {
11180×
            println!(
1119
                "{} {}",
11200×
                ui::strong("Builds from"),
11210×
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1122
            );
11230×
            for h in &all.holds {
11240×
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
11250×
            }
11260×
            for s in &all.settings {
11270×
                let mut said = vec![];
11280×
                if let Some(u) = s.updates {
11290×
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
11300×
                }
11310×
                if let Some(ch) = &s.channel {
11320×
                    said.push(format!("channel {ch}"));
11330×
                }
11340×
                if let Some(w) = &s.window {
11350×
                    said.push(format!("window {w} UTC"));
11360×
                }
11370×
                if let Some(d) = s.dry_run {
11380×
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
11390×
                }
11400×
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
11410×
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1142
            }
11430×
            for g in &all.groups {
11440×
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
11450×
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
11460×
                if let Some(w) = g.wave {
11470×
                    what.push_str(&format!(", wave {w}"));
11480×
                }
11490×
                println!(
1150
                    "  group {} ({what}): {}",
11510×
                    ui::strong(&g.name),
11520×
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1153
                );
1154
            }
11550×
            for r in &all.runners {
11560×
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
11570×
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1158
            }
1159
        }
11600×
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
11610×
            let (scope, key) = update_scope(&scope, &all)?;
11620×
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
11630×
                scope: scope.clone(),
11640×
                key: key.clone(),
11650×
                ..Default::default()
11660×
            });
11670×
            if let Some(u) = switch(updates.as_deref())? {
11680×
                s.updates = u;
11690×
            }
11700×
            if let Some(d) = switch(dry_run.as_deref())? {
11710×
                s.dry_run = d;
11720×
            }
11730×
            if let Some(ch) = channel {
11740×
                s.channel = Some(ch).filter(|c| c != "inherit");
11750×
            }
11760×
            if let Some(w) = window {
11770×
                s.window = Some(w).filter(|w| w != "inherit");
11780×
            }
11790×
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
11800×
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1181
        }
11820×
        RunnerUpdatesCmd::Lift { version } => {
11830×
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
11840×
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1185
        }
1186
    }
11870×
    Ok(0)
11880×
}
1189
1190
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
11917×
fn drop_id(s: &str) -> Result<String> {
11927×
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1193144×
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
11941×
        bail!("{s:?} is not a drop's id or address");
11956×
    }
11966×
    Ok(id.to_ascii_lowercase())
11977×
}
1198
11992×
fn drop_line(d: &hub_api::Drop) -> String {
12002×
    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() };
12014×
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
12022×
    format!(
1203
        "{} {} {}{}",
12042×
        ui::dim(&d.id),
12052×
        ui::strong(&title),
12062×
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
12072×
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1208
    )
12092×
}
1210
1211
/// `oh drop star|unstar` (oxygenhub#349).
12120×
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
12130×
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
12140×
    if json {
12150×
        println!("{}", serde_json::to_string(&s)?);
1216
    } else {
12170×
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1218
    }
12190×
    Ok(())
12200×
}
1221
12227×
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
12237×
    match cmd {
12241×
        DropCmd::Create { files, secret, description, title } => {
12251×
            let mut out = Vec::with_capacity(files.len());
12262×
            for f in &files {
12272×
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
12282×
                let content =
12292×
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
12302×
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1231
            }
12321×
            let new =
12331×
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
12341×
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
12351×
            if json {
12361×
                println!("{}", serde_json::to_string(&d)?);
1237
            } else {
12380×
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
12390×
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1240
            }
1241
        }
12422×
        DropCmd::List { user } => {
12432×
            let path = match &user {
12441×
                Some(u) => format!("/users/{}/drops", enc(u)),
12451×
                None => "/drops".to_string(),
1246
            };
12472×
            if json {
12481×
                println!("{}", c.get_text(&path)?);
12491×
                return Ok(0);
12501×
            }
12511×
            let list: Vec<hub_api::Drop> = c.get(&path)?;
12521×
            if list.is_empty() {
12530×
                println!("{}", ui::dim("No drops."));
12541×
            }
12551×
            for d in &list {
12561×
                println!("{}", drop_line(d));
12571×
            }
1258
        }
12593×
        DropCmd::View { id, file } => {
12603×
            let path = format!("/drops/{}", drop_id(&id)?);
12613×
            if json && file.is_none() {
12620×
                println!("{}", c.get_text(&path)?);
12630×
                return Ok(0);
12643×
            }
12653×
            let d: hub_api::Drop = c.get(&path)?;
12662×
            if let Some(name) = file {
12672×
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
12681×
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
12691×
                print!("{content}");
12701×
                return Ok(0);
12711×
            }
12721×
            println!("{}", drop_line(&d));
12731×
            if !d.description.is_empty() {
12741×
                println!("{}", d.description);
12751×
            }
12761×
            println!("{}", ui::kv("url", &d.url));
12771×
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
12782×
            for f in &d.files {
12792×
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
12802×
                match &f.content {
12812×
                    Some(text) => {
12822×
                        print!("{text}");
12832×
                        if !text.ends_with('\n') && !text.is_empty() {
12840×
                            println!();
12852×
                        }
1286
                    }
12870×
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1288
                }
1289
            }
1290
        }
12911×
        DropCmd::Delete { id } => {
12921×
            let id = drop_id(&id)?;
12931×
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
12941×
            println!("{} drop {id}", ui::ok("✔ deleted"));
1295
        }
12960×
        DropCmd::Fork { id } => {
12970×
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
12980×
            if json {
12990×
                println!("{}", serde_json::to_string(&d)?);
13000×
            } else {
13010×
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
13020×
            }
1303
        }
13040×
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
13050×
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
13060×
        DropCmd::Comments { id } => {
13070×
            let path = format!("/drops/{}/comments", drop_id(&id)?);
13080×
            if json {
13090×
                println!("{}", c.get_text(&path)?);
13100×
                return Ok(0);
13110×
            }
13120×
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
13130×
            if list.is_empty() {
13140×
                println!("{}", ui::dim("No comments."));
13150×
            }
13160×
            for m in &list {
13170×
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
13180×
                println!("{}\n", m.body);
13190×
            }
1320
        }
13210×
        DropCmd::Comment { id, message } => {
13220×
            let m: hub_api::DropComment =
13230×
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
13240×
            if json {
13250×
                println!("{}", serde_json::to_string(&m)?);
13260×
            } else {
13270×
                println!("{} commented (#{})", ui::ok("✔"), m.id);
13280×
            }
1329
        }
1330
    }
13314×
    Ok(0)
13327×
}
1333
1334
/// `30d`, `12h`, `90m` in milliseconds.
13350×
fn duration_ms(s: &str) -> Result<i64> {
13360×
    let s = s.trim();
13370×
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
13380×
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
13390×
    let per = match unit {
13400×
        "d" => 86_400_000,
13410×
        "h" => 3_600_000,
13420×
        "m" => 60_000,
13430×
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1344
    };
13450×
    if n <= 0 {
13460×
        bail!("a grant must last some time");
13470×
    }
13480×
    Ok(n * per)
13490×
}
1350
13510×
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1352
    use oxy_core::cert::{Grant, SignedGrant};
1353
    use oxy_core::identity::{Identity, Scope};
13540×
    match cmd {
13550×
        AgentCmd::Grant { name, scope, lasts } => {
13560×
            let home = oxy_core::repo::default_home();
13570×
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
13580×
                format!(
1359
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
13600×
                    home.display()
1361
                )
13620×
            })?;
13630×
            let me: serde_json::Value = c.get("/user")?;
13640×
            let username = me["username"].as_str().context("the hub did not say who you are")?;
13650×
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
13660×
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
13670×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
13680×
            let grant = Grant {
13690×
                grantor: me_id.hash(),
13700×
                subject: format!("agent:{name}@{username}"),
13710×
                issuer: hub.hash(),
13720×
                scope,
13730×
                not_before: (now - 60_000) as u64,
13740×
                expires: (now + duration_ms(&lasts)?) as u64,
1375
            };
13760×
            let signed = SignedGrant::sign(grant, &me_id, &sk);
13770×
            let r: serde_json::Value =
13780×
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
13790×
            if json {
13800×
                println!("{r}");
13810×
                return Ok(0);
13820×
            }
13830×
            println!(
1384
                "{} {} to act for you as {} ({}), until {}",
13850×
                ui::ok("✔ granted"),
13860×
                ui::strong(&name),
13870×
                r["subject"].as_str().unwrap_or(""),
13880×
                r["scope"].as_str().unwrap_or(""),
13890×
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1390
            );
13910×
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
13920×
            println!(
1393
                "  {}",
13940×
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1395
            );
13960×
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
13970×
            Ok(0)
1398
        }
1399
        AgentCmd::List => {
14000×
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
14010×
            if json {
14020×
                println!("{}", serde_json::to_string(&grants)?);
14030×
                return Ok(0);
14040×
            }
14050×
            if grants.is_empty() {
14060×
                println!("{}", ui::dim("no agent grants"));
14070×
            }
14080×
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
14090×
            for g in grants {
14100×
                let state = if g["revoked_ms"].is_i64() {
14110×
                    ui::bad("revoked")
14120×
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
14130×
                    ui::dim("ended")
1414
                } else {
14150×
                    ui::ok("live")
1416
                };
14170×
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
14180×
                println!(
1419
                    "#{:<4} {:<8} {} · {} · until {} · {}",
14200×
                    g["id"],
1421
                    state,
14220×
                    ui::strong(g["subject"].as_str().unwrap_or("")),
14230×
                    g["scope"].as_str().unwrap_or(""),
14240×
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
14250×
                    ui::dim(&used)
1426
                );
1427
            }
14280×
            Ok(0)
1429
        }
14300×
        AgentCmd::Revoke { id } => {
14310×
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
14320×
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
14330×
            Ok(0)
1434
        }
1435
    }
14360×
}
1437
14381×
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
14391×
    let hub = url.trim_end_matches('/').to_string();
14401×
    let token = match token.as_deref() {
14411×
        Some("-") => {
14420×
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
14430×
            let mut line = String::new();
14440×
            std::io::stdin().read_line(&mut line)?;
14450×
            line.trim().to_string()
1446
        }
14471×
        Some(t) => t.to_string(),
14480×
        None => device_sign_in(&hub, ca.clone())?,
1449
    };
14501×
    if token.is_empty() {
14510×
        bail!("no token given");
14521×
    }
14531×
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
14541×
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
14551×
    let account = me["username"].as_str().unwrap_or("?");
1456
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
14571×
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
14581×
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
14591×
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
14601×
    cfg.default_hub = Some(hub.clone());
14611×
    cfg.save()?;
14621×
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
14631×
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
14641×
    Ok(0)
14651×
}
1466
1467
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1468
/// it on the web, and the token arrives here.
14690×
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
14700×
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
14710×
    let c = Client::new(&t)?;
14720×
    let host = std::fs::read_to_string("/etc/hostname")
14730×
        .ok()
14740×
        .or_else(|| std::env::var("COMPUTERNAME").ok())
14750×
        .map(|h| h.trim().to_string())
14760×
        .filter(|h| !h.is_empty());
14770×
    let client = match host {
14780×
        Some(h) => format!("oh on {h}"),
14790×
        None => "oh".to_string(),
1480
    };
14810×
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
14820×
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
14830×
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
14840×
    if code != 200 {
14850×
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
14860×
    }
14870×
    let device = v["device_code"].as_str().context("no device code")?.to_string();
14880×
    let user = v["user_code"].as_str().unwrap_or("?");
14890×
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
14900×
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
14910×
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
14920×
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
14930×
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1494
    loop {
14950×
        std::thread::sleep(std::time::Duration::from_secs(interval));
14960×
        if std::time::Instant::now() > deadline {
14970×
            bail!("the code expired before it was approved; run oh auth login again");
14980×
        }
14990×
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
15000×
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
15010×
        if code == 200 {
15020×
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
15030×
        }
15040×
        match v["error"].as_str() {
15050×
            Some("authorization_pending") => {}
15060×
            Some("slow_down") => interval += 5,
15070×
            Some("access_denied") => bail!("the sign-in was denied on the web"),
15080×
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
15090×
            _ => bail!("signing in: HTTP {code}: {body}"),
1510
        }
1511
    }
15120×
}
1513
151410×
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
151510×
    match (body, file) {
15163×
        (Some(b), _) => Ok(b),
15171×
        (None, Some(f)) if f == "-" => {
15180×
            let mut s = String::new();
15190×
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
15200×
            Ok(s)
1521
        }
15221×
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
15236×
        (None, None) => Ok(String::new()),
1524
    }
152510×
}
1526
15273×
fn issue_line(i: &Issue) -> String {
15283×
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
15293×
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
15303×
    format!(
1531
        "{glyph} {} {}{}{}",
15323×
        ui::dim(&format!("#{}", i.number)),
1533
        i.title,
15343×
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
15353×
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1536
    )
15373×
}
1538
153918×
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
154018×
    let base = t.repo_path()?;
154118×
    match cmd {
15423×
        IssueCmd::List { state } => {
15433×
            let path = format!("{base}/issues?state={}", enc(&state));
15443×
            if json {
15451×
                println!("{}", c.get_text(&path)?);
15461×
                return Ok(0);
15472×
            }
15482×
            let list: Vec<Issue> = c.get(&path)?;
15492×
            if list.is_empty() {
15501×
                println!("{}", ui::dim(&format!("No {state} issues.")));
15511×
            }
15522×
            for i in &list {
15532×
                println!("{}", issue_line(i));
15542×
            }
1555
        }
15562×
        IssueCmd::View { number } => {
15572×
            let path = format!("{base}/issues/{number}");
15582×
            if json {
15591×
                println!("{}", c.get_text(&path)?);
15601×
                return Ok(0);
15611×
            }
15621×
            let i: Issue = c.get(&path)?;
15631×
            println!("{}", issue_line(&i));
15641×
            if !i.body.trim().is_empty() {
15651×
                println!("\n{}\n", i.body.trim_end());
15661×
            }
15671×
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
15682×
            for cm in comments {
15692×
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
15702×
            }
15711×
            println!("{}", ui::dim(&i.url));
1572
        }
15734×
        IssueCmd::Create { title, body, body_file, label, project, column, attach } => {
15744×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
15754×
            let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None };
15764×
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
15773×
            if json {
15781×
                println!("{}", serde_json::to_string(&i)?);
15792×
            } else {
15802×
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
15812×
            }
15823×
            if let Some(n) = project {
15831×
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
15841×
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
15851×
                if !json {
15861×
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
15871×
                }
15882×
            }
1589
        }
15901×
        IssueCmd::Close { number, reason, comment } => {
15911×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
15921×
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
15931×
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1594
        }
15950×
        IssueCmd::Reopen { number, comment } => {
15960×
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
15970×
            let i: Issue =
15980×
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
15990×
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1600
        }
16013×
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
16023×
            let body = match (&body, &body_file) {
16033×
                (None, None) => None,
16040×
                _ => Some(body_of(body, body_file)?),
1605
            };
16063×
            let labels = if no_labels {
16071×
                Some(Vec::new())
16082×
            } else if label.is_empty() {
16091×
                None
1610
            } else {
16111×
                Some(label)
1612
            };
16133×
            let assignees = if no_assignees {
16141×
                Some(Vec::new())
16152×
            } else if assignee.is_empty() {
16161×
                None
1617
            } else {
16181×
                Some(assignee)
1619
            };
16203×
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
16211×
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
16222×
            }
16232×
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
16242×
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
16252×
            if json {
16261×
                println!("{}", serde_json::to_string(&i)?);
16271×
            } else {
16281×
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
16291×
            }
1630
        }
16310×
        IssueCmd::Label(change) => {
16320×
            let path = format!("{base}/issues/{}", change.number);
16330×
            let now: Issue = c.get(&path)?;
16340×
            let labels = change.apply(&now.labels)?;
16350×
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
16360×
            let i: Issue = c.send("PATCH", &path, &edit)?;
16370×
            if json {
16380×
                println!("{}", serde_json::to_string(&i)?);
16390×
            } else {
16400×
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
16410×
            }
1642
        }
16435×
        IssueCmd::Comment { number, body, body_file, attach } => {
16445×
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
16454×
            if body.trim().is_empty() {
16461×
                bail!("give the comment with --body, --body-file or --attach");
16473×
            }
16483×
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
16493×
            println!("{} commented on #{number}", ui::ok("✔"));
1650
        }
1651
    }
165212×
    Ok(0)
165318×
}
1654
1655
/// A comment to post with a close or reopen (#368): saying why, in the
1656
/// same command.
1657
#[derive(clap::Args)]
1658
struct StateComment {
1659
    /// Say why, as a comment posted first
1660
    #[arg(long, short)]
1661
    body: Option<String>,
1662
    /// Read the comment from a file ("-" for stdin)
1663
    #[arg(long, short = 'F', conflicts_with = "body")]
1664
    body_file: Option<String>,
1665
    /// Attach a file to the comment (repeatable)
1666
    #[arg(long, short = 'a', value_name = "FILE")]
1667
    attach: Vec<std::path::PathBuf>,
1668
}
1669
1670
impl StateComment {
16711×
    fn post(self, c: &Client, base: &str, path: &str) -> Result<()> {
16721×
        if self.body.is_none() && self.body_file.is_none() && self.attach.is_empty() {
16731×
            return Ok(());
16740×
        }
16750×
        let body = with_attachments(c, base, body_of(self.body, self.body_file)?, &self.attach)?;
16760×
        if !body.trim().is_empty() {
16770×
            c.send_text("POST", path, &NewComment { body, path: None, line: None })?;
16780×
        }
16790×
        Ok(())
16801×
    }
1681
}
1682
1683
/// `number`, or the newest run (of `bookmark`, when given): what a push
1684
/// just started is what one usually wants to follow (#367).
16851×
fn run_or_newest(c: &Client, base: &str, number: Option<i64>, bookmark: Option<&str>) -> Result<i64> {
16861×
    if let Some(n) = number {
16871×
        return Ok(n);
16880×
    }
16890×
    let runs: Vec<FlowRun> = c.get(&format!("{base}/flow/runs?limit=100"))?;
16900×
    runs.iter().filter(|r| bookmark.is_none_or(|b| r.bookmark == b)).map(|r| r.number).max().with_context(|| match bookmark {
16910×
        Some(b) => format!("no runs of {b} among the latest 100"),
16920×
        None => "no runs yet".to_string(),
16930×
    })
16941×
}
1695
1696
/// `body` with each file attached to the repository and linked under it:
1697
/// an image shown in place, anything else a download (#350). Files are
1698
/// uploaded first, so a failed upload leaves nothing half made.
16999×
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> {
17009×
    if files.is_empty() {
17016×
        return Ok(body);
17023×
    }
17033×
    let mut links = Vec::new();
17044×
    for f in files {
17054×
        let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?;
17063×
        let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
17073×
        let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?;
17083×
        let a: hub_api::Attachment =
17093×
            serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?;
17103×
        links.push(a.markdown);
1711
    }
17122×
    let links = links.join("\n\n");
17132×
    Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) })
17149×
}
1715
17161×
fn source_name(s: &hub_api::ProposalSource) -> String {
17171×
    match s {
17181×
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
17190×
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
17200×
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1721
    }
17221×
}
1723
17241×
fn proposal_line(p: &Proposal) -> String {
17251×
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
17261×
    let glyph = match state.as_str() {
17271×
        "open" => ui::ok("●"),
17280×
        "draft" => ui::dim("◌"),
17290×
        "landed" => ui::strong("✔"),
17300×
        _ => ui::dim("○"),
1731
    };
17321×
    format!(
1733
        "{glyph} {} {} {}{}",
17341×
        ui::dim(&format!("#{}", p.number)),
1735
        p.title,
17361×
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
17371×
        ui::dim(&format!(" · {} · {state}", p.author))
1738
    )
17391×
}
1740
17414×
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
17424×
    let base = t.repo_path()?;
17434×
    match cmd {
17440×
        ProposalCmd::List { state, limit } => {
17450×
            let path = format!("{base}/proposals?state={state}&limit={limit}");
17460×
            if json {
17470×
                println!("{}", c.get_text(&path)?);
17480×
                return Ok(0);
17490×
            }
17500×
            let list: Vec<Proposal> = c.get(&path)?;
17510×
            if list.is_empty() {
17520×
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
17530×
            }
17540×
            for p in &list {
17550×
                println!("{}", proposal_line(p));
17560×
            }
1757
        }
17581×
        ProposalCmd::View { number } => {
17591×
            let path = format!("{base}/proposals/{number}");
17601×
            if json {
17610×
                println!("{}", c.get_text(&path)?);
17620×
                return Ok(0);
17631×
            }
17641×
            let p: Proposal = c.get(&path)?;
17651×
            println!("{}", proposal_line(&p));
17661×
            if !p.body.trim().is_empty() {
17670×
                println!("\n{}\n", p.body.trim_end());
17681×
            }
17691×
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
17701×
            for ch in &p.changes {
17711×
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
17721×
            }
17731×
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
17741×
            if p.landable {
17751×
                println!("{} can land", ui::ok("✔"));
17761×
            } else {
17770×
                for b in &p.blockers {
17780×
                    println!("{} {b}", ui::bad("✘"));
17790×
                }
1780
            }
17811×
            if p.conflicted {
17820×
                println!("{} landing it would leave conflicts", ui::bad("!"));
17831×
            }
17841×
            println!("{}", ui::dim(&p.url));
1785
        }
17861×
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
17871×
            let target = match into {
17880×
                Some(i) => i,
17891×
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1790
            };
17911×
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
17921×
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
17931×
            if json {
17940×
                println!("{}", serde_json::to_string(&p)?);
17951×
            } else {
17961×
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
17971×
            }
1798
        }
17990×
        ProposalCmd::Edit { number, title, body, body_file } => {
18000×
            let body = match (&body, &body_file) {
18010×
                (None, None) => None,
18020×
                _ => Some(body_of(body, body_file)?),
1803
            };
18040×
            if title.is_none() && body.is_none() {
18050×
                bail!("say what to change: --title, --body or --body-file");
18060×
            }
18070×
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
18080×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
18090×
            if json {
18100×
                println!("{}", serde_json::to_string(&p)?);
18110×
            } else {
18120×
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
18130×
            }
1814
        }
18150×
        ProposalCmd::Label(change) => {
18160×
            let path = format!("{base}/proposals/{}", change.number);
18170×
            let now: Proposal = c.get(&path)?;
18180×
            let labels = change.apply(&now.labels)?;
18190×
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
18200×
            let p: Proposal = c.send("PATCH", &path, &edit)?;
18210×
            if json {
18220×
                println!("{}", serde_json::to_string(&p)?);
18230×
            } else {
18240×
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
18250×
            }
1826
        }
18270×
        ProposalCmd::Comment { number, body, body_file } => {
18280×
            let body = body_of(body, body_file)?;
18290×
            if body.trim().is_empty() {
18300×
                bail!("give the comment with --body or --body-file");
18310×
            }
18320×
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
18330×
            println!("{} commented on #{number}", ui::ok("✔"));
1834
        }
18350×
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
18360×
            let path = format!("{base}/proposals/{number}/auto-land");
18370×
            let p: Proposal =
18380×
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
18390×
            if json {
18400×
                println!("{}", serde_json::to_string(&p)?);
18410×
            } else if p.landed.is_some() {
18420×
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
18430×
            } else if p.auto_land.is_some() {
18440×
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
18450×
            } else {
18460×
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
18470×
            }
1848
        }
18492×
        ProposalCmd::Land { number, over_checks, .. } => {
18502×
            let body = match &over_checks {
18510×
                Some(r) => serde_json::json!({ "over_checks": r }),
18522×
                None => serde_json::json!({}),
1853
            };
18542×
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
18551×
            if json {
18560×
                println!("{}", serde_json::to_string(&p)?);
18571×
            } else {
18581×
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
18591×
            }
1860
        }
18610×
        ProposalCmd::Close { number, message } => {
18620×
            if let Some(body) = message {
18630×
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
18640×
            }
18650×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
18660×
            if json {
18670×
                println!("{}", serde_json::to_string(&p)?);
18680×
            } else {
18690×
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
18700×
            }
1871
        }
18720×
        ProposalCmd::Reopen { number } => {
18730×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
18740×
            if json {
18750×
                println!("{}", serde_json::to_string(&p)?);
18760×
            } else {
18770×
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
18780×
            }
1879
        }
18800×
        ProposalCmd::Ready { number, undo } => {
18810×
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
18820×
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
18830×
            if json {
18840×
                println!("{}", serde_json::to_string(&p)?);
18850×
            } else if undo {
18860×
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
18870×
            } else {
18880×
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
18890×
            }
1890
        }
18910×
        ProposalCmd::Checks { number } => {
18920×
            let path = format!("{base}/proposals/{number}/checks");
18930×
            if json {
18940×
                println!("{}", c.get_text(&path)?);
18950×
                return Ok(0);
18960×
            }
18970×
            let checks: Vec<hub_api::Check> = c.get(&path)?;
18980×
            if checks.is_empty() {
18990×
                println!("{}", ui::dim("No checks yet."));
19000×
            }
19010×
            for ch in checks {
19020×
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
19030×
            }
1904
        }
1905
    }
19063×
    Ok(0)
19074×
}
1908
19091×
fn run_line(r: &FlowRun) -> String {
19101×
    let what =
19111×
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
19121×
    format!(
1913
        "{} {} {} {}",
19141×
        ui::status(&r.status),
19151×
        ui::dim(&format!("#{}", r.number)),
1916
        what,
19171×
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1918
    )
19191×
}
1920
19211×
fn print_run(r: &FlowRun, timings: bool) {
19221×
    println!("{}", run_line(r));
19231×
    for j in &r.jobs {
19241×
        let dur = match (j.started_ms, j.finished_ms) {
19250×
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
19261×
            _ => String::new(),
1927
        };
19281×
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
19291×
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1930
        // Why a queued job no runner can take waits (oxygenhub#28), and
1931
        // why a job ran where it did (oxygenflow#42).
19321×
        if j.status == "queued" && !j.waiting.is_empty() {
19330×
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
19341×
        } else if !j.placed.is_empty() {
19350×
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
19361×
        }
19371×
        if timings {
19380×
            let t = timing_line(j);
19390×
            if !t.is_empty() {
19400×
                println!("    {}", ui::dim(&t));
19410×
            }
19421×
        }
1943
    }
19441×
    if !r.error.is_empty() {
19450×
        println!("{}", ui::bad(&r.error));
19461×
    }
19471×
    println!("{}", ui::dim(&r.url));
19481×
}
1949
1950
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
19513×
fn took(ms: i64) -> String {
19523×
    match ms {
19533×
        ..=999 => format!("{ms} ms"),
19542×
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
19551×
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1956
    }
19573×
}
1958
1959
/// MiB as a person reads them.
19602×
fn mib(m: i64) -> String {
19612×
    if m >= 1024 {
19621×
        format!("{:.1} GiB", m as f64 / 1024.0)
1963
    } else {
19641×
        format!("{m} MiB")
1965
    }
19662×
}
1967
1968
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1969
/// phase its runner reported, and the most disk and memory it took.
19702×
fn timing_line(j: &FlowJob) -> String {
19712×
    let mut parts = vec![];
19722×
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
19731×
        parts.push(format!("waited {}", took((s - q).max(0))));
19741×
    }
19752×
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
19762×
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
19772×
        .into_iter()
19784×
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
19792×
        .collect();
19802×
    if !peaks.is_empty() {
19811×
        parts.push(format!("peak {}", peaks.join(", ")));
19821×
    }
19832×
    parts.join(" · ")
19842×
}
1985
1986
/// A report's path, its segments encoded and its slashes kept.
19871×
fn enc_path(path: &str) -> String {
19881×
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
19891×
}
1990
1991
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1992
/// files are at `files(path)`. By default its report.toml; with `list`
1993
/// what it holds; with `file` one file, to stdout or `output`.
19940×
fn show_report(
19950×
    c: &Client,
19960×
    at: &str,
19970×
    files: impl Fn(&str) -> String,
19980×
    list: bool,
19990×
    file: Option<String>,
20000×
    output: Option<std::path::PathBuf>,
20010×
    json: bool,
20020×
) -> Result<()> {
2003
    use std::io::Write;
20040×
    if let Some(path) = file {
20050×
        let bytes = c.get_bytes(&files(&path))?;
20060×
        match output {
20070×
            Some(out) => {
20080×
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
20090×
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
2010
            }
20110×
            None => std::io::stdout().write_all(&bytes)?,
2012
        }
20130×
        return Ok(());
20140×
    }
20150×
    if json {
20160×
        println!("{}", c.get_text(at)?);
20170×
        return Ok(());
20180×
    }
20190×
    if !list {
20200×
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
20210×
        return Ok(());
20220×
    }
20230×
    let r: Report = c.get(at)?;
20240×
    print_report(&r);
20250×
    if r.files_expired_ms.is_some() {
20260×
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
20270×
    }
20280×
    for f in &r.manifest {
20290×
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
20300×
    }
20310×
    println!("{}", ui::dim(&r.url));
20320×
    Ok(())
20330×
}
2034
2035
/// A report's heading, metrics and context.
20360×
fn print_report(r: &Report) {
20370×
    let from = match r.run {
20380×
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
20390×
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
2040
    };
20410×
    println!(
2042
        "{} {} {}",
20430×
        ui::strong(&r.name),
20440×
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
20450×
        ui::dim(&format!("· {from} · {} files", r.files))
2046
    );
20470×
    if !r.summary.is_empty() {
20480×
        println!("  {}", r.summary);
20490×
    }
20500×
    for m in &r.metrics {
20510×
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
20520×
        let mut notes = vec![];
20530×
        if !m.better.is_empty() {
20540×
            notes.push(format!("{} is better", m.better));
20550×
        }
20560×
        if let Some(a) = m.fail_above {
20570×
            notes.push(format!("fails above {a}"));
20580×
        }
20590×
        if let Some(b) = m.fail_below {
20600×
            notes.push(format!("fails below {b}"));
20610×
        }
20620×
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
20630×
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
2064
    }
20650×
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
20660×
        let line: Vec<String> =
20670×
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
20680×
        println!("  {}", ui::dim(&line.join(" ")));
20690×
    }
20700×
}
2071
2072
/// `oh report …` (oxygenhub#348).
20730×
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
20740×
    let base = t.repo_path()?;
20750×
    match cmd {
20760×
        ReportCmd::List { bookmark } => {
20770×
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
20780×
            if json {
20790×
                println!("{}", c.get_text(&path)?);
20800×
                return Ok(0);
20810×
            }
20820×
            let list: Vec<Report> = c.get(&path)?;
20830×
            if list.is_empty() {
20840×
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
20850×
            }
20860×
            for r in &list {
20870×
                print_report(r);
20880×
            }
2089
        }
20900×
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
20910×
            let at = format!("{base}/reports/{}", enc(&report));
20920×
            let query = match (id, bookmark) {
20930×
                (Some(id), _) => format!("?id={id}"),
20940×
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
20950×
                (None, None) => String::new(),
2096
            };
20970×
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
20980×
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
2099
        }
2100
    }
21010×
    Ok(0)
21020×
}
2103
21040×
fn live(status: &str) -> bool {
21050×
    matches!(status, "queued" | "running")
21060×
}
2107
2108
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
21090×
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
21100×
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
21110×
    if json {
21120×
        println!("{done}");
21130×
    } else {
21140×
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
21150×
    }
21160×
    Ok(())
21170×
}
2118
21190×
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
21200×
    let path = format!("{base}/flow/runs/{number}");
21210×
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2122
    loop {
21230×
        let r: FlowRun = c.get(&path)?;
21240×
        if !json {
21250×
            for j in &r.jobs {
21260×
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
21270×
                if seen.get(&j.name) != Some(&shown) {
21280×
                    println!("{} {}", ui::status(&j.status), j.name);
21290×
                    if j.status == "queued" && !j.waiting.is_empty() {
21300×
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
21310×
                    }
21320×
                    seen.insert(j.name.clone(), shown);
21330×
                }
2134
            }
21350×
        }
21360×
        if !live(&r.status) {
21370×
            if json {
21380×
                println!("{}", serde_json::to_string(&r)?);
21390×
            } else {
21400×
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
21410×
            }
21420×
            return Ok(if r.status == "passed" { 0 } else { 1 });
21430×
        }
21440×
        std::thread::sleep(Duration::from_secs(3));
2145
    }
21460×
}
2147
21483×
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
21493×
    let base = t.repo_path()?;
21500×
    match cmd {
21511×
        RunCmd::List { limit } => {
21521×
            let path = format!("{base}/flow/runs?limit={limit}");
21531×
            if json {
21541×
                println!("{}", c.get_text(&path)?);
21551×
                return Ok(0);
21560×
            }
21570×
            let runs: Vec<FlowRun> = c.get(&path)?;
21580×
            if runs.is_empty() {
21590×
                println!("{}", ui::dim("No runs yet."));
21600×
            }
21610×
            for r in &runs {
21620×
                println!("{}", run_line(r));
21630×
            }
2164
        }
21651×
        RunCmd::View { number, bookmark, timings } => {
21661×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
21671×
            let path = format!("{base}/flow/runs/{number}");
21681×
            if json {
21690×
                println!("{}", c.get_text(&path)?);
21700×
                return Ok(0);
21711×
            }
21721×
            print_run(&c.get(&path)?, timings);
2173
        }
21741×
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
21751×
            let mut body = match (bookmark, change) {
21760×
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
21770×
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
21781×
                (None, None) => serde_json::json!({}),
2179
            };
21801×
            if !jobs.is_empty() {
21810×
                body["jobs"] = serde_json::json!(jobs);
21821×
            }
21831×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
21841×
            let n = started["number"].as_i64().context("the hub named no run")?;
21851×
            if !json || !follow {
21861×
                if json {
21870×
                    println!("{started}");
21881×
                } else {
21891×
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
21901×
                }
21910×
            }
21921×
            if follow {
21930×
                return watch(c, &base, n, json);
21941×
            }
2195
        }
21960×
        RunCmd::Watch { number, bookmark } => {
21970×
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
21980×
            return watch(c, &base, number, json);
2199
        }
22000×
        RunCmd::Log { number, job } => {
22010×
            let mut after = 0;
2202
            loop {
22030×
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
22040×
                let lines: Vec<FlowLogLine> = c.get(&path)?;
22050×
                if lines.is_empty() {
22060×
                    break;
22070×
                }
22080×
                for l in &lines {
22090×
                    if json {
22100×
                        println!("{}", serde_json::to_string(l)?);
22110×
                    } else if l.stream == "flow" {
22120×
                        println!("{}", ui::dim(&l.text));
22130×
                    } else {
22140×
                        println!("{}", l.text);
22150×
                    }
2216
                }
22170×
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2218
            }
2219
        }
22200×
        RunCmd::Report { number, job, pick } => {
22210×
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
22220×
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
22230×
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
22240×
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2225
        }
22260×
        RunCmd::Rerun { number, job: Some(job) } => {
22270×
            let queued: serde_json::Value =
22280×
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
22290×
            if json {
22300×
                println!("{queued}");
22310×
            } else {
22320×
                let n = queued["queued"].as_i64().unwrap_or(1);
22330×
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
22340×
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2235
            }
2236
        }
22370×
        RunCmd::Rerun { number, job: None } => {
22380×
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
22390×
            if json {
22400×
                println!("{started}");
22410×
            } else {
22420×
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
22430×
            }
2244
        }
22450×
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
22460×
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
22470×
        RunCmd::Cancel { number } => {
22480×
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
22490×
            if json {
22500×
                println!("{done}");
22510×
            } else {
22520×
                println!("{} cancelled run #{number}", ui::ok("✔"));
22530×
            }
2254
        }
2255
    }
22562×
    Ok(0)
22573×
}
2258
22590×
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
22600×
    let base = t.repo_path()?;
22610×
    match cmd {
2262
        LabelCmd::List => {
22630×
            let path = format!("{base}/labels");
22640×
            if json {
22650×
                println!("{}", c.get_text(&path)?);
22660×
                return Ok(0);
22670×
            }
22680×
            let labels: Vec<hub_api::Label> = c.get(&path)?;
22690×
            if labels.is_empty() {
22700×
                println!("{}", ui::dim("No labels."));
22710×
            }
22720×
            for l in labels {
22730×
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
22740×
            }
2275
        }
22760×
        LabelCmd::Create { name, colour, description } => {
22770×
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
22780×
            if json {
22790×
                println!("{}", serde_json::to_string(&l)?);
22800×
            } else {
22810×
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
22820×
            }
2283
        }
22840×
        LabelCmd::Delete { name } => {
22850×
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
22860×
            println!("{} deleted label {name}", ui::ok("✔"));
2287
        }
2288
    }
22890×
    Ok(0)
22900×
}
2291
22920×
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
22930×
    let base = match (&org, site) {
22940×
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
22950×
        (None, true) => "/admin/assistants".to_string(),
22960×
        (None, false) => format!("{}/assistants", t.repo_path()?),
2297
    };
22980×
    match cmd {
2299
        AssistantCmd::List => {
23000×
            if json {
23010×
                println!("{}", c.get_text(&base)?);
23020×
                return Ok(0);
23030×
            }
23040×
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
23050×
            if list.is_empty() {
23060×
                println!("{}", ui::dim("No assistants."));
23070×
            }
23080×
            for a in list {
23090×
                let state = if a.enabled && !a.off_above {
23100×
                    ui::ok("on")
23110×
                } else if a.off_above {
23120×
                    ui::dim("off above")
2313
                } else {
23140×
                    ui::dim("off")
2315
                };
23160×
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
23170×
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2318
            }
2319
        }
23200×
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
23210×
            let token = match token_env {
23220×
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
23230×
                None => String::new(),
2324
            };
23250×
            let body =
23260×
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
23270×
            let r: serde_json::Value = c.send("POST", &base, &body)?;
23280×
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2329
        }
23300×
        AssistantCmd::Remove { name } => {
23310×
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
23320×
            println!("{} removed {name}", ui::ok("✔"));
2333
        }
23340×
        AssistantCmd::Prompt { set } => {
23350×
            let p: hub_api::AssistantPrompt = match set {
23360×
                Some(path) => {
23370×
                    let text = if path.as_os_str() == "-" {
23380×
                        let mut s = String::new();
23390×
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
23400×
                        s
2341
                    } else {
23420×
                        std::fs::read_to_string(&path)?
2343
                    };
23440×
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2345
                }
23460×
                None => c.get(&format!("{base}/prompt"))?,
2347
            };
23480×
            if json {
23490×
                println!("{}", serde_json::to_string(&p)?);
23500×
                return Ok(0);
23510×
            }
23520×
            for (from, text) in &p.inherited {
23530×
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
23540×
            }
23550×
            if p.prompt.is_empty() {
23560×
                println!("{}", ui::dim("No prompt of its own."));
23570×
            } else {
23580×
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
23590×
            }
2360
        }
2361
    }
23620×
    Ok(0)
23630×
}
2364
23652×
fn project_line(p: &hub_api::Project) -> String {
23662×
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
23672×
    let private = if p.public { "" } else { " · private" };
23682×
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
23692×
}
2370
237110×
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
237210×
    let owner = match owner {
23730×
        Some(o) => o,
237410×
        None => t.repo()?.0.to_string(),
2375
    };
237610×
    let base = format!("/projects/{}", enc(&owner));
237710×
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
23781×
        let p: hub_api::Project =
23791×
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
23801×
        if json {
23810×
            println!("{}", serde_json::to_string(&p)?);
23821×
        } else {
23831×
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
23841×
        }
23851×
        Ok(())
23861×
    };
23874×
    match cmd {
2388
        ProjectCmd::List => {
23891×
            if json {
23900×
                println!("{}", c.get_text(&base)?);
23910×
                return Ok(0);
23921×
            }
23931×
            let list: Vec<hub_api::Project> = c.get(&base)?;
23941×
            if list.is_empty() {
23950×
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
23961×
            }
23971×
            for p in &list {
23981×
                println!("{}", project_line(p));
23991×
            }
2400
        }
24013×
        ProjectCmd::View { number, archived, filter, view } => {
24023×
            let cards = format!("{base}/{number}/cards?archived=true");
24033×
            let path = match (&filter, &view) {
24040×
                (Some(q), _) => format!("{base}/{number}?q={}", enc(q)),
24050×
                (None, Some(v)) => format!("{base}/{number}?view={}", enc(v)),
24063×
                (None, None) => format!("{base}/{number}"),
2407
            };
24083×
            if json {
24092×
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
24102×
                return Ok(0);
24111×
            }
24121×
            let mut b: hub_api::Board = c.get(&path)?;
24131×
            if archived {
24140×
                b.columns = c.get(&cards)?;
24151×
            }
24161×
            println!("{}", project_line(&b.project));
24171×
            if !b.project.description.is_empty() {
24181×
                println!("{}", b.project.description);
24191×
            }
24201×
            if !b.filter.is_empty() {
24210×
                println!("{}", ui::dim(&format!("filter: {}", b.filter)));
24221×
            }
24231×
            if !b.views.is_empty() && filter.is_none() && view.is_none() {
24240×
                let names: Vec<&str> = b.views.iter().map(|v| v.name.as_str()).collect();
24250×
                println!("{}", ui::dim(&format!("views: {} (oh project view {number} --view NAME)", names.join(", "))));
24261×
            }
24273×
            for col in &b.columns {
24283×
                println!();
24293×
                let wip = match col.wip_limit {
24300×
                    Some(w) if col.cards.len() as i64 > w => format!(" · over its limit of {w}"),
24310×
                    Some(w) => format!(" · limit {w}"),
24323×
                    None => String::new(),
2433
                };
24343×
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}{wip}", col.cards.len(), col.id)));
24353×
                if col.cards.is_empty() {
24361×
                    println!("  {}", ui::dim("(empty)"));
24372×
                }
24383×
                for card in &col.cards {
24392×
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
24402×
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
24412×
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
24422×
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
24432×
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
24442×
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2445
                }
2446
            }
24471×
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2448
        }
24491×
        ProjectCmd::Create { title, description, private } => {
24501×
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
24511×
            if json {
24520×
                println!("{}", serde_json::to_string(&p)?);
24531×
            } else {
24541×
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
24551×
            }
2456
        }
24570×
        ProjectCmd::Charts { number, filter } => {
24580×
            let path = match &filter {
24590×
                Some(q) => format!("{base}/{number}/charts?q={}", enc(q)),
24600×
                None => format!("{base}/{number}/charts"),
2461
            };
24620×
            if json {
24630×
                println!("{}", c.get_text(&path)?);
24640×
                return Ok(0);
24650×
            }
24660×
            let ch: hub_api::BoardCharts = c.get(&path)?;
24670×
            println!("{}", ui::strong("Forecasts"));
24680×
            for f in &ch.forecasts {
24690×
                let when = match (&f.p50, &f.p85) {
24700×
                    (Some(a), Some(b)) => format!("50% by {a}, 85% by {b}"),
24710×
                    (Some(a), None) => format!("50% by {a}, 85% beyond ten years"),
24720×
                    _ => "no forecast: nothing has reached Done in the weeks it draws from".to_string(),
2473
                };
24740×
                println!("  {}  {} left · {when}", f.scope, f.remaining);
2475
            }
24760×
            if let Some(f) = ch.forecasts.first() {
24770×
                println!("  {}", ui::dim(&format!("from {} week(s) of throughput", f.weeks_of_history)));
24780×
            }
24790×
            println!();
24800×
            match (ch.cycle_time_median_days, ch.cycle_time_p85_days) {
24810×
                (Some(m), Some(p)) => {
24820×
                    println!("{} median {m} d, 85th percentile {p} d over {} finished", ui::strong("Cycle time"), ch.finished)
2483
                }
24840×
                _ => println!("{} {}", ui::strong("Cycle time"), ui::dim("no card has gone from started to Done yet")),
2485
            }
24860×
            let weeks: Vec<String> = ch.throughput.iter().map(|w| w.done.to_string()).collect();
24870×
            println!("{} {} {}", ui::strong("Throughput"), weeks.join(" "), ui::dim("(cards done each week, oldest first)"));
24880×
            if let Some(b) = &ch.burn_down {
24890×
                println!(
24900×
                    "{} {}: {} left of {}",
24910×
                    ui::strong("Burn-down"),
24920×
                    b.iteration,
24930×
                    b.left.last().unwrap_or(&0),
24940×
                    b.scope.last().unwrap_or(&0)
24950×
                );
24960×
            }
2497
        }
24980×
        ProjectCmd::Column { cmd } => {
24990×
            let col_path = |number: i64, column: &str| format!("{base}/{number}/columns/{}", enc(column));
25000×
            let (number, b, what): (i64, hub_api::Board, String) = match cmd {
25010×
                ColumnCmd::Add { number, name } => {
25020×
                    let b = c.send("POST", &format!("{base}/{number}/columns"), &hub_api::NewColumn { name: name.clone() })?;
25030×
                    (number, b, format!("added column {name}"))
2504
                }
25050×
                ColumnCmd::Rename { number, column, to } => {
25060×
                    let edit = hub_api::ColumnEdit { name: Some(to.clone()), position: None };
25070×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("renamed column {column} to {to}"))
2508
                }
25090×
                ColumnCmd::Move { number, column, to, left, right } => {
25100×
                    let position = match to {
25110×
                        Some(n) => n - 1,
2512
                        None => {
25130×
                            let now: hub_api::Board = c.get(&format!("{base}/{number}"))?;
25140×
                            let at = now
25150×
                                .columns
25160×
                                .iter()
25170×
                                .position(|col| col.id.to_string() == column || col.name.eq_ignore_ascii_case(&column))
25180×
                                .with_context(|| format!("no column {column} on board {number}"))?
2519
                                as i64;
25200×
                            if left {
25210×
                                (at - 1).max(0)
2522
                            } else {
25230×
                                debug_assert!(right);
25240×
                                at + 1
2525
                            }
2526
                        }
2527
                    };
25280×
                    let edit = hub_api::ColumnEdit { name: None, position: Some(position) };
25290×
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("moved column {column}"))
2530
                }
25310×
                ColumnCmd::Remove { number, column } => {
25320×
                    (number, c.send("DELETE", &col_path(number, &column), &serde_json::json!({}))?, format!("removed column {column}"))
2533
                }
2534
            };
25350×
            if json {
25360×
                println!("{}", serde_json::to_string(&b)?);
2537
            } else {
25380×
                let order: Vec<&str> = b.columns.iter().map(|col| col.name.as_str()).collect();
25390×
                println!("{} {what} on board {number}: {}", ui::ok("✔"), ui::dim(&order.join(" · ")));
2540
            }
2541
        }
25421×
        ProjectCmd::Close { number } => state(number, true, "closed")?,
25430×
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
25440×
        ProjectCmd::Transfer { number, to } => {
25450×
            let p: hub_api::Project =
25460×
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
25470×
            if json {
25480×
                println!("{}", serde_json::to_string(&p)?);
25490×
            } else {
25500×
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
25510×
            }
2552
        }
25532×
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2554
            // The hub names a card's issue as `repo#N` among the owner's
2555
            // repositories.
25562×
            let reference = match reference {
25571×
                None => String::new(),
25581×
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
25590×
                    Some((o, rest)) if o == owner => rest.to_string(),
25600×
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
25610×
                    None => r,
2562
                },
25631×
                Some(r) => {
25641×
                    let n = r.trim_start_matches('#');
25651×
                    if n.parse::<i64>().is_err() {
25660×
                        bail!("{r}: give an issue or proposal number, or NAME#N");
25671×
                    }
25681×
                    format!("{}#{n}", t.repo()?.1)
2569
                }
2570
            };
25712×
            let note = note.unwrap_or_default();
25722×
            if reference.is_empty() && note.is_empty() {
25730×
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
25742×
            }
25751×
            let card: hub_api::ProjectCard =
25762×
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
25771×
            if json {
25780×
                println!("{}", serde_json::to_string(&card)?);
2579
            } else {
25801×
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2581
            }
2582
        }
25831×
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
25841×
            (Some(card), None) => {
25851×
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
25861×
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2587
            }
25880×
            (None, Some(from)) => {
25890×
                let r: hub_api::CardsMoved = c.send(
25900×
                    "POST",
25910×
                    &format!("{base}/{number}/cards/move"),
25920×
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
25930×
                )?;
25940×
                if json {
25950×
                    println!("{}", serde_json::to_string(&r)?);
25960×
                    return Ok(0);
25970×
                }
25980×
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
25990×
                for m in &r.moved {
26000×
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2601
                }
26020×
                let verb = if dry_run { "would move" } else { "moved" };
26030×
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2604
            }
26050×
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2606
        },
26070×
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
26080×
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
26090×
                None => None,
26100×
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2611
            };
26120×
            let r: hub_api::CardsArchived = c.send(
26130×
                "POST",
26140×
                &format!("{base}/{number}/cards/archive"),
26150×
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
26160×
            )?;
26170×
            if json {
26180×
                println!("{}", serde_json::to_string(&r)?);
26190×
                return Ok(0);
26200×
            }
26210×
            let verb = if dry_run { "would archive" } else { "archived" };
26220×
            for a in &r.archived {
26230×
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
26240×
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2625
            }
26260×
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2627
        }
26280×
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
26290×
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
26300×
            println!("{} card {card} restored", ui::ok("✔"));
2631
        }
26321×
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
26331×
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
26341×
            println!("{} card {card} removed", ui::ok("✔"));
2635
        }
2636
    }
26377×
    Ok(0)
263810×
}
2639
26400×
fn milestone_line(m: &hub_api::Milestone) -> String {
26410×
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
26420×
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
26430×
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
26440×
}
2645
26460×
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
26470×
    let base = t.repo_path()?;
26480×
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
26490×
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
26500×
        if json {
26510×
            println!("{}", serde_json::to_string(&m)?);
26520×
        } else {
26530×
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
26540×
        }
26550×
        Ok(())
26560×
    };
26570×
    match cmd {
2658
        MilestoneCmd::List => {
26590×
            let path = format!("{base}/milestones");
26600×
            if json {
26610×
                println!("{}", c.get_text(&path)?);
26620×
                return Ok(0);
26630×
            }
26640×
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
26650×
            if list.is_empty() {
26660×
                println!("{}", ui::dim("No milestones."));
26670×
            }
26680×
            for m in &list {
26690×
                println!("{}", milestone_line(m));
26700×
            }
2671
        }
26720×
        MilestoneCmd::Create { title, description, due } => {
26730×
            let m: hub_api::Milestone =
26740×
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
26750×
            if json {
26760×
                println!("{}", serde_json::to_string(&m)?);
26770×
            } else {
26780×
                println!("{} milestone {}", ui::ok("✔"), m.title);
26790×
            }
2680
        }
26810×
        MilestoneCmd::Edit { title, rename, description, due } => {
26820×
            if rename.is_none() && description.is_none() && due.is_none() {
26830×
                bail!("say what to change: --rename, --description or --due");
26840×
            }
26850×
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2686
        }
26870×
        MilestoneCmd::Close { title } => {
26880×
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2689
        }
26900×
        MilestoneCmd::Reopen { title } => {
26910×
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2692
        }
2693
    }
26940×
    Ok(0)
26950×
}
2696
26970×
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
26980×
    let base = t.repo_path()?;
26990×
    match cmd {
2700
        TagCmd::List => {
27010×
            let path = format!("{base}/tags");
27020×
            if json {
27030×
                println!("{}", c.get_text(&path)?);
27040×
                return Ok(0);
27050×
            }
27060×
            let tags: Vec<Tag> = c.get(&path)?;
27070×
            if tags.is_empty() {
27080×
                println!("{}", ui::dim("no tags"));
27090×
            }
27100×
            for t in tags {
27110×
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
27120×
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
27130×
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2714
            }
2715
        }
27160×
        TagCmd::Create { name, target, message } => {
27170×
            let new = hub_api::NewTag { name, target, message };
27180×
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
27190×
            if json {
27200×
                println!("{}", serde_json::to_string(&made)?);
27210×
            } else {
27220×
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
27230×
            }
2724
        }
27250×
        TagCmd::Delete { name, reason } => {
27260×
            let reason = reason.unwrap_or_default();
27270×
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
27280×
            if json {
27290×
                println!("{}", serde_json::json!({ "withdrawn": name }));
27300×
            } else {
27310×
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
27320×
            }
2733
        }
2734
    }
27350×
    Ok(0)
27360×
}
2737
27384×
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
27394×
    let base = t.repo_path()?;
27404×
    match cmd {
2741
        ReleaseCmd::List => {
27421×
            let path = format!("{base}/releases");
27431×
            if json {
27441×
                println!("{}", c.get_text(&path)?);
27451×
                return Ok(0);
27460×
            }
27470×
            let list: Vec<Release> = c.get(&path)?;
27480×
            if list.is_empty() {
27490×
                println!("{}", ui::dim("No releases."));
27500×
            }
27510×
            for r in &list {
27520×
                println!(
2753
                    "{} {} {}{}",
27540×
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
27550×
                    ui::strong(&r.tag),
2756
                    r.title,
27570×
                    ui::dim(&format!(
2758
                        " · {} asset{} · {}",
27590×
                        r.assets.len(),
27600×
                        if r.assets.len() == 1 { "" } else { "s" },
27610×
                        ui::ago(r.created_ms)
2762
                    ))
2763
                );
2764
            }
2765
        }
27661×
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
27671×
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
27681×
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
27691×
            if json {
27700×
                println!("{}", serde_json::to_string(&r)?);
27711×
            } else {
27721×
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
27731×
            }
2774
        }
27750×
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
27760×
            let notes = match notes.as_deref() {
27770×
                Some("-") => Some(body_of(None, Some("-".into()))?),
27780×
                _ => notes,
2779
            };
27800×
            if title.is_none() && notes.is_none() && prerelease.is_none() {
27810×
                bail!("say what to change: --title, --notes or --prerelease");
27820×
            }
27830×
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
27840×
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
27850×
            if json {
27860×
                println!("{}", serde_json::to_string(&r)?);
27870×
            } else {
27880×
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
27890×
            }
2790
        }
27911×
        ReleaseCmd::Upload { tag, files } => {
27921×
            if files.is_empty() {
27930×
                bail!("name the files to attach");
27941×
            }
27951×
            for f in files {
27961×
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
27971×
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
27981×
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
27991×
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2800
            }
2801
        }
28021×
        ReleaseCmd::Trust { tag } => {
28031×
            let path = format!("{base}/releases/trust/{}", enc(&tag));
28041×
            if json {
28050×
                println!("{}", c.get_text(&path)?);
28060×
                return Ok(0);
28071×
            }
28081×
            let r: serde_json::Value = c.get(&path)?;
28091×
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
28101×
            let mut worst = 0;
28114×
            for ch in r["audit"].as_array().into_iter().flatten() {
28124×
                let v = ch["verdict"].as_str().unwrap_or("");
28134×
                worst = worst.max(match v {
28144×
                    "fail" => 2,
28154×
                    "warn" => 1,
28163×
                    _ => 0,
2817
                });
28184×
                let g = match v {
28194×
                    "pass" => ui::ok("✔"),
28201×
                    "warn" => ui::warn("!"),
28210×
                    _ => ui::bad("✘"),
2822
                };
28234×
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2824
            }
28251×
            return Ok(if worst == 2 { 1 } else { 0 });
2826
        }
2827
    }
28282×
    Ok(0)
28294×
}
2830
2831
#[cfg(test)]
2832
mod tests {
2833
2834
    #[test]
28351×
    fn job_timings_and_report_commands_read_plainly() {
2836
        use clap::Parser;
28371×
        let job = hub_api::FlowJob {
28381×
            name: "perf".into(),
28391×
            status: "passed".into(),
28401×
            depends_on: vec![],
28411×
            runner: "earth-1".into(),
28421×
            exit_code: Some(0),
28431×
            error: String::new(),
28441×
            started_ms: Some(13_000),
28451×
            finished_ms: Some(200_000),
28461×
            log_lines: 10,
28471×
            waiting: String::new(),
28481×
            placed: String::new(),
28491×
            approval: String::new(),
28501×
            queued_ms: Some(1_000),
28511×
            ready_ms: Some(12_500),
28521×
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
28531×
            peak_disk_mib: Some(2150),
28541×
            peak_memory_mib: Some(900),
28551×
        };
28561×
        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");
28571×
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
28581×
        assert_eq!(super::timing_line(&bare), "");
28591×
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2860
28611×
        let cli =
28621×
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
28631×
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
28641×
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
28651×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
28661×
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
28671×
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
28681×
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
28691×
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
28701×
    }
2871
2872
    #[test]
28731×
    fn runner_update_scopes_resolve_by_name_or_id() {
28741×
        let all = hub_api::RunnerUpdates {
28751×
            repo: String::new(),
28761×
            settings: vec![],
28771×
            groups: vec![hub_api::RunnerGroup {
28781×
                id: 4,
28791×
                owner: "acme".into(),
28801×
                name: "canary".into(),
28811×
                percent: None,
28821×
                members: vec![],
28831×
                wave: None,
28841×
            }],
28851×
            runners: vec![],
28861×
            holds: vec![],
28871×
        };
28881×
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
28891×
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
28903×
        for g in ["group:canary", "group:acme/canary", "group:4"] {
28913×
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2892
        }
28931×
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
28941×
        assert!(update_scope("everyone", &all).is_err());
28951×
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
28961×
        assert!(switch(Some("yes")).is_err());
28971×
    }
2898
    use super::*;
2899
2900
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2901
    /// help says, and a drop is named by its id or its address.
2902
    #[test]
29031×
    fn drop_commands_parse() {
29041×
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
29051×
        match cli.cmd {
29061×
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
29071×
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
29081×
                assert!(secret);
29091×
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2910
            }
29110×
            _ => panic!("not drop create"),
2912
        }
29131×
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
29141×
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
29151×
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
29161×
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
29171×
                assert!(channel.is_none() && dry_run.is_none());
2918
            }
29190×
            _ => panic!("not runner-updates set"),
2920
        }
29211×
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
29221×
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
29231×
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
29240×
            _ => panic!("not drop list"),
2925
        }
29261×
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
29271×
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
29281×
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2929
            }
29300×
            _ => panic!("not drop view"),
2931
        }
29321×
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
29334×
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
29344×
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2935
        }
29361×
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
29371×
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
29381×
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
29390×
            _ => panic!("not drop comment"),
2940
        }
29411×
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
29421×
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
29431×
        assert!(drop_id("andy/notes").is_err());
29441×
    }
2945
}