OXYGENHUB
# 50928fab5ffc oxygenhub / crates / oh / src / main.rs
115.6 KiB · Rust · last changed Board columns by API and oh, newest-run watch, close with a comment (closes #366, closes #367, closes #368) 2 days ago source blame history raw
1
//! `oh`: OxygenHub from the command line, as `gh` is for GitHub. It talks
2
//! to the hub's JSON API (hub spec §12) as the checkout's remote does:
3
//! same hub, same token, same CA.
4
5
mod client;
6
mod mcp;
7
mod target;
8
mod ui;
9
10
use anyhow::{bail, Context, Result};
11
use clap::{Parser, Subcommand};
12
use client::Client;
13
use hub_api::{
14
    FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag,
15
};
16
use std::time::Duration;
17
use target::{Choice, Config, Target};
18
19
#[derive(Parser)]
20
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")]
21
struct Cli {
22
    /// The repository, when not inside an Oxygen checkout
23
    #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")]
24
    repo: Option<String>,
25
    /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved)
26
    #[arg(long, global = true, value_name = "URL")]
27
    hub: Option<String>,
28
    /// Which of the checkout's remotes to use (default: origin, or the only one)
29
    #[arg(long, global = true)]
30
    remote: Option<String>,
31
    /// Machine-readable output: the API's JSON, unchanged
32
    #[arg(long, global = true)]
33
    json: bool,
34
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
35
    #[arg(long, global = true)]
36
    plain: bool,
37
    #[command(subcommand)]
38
    cmd: Cmd,
39
}
40
41
#[derive(Subcommand)]
42
enum Cmd {
43
    /// Sign in to a hub, or show who you are signed in as
44
    Auth {
45
        #[command(subcommand)]
46
        cmd: AuthCmd,
47
    },
48
    /// The repository
49
    Repo {
50
        #[command(subcommand)]
51
        cmd: RepoCmd,
52
    },
53
    /// Issues
54
    Issue {
55
        #[command(subcommand)]
56
        cmd: IssueCmd,
57
    },
58
    /// Proposals (pull requests)
59
    Proposal {
60
        #[command(subcommand)]
61
        cmd: ProposalCmd,
62
    },
63
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
64
    Coverage {
65
        #[command(subcommand)]
66
        cmd: CoverageCmd,
67
    },
68
    /// OxygenFlow runs
69
    Run {
70
        #[command(subcommand)]
71
        cmd: RunCmd,
72
    },
73
    /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348)
74
    Report {
75
        #[command(subcommand)]
76
        cmd: ReportCmd,
77
    },
78
    /// Releases
79
    Release {
80
        #[command(subcommand)]
81
        cmd: ReleaseCmd,
82
    },
83
    /// Tags: list, create, withdraw
84
    Tag {
85
        #[command(subcommand)]
86
        cmd: TagCmd,
87
    },
88
    /// The repository's labels
89
    Label {
90
        #[command(subcommand)]
91
        cmd: LabelCmd,
92
    },
93
    /// Milestones: list, create, edit, close
94
    Milestone {
95
        #[command(subcommand)]
96
        cmd: MilestoneCmd,
97
    },
98
    /// Project boards of the repository's owner (or --owner): list,
99
    /// create, view, and cards
100
    Project {
101
        #[command(subcommand)]
102
        cmd: ProjectCmd,
103
        /// A user or organisation other than the repository's owner
104
        #[arg(long, global = true)]
105
        owner: Option<String>,
106
    },
107
    /// AI assistants of the repository (its admins), or with --org or
108
    /// --site of an organisation or the site
109
    Assistant {
110
        #[command(subcommand)]
111
        cmd: AssistantCmd,
112
        /// An organisation's assistants instead of the repository's
113
        #[arg(long, global = true)]
114
        org: Option<String>,
115
        /// The site's assistants (administrators)
116
        #[arg(long, global = true, conflicts_with = "org")]
117
        site: bool,
118
    },
119
    /// Agents that act for you without a key of their own (keyless
120
    /// signing): grant, list, revoke
121
    Agent {
122
        #[command(subcommand)]
123
        cmd: AgentCmd,
124
    },
125
    /// Drops: small snippets of files, each its own repository, never
126
    /// listed among your repositories (oxygenhub#279)
127
    Drop {
128
        #[command(subcommand)]
129
        cmd: DropCmd,
130
    },
131
    /// Runners that update themselves (site administrators; oxygenhub#322):
132
    /// where builds come from, who takes them, what is held back
133
    #[command(name = "runner-updates")]
134
    RunnerUpdates {
135
        #[command(subcommand)]
136
        cmd: Option<RunnerUpdatesCmd>,
137
    },
138
    /// Serve this repository's hub to an AI agent over the Model Context Protocol (stdio); read-only unless --allow-write
139
    Mcp {
140
        /// Also offer tools that change the hub: create, comment on and close issues, comment on proposals, re-run Flow runs
141
        #[arg(long)]
142
        allow_write: bool,
143
    },
144
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
145
    Api {
146
        /// A path under /api/v1
147
        path: String,
148
        /// The method
149
        #[arg(long, short = 'X', default_value = "GET")]
150
        method: String,
151
        /// A JSON body
152
        #[arg(long, short = 'd')]
153
        data: Option<String>,
154
    },
155
}
156
157
#[derive(Subcommand)]
158
enum AgentCmd {
159
    /// Let an agent act for you: your oxy key (the one your oxy home names
160
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
161
    /// the agent a token it exchanges for ten-minute certificates. The
162
    /// token is printed once: give it to the agent (`oxy auth grant`)
163
    Grant {
164
        /// The agent's name, as in agent:NAME@YOU
165
        name: String,
166
        /// What its keys may do for you: changes, seal, refs
167
        #[arg(long, default_value = "changes,seal,refs")]
168
        scope: String,
169
        /// How long the grant lasts: 30d, 12h, 90m
170
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
171
        lasts: String,
172
    },
173
    /// Your grants, live and past
174
    List,
175
    /// Stop a grant at once: no more certificates under it
176
    Revoke { id: i64 },
177
}
178
179
#[derive(Subcommand)]
180
enum DropCmd {
181
    /// Make a drop of these files, signed by the hub as your delegate
182
    Create {
183
        /// The files (their names in the drop are their file names)
184
        #[arg(required = true)]
185
        files: Vec<std::path::PathBuf>,
186
        /// Unlisted: readable by anyone with its address, listed nowhere
187
        #[arg(long)]
188
        secret: bool,
189
        /// A description
190
        #[arg(long, short = 'd', value_name = "TEXT")]
191
        description: Option<String>,
192
        /// A title (default: the first file's name)
193
        #[arg(long, short = 't')]
194
        title: Option<String>,
195
    },
196
    /// Your drops, or someone's public ones
197
    List {
198
        /// Whose drops
199
        #[arg(long, short = 'u', value_name = "NAME")]
200
        user: Option<String>,
201
    },
202
    /// A drop's files, printed (by id or address)
203
    View {
204
        /// The drop's id, or its address
205
        id: String,
206
        /// Print only this file's content
207
        #[arg(long, short = 'f', value_name = "NAME")]
208
        file: Option<String>,
209
    },
210
    /// Delete a drop and its history
211
    Delete {
212
        /// The drop's id, or its address
213
        id: String,
214
    },
215
    /// A copy of someone's drop, history and all, as a drop of yours
216
    Fork {
217
        /// The drop's id, or its address
218
        id: String,
219
    },
220
    /// Star a drop
221
    Star {
222
        /// The drop's id, or its address
223
        id: String,
224
    },
225
    /// Take your star back
226
    Unstar {
227
        /// The drop's id, or its address
228
        id: String,
229
    },
230
    /// A drop's comments, oldest first
231
    Comments {
232
        /// The drop's id, or its address
233
        id: String,
234
    },
235
    /// Comment on a drop (Markdown); its owner is told
236
    Comment {
237
        /// The drop's id, or its address
238
        id: String,
239
        /// What to say
240
        #[arg(long, short = 'm')]
241
        message: String,
242
    },
243
}
244
245
#[derive(Subcommand)]
246
enum RunnerUpdatesCmd {
247
    /// Every level's settings, the test groups, each runner's policy and what it is offered (the default)
248
    Show,
249
    /// Change one level's settings; what is not given stays as it is
250
    Set {
251
        /// `site`, `owner:NAME`, `group:NAME` (or `group:OWNER/NAME`, `group:ID`), `runner:NAME` (or `runner:ID`)
252
        scope: String,
253
        /// `on`, `off` or `inherit`
254
        #[arg(long)]
255
        updates: Option<String>,
256
        /// `stable`, `canary`, a version, or `inherit`
257
        #[arg(long)]
258
        channel: Option<String>,
259
        /// Hours (UTC) updates may start in, `02-05`, or `inherit`
260
        #[arg(long)]
261
        window: Option<String>,
262
        /// `on`, `off` or `inherit`
263
        #[arg(long)]
264
        dry_run: Option<String>,
265
    },
266
    /// Offer a held build again (it rolled back on a runner)
267
    Lift { version: String },
268
}
269
270
#[derive(Subcommand)]
271
enum AuthCmd {
272
    /// Sign in to a hub and make it the default: approve a code on the web
273
    /// (device sign-in), or give a token
274
    Login {
275
        /// The hub, e.g. https://oxygenhub.io
276
        #[arg(long = "with-hub", value_name = "URL")]
277
        url: String,
278
        /// An API token from the hub's Settings → Tokens, instead of
279
        /// approving a code ("-" reads it from stdin)
280
        #[arg(long)]
281
        token: Option<String>,
282
        /// The hub's CA certificate, when self-signed
283
        #[arg(long)]
284
        ca: Option<std::path::PathBuf>,
285
    },
286
    /// Who the token in use belongs to
287
    Status,
288
}
289
290
#[derive(Subcommand)]
291
enum RepoCmd {
292
    /// Name, description, visibility and default bookmark
293
    View,
294
}
295
296
#[derive(Subcommand)]
297
enum IssueCmd {
298
    /// Put labels on an issue or take them off (triage)
299
    Label(LabelChange),
300
    /// Open issues (or --state closed|all)
301
    List {
302
        #[arg(long, default_value = "open")]
303
        state: String,
304
    },
305
    /// One issue with its comments
306
    View { number: i64 },
307
    /// Open an issue
308
    Create {
309
        #[arg(long, short)]
310
        title: String,
311
        #[arg(long, short)]
312
        body: Option<String>,
313
        /// Read the body from a file ("-" for stdin)
314
        #[arg(long, short = 'F')]
315
        body_file: Option<String>,
316
        /// A label (repeatable)
317
        #[arg(long, short)]
318
        label: Vec<String>,
319
        /// Also put it on this board of the repository's owner
320
        #[arg(long, short)]
321
        project: Option<i64>,
322
        /// The board's column for it, by name (default: the first)
323
        #[arg(long, requires = "project")]
324
        column: Option<String>,
325
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
326
        #[arg(long, short = 'a', value_name = "FILE")]
327
        attach: Vec<std::path::PathBuf>,
328
    },
329
    /// Close an issue, with an optional comment saying why
330
    Close {
331
        number: i64,
332
        /// `completed` or `not_planned`
333
        #[arg(long, default_value = "completed")]
334
        reason: String,
335
        #[command(flatten)]
336
        comment: StateComment,
337
    },
338
    /// Reopen an issue, with an optional comment saying why
339
    Reopen {
340
        number: i64,
341
        #[command(flatten)]
342
        comment: StateComment,
343
    },
344
    /// Change an issue's title or body (its author or triage), or its
345
    /// labels, assignees or milestone as whole sets (triage)
346
    Edit {
347
        number: i64,
348
        #[arg(long, short)]
349
        title: Option<String>,
350
        #[arg(long, short)]
351
        body: Option<String>,
352
        /// Read the body from a file ("-" for stdin)
353
        #[arg(long, short = 'F', conflicts_with = "body")]
354
        body_file: Option<String>,
355
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
356
        #[arg(long, short)]
357
        label: Vec<String>,
358
        /// Clear its labels
359
        #[arg(long, conflicts_with = "label")]
360
        no_labels: bool,
361
        /// The users it should be assigned to (repeatable)
362
        #[arg(long, short)]
363
        assignee: Vec<String>,
364
        /// Take everyone off it
365
        #[arg(long, conflicts_with = "assignee")]
366
        no_assignees: bool,
367
        /// A milestone's title ("" takes it out of its milestone)
368
        #[arg(long, short)]
369
        milestone: Option<String>,
370
    },
371
    /// Comment on an issue
372
    Comment {
373
        number: i64,
374
        #[arg(long, short)]
375
        body: Option<String>,
376
        /// Read the body from a file ("-" for stdin), as proposal comment
377
        /// does (#260)
378
        #[arg(long, short = 'F', conflicts_with = "body")]
379
        body_file: Option<String>,
380
        /// Attach a file (repeatable): a screenshot shows in place, anything else is a download link (#350)
381
        #[arg(long, short = 'a', value_name = "FILE")]
382
        attach: Vec<std::path::PathBuf>,
383
    },
384
}
385
386
#[derive(Subcommand)]
387
enum ProposalCmd {
388
    /// Open proposals (or --state draft|landed|closed|all), newest first
389
    List {
390
        #[arg(long, default_value = "open")]
391
        state: String,
392
        /// At most this many
393
        #[arg(long, default_value_t = 30)]
394
        limit: usize,
395
    },
396
    /// One proposal: its changes, approvals and whether it can land
397
    View { number: i64 },
398
    /// Propose a bookmark's changes for another bookmark
399
    Create {
400
        #[arg(long, short)]
401
        title: String,
402
        #[arg(long, short)]
403
        body: Option<String>,
404
        /// Read the body from a file ("-" for stdin)
405
        #[arg(long, short = 'F', conflicts_with = "body")]
406
        body_file: Option<String>,
407
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
408
        #[arg(long)]
409
        from: String,
410
        /// The bookmark to land them on (default: the repository's default bookmark)
411
        #[arg(long)]
412
        into: Option<String>,
413
        #[arg(long)]
414
        draft: bool,
415
    },
416
    /// Change a proposal's title or description (its author or a maintainer)
417
    Edit {
418
        number: i64,
419
        #[arg(long, short)]
420
        title: Option<String>,
421
        #[arg(long, short)]
422
        body: Option<String>,
423
        /// Read the body from a file ("-" for stdin)
424
        #[arg(long, short = 'F', conflicts_with = "body")]
425
        body_file: Option<String>,
426
    },
427
    /// Put labels on a proposal or take them off (triage)
428
    Label(LabelChange),
429
    /// Comment on a proposal's conversation
430
    Comment {
431
        number: i64,
432
        #[arg(long, short)]
433
        body: Option<String>,
434
        /// Read the comment from a file ("-" for stdin)
435
        #[arg(long, short = 'F', conflicts_with = "body")]
436
        body_file: Option<String>,
437
    },
438
    /// The checks on a proposal's projected state
439
    Checks { number: i64 },
440
    /// Land a proposal on its target, as the page's Land button does
441
    Land {
442
        number: i64,
443
        /// Land before its required checks pass, saying why (maintainers;
444
        /// recorded and audited, #261)
445
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
446
        over_checks: Option<String>,
447
        /// Land it by itself once its checks pass (#261); with --off, don't
448
        #[arg(long)]
449
        when_ready: bool,
450
        /// With --when-ready: turn it off
451
        #[arg(long, requires = "when_ready")]
452
        off: bool,
453
    },
454
    /// Close a proposal without landing it, with an optional comment
455
    Close {
456
        number: i64,
457
        /// Say why, as a comment before it closes
458
        #[arg(long, short = 'm')]
459
        message: Option<String>,
460
    },
461
    /// Reopen a closed proposal
462
    Reopen { number: i64 },
463
    /// Take a draft proposal out of draft, ready for review (its author or triage)
464
    Ready {
465
        number: i64,
466
        /// Turn an open proposal back into a draft instead
467
        #[arg(long)]
468
        undo: bool,
469
    },
470
}
471
472
#[derive(Subcommand)]
473
enum AssistantCmd {
474
    /// The assistants this level sees, its own and those inherited
475
    List,
476
    /// Add an assistant, or change the one of that name
477
    Add {
478
        /// How it shows on reviews (default: the provider's name)
479
        #[arg(long, default_value = "")]
480
        name: String,
481
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
482
        #[arg(long, default_value = "")]
483
        preset: String,
484
        /// The endpoint, when no preset or another one
485
        #[arg(long, default_value = "")]
486
        endpoint: String,
487
        /// chat-completions or anthropic-messages
488
        #[arg(long, default_value = "")]
489
        api: String,
490
        /// One the endpoint lists (`oh assistant models` shows them)
491
        #[arg(long)]
492
        model: String,
493
        /// The API key, read from this environment variable (never typed on the command line)
494
        #[arg(long, value_name = "VAR")]
495
        token_env: Option<String>,
496
        /// Add it turned off
497
        #[arg(long)]
498
        off: bool,
499
    },
500
    /// Remove this level's assistant of that name
501
    Remove { name: String },
502
    /// Show this level's prompt, and those it inherits
503
    Prompt {
504
        /// Set it from this file (`-` for standard input; an empty file clears it)
505
        #[arg(long, value_name = "FILE")]
506
        set: Option<std::path::PathBuf>,
507
    },
508
}
509
510
#[derive(Subcommand)]
511
enum LabelCmd {
512
    /// The repository's labels
513
    List,
514
    /// Create a label, or change the one of that name (triage)
515
    Create {
516
        name: String,
517
        /// `#rrggbb` (default: one the hub picks)
518
        #[arg(long)]
519
        colour: Option<String>,
520
        #[arg(long, short, default_value = "")]
521
        description: String,
522
    },
523
    /// Delete a label, taking it off every issue and proposal (triage)
524
    Delete { name: String },
525
}
526
527
#[derive(Subcommand)]
528
enum ProjectCmd {
529
    /// The owner's boards
530
    List,
531
    /// One board: its columns and cards
532
    View {
533
        number: i64,
534
        /// Its archived cards instead (#293)
535
        #[arg(long)]
536
        archived: bool,
537
    },
538
    /// Create a board (owner, or an organisation's members)
539
    Create {
540
        title: String,
541
        #[arg(long, short, default_value = "")]
542
        description: String,
543
        /// Only the owner (or the organisation's members) can see it
544
        #[arg(long)]
545
        private: bool,
546
    },
547
    /// Close a board
548
    Close { number: i64 },
549
    /// Reopen a board
550
    Reopen { number: i64 },
551
    /// Move a board to another owner you may make boards under (an
552
    /// organisation, say); it takes the next number there
553
    Transfer {
554
        number: i64,
555
        /// The new owner
556
        #[arg(long)]
557
        to: String,
558
    },
559
    /// Cards on a board: add, move, archive, restore, remove
560
    Card {
561
        #[command(subcommand)]
562
        cmd: CardCmd,
563
    },
564
    /// A board's columns: add, rename, move, remove (#366)
565
    Column {
566
        #[command(subcommand)]
567
        cmd: ColumnCmd,
568
    },
569
}
570
571
#[derive(Subcommand)]
572
enum ColumnCmd {
573
    /// Add a column at the right
574
    Add {
575
        /// The board
576
        number: i64,
577
        name: String,
578
    },
579
    /// Rename a column (by name or id)
580
    Rename {
581
        /// The board
582
        number: i64,
583
        column: String,
584
        /// Its new name
585
        to: String,
586
    },
587
    /// Move a column: --to POSITION (1 is the leftmost), --left or --right
588
    Move {
589
        /// The board
590
        number: i64,
591
        column: String,
592
        /// Its place, counting from 1 at the left
593
        #[arg(long, conflicts_with_all = ["left", "right"], required_unless_present_any = ["left", "right"])]
594
        to: Option<i64>,
595
        /// One place to the left
596
        #[arg(long, conflicts_with = "right")]
597
        left: bool,
598
        /// One place to the right
599
        #[arg(long)]
600
        right: bool,
601
    },
602
    /// Remove a column; its cards go to the first remaining one
603
    Remove {
604
        /// The board
605
        number: i64,
606
        column: String,
607
    },
608
}
609
610
#[derive(Subcommand)]
611
enum CardCmd {
612
    /// Put an issue or proposal on a board (`12` or `#12` in this
613
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
614
    /// or a note with --note
615
    Add {
616
        number: i64,
617
        /// The issue or proposal; a number means this repository's
618
        reference: Option<String>,
619
        /// A note card instead
620
        #[arg(long, conflicts_with = "reference")]
621
        note: Option<String>,
622
        /// The column, by name or id (default: the first)
623
        #[arg(long, short)]
624
        column: Option<String>,
625
    },
626
    /// Move a card to another column (by name or id), or with --from every
627
    /// card of a column at once
628
    Move {
629
        number: i64,
630
        /// The card (its id); leave it out with --from
631
        card: Option<i64>,
632
        #[arg(long, short)]
633
        column: String,
634
        /// Move every card of this column (#289)
635
        #[arg(long, conflicts_with = "card")]
636
        from: Option<String>,
637
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
638
        #[arg(long, value_delimiter = ',', requires = "from")]
639
        except: Vec<String>,
640
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
641
        #[arg(long, value_delimiter = ',', requires = "from")]
642
        state: Vec<String>,
643
        /// With --from: say what would move, and move nothing
644
        #[arg(long, requires = "from")]
645
        dry_run: bool,
646
    },
647
    /// Archive a column's cards: off the board, kept and restorable (#293)
648
    Archive {
649
        number: i64,
650
        /// The column, by name or id
651
        #[arg(long)]
652
        from: String,
653
        /// Only cards that joined the column more than this long ago (14d, or 14)
654
        #[arg(long)]
655
        older: Option<String>,
656
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
657
        #[arg(long, value_delimiter = ',')]
658
        except: Vec<String>,
659
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
660
        #[arg(long, value_delimiter = ',')]
661
        state: Vec<String>,
662
        /// Say what would be archived, and archive nothing
663
        #[arg(long)]
664
        dry_run: bool,
665
    },
666
    /// Put an archived card back at the end of its column
667
    Restore { number: i64, card: i64 },
668
    /// Take a card off a board
669
    Remove { number: i64, card: i64 },
670
}
671
672
#[derive(Subcommand)]
673
enum MilestoneCmd {
674
    /// The repository's milestones
675
    List,
676
    /// Create a milestone, or change the one of that title (triage)
677
    Create {
678
        title: String,
679
        #[arg(long, short, default_value = "")]
680
        description: String,
681
        /// Due date, YYYY-MM-DD
682
        #[arg(long)]
683
        due: Option<String>,
684
    },
685
    /// Change a milestone's title, description or due date (triage)
686
    Edit {
687
        title: String,
688
        #[arg(long, short)]
689
        rename: Option<String>,
690
        #[arg(long, short)]
691
        description: Option<String>,
692
        /// Due date, YYYY-MM-DD ("" for none)
693
        #[arg(long)]
694
        due: Option<String>,
695
    },
696
    /// Close a milestone
697
    Close { title: String },
698
    /// Reopen a milestone
699
    Reopen { title: String },
700
}
701
702
/// Labels to put on or take off an issue or proposal.
703
#[derive(clap::Args)]
704
struct LabelChange {
705
    number: i64,
706
    /// A label to add (repeatable)
707
    #[arg(long, short)]
708
    add: Vec<String>,
709
    /// A label to take off (repeatable)
710
    #[arg(long, short)]
711
    remove: Vec<String>,
712
}
713
714
impl LabelChange {
715
    /// The set after the change, from the one there now.
716
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
717
        if self.add.is_empty() && self.remove.is_empty() {
718
            bail!("say what to change: --add NAME or --remove NAME");
719
        }
720
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
721
        for a in &self.add {
722
            if !names.contains(a) {
723
                names.push(a.clone());
724
            }
725
        }
726
        Ok(names)
727
    }
728
}
729
730
fn label_names(labels: &[String]) -> String {
731
    if labels.is_empty() {
732
        ui::dim("no labels")
733
    } else {
734
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
735
    }
736
}
737
738
#[derive(Subcommand)]
739
enum CoverageCmd {
740
    /// Upload an LCOV or Cobertura report measured on this machine, as the
741
    /// coverage of a bookmark's current state (default: the default
742
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
743
    /// not measured by a runner, and sets no check from it
744
    Upload {
745
        file: std::path::PathBuf,
746
        #[arg(long)]
747
        bookmark: Option<String>,
748
        /// A change's full hash
749
        #[arg(long, conflicts_with = "bookmark")]
750
        change: Option<String>,
751
    },
752
}
753
754
#[derive(Subcommand)]
755
enum RunCmd {
756
    /// Recent runs, newest first
757
    List {
758
        #[arg(long, default_value_t = 20)]
759
        limit: i64,
760
    },
761
    /// A run and its jobs (default: the newest run)
762
    View {
763
        /// The run (default: the newest, or the newest of --bookmark)
764
        number: Option<i64>,
765
        /// With no number: the newest run of this bookmark
766
        #[arg(long, conflicts_with = "number")]
767
        bookmark: Option<String>,
768
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
769
        #[arg(long)]
770
        timings: bool,
771
    },
772
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
773
    Start {
774
        #[arg(long)]
775
        bookmark: Option<String>,
776
        /// A change's full hash
777
        #[arg(long, conflicts_with = "bookmark")]
778
        change: Option<String>,
779
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
780
        #[arg(long = "job", value_name = "NAME")]
781
        jobs: Vec<String>,
782
        /// Wait for the run and exit 1 unless it passes
783
        #[arg(long)]
784
        watch: bool,
785
    },
786
    /// Follow a run until it finishes (default: the newest run); exit 1 unless it passes
787
    Watch {
788
        /// The run (default: the newest, or the newest of --bookmark) (#367)
789
        number: Option<i64>,
790
        /// With no number: the newest run of this bookmark
791
        #[arg(long, conflicts_with = "number")]
792
        bookmark: Option<String>,
793
    },
794
    /// A job's log
795
    Log { number: i64, job: String },
796
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
797
    Report {
798
        number: i64,
799
        job: String,
800
        #[command(flatten)]
801
        pick: ReportPick,
802
    },
803
    /// Run a finished run's state again; with --job, only that job (and the
804
    /// jobs that depend on it) in the same run
805
    Rerun {
806
        number: i64,
807
        #[arg(long)]
808
        job: Option<String>,
809
    },
810
    /// Cancel a run still queued or running; its running jobs are stopped
811
    Cancel { number: i64 },
812
    /// Approve a job that waits for a person (oxygenflow#57)
813
    Approve {
814
        number: i64,
815
        #[arg(long)]
816
        job: String,
817
    },
818
    /// Reject a job that waits for a person: it ends cancelled
819
    Reject {
820
        number: i64,
821
        #[arg(long)]
822
        job: String,
823
    },
824
}
825
826
/// Which report of a job, and what of it to show.
827
#[derive(clap::Args)]
828
struct ReportPick {
829
    /// Which report, when the job published more than one
830
    #[arg(long)]
831
    name: Option<String>,
832
    /// What it holds: its metrics, context and files
833
    #[arg(long, conflicts_with = "file")]
834
    list: bool,
835
    /// One file of it (`data/frames.csv`), as published
836
    #[arg(long, value_name = "PATH")]
837
    file: Option<String>,
838
    /// Write the file here instead of to stdout
839
    #[arg(long, short, value_name = "FILE", requires = "file")]
840
    output: Option<std::path::PathBuf>,
841
}
842
843
#[derive(Subcommand)]
844
enum ReportCmd {
845
    /// The newest run of each report, newest first
846
    List {
847
        /// Only runs on this bookmark
848
        #[arg(long)]
849
        bookmark: Option<String>,
850
    },
851
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
852
    Show {
853
        report: String,
854
        #[arg(long, conflicts_with = "bookmark")]
855
        id: Option<i64>,
856
        #[arg(long)]
857
        bookmark: Option<String>,
858
        /// What it holds: its metrics, context and files
859
        #[arg(long, conflicts_with = "file")]
860
        list: bool,
861
        /// One file of it, as published
862
        #[arg(long, value_name = "PATH")]
863
        file: Option<String>,
864
        /// Write the file here instead of to stdout
865
        #[arg(long, short, value_name = "FILE", requires = "file")]
866
        output: Option<std::path::PathBuf>,
867
    },
868
}
869
870
#[derive(Subcommand)]
871
enum TagCmd {
872
    /// Tags, newest name first
873
    List,
874
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
875
    /// delegate (as `oxy tag create` and a push would be)
876
    Create {
877
        name: String,
878
        /// What to tag (default: the default bookmark)
879
        #[arg(long)]
880
        target: Option<String>,
881
        #[arg(long, short)]
882
        message: Option<String>,
883
    },
884
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
885
    /// their next fetch, and the name is never used again. Refused while a
886
    /// release uses the tag
887
    Delete {
888
        name: String,
889
        /// Why, recorded with the withdrawal
890
        #[arg(long, short)]
891
        reason: Option<String>,
892
    },
893
}
894
895
#[derive(Subcommand)]
896
enum ReleaseCmd {
897
    /// Releases, newest first
898
    List,
899
    /// Create a release on an existing tag
900
    Create {
901
        tag: String,
902
        #[arg(long, short)]
903
        title: Option<String>,
904
        /// Notes in Markdown (default: generated from the changes since the previous release)
905
        #[arg(long, short)]
906
        notes: Option<String>,
907
        #[arg(long)]
908
        prerelease: bool,
909
    },
910
    /// Change a release's title, notes or prerelease flag
911
    Edit {
912
        tag: String,
913
        #[arg(long, short)]
914
        title: Option<String>,
915
        /// New notes in Markdown ("-" reads them from stdin)
916
        #[arg(long, short)]
917
        notes: Option<String>,
918
        /// Mark it a prerelease (true) or not (false)
919
        #[arg(long)]
920
        prerelease: Option<bool>,
921
    },
922
    /// Attach files to a release
923
    Upload { tag: String, files: Vec<std::path::PathBuf> },
924
    /// The release's trust report: signatures, builds, receipts and audit
925
    Trust { tag: String },
926
}
927
928
fn main() {
929
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
930
    // other command-line tools do, instead of panicking on the failed
931
    // write (oxygenhub#92).
932
    #[cfg(unix)]
933
    unsafe {
934
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
935
    }
936
    let cli = Cli::parse();
937
    ui::init(cli.plain);
938
    match run(cli) {
939
        Ok(code) => std::process::exit(code),
940
        Err(e) => {
941
            eprintln!("{} {e:#}", ui::bad("error:"));
942
            std::process::exit(2);
943
        }
944
    }
945
}
946
947
fn enc(s: &str) -> String {
948
    let mut out = String::new();
949
    for b in s.bytes() {
950
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
951
            out.push(b as char);
952
        } else {
953
            out.push_str(&format!("%{b:02X}"));
954
        }
955
    }
956
    out
957
}
958
959
fn run(cli: Cli) -> Result<i32> {
960
    let cfg = Config::load()?;
961
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
962
        return login(cfg, url, token.clone(), ca.clone());
963
    }
964
    let here = std::env::current_dir()?;
965
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
966
    let c = Client::new(&t)?;
967
    let json = cli.json;
968
    match cli.cmd {
969
        Cmd::Auth { cmd: AuthCmd::Status } => {
970
            let me: serde_json::Value = c.get("/user")?;
971
            if json {
972
                println!("{me}");
973
            } else {
974
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
975
            }
976
            Ok(0)
977
        }
978
        Cmd::Auth { .. } => unreachable!(),
979
        Cmd::Mcp { allow_write } => {
980
            t.repo().context("oh mcp serves one repository: start it in a checkout, or give --repo OWNER/NAME")?;
981
            mcp::serve(c, t, allow_write)
982
        }
983
        Cmd::Api { path, method, data } => {
984
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
985
            let text = match data {
986
                Some(d) => c.send_text(
987
                    &method.to_uppercase(),
988
                    &path,
989
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
990
                )?,
991
                None => c.get_text(&path)?,
992
            };
993
            println!("{text}");
994
            Ok(0)
995
        }
996
        Cmd::Repo { cmd: RepoCmd::View } => {
997
            let path = t.repo_path()?;
998
            if json {
999
                println!("{}", c.get_text(&path)?);
1000
                return Ok(0);
1001
            }
1002
            let r: serde_json::Value = c.get(&path)?;
1003
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
1004
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
1005
                println!("{d}");
1006
            }
1007
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
1008
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
1009
            Ok(0)
1010
        }
1011
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
1012
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
1013
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
1014
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
1015
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
1016
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
1017
            let mut body = serde_json::json!({ "content": content });
1018
            if let Some(b) = bookmark {
1019
                body["bookmark"] = b.into();
1020
            }
1021
            if let Some(ch) = change {
1022
                body["change"] = ch.into();
1023
            }
1024
            let base = t.repo_path()?;
1025
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
1026
            if json {
1027
                println!("{}", serde_json::to_string(&r)?);
1028
            } else {
1029
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
1030
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
1031
                println!(
1032
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
1033
                    ui::ok("✔"),
1034
                    r.lines_hit,
1035
                    r.lines_found,
1036
                    r.files,
1037
                    ui::dim(&r.url)
1038
                );
1039
                if r.dropped > 0 {
1040
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
1041
                }
1042
            }
1043
            Ok(0)
1044
        }
1045
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
1046
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
1047
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
1048
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
1049
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
1050
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
1051
        Cmd::Agent { cmd } => agent(&c, cmd, json),
1052
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
1053
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
1054
    }
1055
}
1056
1057
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
1058
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
1059
    Ok(match v {
1060
        None => None,
1061
        Some("on") => Some(Some(true)),
1062
        Some("off") => Some(Some(false)),
1063
        Some("inherit") => Some(None),
1064
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1065
    })
1066
}
1067
1068
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
1069
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
1070
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
1071
    Ok(match kind {
1072
        "site" if name.is_empty() => ("site".into(), String::new()),
1073
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
1074
        "group" => {
1075
            let g = all
1076
                .groups
1077
                .iter()
1078
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
1079
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
1080
            ("group".into(), g.id.to_string())
1081
        }
1082
        "runner" => {
1083
            let r = all
1084
                .runners
1085
                .iter()
1086
                .find(|r| r.id.to_string() == name || r.name == name)
1087
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
1088
            ("runner".into(), r.id.to_string())
1089
        }
1090
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1091
    })
1092
}
1093
1094
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
1095
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
1096
    match cmd {
1097
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1098
        RunnerUpdatesCmd::Show => {
1099
            println!(
1100
                "{} {}",
1101
                ui::strong("Builds from"),
1102
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1103
            );
1104
            for h in &all.holds {
1105
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
1106
            }
1107
            for s in &all.settings {
1108
                let mut said = vec![];
1109
                if let Some(u) = s.updates {
1110
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
1111
                }
1112
                if let Some(ch) = &s.channel {
1113
                    said.push(format!("channel {ch}"));
1114
                }
1115
                if let Some(w) = &s.window {
1116
                    said.push(format!("window {w} UTC"));
1117
                }
1118
                if let Some(d) = s.dry_run {
1119
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
1120
                }
1121
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
1122
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1123
            }
1124
            for g in &all.groups {
1125
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
1126
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
1127
                if let Some(w) = g.wave {
1128
                    what.push_str(&format!(", wave {w}"));
1129
                }
1130
                println!(
1131
                    "  group {} ({what}): {}",
1132
                    ui::strong(&g.name),
1133
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1134
                );
1135
            }
1136
            for r in &all.runners {
1137
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
1138
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1139
            }
1140
        }
1141
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
1142
            let (scope, key) = update_scope(&scope, &all)?;
1143
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
1144
                scope: scope.clone(),
1145
                key: key.clone(),
1146
                ..Default::default()
1147
            });
1148
            if let Some(u) = switch(updates.as_deref())? {
1149
                s.updates = u;
1150
            }
1151
            if let Some(d) = switch(dry_run.as_deref())? {
1152
                s.dry_run = d;
1153
            }
1154
            if let Some(ch) = channel {
1155
                s.channel = Some(ch).filter(|c| c != "inherit");
1156
            }
1157
            if let Some(w) = window {
1158
                s.window = Some(w).filter(|w| w != "inherit");
1159
            }
1160
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
1161
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1162
        }
1163
        RunnerUpdatesCmd::Lift { version } => {
1164
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
1165
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1166
        }
1167
    }
1168
    Ok(0)
1169
}
1170
1171
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
1172
fn drop_id(s: &str) -> Result<String> {
1173
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1174
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
1175
        bail!("{s:?} is not a drop's id or address");
1176
    }
1177
    Ok(id.to_ascii_lowercase())
1178
}
1179
1180
fn drop_line(d: &hub_api::Drop) -> String {
1181
    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() };
1182
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
1183
    format!(
1184
        "{} {} {}{}",
1185
        ui::dim(&d.id),
1186
        ui::strong(&title),
1187
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
1188
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1189
    )
1190
}
1191
1192
/// `oh drop star|unstar` (oxygenhub#349).
1193
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
1194
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
1195
    if json {
1196
        println!("{}", serde_json::to_string(&s)?);
1197
    } else {
1198
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1199
    }
1200
    Ok(())
1201
}
1202
1203
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
1204
    match cmd {
1205
        DropCmd::Create { files, secret, description, title } => {
1206
            let mut out = Vec::with_capacity(files.len());
1207
            for f in &files {
1208
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
1209
                let content =
1210
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
1211
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1212
            }
1213
            let new =
1214
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
1215
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
1216
            if json {
1217
                println!("{}", serde_json::to_string(&d)?);
1218
            } else {
1219
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
1220
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1221
            }
1222
        }
1223
        DropCmd::List { user } => {
1224
            let path = match &user {
1225
                Some(u) => format!("/users/{}/drops", enc(u)),
1226
                None => "/drops".to_string(),
1227
            };
1228
            if json {
1229
                println!("{}", c.get_text(&path)?);
1230
                return Ok(0);
1231
            }
1232
            let list: Vec<hub_api::Drop> = c.get(&path)?;
1233
            if list.is_empty() {
1234
                println!("{}", ui::dim("No drops."));
1235
            }
1236
            for d in &list {
1237
                println!("{}", drop_line(d));
1238
            }
1239
        }
1240
        DropCmd::View { id, file } => {
1241
            let path = format!("/drops/{}", drop_id(&id)?);
1242
            if json && file.is_none() {
1243
                println!("{}", c.get_text(&path)?);
1244
                return Ok(0);
1245
            }
1246
            let d: hub_api::Drop = c.get(&path)?;
1247
            if let Some(name) = file {
1248
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
1249
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
1250
                print!("{content}");
1251
                return Ok(0);
1252
            }
1253
            println!("{}", drop_line(&d));
1254
            if !d.description.is_empty() {
1255
                println!("{}", d.description);
1256
            }
1257
            println!("{}", ui::kv("url", &d.url));
1258
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
1259
            for f in &d.files {
1260
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
1261
                match &f.content {
1262
                    Some(text) => {
1263
                        print!("{text}");
1264
                        if !text.ends_with('\n') && !text.is_empty() {
1265
                            println!();
1266
                        }
1267
                    }
1268
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1269
                }
1270
            }
1271
        }
1272
        DropCmd::Delete { id } => {
1273
            let id = drop_id(&id)?;
1274
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
1275
            println!("{} drop {id}", ui::ok("✔ deleted"));
1276
        }
1277
        DropCmd::Fork { id } => {
1278
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
1279
            if json {
1280
                println!("{}", serde_json::to_string(&d)?);
1281
            } else {
1282
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
1283
            }
1284
        }
1285
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
1286
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
1287
        DropCmd::Comments { id } => {
1288
            let path = format!("/drops/{}/comments", drop_id(&id)?);
1289
            if json {
1290
                println!("{}", c.get_text(&path)?);
1291
                return Ok(0);
1292
            }
1293
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
1294
            if list.is_empty() {
1295
                println!("{}", ui::dim("No comments."));
1296
            }
1297
            for m in &list {
1298
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
1299
                println!("{}\n", m.body);
1300
            }
1301
        }
1302
        DropCmd::Comment { id, message } => {
1303
            let m: hub_api::DropComment =
1304
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
1305
            if json {
1306
                println!("{}", serde_json::to_string(&m)?);
1307
            } else {
1308
                println!("{} commented (#{})", ui::ok("✔"), m.id);
1309
            }
1310
        }
1311
    }
1312
    Ok(0)
1313
}
1314
1315
/// `30d`, `12h`, `90m` in milliseconds.
1316
fn duration_ms(s: &str) -> Result<i64> {
1317
    let s = s.trim();
1318
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
1319
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
1320
    let per = match unit {
1321
        "d" => 86_400_000,
1322
        "h" => 3_600_000,
1323
        "m" => 60_000,
1324
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1325
    };
1326
    if n <= 0 {
1327
        bail!("a grant must last some time");
1328
    }
1329
    Ok(n * per)
1330
}
1331
1332
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1333
    use oxy_core::cert::{Grant, SignedGrant};
1334
    use oxy_core::identity::{Identity, Scope};
1335
    match cmd {
1336
        AgentCmd::Grant { name, scope, lasts } => {
1337
            let home = oxy_core::repo::default_home();
1338
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
1339
                format!(
1340
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
1341
                    home.display()
1342
                )
1343
            })?;
1344
            let me: serde_json::Value = c.get("/user")?;
1345
            let username = me["username"].as_str().context("the hub did not say who you are")?;
1346
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
1347
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
1348
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
1349
            let grant = Grant {
1350
                grantor: me_id.hash(),
1351
                subject: format!("agent:{name}@{username}"),
1352
                issuer: hub.hash(),
1353
                scope,
1354
                not_before: (now - 60_000) as u64,
1355
                expires: (now + duration_ms(&lasts)?) as u64,
1356
            };
1357
            let signed = SignedGrant::sign(grant, &me_id, &sk);
1358
            let r: serde_json::Value =
1359
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
1360
            if json {
1361
                println!("{r}");
1362
                return Ok(0);
1363
            }
1364
            println!(
1365
                "{} {} to act for you as {} ({}), until {}",
1366
                ui::ok("✔ granted"),
1367
                ui::strong(&name),
1368
                r["subject"].as_str().unwrap_or(""),
1369
                r["scope"].as_str().unwrap_or(""),
1370
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1371
            );
1372
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
1373
            println!(
1374
                "  {}",
1375
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1376
            );
1377
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
1378
            Ok(0)
1379
        }
1380
        AgentCmd::List => {
1381
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
1382
            if json {
1383
                println!("{}", serde_json::to_string(&grants)?);
1384
                return Ok(0);
1385
            }
1386
            if grants.is_empty() {
1387
                println!("{}", ui::dim("no agent grants"));
1388
            }
1389
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
1390
            for g in grants {
1391
                let state = if g["revoked_ms"].is_i64() {
1392
                    ui::bad("revoked")
1393
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
1394
                    ui::dim("ended")
1395
                } else {
1396
                    ui::ok("live")
1397
                };
1398
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
1399
                println!(
1400
                    "#{:<4} {:<8} {} · {} · until {} · {}",
1401
                    g["id"],
1402
                    state,
1403
                    ui::strong(g["subject"].as_str().unwrap_or("")),
1404
                    g["scope"].as_str().unwrap_or(""),
1405
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
1406
                    ui::dim(&used)
1407
                );
1408
            }
1409
            Ok(0)
1410
        }
1411
        AgentCmd::Revoke { id } => {
1412
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
1413
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
1414
            Ok(0)
1415
        }
1416
    }
1417
}
1418
1419
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
1420
    let hub = url.trim_end_matches('/').to_string();
1421
    let token = match token.as_deref() {
1422
        Some("-") => {
1423
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
1424
            let mut line = String::new();
1425
            std::io::stdin().read_line(&mut line)?;
1426
            line.trim().to_string()
1427
        }
1428
        Some(t) => t.to_string(),
1429
        None => device_sign_in(&hub, ca.clone())?,
1430
    };
1431
    if token.is_empty() {
1432
        bail!("no token given");
1433
    }
1434
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
1435
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
1436
    let account = me["username"].as_str().unwrap_or("?");
1437
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
1438
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
1439
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
1440
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
1441
    cfg.default_hub = Some(hub.clone());
1442
    cfg.save()?;
1443
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
1444
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
1445
    Ok(0)
1446
}
1447
1448
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1449
/// it on the web, and the token arrives here.
1450
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
1451
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
1452
    let c = Client::new(&t)?;
1453
    let host = std::fs::read_to_string("/etc/hostname")
1454
        .ok()
1455
        .or_else(|| std::env::var("COMPUTERNAME").ok())
1456
        .map(|h| h.trim().to_string())
1457
        .filter(|h| !h.is_empty());
1458
    let client = match host {
1459
        Some(h) => format!("oh on {h}"),
1460
        None => "oh".to_string(),
1461
    };
1462
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
1463
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
1464
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
1465
    if code != 200 {
1466
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
1467
    }
1468
    let device = v["device_code"].as_str().context("no device code")?.to_string();
1469
    let user = v["user_code"].as_str().unwrap_or("?");
1470
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
1471
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
1472
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
1473
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
1474
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1475
    loop {
1476
        std::thread::sleep(std::time::Duration::from_secs(interval));
1477
        if std::time::Instant::now() > deadline {
1478
            bail!("the code expired before it was approved; run oh auth login again");
1479
        }
1480
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
1481
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
1482
        if code == 200 {
1483
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
1484
        }
1485
        match v["error"].as_str() {
1486
            Some("authorization_pending") => {}
1487
            Some("slow_down") => interval += 5,
1488
            Some("access_denied") => bail!("the sign-in was denied on the web"),
1489
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
1490
            _ => bail!("signing in: HTTP {code}: {body}"),
1491
        }
1492
    }
1493
}
1494
1495
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
1496
    match (body, file) {
1497
        (Some(b), _) => Ok(b),
1498
        (None, Some(f)) if f == "-" => {
1499
            let mut s = String::new();
1500
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1501
            Ok(s)
1502
        }
1503
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
1504
        (None, None) => Ok(String::new()),
1505
    }
1506
}
1507
1508
fn issue_line(i: &Issue) -> String {
1509
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
1510
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
1511
    format!(
1512
        "{glyph} {} {}{}{}",
1513
        ui::dim(&format!("#{}", i.number)),
1514
        i.title,
1515
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
1516
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1517
    )
1518
}
1519
1520
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
1521
    let base = t.repo_path()?;
1522
    match cmd {
1523
        IssueCmd::List { state } => {
1524
            let path = format!("{base}/issues?state={}", enc(&state));
1525
            if json {
1526
                println!("{}", c.get_text(&path)?);
1527
                return Ok(0);
1528
            }
1529
            let list: Vec<Issue> = c.get(&path)?;
1530
            if list.is_empty() {
1531
                println!("{}", ui::dim(&format!("No {state} issues.")));
1532
            }
1533
            for i in &list {
1534
                println!("{}", issue_line(i));
1535
            }
1536
        }
1537
        IssueCmd::View { number } => {
1538
            let path = format!("{base}/issues/{number}");
1539
            if json {
1540
                println!("{}", c.get_text(&path)?);
1541
                return Ok(0);
1542
            }
1543
            let i: Issue = c.get(&path)?;
1544
            println!("{}", issue_line(&i));
1545
            if !i.body.trim().is_empty() {
1546
                println!("\n{}\n", i.body.trim_end());
1547
            }
1548
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
1549
            for cm in comments {
1550
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
1551
            }
1552
            println!("{}", ui::dim(&i.url));
1553
        }
1554
        IssueCmd::Create { title, body, body_file, label, project, column, attach } => {
1555
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
1556
            let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None };
1557
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
1558
            if json {
1559
                println!("{}", serde_json::to_string(&i)?);
1560
            } else {
1561
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
1562
            }
1563
            if let Some(n) = project {
1564
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
1565
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
1566
                if !json {
1567
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
1568
                }
1569
            }
1570
        }
1571
        IssueCmd::Close { number, reason, comment } => {
1572
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
1573
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
1574
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1575
        }
1576
        IssueCmd::Reopen { number, comment } => {
1577
            comment.post(c, &base, &format!("{base}/issues/{number}/comments"))?;
1578
            let i: Issue =
1579
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
1580
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1581
        }
1582
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
1583
            let body = match (&body, &body_file) {
1584
                (None, None) => None,
1585
                _ => Some(body_of(body, body_file)?),
1586
            };
1587
            let labels = if no_labels {
1588
                Some(Vec::new())
1589
            } else if label.is_empty() {
1590
                None
1591
            } else {
1592
                Some(label)
1593
            };
1594
            let assignees = if no_assignees {
1595
                Some(Vec::new())
1596
            } else if assignee.is_empty() {
1597
                None
1598
            } else {
1599
                Some(assignee)
1600
            };
1601
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
1602
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
1603
            }
1604
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
1605
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
1606
            if json {
1607
                println!("{}", serde_json::to_string(&i)?);
1608
            } else {
1609
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
1610
            }
1611
        }
1612
        IssueCmd::Label(change) => {
1613
            let path = format!("{base}/issues/{}", change.number);
1614
            let now: Issue = c.get(&path)?;
1615
            let labels = change.apply(&now.labels)?;
1616
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
1617
            let i: Issue = c.send("PATCH", &path, &edit)?;
1618
            if json {
1619
                println!("{}", serde_json::to_string(&i)?);
1620
            } else {
1621
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
1622
            }
1623
        }
1624
        IssueCmd::Comment { number, body, body_file, attach } => {
1625
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
1626
            if body.trim().is_empty() {
1627
                bail!("give the comment with --body, --body-file or --attach");
1628
            }
1629
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
1630
            println!("{} commented on #{number}", ui::ok("✔"));
1631
        }
1632
    }
1633
    Ok(0)
1634
}
1635
1636
/// A comment to post with a close or reopen (#368): saying why, in the
1637
/// same command.
1638
#[derive(clap::Args)]
1639
struct StateComment {
1640
    /// Say why, as a comment posted first
1641
    #[arg(long, short)]
1642
    body: Option<String>,
1643
    /// Read the comment from a file ("-" for stdin)
1644
    #[arg(long, short = 'F', conflicts_with = "body")]
1645
    body_file: Option<String>,
1646
    /// Attach a file to the comment (repeatable)
1647
    #[arg(long, short = 'a', value_name = "FILE")]
1648
    attach: Vec<std::path::PathBuf>,
1649
}
1650
1651
impl StateComment {
1652
    fn post(self, c: &Client, base: &str, path: &str) -> Result<()> {
1653
        if self.body.is_none() && self.body_file.is_none() && self.attach.is_empty() {
1654
            return Ok(());
1655
        }
1656
        let body = with_attachments(c, base, body_of(self.body, self.body_file)?, &self.attach)?;
1657
        if !body.trim().is_empty() {
1658
            c.send_text("POST", path, &NewComment { body, path: None, line: None })?;
1659
        }
1660
        Ok(())
1661
    }
1662
}
1663
1664
/// `number`, or the newest run (of `bookmark`, when given): what a push
1665
/// just started is what one usually wants to follow (#367).
1666
fn run_or_newest(c: &Client, base: &str, number: Option<i64>, bookmark: Option<&str>) -> Result<i64> {
1667
    if let Some(n) = number {
1668
        return Ok(n);
1669
    }
1670
    let runs: Vec<FlowRun> = c.get(&format!("{base}/flow/runs?limit=100"))?;
1671
    runs.iter().filter(|r| bookmark.is_none_or(|b| r.bookmark == b)).map(|r| r.number).max().with_context(|| match bookmark {
1672
        Some(b) => format!("no runs of {b} among the latest 100"),
1673
        None => "no runs yet".to_string(),
1674
    })
1675
}
1676
1677
/// `body` with each file attached to the repository and linked under it:
1678
/// an image shown in place, anything else a download (#350). Files are
1679
/// uploaded first, so a failed upload leaves nothing half made.
1680
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> {
1681
    if files.is_empty() {
1682
        return Ok(body);
1683
    }
1684
    let mut links = Vec::new();
1685
    for f in files {
1686
        let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?;
1687
        let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
1688
        let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?;
1689
        let a: hub_api::Attachment =
1690
            serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?;
1691
        links.push(a.markdown);
1692
    }
1693
    let links = links.join("\n\n");
1694
    Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) })
1695
}
1696
1697
fn source_name(s: &hub_api::ProposalSource) -> String {
1698
    match s {
1699
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
1700
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
1701
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1702
    }
1703
}
1704
1705
fn proposal_line(p: &Proposal) -> String {
1706
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
1707
    let glyph = match state.as_str() {
1708
        "open" => ui::ok("●"),
1709
        "draft" => ui::dim("◌"),
1710
        "landed" => ui::strong("✔"),
1711
        _ => ui::dim("○"),
1712
    };
1713
    format!(
1714
        "{glyph} {} {} {}{}",
1715
        ui::dim(&format!("#{}", p.number)),
1716
        p.title,
1717
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
1718
        ui::dim(&format!(" · {} · {state}", p.author))
1719
    )
1720
}
1721
1722
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
1723
    let base = t.repo_path()?;
1724
    match cmd {
1725
        ProposalCmd::List { state, limit } => {
1726
            let path = format!("{base}/proposals?state={state}&limit={limit}");
1727
            if json {
1728
                println!("{}", c.get_text(&path)?);
1729
                return Ok(0);
1730
            }
1731
            let list: Vec<Proposal> = c.get(&path)?;
1732
            if list.is_empty() {
1733
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
1734
            }
1735
            for p in &list {
1736
                println!("{}", proposal_line(p));
1737
            }
1738
        }
1739
        ProposalCmd::View { number } => {
1740
            let path = format!("{base}/proposals/{number}");
1741
            if json {
1742
                println!("{}", c.get_text(&path)?);
1743
                return Ok(0);
1744
            }
1745
            let p: Proposal = c.get(&path)?;
1746
            println!("{}", proposal_line(&p));
1747
            if !p.body.trim().is_empty() {
1748
                println!("\n{}\n", p.body.trim_end());
1749
            }
1750
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
1751
            for ch in &p.changes {
1752
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
1753
            }
1754
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
1755
            if p.landable {
1756
                println!("{} can land", ui::ok("✔"));
1757
            } else {
1758
                for b in &p.blockers {
1759
                    println!("{} {b}", ui::bad("✘"));
1760
                }
1761
            }
1762
            if p.conflicted {
1763
                println!("{} landing it would leave conflicts", ui::bad("!"));
1764
            }
1765
            println!("{}", ui::dim(&p.url));
1766
        }
1767
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
1768
            let target = match into {
1769
                Some(i) => i,
1770
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1771
            };
1772
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
1773
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
1774
            if json {
1775
                println!("{}", serde_json::to_string(&p)?);
1776
            } else {
1777
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1778
            }
1779
        }
1780
        ProposalCmd::Edit { number, title, body, body_file } => {
1781
            let body = match (&body, &body_file) {
1782
                (None, None) => None,
1783
                _ => Some(body_of(body, body_file)?),
1784
            };
1785
            if title.is_none() && body.is_none() {
1786
                bail!("say what to change: --title, --body or --body-file");
1787
            }
1788
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
1789
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1790
            if json {
1791
                println!("{}", serde_json::to_string(&p)?);
1792
            } else {
1793
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1794
            }
1795
        }
1796
        ProposalCmd::Label(change) => {
1797
            let path = format!("{base}/proposals/{}", change.number);
1798
            let now: Proposal = c.get(&path)?;
1799
            let labels = change.apply(&now.labels)?;
1800
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
1801
            let p: Proposal = c.send("PATCH", &path, &edit)?;
1802
            if json {
1803
                println!("{}", serde_json::to_string(&p)?);
1804
            } else {
1805
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
1806
            }
1807
        }
1808
        ProposalCmd::Comment { number, body, body_file } => {
1809
            let body = body_of(body, body_file)?;
1810
            if body.trim().is_empty() {
1811
                bail!("give the comment with --body or --body-file");
1812
            }
1813
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1814
            println!("{} commented on #{number}", ui::ok("✔"));
1815
        }
1816
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
1817
            let path = format!("{base}/proposals/{number}/auto-land");
1818
            let p: Proposal =
1819
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
1820
            if json {
1821
                println!("{}", serde_json::to_string(&p)?);
1822
            } else if p.landed.is_some() {
1823
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
1824
            } else if p.auto_land.is_some() {
1825
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
1826
            } else {
1827
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
1828
            }
1829
        }
1830
        ProposalCmd::Land { number, over_checks, .. } => {
1831
            let body = match &over_checks {
1832
                Some(r) => serde_json::json!({ "over_checks": r }),
1833
                None => serde_json::json!({}),
1834
            };
1835
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
1836
            if json {
1837
                println!("{}", serde_json::to_string(&p)?);
1838
            } else {
1839
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
1840
            }
1841
        }
1842
        ProposalCmd::Close { number, message } => {
1843
            if let Some(body) = message {
1844
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1845
            }
1846
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
1847
            if json {
1848
                println!("{}", serde_json::to_string(&p)?);
1849
            } else {
1850
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
1851
            }
1852
        }
1853
        ProposalCmd::Reopen { number } => {
1854
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
1855
            if json {
1856
                println!("{}", serde_json::to_string(&p)?);
1857
            } else {
1858
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
1859
            }
1860
        }
1861
        ProposalCmd::Ready { number, undo } => {
1862
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
1863
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1864
            if json {
1865
                println!("{}", serde_json::to_string(&p)?);
1866
            } else if undo {
1867
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
1868
            } else {
1869
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
1870
            }
1871
        }
1872
        ProposalCmd::Checks { number } => {
1873
            let path = format!("{base}/proposals/{number}/checks");
1874
            if json {
1875
                println!("{}", c.get_text(&path)?);
1876
                return Ok(0);
1877
            }
1878
            let checks: Vec<hub_api::Check> = c.get(&path)?;
1879
            if checks.is_empty() {
1880
                println!("{}", ui::dim("No checks yet."));
1881
            }
1882
            for ch in checks {
1883
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
1884
            }
1885
        }
1886
    }
1887
    Ok(0)
1888
}
1889
1890
fn run_line(r: &FlowRun) -> String {
1891
    let what =
1892
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
1893
    format!(
1894
        "{} {} {} {}",
1895
        ui::status(&r.status),
1896
        ui::dim(&format!("#{}", r.number)),
1897
        what,
1898
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1899
    )
1900
}
1901
1902
fn print_run(r: &FlowRun, timings: bool) {
1903
    println!("{}", run_line(r));
1904
    for j in &r.jobs {
1905
        let dur = match (j.started_ms, j.finished_ms) {
1906
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
1907
            _ => String::new(),
1908
        };
1909
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
1910
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1911
        // Why a queued job no runner can take waits (oxygenhub#28), and
1912
        // why a job ran where it did (oxygenflow#42).
1913
        if j.status == "queued" && !j.waiting.is_empty() {
1914
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
1915
        } else if !j.placed.is_empty() {
1916
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
1917
        }
1918
        if timings {
1919
            let t = timing_line(j);
1920
            if !t.is_empty() {
1921
                println!("    {}", ui::dim(&t));
1922
            }
1923
        }
1924
    }
1925
    if !r.error.is_empty() {
1926
        println!("{}", ui::bad(&r.error));
1927
    }
1928
    println!("{}", ui::dim(&r.url));
1929
}
1930
1931
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
1932
fn took(ms: i64) -> String {
1933
    match ms {
1934
        ..=999 => format!("{ms} ms"),
1935
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
1936
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1937
    }
1938
}
1939
1940
/// MiB as a person reads them.
1941
fn mib(m: i64) -> String {
1942
    if m >= 1024 {
1943
        format!("{:.1} GiB", m as f64 / 1024.0)
1944
    } else {
1945
        format!("{m} MiB")
1946
    }
1947
}
1948
1949
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1950
/// phase its runner reported, and the most disk and memory it took.
1951
fn timing_line(j: &FlowJob) -> String {
1952
    let mut parts = vec![];
1953
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
1954
        parts.push(format!("waited {}", took((s - q).max(0))));
1955
    }
1956
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
1957
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
1958
        .into_iter()
1959
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
1960
        .collect();
1961
    if !peaks.is_empty() {
1962
        parts.push(format!("peak {}", peaks.join(", ")));
1963
    }
1964
    parts.join(" · ")
1965
}
1966
1967
/// A report's path, its segments encoded and its slashes kept.
1968
fn enc_path(path: &str) -> String {
1969
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
1970
}
1971
1972
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1973
/// files are at `files(path)`. By default its report.toml; with `list`
1974
/// what it holds; with `file` one file, to stdout or `output`.
1975
fn show_report(
1976
    c: &Client,
1977
    at: &str,
1978
    files: impl Fn(&str) -> String,
1979
    list: bool,
1980
    file: Option<String>,
1981
    output: Option<std::path::PathBuf>,
1982
    json: bool,
1983
) -> Result<()> {
1984
    use std::io::Write;
1985
    if let Some(path) = file {
1986
        let bytes = c.get_bytes(&files(&path))?;
1987
        match output {
1988
            Some(out) => {
1989
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
1990
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
1991
            }
1992
            None => std::io::stdout().write_all(&bytes)?,
1993
        }
1994
        return Ok(());
1995
    }
1996
    if json {
1997
        println!("{}", c.get_text(at)?);
1998
        return Ok(());
1999
    }
2000
    if !list {
2001
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
2002
        return Ok(());
2003
    }
2004
    let r: Report = c.get(at)?;
2005
    print_report(&r);
2006
    if r.files_expired_ms.is_some() {
2007
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
2008
    }
2009
    for f in &r.manifest {
2010
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
2011
    }
2012
    println!("{}", ui::dim(&r.url));
2013
    Ok(())
2014
}
2015
2016
/// A report's heading, metrics and context.
2017
fn print_report(r: &Report) {
2018
    let from = match r.run {
2019
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
2020
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
2021
    };
2022
    println!(
2023
        "{} {} {}",
2024
        ui::strong(&r.name),
2025
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
2026
        ui::dim(&format!("· {from} · {} files", r.files))
2027
    );
2028
    if !r.summary.is_empty() {
2029
        println!("  {}", r.summary);
2030
    }
2031
    for m in &r.metrics {
2032
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
2033
        let mut notes = vec![];
2034
        if !m.better.is_empty() {
2035
            notes.push(format!("{} is better", m.better));
2036
        }
2037
        if let Some(a) = m.fail_above {
2038
            notes.push(format!("fails above {a}"));
2039
        }
2040
        if let Some(b) = m.fail_below {
2041
            notes.push(format!("fails below {b}"));
2042
        }
2043
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
2044
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
2045
    }
2046
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
2047
        let line: Vec<String> =
2048
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
2049
        println!("  {}", ui::dim(&line.join(" ")));
2050
    }
2051
}
2052
2053
/// `oh report …` (oxygenhub#348).
2054
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
2055
    let base = t.repo_path()?;
2056
    match cmd {
2057
        ReportCmd::List { bookmark } => {
2058
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
2059
            if json {
2060
                println!("{}", c.get_text(&path)?);
2061
                return Ok(0);
2062
            }
2063
            let list: Vec<Report> = c.get(&path)?;
2064
            if list.is_empty() {
2065
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
2066
            }
2067
            for r in &list {
2068
                print_report(r);
2069
            }
2070
        }
2071
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
2072
            let at = format!("{base}/reports/{}", enc(&report));
2073
            let query = match (id, bookmark) {
2074
                (Some(id), _) => format!("?id={id}"),
2075
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
2076
                (None, None) => String::new(),
2077
            };
2078
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
2079
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
2080
        }
2081
    }
2082
    Ok(0)
2083
}
2084
2085
fn live(status: &str) -> bool {
2086
    matches!(status, "queued" | "running")
2087
}
2088
2089
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
2090
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
2091
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
2092
    if json {
2093
        println!("{done}");
2094
    } else {
2095
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
2096
    }
2097
    Ok(())
2098
}
2099
2100
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
2101
    let path = format!("{base}/flow/runs/{number}");
2102
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2103
    loop {
2104
        let r: FlowRun = c.get(&path)?;
2105
        if !json {
2106
            for j in &r.jobs {
2107
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
2108
                if seen.get(&j.name) != Some(&shown) {
2109
                    println!("{} {}", ui::status(&j.status), j.name);
2110
                    if j.status == "queued" && !j.waiting.is_empty() {
2111
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
2112
                    }
2113
                    seen.insert(j.name.clone(), shown);
2114
                }
2115
            }
2116
        }
2117
        if !live(&r.status) {
2118
            if json {
2119
                println!("{}", serde_json::to_string(&r)?);
2120
            } else {
2121
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
2122
            }
2123
            return Ok(if r.status == "passed" { 0 } else { 1 });
2124
        }
2125
        std::thread::sleep(Duration::from_secs(3));
2126
    }
2127
}
2128
2129
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
2130
    let base = t.repo_path()?;
2131
    match cmd {
2132
        RunCmd::List { limit } => {
2133
            let path = format!("{base}/flow/runs?limit={limit}");
2134
            if json {
2135
                println!("{}", c.get_text(&path)?);
2136
                return Ok(0);
2137
            }
2138
            let runs: Vec<FlowRun> = c.get(&path)?;
2139
            if runs.is_empty() {
2140
                println!("{}", ui::dim("No runs yet."));
2141
            }
2142
            for r in &runs {
2143
                println!("{}", run_line(r));
2144
            }
2145
        }
2146
        RunCmd::View { number, bookmark, timings } => {
2147
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
2148
            let path = format!("{base}/flow/runs/{number}");
2149
            if json {
2150
                println!("{}", c.get_text(&path)?);
2151
                return Ok(0);
2152
            }
2153
            print_run(&c.get(&path)?, timings);
2154
        }
2155
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
2156
            let mut body = match (bookmark, change) {
2157
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
2158
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
2159
                (None, None) => serde_json::json!({}),
2160
            };
2161
            if !jobs.is_empty() {
2162
                body["jobs"] = serde_json::json!(jobs);
2163
            }
2164
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
2165
            let n = started["number"].as_i64().context("the hub named no run")?;
2166
            if !json || !follow {
2167
                if json {
2168
                    println!("{started}");
2169
                } else {
2170
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
2171
                }
2172
            }
2173
            if follow {
2174
                return watch(c, &base, n, json);
2175
            }
2176
        }
2177
        RunCmd::Watch { number, bookmark } => {
2178
            let number = run_or_newest(c, &base, number, bookmark.as_deref())?;
2179
            return watch(c, &base, number, json);
2180
        }
2181
        RunCmd::Log { number, job } => {
2182
            let mut after = 0;
2183
            loop {
2184
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
2185
                let lines: Vec<FlowLogLine> = c.get(&path)?;
2186
                if lines.is_empty() {
2187
                    break;
2188
                }
2189
                for l in &lines {
2190
                    if json {
2191
                        println!("{}", serde_json::to_string(l)?);
2192
                    } else if l.stream == "flow" {
2193
                        println!("{}", ui::dim(&l.text));
2194
                    } else {
2195
                        println!("{}", l.text);
2196
                    }
2197
                }
2198
                after = lines.last().map(|l| l.seq).unwrap_or(after);
2199
            }
2200
        }
2201
        RunCmd::Report { number, job, pick } => {
2202
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
2203
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
2204
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
2205
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
2206
        }
2207
        RunCmd::Rerun { number, job: Some(job) } => {
2208
            let queued: serde_json::Value =
2209
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
2210
            if json {
2211
                println!("{queued}");
2212
            } else {
2213
                let n = queued["queued"].as_i64().unwrap_or(1);
2214
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
2215
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
2216
            }
2217
        }
2218
        RunCmd::Rerun { number, job: None } => {
2219
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
2220
            if json {
2221
                println!("{started}");
2222
            } else {
2223
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
2224
            }
2225
        }
2226
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
2227
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
2228
        RunCmd::Cancel { number } => {
2229
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
2230
            if json {
2231
                println!("{done}");
2232
            } else {
2233
                println!("{} cancelled run #{number}", ui::ok("✔"));
2234
            }
2235
        }
2236
    }
2237
    Ok(0)
2238
}
2239
2240
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
2241
    let base = t.repo_path()?;
2242
    match cmd {
2243
        LabelCmd::List => {
2244
            let path = format!("{base}/labels");
2245
            if json {
2246
                println!("{}", c.get_text(&path)?);
2247
                return Ok(0);
2248
            }
2249
            let labels: Vec<hub_api::Label> = c.get(&path)?;
2250
            if labels.is_empty() {
2251
                println!("{}", ui::dim("No labels."));
2252
            }
2253
            for l in labels {
2254
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
2255
            }
2256
        }
2257
        LabelCmd::Create { name, colour, description } => {
2258
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
2259
            if json {
2260
                println!("{}", serde_json::to_string(&l)?);
2261
            } else {
2262
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
2263
            }
2264
        }
2265
        LabelCmd::Delete { name } => {
2266
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
2267
            println!("{} deleted label {name}", ui::ok("✔"));
2268
        }
2269
    }
2270
    Ok(0)
2271
}
2272
2273
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
2274
    let base = match (&org, site) {
2275
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
2276
        (None, true) => "/admin/assistants".to_string(),
2277
        (None, false) => format!("{}/assistants", t.repo_path()?),
2278
    };
2279
    match cmd {
2280
        AssistantCmd::List => {
2281
            if json {
2282
                println!("{}", c.get_text(&base)?);
2283
                return Ok(0);
2284
            }
2285
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
2286
            if list.is_empty() {
2287
                println!("{}", ui::dim("No assistants."));
2288
            }
2289
            for a in list {
2290
                let state = if a.enabled && !a.off_above {
2291
                    ui::ok("on")
2292
                } else if a.off_above {
2293
                    ui::dim("off above")
2294
                } else {
2295
                    ui::dim("off")
2296
                };
2297
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
2298
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2299
            }
2300
        }
2301
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
2302
            let token = match token_env {
2303
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
2304
                None => String::new(),
2305
            };
2306
            let body =
2307
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
2308
            let r: serde_json::Value = c.send("POST", &base, &body)?;
2309
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2310
        }
2311
        AssistantCmd::Remove { name } => {
2312
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
2313
            println!("{} removed {name}", ui::ok("✔"));
2314
        }
2315
        AssistantCmd::Prompt { set } => {
2316
            let p: hub_api::AssistantPrompt = match set {
2317
                Some(path) => {
2318
                    let text = if path.as_os_str() == "-" {
2319
                        let mut s = String::new();
2320
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
2321
                        s
2322
                    } else {
2323
                        std::fs::read_to_string(&path)?
2324
                    };
2325
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2326
                }
2327
                None => c.get(&format!("{base}/prompt"))?,
2328
            };
2329
            if json {
2330
                println!("{}", serde_json::to_string(&p)?);
2331
                return Ok(0);
2332
            }
2333
            for (from, text) in &p.inherited {
2334
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
2335
            }
2336
            if p.prompt.is_empty() {
2337
                println!("{}", ui::dim("No prompt of its own."));
2338
            } else {
2339
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
2340
            }
2341
        }
2342
    }
2343
    Ok(0)
2344
}
2345
2346
fn project_line(p: &hub_api::Project) -> String {
2347
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
2348
    let private = if p.public { "" } else { " · private" };
2349
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
2350
}
2351
2352
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
2353
    let owner = match owner {
2354
        Some(o) => o,
2355
        None => t.repo()?.0.to_string(),
2356
    };
2357
    let base = format!("/projects/{}", enc(&owner));
2358
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
2359
        let p: hub_api::Project =
2360
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
2361
        if json {
2362
            println!("{}", serde_json::to_string(&p)?);
2363
        } else {
2364
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
2365
        }
2366
        Ok(())
2367
    };
2368
    match cmd {
2369
        ProjectCmd::List => {
2370
            if json {
2371
                println!("{}", c.get_text(&base)?);
2372
                return Ok(0);
2373
            }
2374
            let list: Vec<hub_api::Project> = c.get(&base)?;
2375
            if list.is_empty() {
2376
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
2377
            }
2378
            for p in &list {
2379
                println!("{}", project_line(p));
2380
            }
2381
        }
2382
        ProjectCmd::View { number, archived } => {
2383
            let path = format!("{base}/{number}");
2384
            let cards = format!("{path}/cards?archived=true");
2385
            if json {
2386
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
2387
                return Ok(0);
2388
            }
2389
            let mut b: hub_api::Board = c.get(&path)?;
2390
            if archived {
2391
                b.columns = c.get(&cards)?;
2392
            }
2393
            println!("{}", project_line(&b.project));
2394
            if !b.project.description.is_empty() {
2395
                println!("{}", b.project.description);
2396
            }
2397
            for col in &b.columns {
2398
                println!();
2399
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
2400
                if col.cards.is_empty() {
2401
                    println!("  {}", ui::dim("(empty)"));
2402
                }
2403
                for card in &col.cards {
2404
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
2405
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
2406
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
2407
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
2408
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
2409
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2410
                }
2411
            }
2412
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2413
        }
2414
        ProjectCmd::Create { title, description, private } => {
2415
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
2416
            if json {
2417
                println!("{}", serde_json::to_string(&p)?);
2418
            } else {
2419
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
2420
            }
2421
        }
2422
        ProjectCmd::Column { cmd } => {
2423
            let col_path = |number: i64, column: &str| format!("{base}/{number}/columns/{}", enc(column));
2424
            let (number, b, what): (i64, hub_api::Board, String) = match cmd {
2425
                ColumnCmd::Add { number, name } => {
2426
                    let b = c.send("POST", &format!("{base}/{number}/columns"), &hub_api::NewColumn { name: name.clone() })?;
2427
                    (number, b, format!("added column {name}"))
2428
                }
2429
                ColumnCmd::Rename { number, column, to } => {
2430
                    let edit = hub_api::ColumnEdit { name: Some(to.clone()), position: None };
2431
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("renamed column {column} to {to}"))
2432
                }
2433
                ColumnCmd::Move { number, column, to, left, right } => {
2434
                    let position = match to {
2435
                        Some(n) => n - 1,
2436
                        None => {
2437
                            let now: hub_api::Board = c.get(&format!("{base}/{number}"))?;
2438
                            let at = now
2439
                                .columns
2440
                                .iter()
2441
                                .position(|col| col.id.to_string() == column || col.name.eq_ignore_ascii_case(&column))
2442
                                .with_context(|| format!("no column {column} on board {number}"))?
2443
                                as i64;
2444
                            if left {
2445
                                (at - 1).max(0)
2446
                            } else {
2447
                                debug_assert!(right);
2448
                                at + 1
2449
                            }
2450
                        }
2451
                    };
2452
                    let edit = hub_api::ColumnEdit { name: None, position: Some(position) };
2453
                    (number, c.send("PATCH", &col_path(number, &column), &edit)?, format!("moved column {column}"))
2454
                }
2455
                ColumnCmd::Remove { number, column } => {
2456
                    (number, c.send("DELETE", &col_path(number, &column), &serde_json::json!({}))?, format!("removed column {column}"))
2457
                }
2458
            };
2459
            if json {
2460
                println!("{}", serde_json::to_string(&b)?);
2461
            } else {
2462
                let order: Vec<&str> = b.columns.iter().map(|col| col.name.as_str()).collect();
2463
                println!("{} {what} on board {number}: {}", ui::ok("✔"), ui::dim(&order.join(" · ")));
2464
            }
2465
        }
2466
        ProjectCmd::Close { number } => state(number, true, "closed")?,
2467
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
2468
        ProjectCmd::Transfer { number, to } => {
2469
            let p: hub_api::Project =
2470
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
2471
            if json {
2472
                println!("{}", serde_json::to_string(&p)?);
2473
            } else {
2474
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
2475
            }
2476
        }
2477
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2478
            // The hub names a card's issue as `repo#N` among the owner's
2479
            // repositories.
2480
            let reference = match reference {
2481
                None => String::new(),
2482
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
2483
                    Some((o, rest)) if o == owner => rest.to_string(),
2484
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
2485
                    None => r,
2486
                },
2487
                Some(r) => {
2488
                    let n = r.trim_start_matches('#');
2489
                    if n.parse::<i64>().is_err() {
2490
                        bail!("{r}: give an issue or proposal number, or NAME#N");
2491
                    }
2492
                    format!("{}#{n}", t.repo()?.1)
2493
                }
2494
            };
2495
            let note = note.unwrap_or_default();
2496
            if reference.is_empty() && note.is_empty() {
2497
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
2498
            }
2499
            let card: hub_api::ProjectCard =
2500
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
2501
            if json {
2502
                println!("{}", serde_json::to_string(&card)?);
2503
            } else {
2504
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2505
            }
2506
        }
2507
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
2508
            (Some(card), None) => {
2509
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
2510
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2511
            }
2512
            (None, Some(from)) => {
2513
                let r: hub_api::CardsMoved = c.send(
2514
                    "POST",
2515
                    &format!("{base}/{number}/cards/move"),
2516
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
2517
                )?;
2518
                if json {
2519
                    println!("{}", serde_json::to_string(&r)?);
2520
                    return Ok(0);
2521
                }
2522
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
2523
                for m in &r.moved {
2524
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2525
                }
2526
                let verb = if dry_run { "would move" } else { "moved" };
2527
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2528
            }
2529
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2530
        },
2531
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
2532
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
2533
                None => None,
2534
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2535
            };
2536
            let r: hub_api::CardsArchived = c.send(
2537
                "POST",
2538
                &format!("{base}/{number}/cards/archive"),
2539
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
2540
            )?;
2541
            if json {
2542
                println!("{}", serde_json::to_string(&r)?);
2543
                return Ok(0);
2544
            }
2545
            let verb = if dry_run { "would archive" } else { "archived" };
2546
            for a in &r.archived {
2547
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
2548
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2549
            }
2550
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2551
        }
2552
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
2553
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
2554
            println!("{} card {card} restored", ui::ok("✔"));
2555
        }
2556
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
2557
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
2558
            println!("{} card {card} removed", ui::ok("✔"));
2559
        }
2560
    }
2561
    Ok(0)
2562
}
2563
2564
fn milestone_line(m: &hub_api::Milestone) -> String {
2565
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
2566
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
2567
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
2568
}
2569
2570
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
2571
    let base = t.repo_path()?;
2572
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
2573
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
2574
        if json {
2575
            println!("{}", serde_json::to_string(&m)?);
2576
        } else {
2577
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
2578
        }
2579
        Ok(())
2580
    };
2581
    match cmd {
2582
        MilestoneCmd::List => {
2583
            let path = format!("{base}/milestones");
2584
            if json {
2585
                println!("{}", c.get_text(&path)?);
2586
                return Ok(0);
2587
            }
2588
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
2589
            if list.is_empty() {
2590
                println!("{}", ui::dim("No milestones."));
2591
            }
2592
            for m in &list {
2593
                println!("{}", milestone_line(m));
2594
            }
2595
        }
2596
        MilestoneCmd::Create { title, description, due } => {
2597
            let m: hub_api::Milestone =
2598
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
2599
            if json {
2600
                println!("{}", serde_json::to_string(&m)?);
2601
            } else {
2602
                println!("{} milestone {}", ui::ok("✔"), m.title);
2603
            }
2604
        }
2605
        MilestoneCmd::Edit { title, rename, description, due } => {
2606
            if rename.is_none() && description.is_none() && due.is_none() {
2607
                bail!("say what to change: --rename, --description or --due");
2608
            }
2609
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2610
        }
2611
        MilestoneCmd::Close { title } => {
2612
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2613
        }
2614
        MilestoneCmd::Reopen { title } => {
2615
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2616
        }
2617
    }
2618
    Ok(0)
2619
}
2620
2621
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
2622
    let base = t.repo_path()?;
2623
    match cmd {
2624
        TagCmd::List => {
2625
            let path = format!("{base}/tags");
2626
            if json {
2627
                println!("{}", c.get_text(&path)?);
2628
                return Ok(0);
2629
            }
2630
            let tags: Vec<Tag> = c.get(&path)?;
2631
            if tags.is_empty() {
2632
                println!("{}", ui::dim("no tags"));
2633
            }
2634
            for t in tags {
2635
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
2636
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
2637
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2638
            }
2639
        }
2640
        TagCmd::Create { name, target, message } => {
2641
            let new = hub_api::NewTag { name, target, message };
2642
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
2643
            if json {
2644
                println!("{}", serde_json::to_string(&made)?);
2645
            } else {
2646
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
2647
            }
2648
        }
2649
        TagCmd::Delete { name, reason } => {
2650
            let reason = reason.unwrap_or_default();
2651
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
2652
            if json {
2653
                println!("{}", serde_json::json!({ "withdrawn": name }));
2654
            } else {
2655
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
2656
            }
2657
        }
2658
    }
2659
    Ok(0)
2660
}
2661
2662
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
2663
    let base = t.repo_path()?;
2664
    match cmd {
2665
        ReleaseCmd::List => {
2666
            let path = format!("{base}/releases");
2667
            if json {
2668
                println!("{}", c.get_text(&path)?);
2669
                return Ok(0);
2670
            }
2671
            let list: Vec<Release> = c.get(&path)?;
2672
            if list.is_empty() {
2673
                println!("{}", ui::dim("No releases."));
2674
            }
2675
            for r in &list {
2676
                println!(
2677
                    "{} {} {}{}",
2678
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
2679
                    ui::strong(&r.tag),
2680
                    r.title,
2681
                    ui::dim(&format!(
2682
                        " · {} asset{} · {}",
2683
                        r.assets.len(),
2684
                        if r.assets.len() == 1 { "" } else { "s" },
2685
                        ui::ago(r.created_ms)
2686
                    ))
2687
                );
2688
            }
2689
        }
2690
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
2691
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
2692
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
2693
            if json {
2694
                println!("{}", serde_json::to_string(&r)?);
2695
            } else {
2696
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
2697
            }
2698
        }
2699
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
2700
            let notes = match notes.as_deref() {
2701
                Some("-") => Some(body_of(None, Some("-".into()))?),
2702
                _ => notes,
2703
            };
2704
            if title.is_none() && notes.is_none() && prerelease.is_none() {
2705
                bail!("say what to change: --title, --notes or --prerelease");
2706
            }
2707
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
2708
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
2709
            if json {
2710
                println!("{}", serde_json::to_string(&r)?);
2711
            } else {
2712
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
2713
            }
2714
        }
2715
        ReleaseCmd::Upload { tag, files } => {
2716
            if files.is_empty() {
2717
                bail!("name the files to attach");
2718
            }
2719
            for f in files {
2720
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
2721
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
2722
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
2723
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2724
            }
2725
        }
2726
        ReleaseCmd::Trust { tag } => {
2727
            let path = format!("{base}/releases/trust/{}", enc(&tag));
2728
            if json {
2729
                println!("{}", c.get_text(&path)?);
2730
                return Ok(0);
2731
            }
2732
            let r: serde_json::Value = c.get(&path)?;
2733
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
2734
            let mut worst = 0;
2735
            for ch in r["audit"].as_array().into_iter().flatten() {
2736
                let v = ch["verdict"].as_str().unwrap_or("");
2737
                worst = worst.max(match v {
2738
                    "fail" => 2,
2739
                    "warn" => 1,
2740
                    _ => 0,
2741
                });
2742
                let g = match v {
2743
                    "pass" => ui::ok("✔"),
2744
                    "warn" => ui::warn("!"),
2745
                    _ => ui::bad("✘"),
2746
                };
2747
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2748
            }
2749
            return Ok(if worst == 2 { 1 } else { 0 });
2750
        }
2751
    }
2752
    Ok(0)
2753
}
2754
2755
#[cfg(test)]
2756
mod tests {
2757
2758
    #[test]
2759
    fn job_timings_and_report_commands_read_plainly() {
2760
        use clap::Parser;
2761
        let job = hub_api::FlowJob {
2762
            name: "perf".into(),
2763
            status: "passed".into(),
2764
            depends_on: vec![],
2765
            runner: "earth-1".into(),
2766
            exit_code: Some(0),
2767
            error: String::new(),
2768
            started_ms: Some(13_000),
2769
            finished_ms: Some(200_000),
2770
            log_lines: 10,
2771
            waiting: String::new(),
2772
            placed: String::new(),
2773
            approval: String::new(),
2774
            queued_ms: Some(1_000),
2775
            ready_ms: Some(12_500),
2776
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
2777
            peak_disk_mib: Some(2150),
2778
            peak_memory_mib: Some(900),
2779
        };
2780
        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");
2781
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
2782
        assert_eq!(super::timing_line(&bare), "");
2783
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2784
2785
        let cli =
2786
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
2787
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
2788
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
2789
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
2790
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
2791
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
2792
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
2793
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
2794
    }
2795
2796
    #[test]
2797
    fn runner_update_scopes_resolve_by_name_or_id() {
2798
        let all = hub_api::RunnerUpdates {
2799
            repo: String::new(),
2800
            settings: vec![],
2801
            groups: vec![hub_api::RunnerGroup {
2802
                id: 4,
2803
                owner: "acme".into(),
2804
                name: "canary".into(),
2805
                percent: None,
2806
                members: vec![],
2807
                wave: None,
2808
            }],
2809
            runners: vec![],
2810
            holds: vec![],
2811
        };
2812
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
2813
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
2814
        for g in ["group:canary", "group:acme/canary", "group:4"] {
2815
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2816
        }
2817
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
2818
        assert!(update_scope("everyone", &all).is_err());
2819
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
2820
        assert!(switch(Some("yes")).is_err());
2821
    }
2822
    use super::*;
2823
2824
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2825
    /// help says, and a drop is named by its id or its address.
2826
    #[test]
2827
    fn drop_commands_parse() {
2828
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
2829
        match cli.cmd {
2830
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
2831
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
2832
                assert!(secret);
2833
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2834
            }
2835
            _ => panic!("not drop create"),
2836
        }
2837
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
2838
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
2839
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
2840
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
2841
                assert!(channel.is_none() && dry_run.is_none());
2842
            }
2843
            _ => panic!("not runner-updates set"),
2844
        }
2845
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
2846
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
2847
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
2848
            _ => panic!("not drop list"),
2849
        }
2850
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
2851
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
2852
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2853
            }
2854
            _ => panic!("not drop view"),
2855
        }
2856
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
2857
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
2858
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2859
        }
2860
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
2861
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
2862
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
2863
            _ => panic!("not drop comment"),
2864
        }
2865
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
2866
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
2867
        assert!(drop_id("andy/notes").is_err());
2868
    }
2869
}