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